From 1394f9d02f77d74a1e357f8f58e2655f302dbdcf Mon Sep 17 00:00:00 2001 From: ido Date: Thu, 19 Feb 2015 14:50:46 +0200 Subject: [PATCH] add es6 sample --- playground/dist/home.min.js | 2 +- playground/dist/rt-main.browser.js | 18264 ++++++++++++++++++++--- playground/dist/rt-main.browser.min.js | 33 +- 3 files changed, 16596 insertions(+), 1703 deletions(-) diff --git a/playground/dist/home.min.js b/playground/dist/home.min.js index 721c68e..0745e70 100644 --- a/playground/dist/home.min.js +++ b/playground/dist/home.min.js @@ -7,4 +7,4 @@ * see: http://github.com/requirejs/text for details */ -(function(e){if(typeof exports=="object"&&typeof module=="object")module.exports=e();else{if(typeof define=="function"&&define.amd)return define("libs/codemirror-4.8/lib/codemirror",[],e);this.CodeMirror=e()}})(function(){function S(e,t){if(!(this instanceof S))return new S(e,t);this.options=t=t?zo(t):{},zo(fi,t,!1),H(t);var n=t.value;typeof n=="string"&&(n=new js(n,t.mode)),this.doc=n;var s=this.display=new x(e,n);s.wrapper.CodeMirror=this,M(this),A(this),t.lineWrapping&&(this.display.wrapper.className+=" CodeMirror-wrap"),t.autofocus&&!d&&er(this),this.state={keyMaps:[],overlays:[],modeGen:0,overwrite:!1,focused:!1,suppressEdits:!1,pasteIncoming:!1,cutIncoming:!1,draggingText:!1,highlight:new Do,keySeq:null},r&&i<11&&setTimeout(Wo(Zn,this,!0),20),rr(this),fu(),kn(this),this.curOp.forceUpdate=!0,Rs(this,n),t.autofocus&&!d||nu()==s.input?setTimeout(Wo(Pr,this),20):Hr(this);for(var o in li)li.hasOwnProperty(o)&&li[o](this,t[o],hi);R(this);for(var u=0;ut.maxLineLength&&(t.maxLineLength=n,t.maxLine=e)})}function H(e){var t=qo(e.gutters,"CodeMirror-linenumbers");t==-1&&e.lineNumbers?e.gutters=e.gutters.concat(["CodeMirror-linenumbers"]):t>-1&&!e.lineNumbers&&(e.gutters=e.gutters.slice(0),e.gutters.splice(t,1))}function B(e){return e.display.scroller.clientHeight-e.display.wrapper.clientHeightt.clientWidth;s&&t.scrollWidth<=t.clientWidth+1&&r>0&&!t.hScrollbarTakesSpace&&(s=!1);var o=i>t.clientHeight;o?(n.scrollbarV.style.display="block",n.scrollbarV.style.bottom=s?r+"px":"0",n.scrollbarV.firstChild.style.height=Math.max(0,i-t.clientHeight+(t.barHeight||n.scrollbarV.clientHeight))+"px"):(n.scrollbarV.style.display="",n.scrollbarV.firstChild.style.height="0"),s?(n.scrollbarH.style.display="block",n.scrollbarH.style.right=o?r+"px":"0",n.scrollbarH.firstChild.style.width=t.scrollWidth-t.clientWidth+(t.barWidth||n.scrollbarH.clientWidth)+"px"):(n.scrollbarH.style.display="",n.scrollbarH.firstChild.style.width="0"),s&&o?(n.scrollbarFiller.style.display="block",n.scrollbarFiller.style.height=n.scrollbarFiller.style.width=r+"px"):n.scrollbarFiller.style.display="",s&&e.options.coverGutterNextToScrollbar&&e.options.fixedGutter?(n.gutterFiller.style.display="block",n.gutterFiller.style.height=r+"px",n.gutterFiller.style.width=n.gutters.offsetWidth+"px"):n.gutterFiller.style.display="";if(!e.state.checkedOverlayScrollbar&&t.clientHeight>0){if(r===0){var u=v&&!c?"12px":"18px";n.scrollbarV.style.minWidth=n.scrollbarH.style.minHeight=u;var a=function(t){mo(t)!=n.scrollbarV&&mo(t)!=n.scrollbarH&&jn(e,ur)(t)};yo(n.scrollbarV,"mousedown",a),yo(n.scrollbarH,"mousedown",a)}e.state.checkedOverlayScrollbar=!0}}function I(e,t,n){var r=n&&n.top!=null?Math.max(0,n.top):e.scroller.scrollTop;r=Math.floor(r-Kt(e));var i=n&&n.bottom!=null?n.bottom:r+e.wrapper.clientHeight,s=$s(t,r),o=$s(t,i);if(n&&n.ensure){var u=n.ensure.from.line,a=n.ensure.to.line;if(u=o)return{from:$s(t,Js(Us(t,a))-e.wrapper.clientHeight),to:a}}return{from:s,to:Math.max(o,s+1)}}function q(e){var t=e.display,n=t.view;if(!t.alignWidgets&&(!t.gutters.firstChild||!e.options.fixedGutter))return;var r=z(t)-t.scroller.scrollLeft+e.doc.scrollLeft,i=t.gutters.offsetWidth,s=r+"px";for(var o=0;o=n.viewFrom&&t.visible.to<=n.viewTo&&(n.updateLineNumbers==null||n.updateLineNumbers>=n.viewTo)&&Jn(e)==0)return!1;R(e)&&(Wn(e),t.dims=Y(e));var i=r.first+r.size,s=Math.max(t.visible.from-e.options.viewportMargin,r.first),o=Math.min(i,t.visible.to+e.options.viewportMargin);n.viewFromo&&n.viewTo-o<20&&(o=Math.min(i,n.viewTo)),E&&(s=rs(e.doc,s),o=is(e.doc,o));var u=s!=n.viewFrom||o!=n.viewTo||n.lastWrapHeight!=t.wrapperHeight||n.lastWrapWidth!=t.wrapperWidth;$n(e,s,o),n.viewOffset=Js(Us(e.doc,n.viewFrom)),e.display.mover.style.top=n.viewOffset+"px";var a=Jn(e);if(!u&&a==0&&!t.force&&(n.updateLineNumbers==null||n.updateLineNumbers>=n.viewTo))return!1;var f=nu();return a>4&&(n.lineDiv.style.display="none"),Z(e,n.updateLineNumbers,t.dims),a>4&&(n.lineDiv.style.display=""),f&&nu()!=f&&f.offsetHeight&&f.focus(),Zo(n.cursorDiv),Zo(n.selectionDiv),u&&(n.lastWrapHeight=t.wrapperHeight,n.lastWrapWidth=t.wrapperWidth,Xt(e,400)),n.updateLineNumbers=null,!0}function V(e,t){var n=t.force,r=t.viewport;for(var i=!0;;i=!1){if(i&&e.options.lineWrapping&&t.oldScrollerWidth!=e.display.scroller.clientWidth)n=!0;else{n=!1,r&&r.top!=null&&(r={top:Math.min(e.doc.height+Qt(e.display)-Lo-e.display.scroller.clientHeight,r.top)}),t.visible=I(e.display,e.doc,r);if(t.visible.from>=e.display.viewFrom&&t.visible.to<=e.display.viewTo)break}if(!X(e,t))break;Q(e);var s=j(e);Rt(e),J(e,s),F(e,s)}So(e,"update",e),(e.display.viewFrom!=t.oldViewFrom||e.display.viewTo!=t.oldViewTo)&&So(e,"viewportChange",e,e.display.viewFrom,e.display.viewTo)}function $(e,t){var n=new W(e,t);if(X(e,n)){Q(e),V(e,n);var r=j(e);Rt(e),J(e,r),F(e,r)}}function J(e,t){e.display.sizer.style.minHeight=e.display.heightForcer.style.top=t.docHeight+"px",e.display.gutters.style.height=Math.max(t.docHeight,t.clientHeight-Lo)+"px"}function K(e,t){e.display.sizer.offsetWidth+e.display.gutters.offsetWidth.001||l<-0.001){Xs(o.line,u),G(o.line);if(o.rest)for(var c=0;c-1&&(d=!1),et(e,h,l,n)),d&&(Zo(h.lineNumber),h.lineNumber.appendChild(document.createTextNode(U(e.options,l)))),u=h.node.nextSibling}l+=h.size}while(u)u=a(u)}function et(e,t,n,r){for(var i=0;i=0){var o=mt(s.from(),i.from()),u=vt(s.to(),i.to()),a=s.empty()?i.from()==i.head:s.from()==s.head;r<=t&&--t,e.splice(--r,2,new yt(a?u:o,a?o:u))}}return new gt(e,t)}function wt(e,t){return new gt([new yt(e,t||e)],0)}function Et(e,t){return Math.max(e.first,Math.min(t,e.first+e.size-1))}function St(e,t){if(t.linen?ht(n,Us(e,n).text.length):xt(t,Us(e,t.line).text.length)}function xt(e,t){var n=e.ch;return n==null||n>t?ht(e.line,t):n<0?ht(e.line,0):e}function Tt(e,t){return t>=e.first&&t=s.ch:f.to>s.ch))){if(r){wo(l,"beforeCursorEnter");if(l.explicitlyCleared){if(!u.markedSpans)break;--a;continue}}if(!l.atomic)continue;var c=l.find(o<0?-1:1);if(pt(c,s)==0){c.ch+=o,c.ch<0?c.line>e.first?c=St(e,ht(c.line-1)):c=null:c.ch>u.text.length&&(c.line3&&(f(d,s.top,null,s.bottom),d=u,s.bottomc.bottom||p.bottom==c.bottom&&p.right>c.right)c=p;d0?t.blinker=setInterval(function(){t.cursorDiv.style.visibility=(n=!n)?"":"hidden"},e.options.cursorBlinkRate):e.options.cursorBlinkRate<0&&(t.cursorDiv.style.visibility="hidden")}function Xt(e,t){e.doc.mode.startState&&e.doc.frontier=e.display.viewTo)return;var n=+(new Date)+e.options.workTime,r=yi(t.mode,Jt(e,t.frontier)),i=[];t.iter(t.frontier,Math.min(t.first+t.size,e.display.viewTo+500),function(s){if(t.frontier>=e.display.viewFrom){var o=s.styles,u=bs(e,s,r,!0);s.styles=u.styles;var a=s.styleClasses,f=u.classes;f?s.styleClasses=f:a&&(s.styleClasses=null);var l=!o||o.length!=s.styles.length||a!=f&&(!a||!f||a.bgClass!=f.bgClass||a.textClass!=f.textClass);for(var c=0;!l&&cn)return Xt(e,e.options.workDelay),!0}),i.length&&Bn(e,function(){for(var t=0;to;--u){if(u<=s.first)return s.first;var a=Us(s,u-1);if(a.stateAfter&&(!n||u<=s.frontier))return u;var f=Po(a.text,null,e.options.tabSize);if(i==null||r>f)i=u-1,r=f}return i}function Jt(e,t,n){var r=e.doc,i=e.display;if(!r.mode.startState)return!0;var s=$t(e,t,n),o=s>r.first&&Us(r,s-1).stateAfter;return o?o=yi(r.mode,o):o=bi(r.mode),r.iter(s,t,function(n){Es(e,n.text,o);var u=s==t-1||s%5==0||s>=i.viewFrom&&s2&&s.push((a.bottom+f.top)/2-n.top)}}s.push(n.bottom-n.top)}}function Zt(e,t,n){if(e.line==t)return{map:e.measure.map,cache:e.measure.cache};for(var r=0;rn)return{map:e.measure.maps[r],cache:e.measure.caches[r],before:!0}}function en(e,t){t=ts(t);var n=Vs(t),r=e.display.externalMeasured=new qn(e.doc,t,n);r.lineN=n;var i=r.built=Ns(e,r);return r.text=i.pre,eu(e.display.lineMeasure,i.pre),r}function tn(e,t,n,r){return sn(e,rn(e,t),n,r)}function nn(e,t){if(t>=e.display.viewFrom&&t=n.lineN&&tn)f=p-h,a=f-1,n>=p&&(l="right");if(a!=null){u=o[c+2],h==p&&s==(u.insertLeft?"left":"right")&&(l=s);if(s=="left"&&a==0)while(c&&o[c-2]==o[c-3]&&o[c-1].insertLeft)u=o[(c-=3)+2],l="left";if(s=="right"&&a==p-h)while(c0&&(l=s="right");var v;e.options.lineWrapping&&(v=u.getClientRects()).length>1?d=v[s=="right"?v.length-1:0]:d=u.getBoundingClientRect()}if(r&&i<9&&!a&&(!d||!d.left&&!d.right)){var m=u.parentNode.getClientRects()[0];m?d={left:m.left,right:m.left+Tn(e.display),top:m.top,bottom:m.bottom}:d=on}var g=d.top-t.rect.top,y=d.bottom-t.rect.top,b=(g+y)/2,w=t.view.measure.heights;for(var c=0;cn.from?o(e-1):o(e,r)}r=r||Us(e.doc,t.line),i||(i=rn(e,r));var a=Ks(r),f=t.ch;if(!a)return o(f);var l=Pu(a,f),c=u(f,l);return Du!=null&&(c.other=u(f,Du)),c}function yn(e,t){var n=0,t=St(e.doc,t);e.options.lineWrapping||(n=Tn(e.display)*t.ch);var r=Us(e.doc,t.line),i=Js(r)+Kt(e.display);return{left:n,right:n,top:i,bottom:i+r.height}}function bn(e,t,n,r){var i=ht(e,t);return i.xRel=r,n&&(i.outside=!0),i}function wn(e,t,n){var r=e.doc;n+=e.display.viewOffset;if(n<0)return bn(r.first,0,!0,-1);var i=$s(r,n),s=r.first+r.size-1;if(i>s)return bn(r.first+r.size-1,Us(r,s).text.length,!0,1);t<0&&(t=0);var o=Us(r,i);for(;;){var u=En(e,o,i,t,n),a=Zi(o),f=a&&a.find(0,!0);if(!a||!(u.ch>f.from.ch||u.ch==f.from.ch&&u.xRel>0))return u;i=Vs(o=f.to.line)}}function En(e,t,n,r,i){function f(r){var i=gn(e,ht(n,r),"line",t,a);return o=!0,s>i.bottom?i.left-u:sm)return bn(n,p,g,1);for(;;){if(l?p==h||p==Bu(t,h,1):p-h<=1){var y=r1?1:0);return w}var E=Math.ceil(c/2),S=h+E;if(l){S=h;for(var x=0;xr){p=S,m=T;if(g=o)m+=1e3;c=E}else h=S,d=T,v=o,c-=E}}function xn(e){if(e.cachedTextHeight!=null)return e.cachedTextHeight;if(Sn==null){Sn=Go("pre");for(var t=0;t<49;++t)Sn.appendChild(document.createTextNode("x")),Sn.appendChild(Go("br"));Sn.appendChild(document.createTextNode("x"))}eu(e.measure,Sn);var n=Sn.offsetHeight/50;return n>3&&(e.cachedTextHeight=n),Zo(e.measure),n||1}function Tn(e){if(e.cachedCharWidth!=null)return e.cachedCharWidth;var t=Go("span","xxxxxxxxxx"),n=Go("pre",[t]);eu(e.measure,n);var r=t.getBoundingClientRect(),i=(r.right-r.left)/10;return i>2&&(e.cachedCharWidth=i),i||10}function kn(e){e.curOp={cm:e,viewChanged:!1,startHeight:e.doc.height,forceUpdate:!1,updateInput:null,typing:!1,changeObjs:null,cursorActivityHandlers:null,cursorActivityCalled:0,selectionChanged:!1,updateMaxLine:!1,scrollLeft:null,scrollTop:null,scrollToPos:null,id:++Cn},Nn?Nn.ops.push(e.curOp):e.curOp.ownsGroup=Nn={ops:[e.curOp],delayedCallbacks:[]}}function Ln(e){var t=e.delayedCallbacks,n=0;do{for(;n=n.viewTo)||n.maxLineChanged&&t.options.lineWrapping,e.update=e.mustUpdate&&new W(t,e.mustUpdate&&{top:e.scrollTop,ensure:e.scrollToPos},e.forceUpdate)}function _n(e){e.updatedDisplay=e.mustUpdate&&X(e.cm,e.update)}function Dn(e){var t=e.cm,n=t.display;e.updatedDisplay&&Q(t),e.barMeasure=j(t),n.maxLineChanged&&!t.options.lineWrapping&&(e.adjustWidthTo=tn(t,n.maxLine,n.maxLine.text.length).left+3,e.maxScrollLeft=Math.max(0,n.sizer.offsetLeft+e.adjustWidthTo+Lo-n.scroller.clientWidth));if(e.updatedDisplay||e.selectionChanged)e.newSelectionNodes=It(t)}function Pn(e){var t=e.cm;e.adjustWidthTo!=null&&(t.display.sizer.style.minWidth=e.adjustWidthTo+"px",e.maxScrollLeft1&&F(t),e.updatedDisplay&&V(t,e.update),n.wheelStartX!=null&&(e.scrollTop!=null||e.scrollLeft!=null||e.scrollToPos)&&(n.wheelStartX=n.wheelStartY=null);if(e.scrollTop!=null&&(n.scroller.scrollTop!=e.scrollTop||e.forceScroll)){var i=Math.max(0,Math.min(n.scroller.scrollHeight-n.scroller.clientHeight,e.scrollTop));n.scroller.scrollTop=n.scrollbarV.scrollTop=r.scrollTop=i}if(e.scrollLeft!=null&&(n.scroller.scrollLeft!=e.scrollLeft||e.forceScroll)){var o=Math.max(0,Math.min(n.scroller.scrollWidth-n.scroller.clientWidth,e.scrollLeft));n.scroller.scrollLeft=n.scrollbarH.scrollLeft=r.scrollLeft=o,q(t)}if(e.scrollToPos){var u=Yr(t,St(r,e.scrollToPos.from),St(r,e.scrollToPos.to),e.scrollToPos.margin);e.scrollToPos.isCursor&&t.state.focused&&Gr(t,u)}var a=e.maybeHiddenMarkers,f=e.maybeUnhiddenMarkers;if(a)for(var l=0;le.barMeasure.clientWidth&&e.barMeasure.scrollWidtht)&&(i.updateLineNumbers=t),e.curOp.viewChanged=!0;if(t>=i.viewTo)E&&rs(e.doc,t)i.viewFrom?Wn(e):(i.viewFrom+=r,i.viewTo+=r);else if(t<=i.viewFrom&&n>=i.viewTo)Wn(e);else if(t<=i.viewFrom){var s=Vn(e,n,n+r,1);s?(i.view=i.view.slice(s.index),i.viewFrom=s.lineN,i.viewTo+=r):Wn(e)}else if(n>=i.viewTo){var s=Vn(e,t,t,-1);s?(i.view=i.view.slice(0,s.index),i.viewTo=s.lineN):Wn(e)}else{var o=Vn(e,t,t,-1),u=Vn(e,n,n+r,1);o&&u?(i.view=i.view.slice(0,o.index).concat(Rn(e,o.lineN,u.lineN)).concat(i.view.slice(u.index)),i.viewTo+=r):Wn(e)}var a=i.externalMeasured;a&&(n=i.lineN&&t=r.viewTo)return;var s=r.view[Xn(e,t)];if(s.node==null)return;var o=s.changes||(s.changes=[]);qo(o,n)==-1&&o.push(n)}function Wn(e){e.display.viewFrom=e.display.viewTo=e.doc.first,e.display.view=[],e.display.viewOffset=0}function Xn(e,t){if(t>=e.display.viewTo)return null;t-=e.display.viewFrom;if(t<0)return null;var n=e.display.view;for(var r=0;r0){if(i==o.length-1)return null;s=a+o[i].size-t,i++}else s=a-t;t+=s,n+=s}while(rs(e.doc,n)!=n){if(i==(r<0?0:o.length-1))return null;n+=r*o[i-(r<0?1:0)].size,i+=r}return{index:i,lineN:n}}function $n(e,t,n){var r=e.display,i=r.view;i.length==0||t>=r.viewTo||n<=r.viewFrom?(r.view=Rn(e,t,n),r.viewFrom=t):(r.viewFrom>t?r.view=Rn(e,t,r.viewFrom).concat(r.view):r.viewFromn&&(r.view=r.view.slice(0,Xn(e,n)))),r.viewTo=n}function Jn(e){var t=e.display.view,n=0;for(var r=0;r=9&&e.display.inputHasSelection===o||v&&/[\uf700-\uf7ff]/.test(o))return Zn(e),!1;var u=!e.curOp;u&&kn(e),e.display.shift=!1,o.charCodeAt(0)==8203&&s.sel==e.display.selForContextMenu&&!n&&(n="​");var a=0,f=Math.min(n.length,o.length);while(a1&&(Gn&&Gn.join("\n")==l?h=s.sel.ranges.length%Gn.length==0&&Ro(Gn,yu):c.length==s.sel.ranges.length&&(h=Ro(c,function(e){return[e]})));for(var p=s.sel.ranges.length-1;p>=0;p--){var d=s.sel.ranges[p],m=d.from(),g=d.to();a-1){ii(e,E.line,"smart");break}}else w.electricInput&&w.electricInput.test(Us(s,E.line).text.slice(0,E.ch))&&ii(e,E.line,"smart")}}return ni(e),e.curOp.updateInput=y,e.curOp.typing=!0,o.length>1e3||o.indexOf("\n")>-1?t.value=e.display.prevInput="":e.display.prevInput=o,u&&An(e),e.state.pasteIncoming=e.state.cutIncoming=!1,!0}function Zn(e,t){var n,s,o=e.doc;if(e.somethingSelected()){e.display.prevInput="";var u=o.sel.primary();n=wu&&(u.to().line-u.from().line>100||(s=e.getSelection()).length>1e3);var a=n?"-":s||e.getSelection();e.display.input.value=a,e.state.focused&&Io(e.display.input),r&&i>=9&&(e.display.inputHasSelection=a)}else t||(e.display.prevInput=e.display.input.value="",r&&i>=9&&(e.display.inputHasSelection=null));e.display.inaccurateSelection=n}function er(e){e.options.readOnly!="nocursor"&&(!d||nu()!=e.display.input)&&e.display.input.focus()}function tr(e){e.state.focused||(er(e),Pr(e))}function nr(e){return e.options.readOnly||e.doc.cantEdit}function rr(e){function n(){e.state.focused&&setTimeout(Wo(er,e),0)}function o(t){To(e,t)||vo(t)}function u(n){if(e.somethingSelected())Gn=e.getSelections(),t.inaccurateSelection&&(t.prevInput="",t.inaccurateSelection=!1,t.input.value=Gn.join("\n"),Io(t.input));else{var r=[],i=[];for(var s=0;s=9&&e.display.inputHasSelection&&(e.display.inputHasSelection=null),Qn(e)}),yo(t.input,"keydown",jn(e,Or)),yo(t.input,"keypress",jn(e,Dr)),yo(t.input,"focus",Wo(Pr,e)),yo(t.input,"blur",Wo(Hr,e)),e.options.dragDrop&&(yo(t.scroller,"dragstart",function(t){gr(e,t)}),yo(t.scroller,"dragenter",o),yo(t.scroller,"dragover",o),yo(t.scroller,"drop",jn(e,mr))),yo(t.scroller,"paste",function(n){if(sr(t,n))return;e.state.pasteIncoming=!0,er(e),Qn(e)}),yo(t.input,"paste",function(){if(s&&!e.state.fakedLastChar&&!(new Date-e.state.lastMiddleDown<200)){var n=t.input.selectionStart,r=t.input.selectionEnd;t.input.value+="$",t.input.selectionEnd=r,t.input.selectionStart=n,e.state.fakedLastChar=!0}e.state.pasteIncoming=!0,Qn(e)}),yo(t.input,"cut",u),yo(t.input,"copy",u),l&&yo(t.sizer,"mouseup",function(){nu()==t.input&&t.input.blur(),er(e)})}function ir(e){var t=e.display;if(t.lastWrapHeight==t.wrapper.clientHeight&&t.lastWrapWidth==t.wrapper.clientWidth)return;t.cachedCharWidth=t.cachedTextHeight=t.cachedPaddingH=null,e.setSize()}function sr(e,t){for(var n=mo(t);n!=e.wrapper;n=n.parentNode)if(!n||n.ignoreEvents||n.parentNode==e.sizer&&n!=e.mover)return!0}function or(e,t,n,r){var i=e.display;if(!n){var s=mo(t);if(s==i.scrollbarH||s==i.scrollbarV||s==i.scrollbarFiller||s==i.gutterFiller)return null}var o,u,a=i.lineSpace.getBoundingClientRect();try{o=t.clientX-a.left,u=t.clientY-a.top}catch(t){return null}var f=wn(e,o,u),l;if(r&&f.xRel==1&&(l=Us(e.doc,f.line).text).length==f.ch){var c=Po(l,l.length,e.options.tabSize)-l.length;f=ht(f.line,Math.max(0,Math.round((o-Gt(e.display).left)/Tn(e.display))-c))}return f}function ur(e){if(To(this,e))return;var t=this,n=t.display;n.shift=e.shiftKey;if(sr(n,e)){s||(n.scroller.draggable=!1,setTimeout(function(){n.scroller.draggable=!0},100));return}if(dr(t,e))return;var r=or(t,e);window.focus();switch(go(e)){case 1:r?lr(t,e,r):mo(e)==n.scroller&&co(e);break;case 2:s&&(t.state.lastMiddleDown=+(new Date)),r&&kt(t.doc,r),setTimeout(Wo(er,t),20),co(e);break;case 3:b&&Br(t,e)}}function lr(e,t,n){setTimeout(Wo(tr,e),0);var r=+(new Date),i;fr&&fr.time>r-400&&pt(fr.pos,n)==0?i="triple":ar&&ar.time>r-400&&pt(ar.pos,n)==0?(i="double",fr={time:r,pos:n}):(i="single",ar={time:r,pos:n});var s=e.doc.sel,o=v?t.metaKey:t.ctrlKey;e.options.dragDrop&&cu&&!nr(e)&&i=="single"&&s.contains(n)>-1&&s.somethingSelected()?cr(e,t,n,o):hr(e,t,n,i,o)}function cr(e,t,n,o){var u=e.display,a=jn(e,function(f){s&&(u.scroller.draggable=!1),e.state.draggingText=!1,bo(document,"mouseup",a),bo(u.scroller,"drop",a),Math.abs(t.clientX-f.clientX)+Math.abs(t.clientY-f.clientY)<10&&(co(f),o||kt(e.doc,n),er(e),r&&i==9&&setTimeout(function(){document.body.focus(),er(e)},20))});s&&(u.scroller.draggable=!0),e.state.draggingText=a,u.scroller.dragDrop&&u.scroller.dragDrop(),yo(document,"mouseup",a),yo(u.scroller,"drop",a)}function hr(e,t,n,r,i){function p(t){if(pt(h,t)==0)return;h=t;if(r=="rect"){var i=[],s=e.options.tabSize,l=Po(Us(o,n.line).text,n.ch,s),c=Po(Us(o,t.line).text,t.ch,s),p=Math.min(l,c),d=Math.max(l,c);for(var v=Math.min(n.line,t.line),m=Math.min(e.lastLine(),Math.max(n.line,t.line));v<=m;v++){var g=Us(o,v).text,y=Ho(g,p,s);p==d?i.push(new yt(ht(v,y),ht(v,y))):g.length>y&&i.push(new yt(ht(v,y),ht(v,Ho(g,d,s))))}i.length||i.push(new yt(n,n)),Dt(o,bt(f.ranges.slice(0,a).concat(i),a),{origin:"*mouse",scroll:!1}),e.scrollIntoView(t)}else{var b=u,w=b.anchor,E=t;if(r!="single"){if(r=="double")var S=e.findWordAt(t);else var S=new yt(ht(t.line,0),St(o,ht(t.line+1,0)));pt(S.anchor,w)>0?(E=S.head,w=mt(b.from(),S.anchor)):(E=S.anchor,w=vt(b.to(),S.head))}var i=f.ranges.slice(0);i[a]=new yt(St(o,w),E),Dt(o,bt(i,a),Mo)}}function m(t){var n=++v,i=or(e,t,!0,r=="rect");if(!i)return;if(pt(i,h)!=0){tr(e),p(i);var u=I(s,o);(i.line>=u.to||i.lined.bottom?20:0;a&&setTimeout(jn(e,function(){if(v!=n)return;s.scroller.scrollTop+=a,m(t)}),50)}}function g(t){v=Infinity,co(t),er(e),bo(document,"mousemove",y),bo(document,"mouseup",b),o.history.lastSelOrigin=null}var s=e.display,o=e.doc;co(t);var u,a,f=o.sel;i&&!t.shiftKey?(a=o.sel.contains(n),a>-1?u=o.sel.ranges[a]:u=new yt(n,n)):u=o.sel.primary();if(t.altKey)r="rect",i||(u=new yt(n,n)),n=or(e,t,!0,!0),a=-1;else if(r=="double"){var l=e.findWordAt(n);e.display.shift||o.extend?u=Ct(o,u,l.anchor,l.head):u=l}else if(r=="triple"){var c=new yt(ht(n.line,0),St(o,ht(n.line+1,0)));e.display.shift||o.extend?u=Ct(o,u,c.anchor,c.head):u=c}else u=Ct(o,u,n);i?a>-1?At(o,a,u,Mo):(a=o.sel.ranges.length,Dt(o,bt(o.sel.ranges.concat([u]),a),{scroll:!1,origin:"*mouse"})):(a=0,Dt(o,new gt([u],0),Mo),f=o.sel);var h=n,d=s.wrapper.getBoundingClientRect(),v=0,y=jn(e,function(e){go(e)?m(e):g(e)}),b=jn(e,g);yo(document,"mousemove",y),yo(document,"mouseup",b)}function pr(e,t,n,r,i){try{var s=t.clientX,o=t.clientY}catch(t){return!1}if(s>=Math.floor(e.display.gutters.getBoundingClientRect().right))return!1;r&&co(t);var u=e.display,a=u.lineDiv.getBoundingClientRect();if(o>a.bottom||!Co(e,n))return po(t);o-=a.top-u.viewOffset;for(var f=0;f=s){var c=$s(e.doc,o),h=e.options.gutters[f];return i(e,n,e,c,h,t),po(t)}}}function dr(e,t){return pr(e,t,"gutterClick",!0,So)}function mr(e){var t=this;if(To(t,e)||sr(t.display,e))return;co(e),r&&(vr=+(new Date));var n=or(t,e,!0),i=e.dataTransfer.files;if(!n||nr(t))return;if(i&&i.length&&window.FileReader&&window.File){var s=i.length,o=Array(s),u=0,a=function(e,r){var i=new FileReader;i.onload=jn(t,function(){o[r]=i.result;if(++u==s){n=St(t.doc,n);var e={from:n,to:n,text:yu(o.join("\n")),origin:"paste"};Wr(t.doc,e),_t(t.doc,wt(n,Fr(e)))}}),i.readAsText(e)};for(var f=0;f-1){t.state.draggingText(e),setTimeout(Wo(er,t),20);return}try{var o=e.dataTransfer.getData("Text");if(o){if(t.state.draggingText&&(v?!e.metaKey:!e.ctrlKey))var l=t.listSelections();Pt(t.doc,wt(n,n));if(l)for(var f=0;fu.clientWidth||i&&u.scrollHeight>u.clientHeight))return;if(i&&v&&s)e:for(var f=n.target,l=o.view;f!=u;f=f.parentNode)for(var c=0;c=9&&(t.display.inputHasSelection=null),Qn(t)}function Pr(e){if(e.options.readOnly=="nocursor")return;e.state.focused||(wo(e,"focus",e),e.state.focused=!0,su(e.display.wrapper,"CodeMirror-focused"),!e.curOp&&e.display.selForContextMenu!=e.doc.sel&&(Zn(e),s&&setTimeout(Wo(Zn,e,!0),0))),Kn(e),Wt(e)}function Hr(e){e.state.focused&&(wo(e,"blur",e),e.state.focused=!1,iu(e.display.wrapper,"CodeMirror-focused")),clearInterval(e.display.blinker),setTimeout(function(){e.state.focused||(e.display.shift=!1)},150)}function Br(e,t){function h(){if(n.input.selectionStart!=null){var t=e.somethingSelected(),r=n.input.value="​"+(t?n.input.value:"");n.prevInput=t?"":"​",n.input.selectionStart=1,n.input.selectionEnd=r.length,n.selForContextMenu=e.doc.sel}}function p(){n.inputDiv.style.position="relative",n.input.style.cssText=l,r&&i<9&&(n.scrollbarV.scrollTop=n.scroller.scrollTop=u),Kn(e);if(n.input.selectionStart!=null){(!r||r&&i<9)&&h();var t=0,s=function(){n.selForContextMenu==e.doc.sel&&n.input.selectionStart==0?jn(e,wi.selectAll)(e):t++<10?n.detectingSelectAll=setTimeout(s,500):Zn(e)};n.detectingSelectAll=setTimeout(s,200)}}if(To(e,t,"contextmenu"))return;var n=e.display;if(sr(n,t)||jr(e,t))return;var o=or(e,t),u=n.scroller.scrollTop;if(!o||a)return;var f=e.options.resetSelectionOnContextMenu;f&&e.doc.sel.contains(o)==-1&&jn(e,Dt)(e.doc,wt(o),Oo);var l=n.input.style.cssText;n.inputDiv.style.position="absolute",n.input.style.cssText="position: fixed; width: 30px; height: 30px; top: "+(t.clientY-5)+"px; left: "+(t.clientX-5)+"px; z-index: 1000; background: "+(r?"rgba(255, 255, 255, .05)":"transparent")+"; outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);";if(s)var c=window.scrollY;er(e),s&&window.scrollTo(null,c),Zn(e),e.somethingSelected()||(n.input.value=n.prevInput=" "),n.selForContextMenu=e.doc.sel,clearTimeout(n.detectingSelectAll),r&&i>=9&&h();if(b){vo(t);var d=function(){bo(window,"mouseup",d),setTimeout(p,20)};yo(window,"mouseup",d)}else setTimeout(p,50)}function jr(e,t){return Co(e,"gutterContextMenu")?pr(e,t,"gutterContextMenu",!1,wo):!1}function Ir(e,t){if(pt(e,t.from)<0)return e;if(pt(e,t.to)<=0)return Fr(t);var n=e.line+t.text.length-(t.to.line-t.from.line)-1,r=e.ch;return e.line==t.to.line&&(r+=Fr(t).ch-t.to.ch),ht(n,r)}function qr(e,t){var n=[];for(var r=0;r=0;--i)Xr(e,{from:r[i].from,to:r[i].to,text:i?[""]:t.text});else Xr(e,t)}function Xr(e,t){if(t.text.length==1&&t.text[0]==""&&pt(t.from,t.to)==0)return;var n=qr(e,t);eo(e,t,n,e.cm?e.cm.curOp.id:NaN),Jr(e,t,n,Ui(e,t));var r=[];qs(e,function(e,n){!n&&qo(r,e.history)==-1&&(lo(e.history,t),r.push(e.history)),Jr(e,t,null,Ui(e,t))})}function Vr(e,t,n){if(e.cm&&e.cm.state.suppressEdits)return;var r=e.history,i,s=e.sel,o=t=="undo"?r.done:r.undone,u=t=="undo"?r.undone:r.done;for(var a=0;a=0;--a){var c=i.changes[a];c.origin=t;if(l&&!zr(e,c,!1)){o.length=0;return}f.push(Gs(e,c));var h=a?qr(e,c):Fo(o);Jr(e,c,h,Wi(e,c)),!a&&e.cm&&e.cm.scrollIntoView({from:c.from,to:Fr(c)});var p=[];qs(e,function(e,t){!t&&qo(p,e.history)==-1&&(lo(e.history,c),p.push(e.history)),Jr(e,c,null,Wi(e,c))})}}function $r(e,t){if(t==0)return;e.first+=t,e.sel=new gt(Ro(e.sel.ranges,function(e){return new yt(ht(e.anchor.line+t,e.anchor.ch),ht(e.head.line+t,e.head.ch))}),e.sel.primIndex);if(e.cm){Un(e.cm,e.first,e.first-t,t);for(var n=e.cm.display,r=n.viewFrom;re.lastLine())return;if(t.from.lines&&(t={from:t.from,to:ht(s,Us(e,s).text.length),text:[t.text[0]],origin:t.origin}),t.removed=zs(e,t.from,t.to),n||(n=qr(e,t)),e.cm?Kr(e.cm,t,r):Ds(e,t,r),Pt(e,n,Oo)}function Kr(e,t,n){var r=e.doc,i=e.display,s=t.from,o=t.to,u=!1,a=s.line;e.options.lineWrapping||(a=Vs(ts(Us(r,s.line))),r.iter(a,o.line+1,function(e){if(e==i.maxLine)return u=!0,!0})),r.sel.contains(t.from,t.to)>-1&&No(e),Ds(r,t,n,k(e)),e.options.lineWrapping||(r.iter(a,s.line+t.text.length,function(e){var t=D(e);t>i.maxLineLength&&(i.maxLine=e,i.maxLineLength=t,i.maxLineChanged=!0,u=!1)}),u&&(e.curOp.updateMaxLine=!0)),r.frontier=Math.min(r.frontier,s.line),Xt(e,400);var f=t.text.length-(o.line-s.line)-1;s.line==o.line&&t.text.length==1&&!_s(e.doc,t)?zn(e,s.line,"text"):Un(e,s.line,o.line+1,f);var l=Co(e,"changes"),c=Co(e,"change");if(c||l){var h={from:s,to:o,text:t.text,removed:t.removed,origin:t.origin};c&&So(e,"change",e,h),l&&(e.curOp.changeObjs||(e.curOp.changeObjs=[])).push(h)}e.display.selForContextMenu=null}function Qr(e,t,n,r,i){r||(r=n);if(pt(r,n)<0){var s=r;r=n,n=s}typeof t=="string"&&(t=yu(t)),Wr(e,{from:n,to:r,text:t,origin:i})}function Gr(e,t){if(To(e,"scrollCursorIntoView"))return;var n=e.display,r=n.sizer.getBoundingClientRect(),i=null;t.top+r.top<0?i=!0:t.bottom+r.top>(window.innerHeight||document.documentElement.clientHeight)&&(i=!1);if(i!=null&&!h){var s=Go("div","​",null,"position: absolute; top: "+(t.top-n.viewOffset-Kt(e.display))+"px; height: "+(t.bottom-t.top+Lo)+"px; left: "+t.left+"px; width: 2px;");e.display.lineSpace.appendChild(s),s.scrollIntoView(i),e.display.lineSpace.removeChild(s)}}function Yr(e,t,n,r){r==null&&(r=0);for(var i=0;i<5;i++){var s=!1,o=gn(e,t),u=!n||n==t?o:gn(e,n),a=ei(e,Math.min(o.left,u.left),Math.min(o.top,u.top)-r,Math.max(o.left,u.left),Math.max(o.bottom,u.bottom)+r),f=e.doc.scrollTop,l=e.doc.scrollLeft;a.scrollTop!=null&&(yr(e,a.scrollTop),Math.abs(e.doc.scrollTop-f)>1&&(s=!0)),a.scrollLeft!=null&&(br(e,a.scrollLeft),Math.abs(e.doc.scrollLeft-l)>1&&(s=!0));if(!s)return o}}function Zr(e,t,n,r,i){var s=ei(e,t,n,r,i);s.scrollTop!=null&&yr(e,s.scrollTop),s.scrollLeft!=null&&br(e,s.scrollLeft)}function ei(e,t,n,r,i){var s=e.display,o=xn(e.display);n<0&&(n=0);var u=e.curOp&&e.curOp.scrollTop!=null?e.curOp.scrollTop:s.scroller.scrollTop,a=s.scroller.clientHeight-Lo,f={};i-n>a&&(i=n+a);var l=e.doc.height+Qt(s),c=nl-o;if(nu+a){var p=Math.min(n,(h?l:i)-a);p!=u&&(f.scrollTop=p)}var d=e.curOp&&e.curOp.scrollLeft!=null?e.curOp.scrollLeft:s.scroller.scrollLeft,v=s.scroller.clientWidth-Lo-s.gutters.offsetWidth,m=r-t>v;return m&&(r=t+v),t<10?f.scrollLeft=0:tv+d-3&&(f.scrollLeft=r+(m?0:10)-v),f}function ti(e,t,n){(t!=null||n!=null)&&ri(e),t!=null&&(e.curOp.scrollLeft=(e.curOp.scrollLeft==null?e.doc.scrollLeft:e.curOp.scrollLeft)+t),n!=null&&(e.curOp.scrollTop=(e.curOp.scrollTop==null?e.doc.scrollTop:e.curOp.scrollTop)+n)}function ni(e){ri(e);var t=e.getCursor(),n=t,r=t;e.options.lineWrapping||(n=t.ch?ht(t.line,t.ch-1):t,r=ht(t.line,t.ch+1)),e.curOp.scrollToPos={from:n,to:r,margin:e.options.cursorScrollMargin,isCursor:!0}}function ri(e){var t=e.curOp.scrollToPos;if(t){e.curOp.scrollToPos=null;var n=yn(e,t.from),r=yn(e,t.to),i=ei(e,Math.min(n.left,r.left),Math.min(n.top,r.top)-t.margin,Math.max(n.right,r.right),Math.max(n.bottom,r.bottom)+t.margin);e.scrollTo(i.scrollLeft,i.scrollTop)}}function ii(e,t,n,r){var i=e.doc,s;n==null&&(n="add"),n=="smart"&&(i.mode.indent?s=Jt(e,t):n="prev");var o=e.options.tabSize,u=Us(i,t),a=Po(u.text,null,o);u.stateAfter&&(u.stateAfter=null);var f=u.text.match(/^\s*/)[0],l;if(!r&&!/\S/.test(u.text))l=0,n="not";else if(n=="smart"){l=i.mode.indent(s,u.text.slice(f.length),u.text);if(l==Ao||l>150){if(!r)return;n="prev"}}n=="prev"?t>i.first?l=Po(Us(i,t-1).text,null,o):l=0:n=="add"?l=a+e.options.indentUnit:n=="subtract"?l=a-e.options.indentUnit:typeof n=="number"&&(l=a+n),l=Math.max(0,l);var c="",h=0;if(e.options.indentWithTabs)for(var p=Math.floor(l/o);p;--p)h+=o,c+=" ";h=0;t--)Qr(e.doc,"",r[t].from,r[t].to,"+delete");ni(e)})}function ui(e,t,n,r,i){function l(){var t=s+n;return t=e.first+e.size?f=!1:(s=t,a=Us(e,t))}function c(e){var t=(i?Bu:ju)(a,o,n,!0);if(t==null){if(!!e||!l())return f=!1;i?o=(n<0?Lu:ku)(a):o=n<0?a.text.length:0}else o=t;return!0}var s=t.line,o=t.ch,u=n,a=Us(e,s),f=!0;if(r=="char")c();else if(r=="column")c(!0);else if(r=="word"||r=="group"){var h=null,p=r=="group",d=e.cm&&e.cm.getHelper(t,"wordChars");for(var v=!0;;v=!1){if(n<0&&!c(!v))break;var m=a.text.charAt(o)||"\n",g=$o(m,d)?"w":p&&m=="\n"?"n":!p||/\s/.test(m)?null:"p";p&&!v&&!g&&(g="s");if(h&&h!=g){n<0&&(n=1,c());break}g&&(h=g);if(n>0&&!c(!v))break}}var y=Ft(e,ht(s,o),u,!0);return f||(y.hitSide=!0),y}function ai(e,t,n,r){var i=e.doc,s=t.left,o;if(r=="page"){var u=Math.min(e.display.wrapper.clientHeight,window.innerHeight||document.documentElement.clientHeight);o=t.top+n*(u-(n<0?1.5:.5)*xn(e.display))}else r=="line"&&(o=n>0?t.bottom+3:t.top-3);for(;;){var a=wn(e,s,o);if(!a.outside)break;if(n<0?o<=0:o>=i.height){a.hitSide=!0;break}o+=n*5}return a}function ci(e,t,n,r){S.defaults[e]=t,n&&(li[e]=r?function(e,t,r){r!=hi&&n(e,t,r)}:n)}function Si(e){var t=e.split(/-(?!$)/),e=t[t.length-1],n,r,i,s;for(var o=0;o0||o==0&&s.clearWhenEmpty!==!1)return s;s.replacedWith&&(s.collapsed=!0,s.widgetNode=Go("span",[s.replacedWith],"CodeMirror-widget"),r.handleMouseEvents||(s.widgetNode.ignoreEvents=!0),r.insertLeft&&(s.widgetNode.insertLeft=!0));if(s.collapsed){if(es(e,t.line,t,n,s)||t.line!=n.line&&es(e,n.line,t,n,s))throw new Error("Inserting collapsed marker partially overlapping an existing one");E=!0}s.addToHistory&&eo(e,{from:t,to:n,origin:"markText"},e.sel,NaN);var u=t.line,a=e.cm,f;e.iter(u,n.line+1,function(e){a&&s.collapsed&&!a.options.lineWrapping&&ts(e)==a.display.maxLine&&(f=!0),s.collapsed&&u!=t.line&&Xs(e,0),Ii(e,new Bi(s,u==t.line?t.ch:null,u==n.line?n.ch:null)),++u}),s.collapsed&&e.iter(t.line,n.line+1,function(t){ss(e,t)&&Xs(t,0)}),s.clearOnEnter&&yo(s,"beforeCursorEnter",function(){s.clear()}),s.readOnly&&(w=!0,(e.history.done.length||e.history.undone.length)&&e.clearHistory()),s.collapsed&&(s.id=++Ai,s.atomic=!0);if(a){f&&(a.curOp.updateMaxLine=!0);if(s.collapsed)Un(a,t.line,n.line+1);else if(s.className||s.title||s.startStyle||s.endStyle)for(var l=t.line;l<=n.line;l++)zn(a,l,"text");s.atomic&&Bt(a.doc),So(a,"markerAdded",a,s)}return s}function _i(e,t,n,r,i){r=zo(r),r.shared=!1;var s=[Oi(e,t,n,r,i)],o=s[0],u=r.widgetNode;return qs(e,function(e){u&&(r.widgetNode=u.cloneNode(!0)),s.push(Oi(e,St(e,t),St(e,n),r,i));for(var a=0;a=t:s.to>t);(i||(i=[])).push(new Bi(o,s.from,a?null:s.to))}}return i}function Ri(e,t,n){if(e)for(var r=0,i;r=t:s.to>t);if(u||s.from==t&&o.type=="bookmark"&&(!n||s.marker.insertLeft)){var a=s.from==null||(o.inclusiveLeft?s.from<=t:s.from0&&u)for(var c=0;c0)continue;var l=[a,1],c=pt(f.from,u.from),h=pt(f.to,u.to);(c<0||!o.inclusiveLeft&&!c)&&l.push({from:f.from,to:u.from}),(h>0||!o.inclusiveRight&&!h)&&l.push({from:u.to,to:f.to}),i.splice.apply(i,l),a+=l.length-1}}return i}function Vi(e){var t=e.markedSpans;if(!t)return;for(var n=0;n=0&&c<=0||l<=0&&c>=0)continue;if(l<=0&&(pt(f.to,n)>0||a.marker.inclusiveRight&&i.inclusiveLeft)||l>=0&&(pt(f.from,r)<0||a.marker.inclusiveLeft&&i.inclusiveRight))return!0}}function ts(e){var t;while(t=Yi(e))e=t.find(-1,!0).line;return e}function ns(e){var t,n;while(t=Zi(e))e=t.find(1,!0).line,(n||(n=[])).push(e);return n}function rs(e,t){var n=Us(e,t),r=ts(n);return n==r?t:Vs(r)}function is(e,t){if(t>e.lastLine())return t;var n=Us(e,t),r;if(!ss(e,n))return t;while(r=Zi(n))n=r.find(1,!0).line;return Vs(n)+1}function ss(e,t){var n=E&&t.markedSpans;if(n)for(var r,i=0;it.start)return s}throw new Error("Mode "+e.name+" failed to advance stream.")}function gs(e,t,n,r){function i(e){return{start:l.start,end:l.pos,string:l.current(),type:u||null,state:e?yi(s.mode,f):f}}var s=e.doc,o=s.mode,u;t=St(s,t);var a=Us(s,t.line),f=Jt(e,t.line,n),l=new ki(a.text,e.options.tabSize),c;r&&(c=[]);while((r||l.pose.options.maxHighlightLength?(u=!1,o&&Es(e,t,r,l.pos),l.pos=t.length,c=null):c=ds(ms(n,l,r,h),s);if(h){var p=h[0].name;p&&(c="m-"+(c?p+" "+c:p))}if(!u||f!=c)ae&&i.splice(a,1,e,i[a+1],r),a+=2,f=Math.min(e,r)}if(!t)return;if(u.opaque)i.splice(n,a-n,e,"cm-overlay "+t),a=n+2;else for(;na&&c.from<=a)break}if(c.to>=f)return e(n,r,i,s,o,u);e(n,r.slice(0,c.to-a),i,s,null,u),s=null,r=r.slice(c.to-a),a=c.to}}}function Os(e,t,n,r){var i=!r&&n.widgetNode;i&&(e.map.push(e.pos,e.pos+t,i),e.content.appendChild(i)),e.pos+=t}function Ms(e,t,n){var r=e.markedSpans,i=e.text,s=0;if(!r){for(var o=1;oa)?(b.to!=null&&c>b.to&&(c=b.to,p=""),w.className&&(h+=" "+w.className),w.startStyle&&b.from==a&&(d+=" "+w.startStyle),w.endStyle&&b.to==c&&(p+=" "+w.endStyle),w.title&&!v&&(v=w.title),w.collapsed&&(!m||Qi(m.marker,w)<0)&&(m=b)):b.from>a&&c>b.from&&(c=b.from),w.type=="bookmark"&&b.from==a&&w.widgetNode&&g.push(w)}if(m&&(m.from||0)==a){Os(t,(m.to==null?u+1:m.to)-a,m.marker,m.from==null);if(m.to==null)return}if(!m&&g.length)for(var y=0;y=u)break;var E=Math.min(u,c);for(;;){if(f){var S=a+f.length;if(!m){var x=S>E?f.slice(0,E-a):f;t.addToken(t,x,l?l+h:h,d,a+x.length==c?p:"",v)}if(S>=E){f=f.slice(E-a),a=E;break}a=S,d=""}f=i.slice(s,s=n[o++]),l=Ts(n[o++],t.cm.options)}}}function _s(e,t){return t.from.ch==0&&t.to.ch==0&&Fo(t.text)==""&&(!e.cm||e.cm.options.wholeLineUpdateBefore)}function Ds(e,t,n,r){function i(e){return n?n[e]:null}function s(e,n,i){hs(e,n,i,r),So(e,"change",e,t)}var o=t.from,u=t.to,a=t.text,f=Us(e,o.line),l=Us(e,u.line),c=Fo(a),h=i(a.length-1),p=u.line-o.line;if(_s(e,t)){for(var d=0,v=[];d1&&e.remove(o.line+1,p-1),e.insert(o.line+1,v)}So(e,"change",e,t)}function Ps(e){this.lines=e,this.parent=null;for(var t=0,n=0;t=e.size)throw new Error("There is no line "+(t+e.first)+" in the document.");for(var n=e;!n.lines;)for(var r=0;;++r){var i=n.children[r],s=i.chunkSize();if(t1&&!e.done[e.done.length-2].ranges)return e.done.pop(),Fo(e.done)}function eo(e,t,n,r){var i=e.history;i.undone.length=0;var s=+(new Date),o;if((i.lastOp==r||i.lastOrigin==t.origin&&t.origin&&(t.origin.charAt(0)=="+"&&e.cm&&i.lastModTime>s-e.cm.options.historyEventDelay||t.origin.charAt(0)=="*"))&&(o=Zs(i,i.lastOp==r))){var u=Fo(o.changes);pt(t.from,t.to)==0&&pt(t.from,u.to)==0?u.to=Fr(t):o.changes.push(Gs(e,t))}else{var a=Fo(i.done);(!a||!a.ranges)&&ro(e.sel,i.done),o={changes:[Gs(e,t)],generation:i.generation},i.done.push(o);while(i.done.length>i.undoDepth)i.done.shift(),i.done[0].ranges||i.done.shift()}i.done.push(n),i.generation=++i.maxGeneration,i.lastModTime=i.lastSelTime=s,i.lastOp=i.lastSelOp=r,i.lastOrigin=i.lastSelOrigin=t.origin,u||wo(e,"historyAdded")}function to(e,t,n,r){var i=t.charAt(0);return i=="*"||i=="+"&&n.ranges.length==r.ranges.length&&n.somethingSelected()==r.somethingSelected()&&new Date-e.history.lastSelTime<=(e.cm?e.cm.options.historyEventDelay:500)}function no(e,t,n,r){var i=e.history,s=r&&r.origin;n==i.lastSelOp||s&&i.lastSelOrigin==s&&(i.lastModTime==i.lastSelTime&&i.lastOrigin==s||to(e,s,Fo(i.done),t))?i.done[i.done.length-1]=t:ro(t,i.done),i.lastSelTime=+(new Date),i.lastSelOrigin=s,i.lastSelOp=n,r&&r.clearRedo!==!1&&Ys(i.undone)}function ro(e,t){var n=Fo(t);n&&n.ranges&&n.equals(e)||t.push(e)}function io(e,t,n,r){var i=t["spans_"+e.id],s=0;e.iter(Math.max(e.first,n),Math.min(e.first+e.size,r),function(n){n.markedSpans&&((i||(i=t["spans_"+e.id]={}))[s]=n.markedSpans),++s})}function so(e){if(!e)return null;for(var t=0,n;t-1&&(Fo(u)[c]=f[c],delete f[c])}}return i}function ao(e,t,n,r){n0}function ko(e){e.prototype.on=function(e,t){yo(this,e,t)},e.prototype.off=function(e,t){bo(this,e,t)}}function Do(){this.id=null}function Ho(e,t,n){for(var r=0,i=0;;){var s=e.indexOf(" ",r);s==-1&&(s=e.length);var o=s-r;if(s==e.length||i+o>=t)return r+Math.min(o,t-i);i+=s-r,i+=n-i%n,r=s+1;if(i>=t)return r}}function jo(e){while(Bo.length<=e)Bo.push(Fo(Bo)+" ");return Bo[e]}function Fo(e){return e[e.length-1]}function qo(e,t){for(var n=0;n-1&&Vo(e)?!0:t.test(e):Vo(e)}function Jo(e){for(var t in e)if(e.hasOwnProperty(t)&&e[t])return!1;return!0}function Qo(e){return e.charCodeAt(0)>=768&&Ko.test(e)}function Go(e,t,n,r){var i=document.createElement(e);n&&(i.className=n),r&&(i.style.cssText=r);if(typeof t=="string")i.appendChild(document.createTextNode(t));else if(t)for(var s=0;s0;--t)e.removeChild(e.firstChild);return e}function eu(e,t){return Zo(e).appendChild(t)}function tu(e,t){if(e.contains)return e.contains(t);while(t=t.parentNode)if(t==e)return!0}function nu(){return document.activeElement}function ru(e){return new RegExp("(^|\\s)"+e+"(?:$|\\s)\\s*")}function ou(e,t){var n=e.split(" ");for(var r=0;r2&&!(r&&i<8))}return du?Go("span","​"):Go("span"," ",null,"display: inline-block; width: 1px; margin-right: -1px")}function gu(e){if(mu!=null)return mu;var t=eu(e,document.createTextNode("AخA")),n=Yo(t,0,1).getBoundingClientRect();if(!n||n.left==n.right)return!1;var r=Yo(t,1,2).getBoundingClientRect();return mu=r.right-n.right<3}function Su(e){if(Eu!=null)return Eu;var t=eu(e,Go("span","x")),n=t.getBoundingClientRect(),r=Yo(t,0,1).getBoundingClientRect();return Eu=Math.abs(n.left-r.left)>1}function Tu(e,t,n,r){if(!e)return r(t,n,"ltr");var i=!1;for(var s=0;st||t==n&&o.to==t)r(Math.max(o.from,t),Math.min(o.to,n),o.level==1?"rtl":"ltr"),i=!0}i||r(t,n,"ltr")}function Nu(e){return e.level%2?e.to:e.from}function Cu(e){return e.level%2?e.from:e.to}function ku(e){var t=Ks(e);return t?Nu(t[0]):0}function Lu(e){var t=Ks(e);return t?Cu(Fo(t)):e.text.length}function Au(e,t){var n=Us(e.doc,t),r=ts(n);r!=n&&(t=Vs(r));var i=Ks(r),s=i?i[0].level%2?Lu(r):ku(r):0;return ht(t,s)}function Ou(e,t){var n,r=Us(e.doc,t);while(n=Zi(r))r=n.find(1,!0).line,t=null;var i=Ks(r),s=i?i[0].level%2?ku(r):Lu(r):r.text.length;return ht(t==null?Vs(r):t,s)}function Mu(e,t){var n=Au(e,t.line),r=Us(e.doc,n.line),i=Ks(r);if(!i||i[0].level==0){var s=Math.max(0,r.text.search(/\S/)),o=t.line==n.line&&t.ch<=s&&t.ch;return ht(n.line,o?0:s)}return n}function _u(e,t,n){var r=e[0].level;return t==r?!0:n==r?!1:tt)return n;if(i.from==t||i.to==t){if(r!=null)return _u(e,i.level,e[r].level)?(i.from!=i.to&&(Du=r),n):(i.from!=i.to&&(Du=n),r);r=n}}return r}function Hu(e,t,n,r){if(!r)return t+n;do t+=n;while(t>0&&Qo(e.text.charAt(t)));return t}function Bu(e,t,n,r){var i=Ks(e);if(!i)return ju(e,t,n,r);var s=Pu(i,t),o=i[s],u=Hu(e,t,o.level%2?-n:n,r);for(;;){if(u>o.from&&u0==o.level%2?o.to:o.from);o=i[s+=n];if(!o)return null;n>0==o.level%2?u=Hu(e,o.to,-1,r):u=Hu(e,o.from,1,r)}}function ju(e,t,n,r){var i=t+n;if(r)while(i>0&&Qo(e.text.charAt(i)))i+=n;return i<0||i>e.text.length?null:i}var e=/gecko\/\d/i.test(navigator.userAgent),t=/MSIE \d/.test(navigator.userAgent),n=/Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent),r=t||n,i=r&&(t?document.documentMode||6:n[1]),s=/WebKit\//.test(navigator.userAgent),o=s&&/Qt\/\d+\.\d+/.test(navigator.userAgent),u=/Chrome\//.test(navigator.userAgent),a=/Opera\//.test(navigator.userAgent),f=/Apple Computer/.test(navigator.vendor),l=/KHTML\//.test(navigator.userAgent),c=/Mac OS X 1\d\D([8-9]|\d\d)\D/.test(navigator.userAgent),h=/PhantomJS/.test(navigator.userAgent),p=/AppleWebKit/.test(navigator.userAgent)&&/Mobile\/\w+/.test(navigator.userAgent),d=p||/Android|webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(navigator.userAgent),v=p||/Mac/.test(navigator.platform),m=/win/i.test(navigator.platform),g=a&&navigator.userAgent.match(/Version\/(\d*\.\d*)/);g&&(g=Number(g[1])),g&&g>=15&&(a=!1,s=!0);var y=v&&(o||a&&(g==null||g<12.11)),b=e||r&&i>=9,w=!1,E=!1,ht=S.Pos=function(e,t){if(!(this instanceof ht))return new ht(e,t);this.line=e,this.ch=t},pt=S.cmpPos=function(e,t){return e.line-t.line||e.ch-t.ch};gt.prototype={primary:function(){return this.ranges[this.primIndex]},equals:function(e){if(e==this)return!0;if(e.primIndex!=this.primIndex||e.ranges.length!=this.ranges.length)return!1;for(var t=0;t=0&&pt(e,r.to())<=0)return n}return-1}},yt.prototype={from:function(){return mt(this.anchor,this.head)},to:function(){return vt(this.anchor,this.head)},empty:function(){return this.head.line==this.anchor.line&&this.head.ch==this.anchor.ch}};var on={left:0,right:0,top:0,bottom:0},Sn,Nn=null,Cn=0,Gn=null,ar,fr,vr=0,wr=0,Er=null;r?Er=-0.53:e?Er=15:u?Er=-0.7:f&&(Er=-1/3);var Nr=new Do,Ar=null,Fr=S.changeEnd=function(e){return e.text?ht(e.from.line+e.text.length-1,Fo(e.text).length+(e.text.length==1?e.from.ch:0)):e.to};S.prototype={constructor:S,focus:function(){window.focus(),er(this),Qn(this)},setOption:function(e,t){var n=this.options,r=n[e];if(n[e]==t&&e!="mode")return;n[e]=t,li.hasOwnProperty(e)&&jn(this,li[e])(this,t,r)},getOption:function(e){return this.options[e]},getDoc:function(){return this.doc},addKeyMap:function(e,t){this.state.keyMaps[t?"push":"unshift"](Ci(e))},removeKeyMap:function(e){var t=this.state.keyMaps;for(var n=0;n0&&At(this.doc,r,new yt(s,f[r].to()),Oo)}else i.head.line>n&&(ii(this,i.head.line,e,!0),n=i.head.line,r==this.doc.sel.primIndex&&ni(this))}}),getTokenAt:function(e,t){return gs(this,e,t)},getLineTokens:function(e,t){return gs(this,ht(e),t,!0)},getTokenTypeAt:function(e){e=St(this.doc,e);var t=ws(this,Us(this.doc,e.line)),n=0,r=(t.length-1)/2,i=e.ch,s;if(i==0)s=t[2];else for(;;){var o=n+r>>1;if((o?t[o*2-1]:0)>=i)r=o;else{if(!(t[o*2+1]r&&(e=r,n=!0);var i=Us(this.doc,e);return dn(this,i,{top:0,left:0},t||"page").top+(n?this.doc.height-Js(i):0)},defaultTextHeight:function(){return xn(this.display)},defaultCharWidth:function(){return Tn(this.display)},setGutterMarker:Fn(function(e,t,n){return si(this.doc,e,"gutter",function(e){var r=e.gutterMarkers||(e.gutterMarkers={});return r[t]=n,!n&&Jo(r)&&(e.gutterMarkers=null),!0})}),clearGutter:Fn(function(e){var t=this,n=t.doc,r=n.first;n.iter(function(n){n.gutterMarkers&&n.gutterMarkers[e]&&(n.gutterMarkers[e]=null,zn(t,r,"gutter"),Jo(n.gutterMarkers)&&(n.gutterMarkers=null)),++r})}),addLineWidget:Fn(function(e,t,n){return ls(this,e,t,n)}),removeLineWidget:function(e){e.clear()},lineInfo:function(e){if(typeof e=="number"){if(!Tt(this.doc,e))return null;var t=e;e=Us(this.doc,e);if(!e)return null}else{var t=Vs(e);if(t==null)return null}return{line:t,handle:e,text:e.text,gutterMarkers:e.gutterMarkers,textClass:e.textClass,bgClass:e.bgClass,wrapClass:e.wrapClass,widgets:e.widgets}},getViewport:function(){return{from:this.display.viewFrom,to:this.display.viewTo}},addWidget:function(e,t,n,r,i){var s=this.display;e=gn(this,St(this.doc,e));var o=e.bottom,u=e.left;t.style.position="absolute",s.sizer.appendChild(t);if(r=="over")o=e.top;else if(r=="above"||r=="near"){var a=Math.max(s.wrapper.clientHeight,this.doc.height),f=Math.max(s.sizer.clientWidth,s.lineSpace.clientWidth);(r=="above"||e.bottom+t.offsetHeight>a)&&e.top>t.offsetHeight?o=e.top-t.offsetHeight:e.bottom+t.offsetHeight<=a&&(o=e.bottom),u+t.offsetWidth>f&&(u=f-t.offsetWidth)}t.style.top=o+"px",t.style.left=t.style.right="",i=="right"?(u=s.sizer.clientWidth-t.offsetWidth,t.style.right="0px"):(i=="left"?u=0:i=="middle"&&(u=(s.sizer.clientWidth-t.offsetWidth)/2),t.style.left=u+"px"),n&&Zr(this,u,o,u+t.offsetWidth,o+t.offsetHeight)},triggerOnKeyDown:Fn(Or),triggerOnKeyPress:Fn(Dr),triggerOnKeyUp:_r,execCommand:function(e){if(wi.hasOwnProperty(e))return wi[e](this)},findPosH:function(e,t,n,r){var i=1;t<0&&(i=-1,t=-t);for(var s=0,o=St(this.doc,e);s0&&u(n.charAt(r-1)))--r;while(i.5)&&L(this),wo(this,"refresh",this)}),swapDoc:Fn(function(e){var t=this.doc;return t.cm=null,Rs(this,e),cn(this),Zn(this),this.scrollTo(e.scrollLeft,e.scrollTop),this.curOp.forceScroll=!0,So(this,"swapDoc",this,t),t}),getInputField:function(){return this.display.input},getWrapperElement:function(){return this.display.wrapper},getScrollerElement:function(){return this.display.scroller},getGutterElement:function(){return this.display.gutters}},ko(S);var fi=S.defaults={},li=S.optionHandlers={},hi=S.Init={toString:function(){return"CodeMirror.Init"}};ci("value","",function(e,t){e.setValue(t)},!0),ci("mode",null,function(e,t){e.doc.modeOption=t,T(e)},!0),ci("indentUnit",2,T,!0),ci("indentWithTabs",!1),ci("smartIndent",!0),ci("tabSize",4,function(e){N(e),cn(e),Un(e)},!0),ci("specialChars",/[\t\u0000-\u0019\u00ad\u200b-\u200f\u2028\u2029\ufeff]/g,function(e,t){e.options.specialChars=new RegExp(t.source+(t.test(" ")?"":"| "),"g"),e.refresh()},!0),ci("specialCharPlaceholder",Cs,function(e){e.refresh()},!0),ci("electricChars",!0),ci("rtlMoveVisually",!m),ci("wholeLineUpdateBefore",!0),ci("theme","default",function(e){A(e),O(e)},!0),ci("keyMap","default",function(e,t,n){var r=Ci(t),i=n!=S.Init&&Ci(n);i&&i.detach&&i.detach(e,r),r.attach&&r.attach(e,i||null)}),ci("extraKeys",null),ci("lineWrapping",!1,C,!0),ci("gutters",[],function(e){H(e.options),O(e)},!0),ci("fixedGutter",!0,function(e,t){e.display.gutters.style.left=t?z(e.display)+"px":"0",e.refresh()},!0),ci("coverGutterNextToScrollbar",!1,F,!0),ci("lineNumbers",!1,function(e){H(e.options),O(e)},!0),ci("firstLineNumber",1,O,!0),ci("lineNumberFormatter",function(e){return e},O,!0),ci("showCursorWhenSelecting",!1,Rt,!0),ci("resetSelectionOnContextMenu",!0),ci("readOnly",!1,function(e,t){t=="nocursor"?(Hr(e),e.display.input.blur(),e.display.disabled=!0):(e.display.disabled=!1,t||Zn(e))}),ci("disableInput",!1,function(e,t){t||Zn(e)},!0),ci("dragDrop",!0),ci("cursorBlinkRate",530),ci("cursorScrollMargin",0),ci("cursorHeight",1,Rt,!0),ci("singleCursorHeightPerLine",!0,Rt,!0),ci("workTime",100),ci("workDelay",100),ci("flattenSpans",!0,N,!0),ci("addModeClass",!1,N,!0),ci("pollInterval",100),ci("undoDepth",200,function(e,t){e.doc.history.undoDepth=t}),ci("historyEventDelay",1250),ci("viewportMargin",10,function(e){e.refresh()},!0),ci("maxHighlightLength",1e4,N,!0),ci("moveInputWithCursor",!0,function(e,t){t||(e.display.inputDiv.style.top=e.display.inputDiv.style.left=0)}),ci("tabindex",null,function(e,t){e.display.input.tabIndex=t||""}),ci("autofocus",null);var pi=S.modes={},di=S.mimeModes={};S.defineMode=function(e,t){!S.defaults.mode&&e!="null"&&(S.defaults.mode=e),arguments.length>2&&(t.dependencies=Array.prototype.slice.call(arguments,2)),pi[e]=t},S.defineMIME=function(e,t){di[e]=t},S.resolveMode=function(e){if(typeof e=="string"&&di.hasOwnProperty(e))e=di[e];else if(e&&typeof e.name=="string"&&di.hasOwnProperty(e.name)){var t=di[e.name];typeof t=="string"&&(t={name:t}),e=Uo(t,e),e.name=t.name}else if(typeof e=="string"&&/^[\w\-]+\/[\w\-]+\+xml$/.test(e))return S.resolveMode("application/xml");return typeof e=="string"?{name:e}:e||{name:"null"}},S.getMode=function(e,t){var t=S.resolveMode(t),n=pi[t.name];if(!n)return S.getMode(e,"text/plain");var r=n(e,t);if(vi.hasOwnProperty(t.name)){var i=vi[t.name];for(var s in i){if(!i.hasOwnProperty(s))continue;r.hasOwnProperty(s)&&(r["_"+s]=r[s]),r[s]=i[s]}}r.name=t.name,t.helperType&&(r.helperType=t.helperType);if(t.modeProps)for(var s in t.modeProps)r[s]=t.modeProps[s];return r},S.defineMode("null",function(){return{token:function(e){e.skipToEnd()}}}),S.defineMIME("text/plain","null");var vi=S.modeExtensions={};S.extendMode=function(e,t){var n=vi.hasOwnProperty(e)?vi[e]:vi[e]={};zo(t,n)},S.defineExtension=function(e,t){S.prototype[e]=t},S.defineDocExtension=function(e,t){js.prototype[e]=t},S.defineOption=ci;var mi=[];S.defineInitHook=function(e){mi.push(e)};var gi=S.helpers={};S.registerHelper=function(e,t,n){gi.hasOwnProperty(e)||(gi[e]=S[e]={_global:[]}),gi[e][t]=n},S.registerGlobalHelper=function(e,t,n,r){S.registerHelper(e,t,r),gi[e]._global.push({pred:n,val:r})};var yi=S.copyState=function(e,t){if(t===!0)return t;if(e.copyState)return e.copyState(t);var n={};for(var r in t){var i=t[r];i instanceof Array&&(i=i.concat([])),n[r]=i}return n},bi=S.startState=function(e,t,n){return e.startState?e.startState(t,n):!0};S.innerMode=function(e,t){while(e.innerMode){var n=e.innerMode(t);if(!n||n.mode==e)break;t=n.state,e=n.mode}return n||{mode:e,state:t}};var wi=S.commands={selectAll:function(e){e.setSelection(ht(e.firstLine(),0),ht(e.lastLine()),Oo)},singleSelection:function(e){e.setSelection(e.getCursor("anchor"),e.getCursor("head"),Oo)},killLine:function(e){oi(e,function(t){if(t.empty()){var n=Us(e.doc,t.head.line).text.length;return t.head.ch==n&&t.head.line0)i=new ht(i.line,i.ch+1),e.replaceRange(s.charAt(i.ch-1)+s.charAt(i.ch-2),ht(i.line,i.ch-2),i,"+transpose");else if(i.line>e.doc.first){var o=Us(e.doc,i.line-1).text;o&&e.replaceRange(s.charAt(0)+"\n"+o.charAt(o.length-1),ht(i.line-1,o.length-1),ht(i.line,1),"+transpose")}}n.push(new yt(i,i))}e.setSelections(n)})},newlineAndIndent:function(e){Bn(e,function(){var t=e.listSelections().length;for(var n=0;n=this.string.length},sol:function(){return this.pos==this.lineStart},peek:function(){return this.string.charAt(this.pos)||undefined},next:function(){if(this.post},eatSpace:function(){var e=this.pos;while(/[\s\u00a0]/.test(this.string.charAt(this.pos)))++this.pos;return this.pos>e},skipToEnd:function(){this.pos=this.string.length},skipTo:function(e){var t=this.string.indexOf(e,this.pos);if(t>-1)return this.pos=t,!0},backUp:function(e){this.pos-=e},column:function(){return this.lastColumnPos0?null:(s&&t!==!1&&(this.pos+=s[0].length),s)}var r=function(e){return n?e.toLowerCase():e},i=this.string.substr(this.pos,e.length);if(r(i)==r(e))return t!==!1&&(this.pos+=e.length),!0},current:function(){return this.string.slice(this.start,this.pos)},hideFirstChars:function(e,t){this.lineStart+=e;try{return t()}finally{this.lineStart-=e}}};var Li=S.TextMarker=function(e,t){this.lines=[],this.type=t,this.doc=e};ko(Li),Li.prototype.clear=function(){if(this.explicitlyCleared)return;var e=this.doc.cm,t=e&&!e.curOp;t&&kn(e);if(Co(this,"clear")){var n=this.find();n&&So(this,"clear",n.from,n.to)}var r=null,i=null;for(var s=0;se.display.maxLineLength&&(e.display.maxLine=a,e.display.maxLineLength=f,e.display.maxLineChanged=!0)}r!=null&&e&&this.collapsed&&Un(e,r,i+1),this.lines.length=0,this.explicitlyCleared=!0,this.atomic&&this.doc.cantEdit&&(this.doc.cantEdit=!1,e&&Bt(e.doc)),e&&So(e,"markerCleared",e,this),t&&An(e),this.parent&&this.parent.clear()},Li.prototype.find=function(e,t){e==null&&this.type=="bookmark"&&(e=1);var n,r;for(var i=0;i1||!(this.children[0]instanceof Ps))){var u=[];this.collapse(u),this.children=[new Ps(u)],this.children[0].parent=this}},collapse:function(e){for(var t=0;t50){while(i.lines.length>50){var o=i.lines.splice(i.lines.length-25,25),u=new Ps(o);i.height-=u.height,this.children.splice(r+1,0,u),u.parent=this}this.maybeSpill()}break}e-=s}},maybeSpill:function(){if(this.children.length<=10)return;var e=this;do{var t=e.children.splice(e.children.length-5,5),n=new Hs(t);if(!e.parent){var r=new Hs(e.children);r.parent=e,e.children=[r,n],e=r}else{e.size-=n.size,e.height-=n.height;var i=qo(e.parent.children,e);e.parent.children.splice(i+1,0,n)}n.parent=e.parent}while(e.children.length>10);e.parent.maybeSpill()},iterN:function(e,t,n){for(var r=0;r=0;s--)Wr(this,r[s]);u?_t(this,u):this.cm&&ni(this.cm)}),undo:In(function(){Vr(this,"undo")}),redo:In(function(){Vr(this,"redo")}),undoSelection:In(function(){Vr(this,"undo",!0)}),redoSelection:In(function(){Vr(this,"redo",!0)}),setExtending:function(e){this.extend=e},getExtending:function(){return this.extend},historySize:function(){var e=this.history,t=0,n=0;for(var r=0;r=e.ch)&&t.push(i.marker.parent||i.marker)}return t},findMarks:function(e,t,n){e=St(this,e),t=St(this,t);var r=[],i=e.line;return this.iter(e.line,t.line+1,function(s){var o=s.markedSpans;if(o)for(var u=0;ua.to||a.from==null&&i!=e.line||i==t.line&&a.from>t.ch)&&(!n||n(a.marker))&&r.push(a.marker.parent||a.marker)}++i}),r},getAllMarks:function(){var e=[];return this.iter(function(t){var n=t.markedSpans;if(n)for(var r=0;re)return t=e,!0;e-=i,++n}),St(this,ht(n,t))},indexFromPos:function(e){e=St(this,e);var t=e.ch;return e.linet&&(t=e.from),e.to!=null&&e.to=t)return o+(t-s);o+=u-s,o+=n-o%n,s=u+1}},Bo=[""],Io=function(e){e.select()};p?Io=function(e){e.selectionStart=0,e.selectionEnd=e.value.length}:r&&(Io=function(e){try{e.select()}catch(t){}}),[].indexOf&&(qo=function(e,t){return e.indexOf(t)}),[].map&&(Ro=function(e,t){return e.map(t)});var Xo=/[\u00df\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/,Vo=S.isWordChar=function(e){return/\w/.test(e)||e>"€"&&(e.toUpperCase()!=e.toLowerCase()||Xo.test(e))},Ko=/[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/,Yo;document.createRange?Yo=function(e,t,n){var r=document.createRange();return r.setEnd(e,n),r.setStart(e,t),r}:Yo=function(e,t,n){var r=document.body.createTextRange();try{r.moveToElementText(e.parentNode)}catch(i){return r}return r.collapse(!0),r.moveEnd("character",n),r.moveStart("character",t),r},r&&i<11&&(nu=function(){try{return document.activeElement}catch(e){return document.body}});var iu=S.rmClass=function(e,t){var n=e.className,r=ru(t).exec(n);if(r){var i=n.slice(r.index+r[0].length);e.className=n.slice(0,r.index)+(i?r[1]+i:"")}},su=S.addClass=function(e,t){var n=e.className;ru(t).test(n)||(e.className+=(n?" ":"")+t)},au=!1,cu=function(){if(r&&i<9)return!1;var e=Go("div");return"draggable"in e||"dragDrop"in e}(),hu,du,mu,yu=S.splitLines="\n\nb".split(/\n/).length!=3?function(e){var t=0,n=[],r=e.length;while(t<=r){var i=e.indexOf("\n",t);i==-1&&(i=e.length);var s=e.slice(t,e.charAt(i-1)=="\r"?i-1:i),o=s.indexOf("\r");o!=-1?(n.push(s.slice(0,o)),t+=o+1):(n.push(s),t=i+1)}return n}:function(e){return e.split(/\r\n?|\n/)},bu=window.getSelection?function(e){try{return e.selectionStart!=e.selectionEnd}catch(t){return!1}}:function(e){try{var t=e.ownerDocument.selection.createRange()}catch(n){}return!t||t.parentElement()!=e?!1:t.compareEndPoints("StartToEnd",t)!=0},wu=function(){var e=Go("div");return"oncopy"in e?!0:(e.setAttribute("oncopy","return;"),typeof e.oncopy=="function")}(),Eu=null,xu={3:"Enter",8:"Backspace",9:"Tab",13:"Enter",16:"Shift",17:"Ctrl",18:"Alt",19:"Pause",20:"CapsLock",27:"Esc",32:"Space",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"Left",38:"Up",39:"Right",40:"Down",44:"PrintScrn",45:"Insert",46:"Delete",59:";",61:"=",91:"Mod",92:"Mod",93:"Mod",107:"=",109:"-",127:"Delete",173:"-",186:";",187:"=",188:",",189:"-",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:"'",63232:"Up",63233:"Down",63234:"Left",63235:"Right",63272:"Delete",63273:"Home",63275:"End",63276:"PageUp",63277:"PageDown",63302:"Insert"};S.keyNames=xu,function(){for(var e=0;e<10;e++)xu[e+48]=xu[e+96]=String(e);for(var e=65;e<=90;e++)xu[e]=String.fromCharCode(e);for(var e=1;e<=12;e++)xu[e+111]=xu[e+63235]="F"+e}();var Du,Fu=function(){function n(n){return n<=247?e.charAt(n):1424<=n&&n<=1524?"R":1536<=n&&n<=1773?t.charAt(n-1536):1774<=n&&n<=2220?"r":8192<=n&&n<=8203?"w":n==8204?"b":"L"}function f(e,t,n){this.level=e,this.from=t,this.to=n}var e="bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN",t="rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmm",r=/[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/,i=/[stwN]/,s=/[LRr]/,o=/[Lb1n]/,u=/[1n]/,a="L";return function(e){if(!r.test(e))return!1;var t=e.length,l=[];for(var c=0,h;c"))return v("=>","operator");if(n=="0"&&e.eat(/x/i))return e.eatWhile(/[\da-f]/i),v("number","number");if(/\d/.test(n))return e.match(/^\d*(?:\.\d*)?(?:[eE][+\-]?\d+)?/),v("number","number");if(n=="/")return e.eat("*")?(t.tokenize=y,y(e,t)):e.eat("/")?(e.skipToEnd(),v("comment","comment")):t.lastType=="operator"||t.lastType=="keyword c"||t.lastType=="sof"||/^[\[{}\(,;:]$/.test(t.lastType)?(h(e),e.eatWhile(/[gimy]/),v("regexp","string-2")):(e.eatWhile(l),v("operator","operator",e.current()));if(n=="`")return t.tokenize=b,b(e,t);if(n=="#")return e.skipToEnd(),v("error","error");if(l.test(n))return e.eatWhile(l),v("operator","operator",e.current());if(a.test(n)){e.eatWhile(a);var r=e.current(),i=f.propertyIsEnumerable(r)&&f[r];return i&&t.lastType!="."?v(i.type,i.style,r):v("variable","variable",r)}}function g(e){return function(t,n){var r=!1,i;if(s&&t.peek()=="@"&&t.match(c))return n.tokenize=m,v("jsonld-keyword","meta");while((i=t.next())!=null){if(i==e&&!r)break;r=!r&&i=="\\"}return r||(n.tokenize=m),v("string","string")}}function y(e,t){var n=!1,r;while(r=e.next()){if(r=="/"&&n){t.tokenize=m;break}n=r=="*"}return v("comment","comment")}function b(e,t){var n=!1,r;while((r=e.next())!=null){if(!n&&(r=="`"||r=="$"&&e.eat("{"))){t.tokenize=m;break}n=!n&&r=="\\"}return v("quasi","string-2",e.current())}function E(e,t){t.fatArrowAt&&(t.fatArrowAt=null);var n=e.string.indexOf("=>",e.start);if(n<0)return;var r=0,i=!1;for(var s=n-1;s>=0;--s){var o=e.string.charAt(s),u=w.indexOf(o);if(u>=0&&u<3){if(!r){++s;break}if(--r==0)break}else if(u>=3&&u<6)++r;else if(a.test(o))i=!0;else if(i&&!r){++s;break}}i&&!r&&(t.fatArrowAt=s)}function x(e,t,n,r,i,s){this.indented=e,this.column=t,this.type=n,this.prev=i,this.info=s,r!=null&&(this.align=r)}function T(e,t){for(var n=e.localVars;n;n=n.next)if(n.name==t)return!0;for(var r=e.context;r;r=r.prev)for(var n=r.vars;n;n=n.next)if(n.name==t)return!0}function N(e,t,n,r,i){var s=e.cc;C.state=e,C.stream=i,C.marked=null,C.cc=s,C.style=t,e.lexical.hasOwnProperty("align")||(e.lexical.align=!0);for(;;){var u=s.length?s.pop():o?j:B;if(u(n,r)){while(s.length&&s[s.length-1].lex)s.pop()();return C.marked?C.marked:n=="variable"&&T(e,r)?"variable-2":t}}}function k(){for(var e=arguments.length-1;e>=0;e--)C.cc.push(arguments[e])}function L(){return k.apply(null,arguments),!0}function A(e){function t(t){for(var n=t;n;n=n.next)if(n.name==e)return!0;return!1}var r=C.state;if(r.context){C.marked="def";if(t(r.localVars))return;r.localVars={name:e,next:r.localVars}}else{if(t(r.globalVars))return;n.globalVars&&(r.globalVars={name:e,next:r.globalVars})}}function M(){C.state.context={prev:C.state.context,vars:C.state.localVars},C.state.localVars=O}function _(){C.state.localVars=C.state.context.vars,C.state.context=C.state.context.prev}function D(e,t){var n=function(){var n=C.state,r=n.indented;if(n.lexical.type=="stat")r=n.lexical.indented;else for(var i=n.lexical;i&&i.type==")"&&i.align;i=i.prev)r=i.indented;n.lexical=new x(r,C.stream.column(),e,null,n.lexical,t)};return n.lex=!0,n}function P(){var e=C.state;e.lexical.prev&&(e.lexical.type==")"&&(e.indented=e.lexical.indented),e.lexical=e.lexical.prev)}function H(e){function t(n){return n==e?L():e==";"?k():L(t)}return t}function B(e,t){return e=="var"?L(D("vardef",t.length),it,H(";"),P):e=="keyword a"?L(D("form"),j,B,P):e=="keyword b"?L(D("form"),B,P):e=="{"?L(D("}"),tt,P):e==";"?L():e=="if"?(C.state.lexical.info=="else"&&C.state.cc[C.state.cc.length-1]==P&&C.state.cc.pop()(),L(D("form"),j,B,P,ft)):e=="function"?L(vt):e=="for"?L(D("form"),lt,B,P):e=="variable"?L(D("stat"),J):e=="switch"?L(D("form"),j,D("}","switch"),H("{"),tt,P,P):e=="case"?L(j,H(":")):e=="default"?L(H(":")):e=="catch"?L(D("form"),M,H("("),mt,H(")"),B,P,_):e=="module"?L(D("form"),M,Et,_,P):e=="class"?L(D("form"),gt,P):e=="export"?L(D("form"),St,P):e=="import"?L(D("form"),xt,P):k(D("stat"),j,H(";"),P)}function j(e){return I(e,!1)}function F(e){return I(e,!0)}function I(e,t){if(C.state.fatArrowAt==C.stream.start){var n=t?$:V;if(e=="(")return L(M,D(")"),Z(st,")"),P,H("=>"),n,_);if(e=="variable")return k(M,st,H("=>"),n,_)}var r=t?z:U;return S.hasOwnProperty(e)?L(r):e=="function"?L(vt,r):e=="keyword c"?L(t?R:q):e=="("?L(D(")"),q,Lt,H(")"),P,r):e=="operator"||e=="spread"?L(t?F:j):e=="["?L(D("]"),Ct,P,r):e=="{"?et(Q,"}",null,r):e=="quasi"?k(W,r):L()}function q(e){return e.match(/[;\}\)\],]/)?k():k(j)}function R(e){return e.match(/[;\}\)\],]/)?k():k(F)}function U(e,t){return e==","?L(j):z(e,t,!1)}function z(e,t,n){var r=n==0?U:z,i=n==0?j:F;if(e=="=>")return L(M,n?$:V,_);if(e=="operator")return/\+\+|--/.test(t)?L(r):t=="?"?L(j,H(":"),i):L(i);if(e=="quasi")return k(W,r);if(e==";")return;if(e=="(")return et(F,")","call",r);if(e==".")return L(K,r);if(e=="[")return L(D("]"),q,H("]"),P,r)}function W(e,t){return e!="quasi"?k():t.slice(t.length-2)!="${"?L(W):L(j,X)}function X(e){if(e=="}")return C.marked="string-2",C.state.tokenize=b,L(W)}function V(e){return E(C.stream,C.state),k(e=="{"?B:j)}function $(e){return E(C.stream,C.state),k(e=="{"?B:F)}function J(e){return e==":"?L(P,B):k(U,H(";"),P)}function K(e){if(e=="variable")return C.marked="property",L()}function Q(e,t){if(e=="variable"||C.style=="keyword")return C.marked="property",t=="get"||t=="set"?L(G):L(Y);if(e=="number"||e=="string")return C.marked=s?"property":C.style+" property",L(Y);if(e=="jsonld-keyword")return L(Y);if(e=="[")return L(j,H("]"),Y)}function G(e){return e!="variable"?k(Y):(C.marked="property",L(vt))}function Y(e){if(e==":")return L(F);if(e=="(")return k(vt)}function Z(e,t){function n(r){if(r==","){var i=C.state.lexical;return i.info=="call"&&(i.pos=(i.pos||0)+1),L(e,n)}return r==t?L():L(H(t))}return function(r){return r==t?L():k(e,n)}}function et(e,t,n){for(var r=3;r!?|~^]/,c=/^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)"/,p,d,w="([{}])",S={atom:!0,number:!0,variable:!0,string:!0,regexp:!0,"this":!0,"jsonld-keyword":!0},C={state:null,column:null,marked:null,cc:null},O={name:"this",next:{name:"arguments"}};return P.lex=!0,{startState:function(e){var t={tokenize:m,lastType:"sof",cc:[],lexical:new x((e||0)-r,0,"block",!1),localVars:n.localVars,context:n.localVars&&{vars:n.localVars},indented:0};return n.globalVars&&typeof n.globalVars=="object"&&(t.globalVars=n.globalVars),t},token:function(e,t){e.sol()&&(t.lexical.hasOwnProperty("align")||(t.lexical.align=!1),t.indented=e.indentation(),E(e,t));if(t.tokenize!=y&&e.eatSpace())return null;var n=t.tokenize(e,t);return p=="comment"?n:(t.lastType=p!="operator"||d!="++"&&d!="--"?p:"incdec",N(t,n,p,d,e))},indent:function(t,s){if(t.tokenize==y)return e.Pass;if(t.tokenize!=m)return 0;var o=s&&s.charAt(0),u=t.lexical;if(!/^\s*else\b/.test(s))for(var a=t.cc.length-1;a>=0;--a){var f=t.cc[a];if(f==P)u=u.prev;else if(f!=ft)break}u.type=="stat"&&o=="}"&&(u=u.prev),i&&u.type==")"&&u.prev.type=="stat"&&(u=u.prev);var l=u.type,c=o==l;return l=="vardef"?u.indented+(t.lastType=="operator"||t.lastType==","?u.info+1:0):l=="form"&&o=="{"?u.indented:l=="form"?u.indented+r:l=="stat"?u.indented+(t.lastType=="operator"||t.lastType==","?i||r:0):u.info=="switch"&&!c&&n.doubleIndentSwitch!=0?u.indented+(/^(?:case|default)\b/.test(s)?r:2*r):u.align?u.column+(c?0:1):u.indented+(c?0:r)},electricInput:/^\s*(?:case .*?:|default:|\{|\})$/,blockCommentStart:o?null:"/*",blockCommentEnd:o?null:"*/",lineComment:o?null:"//",fold:"brace",helperType:o?"json":"javascript",jsonldMode:s,jsonMode:o}}),e.registerHelper("wordChars","javascript",/[\w$]/),e.defineMIME("text/javascript","javascript"),e.defineMIME("text/ecmascript","javascript"),e.defineMIME("application/javascript","javascript"),e.defineMIME("application/x-javascript","javascript"),e.defineMIME("application/ecmascript","javascript"),e.defineMIME("application/json",{name:"javascript",json:!0}),e.defineMIME("application/x-json",{name:"javascript",json:!0}),e.defineMIME("application/ld+json",{name:"javascript",jsonld:!0}),e.defineMIME("text/typescript",{name:"javascript",typescript:!0}),e.defineMIME("application/typescript",{name:"javascript",typescript:!0})}),function(e){typeof exports=="object"&&typeof module=="object"?e(require("../../lib/codemirror")):typeof define=="function"&&define.amd?define("libs/codemirror-4.8/addon/hint/xml-hint",["../../lib/codemirror"],e):e(CodeMirror)}(function(e){function n(n,r){var i=r&&r.schemaInfo,s=r&&r.quoteChar||'"';if(!i)return;var o=n.getCursor(),u=n.getTokenAt(o);if(/^<\/?$/.test(u.string)&&u.end==o.ch){var a=n.getTokenAt(t(o.line,o.ch+1));a.start==o.ch&&/\btag\b/.test(a.type)&&(u=a)}var f=e.innerMode(n.getMode(),u.state);if(f.mode.name!="xml")return;var l=[],c=!1,h,p=/\btag\b/.test(u.type)&&!/>$/.test(u.string),d=p&&/^\w/.test(u.string),v;if(d){var m=n.getLine(o.line).slice(Math.max(0,u.start-2),u.start),g=/<\/$/.test(m)?"close":/<$/.test(m)?"open":null;g&&(v=u.start-(g=="close"?2:1))}else p&&u.string=="<"?g="open":p&&u.string=="")}else{var b=i[f.state.tagName],x=b&&b.attrs,T=i["!attrs"];if(!x&&!T)return;if(!x)x=T;else if(T){var N={};for(var C in T)T.hasOwnProperty(C)&&(N[C]=T[C]);for(var C in x)x.hasOwnProperty(C)&&(N[C]=x[C]);x=N}if(u.type=="string"||u.string=="="){var m=n.getRange(t(o.line,Math.max(0,o.ch-60)),t(o.line,u.type=="string"?u.start:u.end)),k=m.match(/([^\s\u00a0=<>\"\']+)=$/),L;if(!k||!x.hasOwnProperty(k[1])||!(L=x[k[1]]))return;typeof L=="function"&&(L=L.call(this,n));if(u.type=="string"){h=u.string;var A=0;/['"]/.test(u.string.charAt(0))&&(s=u.string.charAt(0),h=u.string.slice(1),A++);var O=u.string.length;/['"]/.test(u.string.charAt(O-1))&&(s=u.string.charAt(O-1),h=u.string.substr(A,O-2)),c=!0}for(var E=0;E][<][=] [X]","device-aspect-ratio: X/Y","orientation:portrait","orientation:landscape","device-height: [X]","device-width: [X]"],u={attrs:{}},a={a:{attrs:{href:null,ping:null,type:null,media:o,target:n,hreflang:t}},abbr:u,acronym:u,address:u,applet:u,area:{attrs:{alt:null,coords:null,href:null,target:null,ping:null,media:o,hreflang:t,type:null,shape:["default","rect","circle","poly"]}},article:u,aside:u,audio:{attrs:{src:null,mediagroup:null,crossorigin:["anonymous","use-credentials"],preload:["none","metadata","auto"],autoplay:["","autoplay"],loop:["","loop"],controls:["","controls"]}},b:u,base:{attrs:{href:null,target:n}},basefont:u,bdi:u,bdo:u,big:u,blockquote:{attrs:{cite:null}},body:u,br:u,button:{attrs:{form:null,formaction:null,name:null,value:null,autofocus:["","autofocus"],disabled:["","autofocus"],formenctype:s,formmethod:i,formnovalidate:["","novalidate"],formtarget:n,type:["submit","reset","button"]}},canvas:{attrs:{width:null,height:null}},caption:u,center:u,cite:u,code:u,col:{attrs:{span:null}},colgroup:{attrs:{span:null}},command:{attrs:{type:["command","checkbox","radio"],label:null,icon:null,radiogroup:null,command:null,title:null,disabled:["","disabled"],checked:["","checked"]}},data:{attrs:{value:null}},datagrid:{attrs:{disabled:["","disabled"],multiple:["","multiple"]}},datalist:{attrs:{data:null}},dd:u,del:{attrs:{cite:null,datetime:null}},details:{attrs:{open:["","open"]}},dfn:u,dir:u,div:u,dl:u,dt:u,em:u,embed:{attrs:{src:null,type:null,width:null,height:null}},eventsource:{attrs:{src:null}},fieldset:{attrs:{disabled:["","disabled"],form:null,name:null}},figcaption:u,figure:u,font:u,footer:u,form:{attrs:{action:null,name:null,"accept-charset":r,autocomplete:["on","off"],enctype:s,method:i,novalidate:["","novalidate"],target:n}},frame:u,frameset:u,h1:u,h2:u,h3:u,h4:u,h5:u,h6:u,head:{attrs:{},children:["title","base","link","style","meta","script","noscript","command"]},header:u,hgroup:u,hr:u,html:{attrs:{manifest:null},children:["head","body"]},i:u,iframe:{attrs:{src:null,srcdoc:null,name:null,width:null,height:null,sandbox:["allow-top-navigation","allow-same-origin","allow-forms","allow-scripts"],seamless:["","seamless"]}},img:{attrs:{alt:null,src:null,ismap:null,usemap:null,width:null,height:null,crossorigin:["anonymous","use-credentials"]}},input:{attrs:{alt:null,dirname:null,form:null,formaction:null,height:null,list:null,max:null,maxlength:null,min:null,name:null,pattern:null,placeholder:null,size:null,src:null,step:null,value:null,width:null,accept:["audio/*","video/*","image/*"],autocomplete:["on","off"],autofocus:["","autofocus"],checked:["","checked"],disabled:["","disabled"],formenctype:s,formmethod:i,formnovalidate:["","novalidate"],formtarget:n,multiple:["","multiple"],readonly:["","readonly"],required:["","required"],type:["hidden","text","search","tel","url","email","password","datetime","date","month","week","time","datetime-local","number","range","color","checkbox","radio","file","submit","image","reset","button"]}},ins:{attrs:{cite:null,datetime:null}},kbd:u,keygen:{attrs:{challenge:null,form:null,name:null,autofocus:["","autofocus"],disabled:["","disabled"],keytype:["RSA"]}},label:{attrs:{"for":null,form:null}},legend:u,li:{attrs:{value:null}},link:{attrs:{href:null,type:null,hreflang:t,media:o,sizes:["all","16x16","16x16 32x32","16x16 32x32 64x64"]}},map:{attrs:{name:null}},mark:u,menu:{attrs:{label:null,type:["list","context","toolbar"]}},meta:{attrs:{content:null,charset:r,name:["viewport","application-name","author","description","generator","keywords"],"http-equiv":["content-language","content-type","default-style","refresh"]}},meter:{attrs:{value:null,min:null,low:null,high:null,max:null,optimum:null}},nav:u,noframes:u,noscript:u,object:{attrs:{data:null,type:null,name:null,usemap:null,form:null,width:null,height:null,typemustmatch:["","typemustmatch"]}},ol:{attrs:{reversed:["","reversed"],start:null,type:["1","a","A","i","I"]}},optgroup:{attrs:{disabled:["","disabled"],label:null}},option:{attrs:{disabled:["","disabled"],label:null,selected:["","selected"],value:null}},output:{attrs:{"for":null,form:null,name:null}},p:u,param:{attrs:{name:null,value:null}},pre:u,progress:{attrs:{value:null,max:null}},q:{attrs:{cite:null}},rp:u,rt:u,ruby:u,s:u,samp:u,script:{attrs:{type:["text/javascript"],src:null,async:["","async"],defer:["","defer"],charset:r}},section:u,select:{attrs:{form:null,name:null,size:null,autofocus:["","autofocus"],disabled:["","disabled"],multiple:["","multiple"]}},small:u,source:{attrs:{src:null,type:null,media:null}},span:u,strike:u,strong:u,style:{attrs:{type:["text/css"],media:o,scoped:null}},sub:u,summary:u,sup:u,table:u,tbody:u,td:{attrs:{colspan:null,rowspan:null,headers:null}},textarea:{attrs:{dirname:null,form:null,maxlength:null,name:null,placeholder:null,rows:null,cols:null,autofocus:["","autofocus"],disabled:["","disabled"],readonly:["","readonly"],required:["","required"],wrap:["soft","hard"]}},tfoot:u,th:{attrs:{colspan:null,rowspan:null,headers:null,scope:["row","col","rowgroup","colgroup"]}},thead:u,time:{attrs:{datetime:null}},title:u,tr:u,track:{attrs:{src:null,label:null,"default":null,kind:["subtitles","captions","descriptions","chapters","metadata"],srclang:t}},tt:u,u:u,ul:u,"var":u,video:{attrs:{src:null,poster:null,width:null,height:null,crossorigin:["anonymous","use-credentials"],preload:["auto","metadata","none"],autoplay:["","autoplay"],mediagroup:["movie"],muted:["","muted"],controls:["","controls"]}},wbr:u},f={accesskey:["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","0","1","2","3","4","5","6","7","8","9"],"class":null,contenteditable:["true","false"],contextmenu:null,dir:["ltr","rtl","auto"],draggable:["true","false","auto"],dropzone:["copy","move","link","string:","file:"],hidden:["hidden"],id:null,inert:["inert"],itemid:null,itemprop:null,itemref:null,itemscope:["itemscope"],itemtype:null,lang:["en","es"],spellcheck:["true","false"],style:null,tabindex:["1","2","3","4","5","6","7","8","9"],title:null,translate:["yes","no"],onclick:null,rel:["stylesheet","alternate","author","bookmark","help","license","next","nofollow","noreferrer","prefetch","prev","search","tag"]};l(u);for(var c in a)a.hasOwnProperty(c)&&a[c]!=u&&l(a[c]);e.htmlSchema=a,e.registerHelper("hint","html",h)}),function(e){typeof exports=="object"&&typeof module=="object"?e(require("../../lib/codemirror")):typeof define=="function"&&define.amd?define("libs/codemirror-4.8/addon/hint/show-hint",["../../lib/codemirror"],e):e(CodeMirror)}(function(e){function r(e,t){this.cm=e,this.options=this.buildOptions(t),this.widget=this.onClose=null}function i(e){return typeof e=="string"?e:e.text}function s(e,t){function s(e,r){var s;typeof r!="string"?s=function(e){return r(e,t)}:n.hasOwnProperty(r)?s=n[r]:s=r,i[e]=s}var n={Up:function(){t.moveFocus(-1)},Down:function(){t.moveFocus(1)},PageUp:function(){t.moveFocus(-t.menuSize()+1,!0)},PageDown:function(){t.moveFocus(t.menuSize()-1,!0)},Home:function(){t.setFocus(0)},End:function(){t.setFocus(t.length-1)},Enter:t.pick,Tab:t.pick,Esc:t.close},r=e.options.customKeys,i=r?{}:n;if(r)for(var o in r)r.hasOwnProperty(o)&&s(o,r[o]);var u=e.options.extraKeys;if(u)for(var o in u)u.hasOwnProperty(o)&&s(o,u[o]);return i}function o(e,t){while(t&&t!=e){if(t.nodeName.toUpperCase()==="LI"&&t.parentNode==e)return t;t=t.parentNode}}function u(r,u){this.completion=r,this.data=u;var a=this,f=r.cm,l=this.hints=document.createElement("ul");l.className="CodeMirror-hints",this.selectedHint=u.selectedHint||0;var c=u.list;for(var h=0;h0){var T=S.bottom-S.top,N=m.top-(m.bottom-S.top);if(N-T>0)l.style.top=(y=m.top-T)+"px",b=!1;else if(T>E){l.style.height=E-5+"px",l.style.top=(y=m.bottom-S.top)+"px";var C=f.getCursor();u.from.ch!=C.ch&&(m=f.cursorCoords(C),l.style.left=(g=m.left)+"px",S=l.getBoundingClientRect())}}var k=S.left-w;k>0&&(S.right-S.left>w&&(l.style.width=w-5+"px",k-=S.right-S.left-w),l.style.left=(g=m.left-k)+"px"),f.addKeyMap(this.keyMap=s(r,{moveFocus:function(e,t){a.changeActive(a.selectedHint+e,t)},setFocus:function(e){a.changeActive(e)},menuSize:function(){return a.screenAmount()},length:c.length,close:function(){r.close()},pick:function(){a.pick()},data:u}));if(r.options.closeOnUnfocus){var L;f.on("blur",this.onBlur=function(){L=setTimeout(function(){r.close()},100)}),f.on("focus",this.onFocus=function(){clearTimeout(L)})}var A=f.getScrollInfo();return f.on("scroll",this.onScroll=function(){var e=f.getScrollInfo(),t=f.getWrapperElement().getBoundingClientRect(),n=y+A.top-e.top,i=n-(window.pageYOffset||(document.documentElement||document.body).scrollTop);b||(i+=l.offsetHeight);if(i<=t.top||i>=t.bottom)return r.close();l.style.top=n+"px",l.style.left=g+A.left-e.left+"px"}),e.on(l,"dblclick",function(e){var t=o(l,e.target||e.srcElement);t&&t.hintId!=null&&(a.changeActive(t.hintId),a.pick())}),e.on(l,"click",function(e){var t=o(l,e.target||e.srcElement);t&&t.hintId!=null&&(a.changeActive(t.hintId),r.options.completeOnSingleClick&&a.pick())}),e.on(l,"mousedown",function(){setTimeout(function(){f.focus()},20)}),e.signal(u,"select",c[0],l.firstChild),!0}var t="CodeMirror-hint",n="CodeMirror-hint-active";e.showHint=function(e,t,n){if(!t)return e.showHint(n);n&&n.async&&(t.async=!0);var r={hint:t};if(n)for(var i in n)r[i]=n[i];return e.showHint(r)},e.defineExtension("showHint",function(t){if(this.listSelections().length>1||this.somethingSelected())return;this.state.completionActive&&this.state.completionActive.close();var n=this.state.completionActive=new r(this,t),i=n.options.hint;if(!i)return;e.signal(this,"startCompletion",this);if(!i.async)return n.showHints(i(this,n.options));i(this,function(e){n.showHints(e)},n.options)}),r.prototype={close:function(){if(!this.active())return;this.cm.state.completionActive=null,this.widget&&this.widget.close(),this.onClose&&this.onClose(),e.signal(this.cm,"endCompletion",this.cm)},active:function(){return this.cm.state.completionActive==this},pick:function(t,n){var r=t.list[n];r.hint?r.hint(this.cm,t,r):this.cm.replaceRange(i(r),r.from||t.from,r.to||t.to,"complete"),e.signal(t,"pick",r),this.close()},showHints:function(e){if(!e||!e.list.length||!this.active())return this.close();this.options.completeSingle&&e.list.length==1?this.pick(e,0):this.showWidget(e)},showWidget:function(t){function c(){if(i)return;i=!0,r.close(),r.cm.off("cursorActivity",v),t&&e.signal(t,"close")}function h(){if(i)return;e.signal(t,"update");var n=r.options.hint;n.async?n(r.cm,p,r.options):p(n(r.cm,r.options))}function p(e){t=e;if(i)return;if(!t||!t.list.length)return c();r.widget&&r.widget.close(),r.widget=new u(r,t)}function d(){n&&(l(n),n=0)}function v(){d();var e=r.cm.getCursor(),t=r.cm.getLine(e.line);e.line!=o.line||t.length-e.ch!=a-o.ch||e.ch=this.data.list.length?t=r?this.data.list.length-1:0:t<0&&(t=r?0:this.data.list.length-1);if(this.selectedHint==t)return;var i=this.hints.childNodes[this.selectedHint];i.className=i.className.replace(" "+n,""),i=this.hints.childNodes[this.selectedHint=t],i.className+=" "+n,i.offsetTopthis.hints.scrollTop+this.hints.clientHeight&&(this.hints.scrollTop=i.offsetTop+i.offsetHeight-this.hints.clientHeight+3),e.signal(this.data,"select",this.data.list[this.selectedHint],i)},screenAmount:function(){return Math.floor(this.hints.clientHeight/this.hints.firstChild.offsetHeight)||1}},e.registerHelper("hint","auto",function(t,n){var r=t.getHelpers(t.getCursor(),"hint"),i;if(r.length)for(var s=0;s,]/,closeOnUnfocus:!0,completeOnSingleClick:!1,container:null,customKeys:null,extraKeys:null};e.defineOption("hintOptions",null)}),function(e){typeof exports=="object"&&typeof module=="object"?e(require("../../lib/codemirror")):typeof define=="function"&&define.amd?define("libs/codemirror-4.8/mode/xml/xml",["../../lib/codemirror"],e):e(CodeMirror)}(function(e){e.defineMode("xml",function(t,n){function l(e,t){function n(n){return t.tokenize=n,n(e,t)}var r=e.next();if(r=="<")return e.eat("!")?e.eat("[")?e.match("CDATA[")?n(p("atom","]]>")):null:e.match("--")?n(p("comment","-->")):e.match("DOCTYPE",!0,!0)?(e.eatWhile(/[\w\._\-]/),n(d(1))):null:e.eat("?")?(e.eatWhile(/[\w\._\-]/),t.tokenize=p("meta","?>"),"meta"):(a=e.eat("/")?"closeTag":"openTag",t.tokenize=c,"tag bracket");if(r=="&"){var i;return e.eat("#")?e.eat("x")?i=e.eatWhile(/[a-fA-F\d]/)&&e.eat(";"):i=e.eatWhile(/[\d]/)&&e.eat(";"):i=e.eatWhile(/[\w\.\-:]/)&&e.eat(";"),i?"atom":"error"}return e.eatWhile(/[^&<]/),null}function c(e,t){var n=e.next();if(n==">"||n=="/"&&e.eat(">"))return t.tokenize=l,a=n==">"?"endTag":"selfcloseTag","tag bracket";if(n=="=")return a="equals",null;if(n=="<"){t.tokenize=l,t.state=y,t.tagName=t.tagStart=null;var r=t.tokenize(e,t);return r?r+" tag error":"tag error"}return/[\'\"]/.test(n)?(t.tokenize=h(n),t.stringStartCol=e.column(),t.tokenize(e,t)):(e.match(/^[^\s\u00a0=<>\"\']*[^\s\u00a0=<>\"\'\/]/),"word")}function h(e){var t=function(t,n){while(!t.eol())if(t.next()==e){n.tokenize=c;break}return"string"};return t.isInAttribute=!0,t}function p(e,t){return function(n,r){while(!n.eol()){if(n.match(t)){r.tokenize=l;break}n.next()}return e}}function d(e){return function(t,n){var r;while((r=t.next())!=null){if(r=="<")return n.tokenize=d(e+1),n.tokenize(t,n);if(r==">"){if(e==1){n.tokenize=l;break}return n.tokenize=d(e-1),n.tokenize(t,n)}}return"meta"}}function v(e,t,n){this.prev=e.context,this.tagName=t,this.indent=e.indented,this.startOfLine=n;if(o.doNotIndent.hasOwnProperty(t)||e.context&&e.context.noIndent)this.noIndent=!0}function m(e){e.context&&(e.context=e.context.prev)}function g(e,t){var n;for(;;){if(!e.context)return;n=e.context.tagName;if(!o.contextGrabbers.hasOwnProperty(n)||!o.contextGrabbers[n].hasOwnProperty(t))return;m(e)}}function y(e,t,n){return e=="openTag"?(n.tagStart=t.column(),b):e=="closeTag"?w:y}function b(e,t,n){return e=="word"?(n.tagName=t.current(),f="tag",x):(f="error",b)}function w(e,t,n){if(e=="word"){var r=t.current();return n.context&&n.context.tagName!=r&&o.implicitlyClosed.hasOwnProperty(n.context.tagName)&&m(n),n.context&&n.context.tagName==r?(f="tag",E):(f="tag error",S)}return f="error",S}function E(e,t,n){return e!="endTag"?(f="error",E):(m(n),y)}function S(e,t,n){return f="error",E(e,t,n)}function x(e,t,n){if(e=="word")return f="attribute",T;if(e=="endTag"||e=="selfcloseTag"){var r=n.tagName,i=n.tagStart;return n.tagName=n.tagStart=null,e=="selfcloseTag"||o.autoSelfClosers.hasOwnProperty(r)?g(n,r):(g(n,r),n.context=new v(n,r,i==n.indented)),y}return f="error",x}function T(e,t,n){return e=="equals"?N:(o.allowMissing||(f="error"),x(e,t,n))}function N(e,t,n){return e=="string"?C:e=="word"&&o.allowUnquoted?(f="string",x):(f="error",x(e,t,n))}function C(e,t,n){return e=="string"?C:x(e,t,n)}var r=t.indentUnit,i=n.multilineTagIndentFactor||1,s=n.multilineTagIndentPastTag;s==null&&(s=!0);var o=n.htmlMode?{autoSelfClosers:{area:!0,base:!0,br:!0,col:!0,command:!0,embed:!0,frame:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0,menuitem:!0},implicitlyClosed:{dd:!0,li:!0,optgroup:!0,option:!0,p:!0,rp:!0,rt:!0,tbody:!0,td:!0,tfoot:!0,th:!0,tr:!0},contextGrabbers:{dd:{dd:!0,dt:!0},dt:{dd:!0,dt:!0},li:{li:!0},option:{option:!0,optgroup:!0},optgroup:{optgroup:!0},p:{address:!0,article:!0,aside:!0,blockquote:!0,dir:!0,div:!0,dl:!0,fieldset:!0,footer:!0,form:!0,h1:!0,h2:!0,h3:!0,h4:!0,h5:!0,h6:!0,header:!0,hgroup:!0,hr:!0,menu:!0,nav:!0,ol:!0,p:!0,pre:!0,section:!0,table:!0,ul:!0},rp:{rp:!0,rt:!0},rt:{rp:!0,rt:!0},tbody:{tbody:!0,tfoot:!0},td:{td:!0,th:!0},tfoot:{tbody:!0},th:{td:!0,th:!0},thead:{tbody:!0,tfoot:!0},tr:{tr:!0}},doNotIndent:{pre:!0},allowUnquoted:!0,allowMissing:!0,caseFold:!0}:{autoSelfClosers:{},implicitlyClosed:{},contextGrabbers:{},doNotIndent:{},allowUnquoted:!1,allowMissing:!1,caseFold:!1},u=n.alignCDATA,a,f;return{startState:function(){return{tokenize:l,state:y,indented:0,tagName:null,tagStart:null,context:null}},token:function(e,t){!t.tagName&&e.sol()&&(t.indented=e.indentation());if(e.eatSpace())return null;a=null;var n=t.tokenize(e,t);return(n||a)&&n!="comment"&&(f=null,t.state=t.state(a||n,e,t),f&&(n=f=="error"?n+" error":f)),n},indent:function(t,n,a){var f=t.context;if(t.tokenize.isInAttribute)return t.tagStart==t.indented?t.stringStartCol+1:t.indented+r;if(f&&f.noIndent)return e.Pass;if(t.tokenize!=c&&t.tokenize!=l)return a?a.match(/^(\s*)/)[0].length:0;if(t.tagName)return s?t.tagStart+t.tagName.length+2:t.tagStart+r*i;if(u&&/$/,blockCommentStart:"",configuration:n.htmlMode?"html":"xml",helperType:n.htmlMode?"html":"xml"}}),e.defineMIME("text/xml","xml"),e.defineMIME("application/xml","xml"),e.mimeModes.hasOwnProperty("text/html")||e.defineMIME("text/html",{name:"xml",htmlMode:!0})}),function(e){typeof exports=="object"&&typeof module=="object"?e(require("../../lib/codemirror")):typeof define=="function"&&define.amd?define("libs/codemirror-4.8/addon/runmode/runmode",["../../lib/codemirror"],e):e(CodeMirror)}(function(e){e.runMode=function(t,n,r,i){var s=e.getMode(e.defaults,n),o=/MSIE \d/.test(navigator.userAgent),u=o&&(document.documentMode==null||document.documentMode<9);if(r.nodeType==1){var a=i&&i.tabSize||e.defaults.tabSize,f=r,l=0;f.innerHTML="",r=function(e,t){if(e=="\n"){f.appendChild(document.createTextNode(u?"\r":e)),l=0;return}var n="";for(var r=0;;){var i=e.indexOf(" ",r);if(i==-1){n+=e.slice(r),l+=e.length-r;break}l+=i-r,n+=e.slice(r,i);var s=a-l%a;l+=s;for(var o=0;o/im,s=/]*>\s*([\s\S]+)\s*<\/body>/im,o=typeof location!="undefined"&&location.href,u=o&&location.protocol&&location.protocol.replace(/\:/,""),a=o&&location.hostname,f=o&&(location.port||undefined),l=[],c=e.config&&e.config()||{};t={version:"2.0.5",strip:function(e){if(e){e=e.replace(i,"");var t=e.match(s);t&&(e=t[1])}else e="";return e},jsEscape:function(e){return e.replace(/(['\\])/g,"\\$1").replace(/[\f]/g,"\\f").replace(/[\b]/g,"\\b").replace(/[\n]/g,"\\n").replace(/[\t]/g,"\\t").replace(/[\r]/g,"\\r").replace(/[\u2028]/g,"\\u2028").replace(/[\u2029]/g,"\\u2029")},createXhr:c.createXhr||function(){var e,t,n;if(typeof XMLHttpRequest!="undefined")return new XMLHttpRequest;if(typeof ActiveXObject!="undefined")for(t=0;t<3;t+=1){n=r[t];try{e=new ActiveXObject(n)}catch(i){}if(e){r=[n];break}}return e},parseName:function(e){var t,n,r,i=!1,s=e.indexOf("."),o=e.indexOf("./")===0||e.indexOf("../")===0;return s!==-1&&(!o||s>1)?(t=e.substring(0,s),n=e.substring(s+1,e.length)):t=e,r=n||t,s=r.indexOf("!"),s!==-1&&(i=r.substring(s+1)==="strip",r=r.substring(0,s),n?n=r:t=r),{moduleName:t,ext:n,strip:i}},xdRegExp:/^((\w+)\:)?\/\/([^\/\\]+)/,useXhr:function(e,n,r,i){var s,o,u,a=t.xdRegExp.exec(e);return a?(s=a[2],o=a[3],o=o.split(":"),u=o[1],o=o[0],(!s||s===n)&&(!o||o.toLowerCase()===r.toLowerCase())&&(!u&&!o||u===i)):!0},finishLoad:function(e,n,r,i){r=n?t.strip(r):r,c.isBuild&&(l[e]=r),i(r)},load:function(e,n,r,i){if(i.isBuild&&!i.inlineText){r();return}c.isBuild=i.isBuild;var s=t.parseName(e),l=s.moduleName+(s.ext?"."+s.ext:""),h=n.toUrl(l),p=c.useXhr||t.useXhr;!o||p(h,u,a,f)?t.get(h,function(n){t.finishLoad(e,s.strip,n,r)},function(e){r.error&&r.error(e)}):n([l],function(e){t.finishLoad(s.moduleName+"."+s.ext,s.strip,e,r)})},write:function(e,n,r,i){if(l.hasOwnProperty(n)){var s=t.jsEscape(l[n]);r.asModule(e+"!"+n,"define(function () { return '"+s+"';});\n")}},writeFile:function(e,n,r,i,s){var o=t.parseName(n),u=o.ext?"."+o.ext:"",a=o.moduleName+u,f=r.toUrl(o.moduleName+u)+".js";t.load(a,r,function(n){var r=function(e){return i(f,e)};r.asModule=function(e,t){return i.asModule(e,f,t)},t.write(e,a,r,s)},s)}};if(c.env==="node"||!c.env&&typeof process!="undefined"&&process.versions&&!!process.versions.node)n=require.nodeRequire("fs"),t.get=function(e,t){var r=n.readFileSync(e,"utf8");r.indexOf("")===0&&(r=r.substring(1)),t(r)};else if(c.env==="xhr"||!c.env&&t.createXhr())t.get=function(e,n,r,i){var s=t.createXhr(),o;s.open("GET",e,!0);if(i)for(o in i)i.hasOwnProperty(o)&&s.setRequestHeader(o.toLowerCase(),i[o]);c.onXhr&&c.onXhr(s,e),s.onreadystatechange=function(t){var i,o;s.readyState===4&&(i=s.status,i>399&&i<600?(o=new Error(e+" HTTP status: "+i),o.xhr=s,r(o)):n(s.responseText))},s.send(null)};else if(c.env==="rhino"||!c.env&&typeof Packages!="undefined"&&typeof java!="undefined")t.get=function(e,t){var n,r,i="utf-8",s=new java.io.File(e),o=java.lang.System.getProperty("line.separator"),u=new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(s),i)),a="";try{n=new java.lang.StringBuffer,r=u.readLine(),r&&r.length()&&r.charAt(0)===65279&&(r=r.substring(1)),n.append(r);while((r=u.readLine())!==null)n.append(o),n.append(r);a=String(n.toString())}finally{u.close()}t(a)};return t}),define("text!samples/hello.code",[],function(){return"var <%= name %> = React.createClass({\n render: function () {\n return <%= name %>RT.apply(this);\n }\n});"}),define("text!samples/hello.rt",[],function(){return"

Hello world

\n"}),define("text!samples/todo.code",[],function(){return"var <%= name %> = React.createClass({\n mixins: [React.addons.LinkedStateMixin],\n getInitialState: function () {\n return {edited: '', todos: [], counter: 0};\n },\n add: function () {\n if (this.state.edited.trim().length === 0) {\n return;\n }\n var newTodo = {value: this.state.edited, done: false, key: this.state.counter};\n this.setState({todos: this.state.todos.concat(newTodo), edited: '', counter: this.state.counter + 1});\n },\n remove: function (todo) {\n this.setState({todos: _.reject(this.state.todos, todo)});\n },\n toggleChecked: function (index) {\n var todos = _.cloneDeep(this.state.todos);\n todos[index].done = !todos[index].done;\n this.setState({todos: todos});\n },\n clearDone: function () {\n this.setState({todos: _.filter(this.state.todos, {done: false})});\n },\n render: function () {\n return <%= name %>RT.apply(this);\n }\n});"}),define("text!samples/todo.rt",[],function(){return'
\n {_.filter(this.state.todos, {done:true}).length}\n done,\n {_.filter(this.state.todos, {done:false}).length}\n pending\n
\n
\n \n \n {todo.value}\n
\n \n
\n \n
'}),define("text!samples/rt-if.code",[],function(){return"var <%= name %> = React.createClass({\n getInitialState: function () {\n return {open: false};\n },\n toggle: function() {\n this.setState({open: !this.state.open});\n },\n render: function () {\n return <%= name %>RT.apply(this);\n }\n});"}),define("text!samples/rt-if.rt",[],function(){return'
\n

\n Click to {this.state.open ? \'close\' : \'open\'}\n

\n

This is my paragraph. It opens and\n closes

\n
'}),define("text!samples/rt-props.code",[],function(){return"var <%= name %> = React.createClass({\n mixins: [React.addons.LinkedStateMixin],\n getInitialState: function() {\n return { key: 'color', val: 'blue' };\n },\n getProps: function() {\n var ret = { style: {\n color: 'black',\n backgroundColor: 'white',\n borderColor: 'black'\n }};\n ret.style[this.state.key] = this.state.val;\n return ret;\n },\n render: function () {\n return <%= name %>RT.apply(this);\n }\n});"}),define("text!samples/rt-props.rt",[],function(){return'
\n Style:\n
\n Value:\n

\n
Sample
\n
'}),define("text!samples/rt-repeat.code",[],function(){return"var <%= name %> = React.createClass({\n getInitialState: function () {\n return {\n items: ['One', 'Two', 'Three']\n };\n },\n render: function () {\n return <%= name %>RT.apply(this);\n }\n});"}),define("text!samples/rt-repeat.rt",[],function(){return'
\n
    \n
  • {item}
  • \n
\n
'}),define("text!samples/weather.code",[],function(){return"var <%= name %> = React.createClass({\n mixins: [React.addons.LinkedStateMixin],\n getInitialState: function() {\n this.cityIds = [5391959,293397,2643743];\n this.fetchWeather();\n return { loading: true, cityToAdd: '', info: [] };\n },\n addCity: function() {\n if (this.state.cityToAdd.trim() == '') {\n return;\n }\n this.setState({ loading: true, cityToAdd: '' });\n $.get('http://api.openweathermap.org/data/2.5/weather?q=' + this.state.cityToAdd, this.findCityCallback);\n },\n findCityCallback: function(result) {\n if (result.id && !_.contains(this.cityIds, result.id)) {\n this.cityIds.unshift(result.id);\n this.fetchWeather();\n } else {\n this.setState({ loading: false });\n }\n },\n refresh: function() {\n this.setState({ loading:true });\n this.fetchWeather();\n },\n fetchWeather: function() {\n $.get('http://api.openweathermap.org/data/2.5/group?id=' + this.cityIds.join(',') + '&units=metric', this.fetchWeatherCallback);\n },\n fetchWeatherCallback: function(result) {\n this.setState({ loading:false, info: result.list });\n },\n render: function () {\n return <%= name %>RT.apply(this);\n }\n});"}),define("text!samples/weather.rt",[],function(){return'
\n

Cities weather report

\n \n \n
\n -- Loading --\n
\n
\n {cityIndex+1})\n \n {city.name}, {city.sys.country}\n
\n \n
'}),define("text!samples/rt-require.rt",[],function(){return'\n\n
\n myComp is just a regular tag\n
\n'}),define("examples",["lodash","react","./examples.rt","text!./samples/hello.code","text!./samples/hello.rt","text!./samples/todo.code","text!./samples/todo.rt","text!./samples/rt-if.code","text!./samples/rt-if.rt","text!./samples/rt-props.code","text!./samples/rt-props.rt","text!./samples/rt-repeat.code","text!./samples/rt-repeat.rt","text!./samples/weather.code","text!./samples/weather.rt","text!./samples/rt-require.rt"],function(e,t,n,r,i,s,o,u,a,f,l,c,h,p,d,v){var m={hello:[r,i],todo:[s,o],props:[f,l],rtIf:[u,a],repeat:[c,h],weather:[p,d]};Object.keys(m).forEach(function(t){m[t]={name:t,templateProps:e.template(m[t][0],{name:t}),templateHTML:m[t][1]}});var g=t.createClass({displayName:"Examples",mixins:[t.addons.LinkedStateMixin],getInitialState:function(){var e=window.reactTemplates.convertTemplateToReact(v,{modules:"amd",name:"template"}),t=window.reactTemplates.convertTemplateToReact(v,{modules:"commonjs",name:"template"});return{rtRequire:{value:v},amd:{value:e},cjs:{value:t},samples:m}},render:n});return g}),requirejs.config({paths:{lodash:"//cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.min",jquery:"//code.jquery.com/jquery-1.11.0.min",firebase:"https://cdn.firebase.com/js/client/2.0.5/firebase",react:"//fb.me/react-with-addons-0.12.2",text:"libs/requirejs-plugins/text",json:"libs/requirejs-plugins/json"},shim:{lodash:{exports:"_"},firebase:{exports:"Firebase"},jquery:{exports:"$"},react:{exports:"React"}},map:{"*":{"react/addons":"react"}}}),requirejs(["jquery","react","./examples"],function(e,t,n){var r=t.createElement(n);t.render(r,document.getElementById("home-section"))}),define("home-main.js",function(){}); \ No newline at end of file +(function(e){if(typeof exports=="object"&&typeof module=="object")module.exports=e();else{if(typeof define=="function"&&define.amd)return define("libs/codemirror-4.8/lib/codemirror",[],e);this.CodeMirror=e()}})(function(){function S(e,t){if(!(this instanceof S))return new S(e,t);this.options=t=t?zo(t):{},zo(fi,t,!1),H(t);var n=t.value;typeof n=="string"&&(n=new js(n,t.mode)),this.doc=n;var s=this.display=new x(e,n);s.wrapper.CodeMirror=this,M(this),A(this),t.lineWrapping&&(this.display.wrapper.className+=" CodeMirror-wrap"),t.autofocus&&!d&&er(this),this.state={keyMaps:[],overlays:[],modeGen:0,overwrite:!1,focused:!1,suppressEdits:!1,pasteIncoming:!1,cutIncoming:!1,draggingText:!1,highlight:new Do,keySeq:null},r&&i<11&&setTimeout(Wo(Zn,this,!0),20),rr(this),fu(),kn(this),this.curOp.forceUpdate=!0,Rs(this,n),t.autofocus&&!d||nu()==s.input?setTimeout(Wo(Pr,this),20):Hr(this);for(var o in li)li.hasOwnProperty(o)&&li[o](this,t[o],hi);R(this);for(var u=0;ut.maxLineLength&&(t.maxLineLength=n,t.maxLine=e)})}function H(e){var t=qo(e.gutters,"CodeMirror-linenumbers");t==-1&&e.lineNumbers?e.gutters=e.gutters.concat(["CodeMirror-linenumbers"]):t>-1&&!e.lineNumbers&&(e.gutters=e.gutters.slice(0),e.gutters.splice(t,1))}function B(e){return e.display.scroller.clientHeight-e.display.wrapper.clientHeightt.clientWidth;s&&t.scrollWidth<=t.clientWidth+1&&r>0&&!t.hScrollbarTakesSpace&&(s=!1);var o=i>t.clientHeight;o?(n.scrollbarV.style.display="block",n.scrollbarV.style.bottom=s?r+"px":"0",n.scrollbarV.firstChild.style.height=Math.max(0,i-t.clientHeight+(t.barHeight||n.scrollbarV.clientHeight))+"px"):(n.scrollbarV.style.display="",n.scrollbarV.firstChild.style.height="0"),s?(n.scrollbarH.style.display="block",n.scrollbarH.style.right=o?r+"px":"0",n.scrollbarH.firstChild.style.width=t.scrollWidth-t.clientWidth+(t.barWidth||n.scrollbarH.clientWidth)+"px"):(n.scrollbarH.style.display="",n.scrollbarH.firstChild.style.width="0"),s&&o?(n.scrollbarFiller.style.display="block",n.scrollbarFiller.style.height=n.scrollbarFiller.style.width=r+"px"):n.scrollbarFiller.style.display="",s&&e.options.coverGutterNextToScrollbar&&e.options.fixedGutter?(n.gutterFiller.style.display="block",n.gutterFiller.style.height=r+"px",n.gutterFiller.style.width=n.gutters.offsetWidth+"px"):n.gutterFiller.style.display="";if(!e.state.checkedOverlayScrollbar&&t.clientHeight>0){if(r===0){var u=v&&!c?"12px":"18px";n.scrollbarV.style.minWidth=n.scrollbarH.style.minHeight=u;var a=function(t){mo(t)!=n.scrollbarV&&mo(t)!=n.scrollbarH&&jn(e,ur)(t)};yo(n.scrollbarV,"mousedown",a),yo(n.scrollbarH,"mousedown",a)}e.state.checkedOverlayScrollbar=!0}}function I(e,t,n){var r=n&&n.top!=null?Math.max(0,n.top):e.scroller.scrollTop;r=Math.floor(r-Kt(e));var i=n&&n.bottom!=null?n.bottom:r+e.wrapper.clientHeight,s=$s(t,r),o=$s(t,i);if(n&&n.ensure){var u=n.ensure.from.line,a=n.ensure.to.line;if(u=o)return{from:$s(t,Js(Us(t,a))-e.wrapper.clientHeight),to:a}}return{from:s,to:Math.max(o,s+1)}}function q(e){var t=e.display,n=t.view;if(!t.alignWidgets&&(!t.gutters.firstChild||!e.options.fixedGutter))return;var r=z(t)-t.scroller.scrollLeft+e.doc.scrollLeft,i=t.gutters.offsetWidth,s=r+"px";for(var o=0;o=n.viewFrom&&t.visible.to<=n.viewTo&&(n.updateLineNumbers==null||n.updateLineNumbers>=n.viewTo)&&Jn(e)==0)return!1;R(e)&&(Wn(e),t.dims=Y(e));var i=r.first+r.size,s=Math.max(t.visible.from-e.options.viewportMargin,r.first),o=Math.min(i,t.visible.to+e.options.viewportMargin);n.viewFromo&&n.viewTo-o<20&&(o=Math.min(i,n.viewTo)),E&&(s=rs(e.doc,s),o=is(e.doc,o));var u=s!=n.viewFrom||o!=n.viewTo||n.lastWrapHeight!=t.wrapperHeight||n.lastWrapWidth!=t.wrapperWidth;$n(e,s,o),n.viewOffset=Js(Us(e.doc,n.viewFrom)),e.display.mover.style.top=n.viewOffset+"px";var a=Jn(e);if(!u&&a==0&&!t.force&&(n.updateLineNumbers==null||n.updateLineNumbers>=n.viewTo))return!1;var f=nu();return a>4&&(n.lineDiv.style.display="none"),Z(e,n.updateLineNumbers,t.dims),a>4&&(n.lineDiv.style.display=""),f&&nu()!=f&&f.offsetHeight&&f.focus(),Zo(n.cursorDiv),Zo(n.selectionDiv),u&&(n.lastWrapHeight=t.wrapperHeight,n.lastWrapWidth=t.wrapperWidth,Xt(e,400)),n.updateLineNumbers=null,!0}function V(e,t){var n=t.force,r=t.viewport;for(var i=!0;;i=!1){if(i&&e.options.lineWrapping&&t.oldScrollerWidth!=e.display.scroller.clientWidth)n=!0;else{n=!1,r&&r.top!=null&&(r={top:Math.min(e.doc.height+Qt(e.display)-Lo-e.display.scroller.clientHeight,r.top)}),t.visible=I(e.display,e.doc,r);if(t.visible.from>=e.display.viewFrom&&t.visible.to<=e.display.viewTo)break}if(!X(e,t))break;Q(e);var s=j(e);Rt(e),J(e,s),F(e,s)}So(e,"update",e),(e.display.viewFrom!=t.oldViewFrom||e.display.viewTo!=t.oldViewTo)&&So(e,"viewportChange",e,e.display.viewFrom,e.display.viewTo)}function $(e,t){var n=new W(e,t);if(X(e,n)){Q(e),V(e,n);var r=j(e);Rt(e),J(e,r),F(e,r)}}function J(e,t){e.display.sizer.style.minHeight=e.display.heightForcer.style.top=t.docHeight+"px",e.display.gutters.style.height=Math.max(t.docHeight,t.clientHeight-Lo)+"px"}function K(e,t){e.display.sizer.offsetWidth+e.display.gutters.offsetWidth.001||l<-0.001){Xs(o.line,u),G(o.line);if(o.rest)for(var c=0;c-1&&(d=!1),et(e,h,l,n)),d&&(Zo(h.lineNumber),h.lineNumber.appendChild(document.createTextNode(U(e.options,l)))),u=h.node.nextSibling}l+=h.size}while(u)u=a(u)}function et(e,t,n,r){for(var i=0;i=0){var o=mt(s.from(),i.from()),u=vt(s.to(),i.to()),a=s.empty()?i.from()==i.head:s.from()==s.head;r<=t&&--t,e.splice(--r,2,new yt(a?u:o,a?o:u))}}return new gt(e,t)}function wt(e,t){return new gt([new yt(e,t||e)],0)}function Et(e,t){return Math.max(e.first,Math.min(t,e.first+e.size-1))}function St(e,t){if(t.linen?ht(n,Us(e,n).text.length):xt(t,Us(e,t.line).text.length)}function xt(e,t){var n=e.ch;return n==null||n>t?ht(e.line,t):n<0?ht(e.line,0):e}function Tt(e,t){return t>=e.first&&t=s.ch:f.to>s.ch))){if(r){wo(l,"beforeCursorEnter");if(l.explicitlyCleared){if(!u.markedSpans)break;--a;continue}}if(!l.atomic)continue;var c=l.find(o<0?-1:1);if(pt(c,s)==0){c.ch+=o,c.ch<0?c.line>e.first?c=St(e,ht(c.line-1)):c=null:c.ch>u.text.length&&(c.line3&&(f(d,s.top,null,s.bottom),d=u,s.bottomc.bottom||p.bottom==c.bottom&&p.right>c.right)c=p;d0?t.blinker=setInterval(function(){t.cursorDiv.style.visibility=(n=!n)?"":"hidden"},e.options.cursorBlinkRate):e.options.cursorBlinkRate<0&&(t.cursorDiv.style.visibility="hidden")}function Xt(e,t){e.doc.mode.startState&&e.doc.frontier=e.display.viewTo)return;var n=+(new Date)+e.options.workTime,r=yi(t.mode,Jt(e,t.frontier)),i=[];t.iter(t.frontier,Math.min(t.first+t.size,e.display.viewTo+500),function(s){if(t.frontier>=e.display.viewFrom){var o=s.styles,u=bs(e,s,r,!0);s.styles=u.styles;var a=s.styleClasses,f=u.classes;f?s.styleClasses=f:a&&(s.styleClasses=null);var l=!o||o.length!=s.styles.length||a!=f&&(!a||!f||a.bgClass!=f.bgClass||a.textClass!=f.textClass);for(var c=0;!l&&cn)return Xt(e,e.options.workDelay),!0}),i.length&&Bn(e,function(){for(var t=0;to;--u){if(u<=s.first)return s.first;var a=Us(s,u-1);if(a.stateAfter&&(!n||u<=s.frontier))return u;var f=Po(a.text,null,e.options.tabSize);if(i==null||r>f)i=u-1,r=f}return i}function Jt(e,t,n){var r=e.doc,i=e.display;if(!r.mode.startState)return!0;var s=$t(e,t,n),o=s>r.first&&Us(r,s-1).stateAfter;return o?o=yi(r.mode,o):o=bi(r.mode),r.iter(s,t,function(n){Es(e,n.text,o);var u=s==t-1||s%5==0||s>=i.viewFrom&&s2&&s.push((a.bottom+f.top)/2-n.top)}}s.push(n.bottom-n.top)}}function Zt(e,t,n){if(e.line==t)return{map:e.measure.map,cache:e.measure.cache};for(var r=0;rn)return{map:e.measure.maps[r],cache:e.measure.caches[r],before:!0}}function en(e,t){t=ts(t);var n=Vs(t),r=e.display.externalMeasured=new qn(e.doc,t,n);r.lineN=n;var i=r.built=Ns(e,r);return r.text=i.pre,eu(e.display.lineMeasure,i.pre),r}function tn(e,t,n,r){return sn(e,rn(e,t),n,r)}function nn(e,t){if(t>=e.display.viewFrom&&t=n.lineN&&tn)f=p-h,a=f-1,n>=p&&(l="right");if(a!=null){u=o[c+2],h==p&&s==(u.insertLeft?"left":"right")&&(l=s);if(s=="left"&&a==0)while(c&&o[c-2]==o[c-3]&&o[c-1].insertLeft)u=o[(c-=3)+2],l="left";if(s=="right"&&a==p-h)while(c0&&(l=s="right");var v;e.options.lineWrapping&&(v=u.getClientRects()).length>1?d=v[s=="right"?v.length-1:0]:d=u.getBoundingClientRect()}if(r&&i<9&&!a&&(!d||!d.left&&!d.right)){var m=u.parentNode.getClientRects()[0];m?d={left:m.left,right:m.left+Tn(e.display),top:m.top,bottom:m.bottom}:d=on}var g=d.top-t.rect.top,y=d.bottom-t.rect.top,b=(g+y)/2,w=t.view.measure.heights;for(var c=0;cn.from?o(e-1):o(e,r)}r=r||Us(e.doc,t.line),i||(i=rn(e,r));var a=Ks(r),f=t.ch;if(!a)return o(f);var l=Pu(a,f),c=u(f,l);return Du!=null&&(c.other=u(f,Du)),c}function yn(e,t){var n=0,t=St(e.doc,t);e.options.lineWrapping||(n=Tn(e.display)*t.ch);var r=Us(e.doc,t.line),i=Js(r)+Kt(e.display);return{left:n,right:n,top:i,bottom:i+r.height}}function bn(e,t,n,r){var i=ht(e,t);return i.xRel=r,n&&(i.outside=!0),i}function wn(e,t,n){var r=e.doc;n+=e.display.viewOffset;if(n<0)return bn(r.first,0,!0,-1);var i=$s(r,n),s=r.first+r.size-1;if(i>s)return bn(r.first+r.size-1,Us(r,s).text.length,!0,1);t<0&&(t=0);var o=Us(r,i);for(;;){var u=En(e,o,i,t,n),a=Zi(o),f=a&&a.find(0,!0);if(!a||!(u.ch>f.from.ch||u.ch==f.from.ch&&u.xRel>0))return u;i=Vs(o=f.to.line)}}function En(e,t,n,r,i){function f(r){var i=gn(e,ht(n,r),"line",t,a);return o=!0,s>i.bottom?i.left-u:sm)return bn(n,p,g,1);for(;;){if(l?p==h||p==Bu(t,h,1):p-h<=1){var y=r1?1:0);return w}var E=Math.ceil(c/2),S=h+E;if(l){S=h;for(var x=0;xr){p=S,m=T;if(g=o)m+=1e3;c=E}else h=S,d=T,v=o,c-=E}}function xn(e){if(e.cachedTextHeight!=null)return e.cachedTextHeight;if(Sn==null){Sn=Go("pre");for(var t=0;t<49;++t)Sn.appendChild(document.createTextNode("x")),Sn.appendChild(Go("br"));Sn.appendChild(document.createTextNode("x"))}eu(e.measure,Sn);var n=Sn.offsetHeight/50;return n>3&&(e.cachedTextHeight=n),Zo(e.measure),n||1}function Tn(e){if(e.cachedCharWidth!=null)return e.cachedCharWidth;var t=Go("span","xxxxxxxxxx"),n=Go("pre",[t]);eu(e.measure,n);var r=t.getBoundingClientRect(),i=(r.right-r.left)/10;return i>2&&(e.cachedCharWidth=i),i||10}function kn(e){e.curOp={cm:e,viewChanged:!1,startHeight:e.doc.height,forceUpdate:!1,updateInput:null,typing:!1,changeObjs:null,cursorActivityHandlers:null,cursorActivityCalled:0,selectionChanged:!1,updateMaxLine:!1,scrollLeft:null,scrollTop:null,scrollToPos:null,id:++Cn},Nn?Nn.ops.push(e.curOp):e.curOp.ownsGroup=Nn={ops:[e.curOp],delayedCallbacks:[]}}function Ln(e){var t=e.delayedCallbacks,n=0;do{for(;n=n.viewTo)||n.maxLineChanged&&t.options.lineWrapping,e.update=e.mustUpdate&&new W(t,e.mustUpdate&&{top:e.scrollTop,ensure:e.scrollToPos},e.forceUpdate)}function _n(e){e.updatedDisplay=e.mustUpdate&&X(e.cm,e.update)}function Dn(e){var t=e.cm,n=t.display;e.updatedDisplay&&Q(t),e.barMeasure=j(t),n.maxLineChanged&&!t.options.lineWrapping&&(e.adjustWidthTo=tn(t,n.maxLine,n.maxLine.text.length).left+3,e.maxScrollLeft=Math.max(0,n.sizer.offsetLeft+e.adjustWidthTo+Lo-n.scroller.clientWidth));if(e.updatedDisplay||e.selectionChanged)e.newSelectionNodes=It(t)}function Pn(e){var t=e.cm;e.adjustWidthTo!=null&&(t.display.sizer.style.minWidth=e.adjustWidthTo+"px",e.maxScrollLeft1&&F(t),e.updatedDisplay&&V(t,e.update),n.wheelStartX!=null&&(e.scrollTop!=null||e.scrollLeft!=null||e.scrollToPos)&&(n.wheelStartX=n.wheelStartY=null);if(e.scrollTop!=null&&(n.scroller.scrollTop!=e.scrollTop||e.forceScroll)){var i=Math.max(0,Math.min(n.scroller.scrollHeight-n.scroller.clientHeight,e.scrollTop));n.scroller.scrollTop=n.scrollbarV.scrollTop=r.scrollTop=i}if(e.scrollLeft!=null&&(n.scroller.scrollLeft!=e.scrollLeft||e.forceScroll)){var o=Math.max(0,Math.min(n.scroller.scrollWidth-n.scroller.clientWidth,e.scrollLeft));n.scroller.scrollLeft=n.scrollbarH.scrollLeft=r.scrollLeft=o,q(t)}if(e.scrollToPos){var u=Yr(t,St(r,e.scrollToPos.from),St(r,e.scrollToPos.to),e.scrollToPos.margin);e.scrollToPos.isCursor&&t.state.focused&&Gr(t,u)}var a=e.maybeHiddenMarkers,f=e.maybeUnhiddenMarkers;if(a)for(var l=0;le.barMeasure.clientWidth&&e.barMeasure.scrollWidtht)&&(i.updateLineNumbers=t),e.curOp.viewChanged=!0;if(t>=i.viewTo)E&&rs(e.doc,t)i.viewFrom?Wn(e):(i.viewFrom+=r,i.viewTo+=r);else if(t<=i.viewFrom&&n>=i.viewTo)Wn(e);else if(t<=i.viewFrom){var s=Vn(e,n,n+r,1);s?(i.view=i.view.slice(s.index),i.viewFrom=s.lineN,i.viewTo+=r):Wn(e)}else if(n>=i.viewTo){var s=Vn(e,t,t,-1);s?(i.view=i.view.slice(0,s.index),i.viewTo=s.lineN):Wn(e)}else{var o=Vn(e,t,t,-1),u=Vn(e,n,n+r,1);o&&u?(i.view=i.view.slice(0,o.index).concat(Rn(e,o.lineN,u.lineN)).concat(i.view.slice(u.index)),i.viewTo+=r):Wn(e)}var a=i.externalMeasured;a&&(n=i.lineN&&t=r.viewTo)return;var s=r.view[Xn(e,t)];if(s.node==null)return;var o=s.changes||(s.changes=[]);qo(o,n)==-1&&o.push(n)}function Wn(e){e.display.viewFrom=e.display.viewTo=e.doc.first,e.display.view=[],e.display.viewOffset=0}function Xn(e,t){if(t>=e.display.viewTo)return null;t-=e.display.viewFrom;if(t<0)return null;var n=e.display.view;for(var r=0;r0){if(i==o.length-1)return null;s=a+o[i].size-t,i++}else s=a-t;t+=s,n+=s}while(rs(e.doc,n)!=n){if(i==(r<0?0:o.length-1))return null;n+=r*o[i-(r<0?1:0)].size,i+=r}return{index:i,lineN:n}}function $n(e,t,n){var r=e.display,i=r.view;i.length==0||t>=r.viewTo||n<=r.viewFrom?(r.view=Rn(e,t,n),r.viewFrom=t):(r.viewFrom>t?r.view=Rn(e,t,r.viewFrom).concat(r.view):r.viewFromn&&(r.view=r.view.slice(0,Xn(e,n)))),r.viewTo=n}function Jn(e){var t=e.display.view,n=0;for(var r=0;r=9&&e.display.inputHasSelection===o||v&&/[\uf700-\uf7ff]/.test(o))return Zn(e),!1;var u=!e.curOp;u&&kn(e),e.display.shift=!1,o.charCodeAt(0)==8203&&s.sel==e.display.selForContextMenu&&!n&&(n="​");var a=0,f=Math.min(n.length,o.length);while(a1&&(Gn&&Gn.join("\n")==l?h=s.sel.ranges.length%Gn.length==0&&Ro(Gn,yu):c.length==s.sel.ranges.length&&(h=Ro(c,function(e){return[e]})));for(var p=s.sel.ranges.length-1;p>=0;p--){var d=s.sel.ranges[p],m=d.from(),g=d.to();a-1){ii(e,E.line,"smart");break}}else w.electricInput&&w.electricInput.test(Us(s,E.line).text.slice(0,E.ch))&&ii(e,E.line,"smart")}}return ni(e),e.curOp.updateInput=y,e.curOp.typing=!0,o.length>1e3||o.indexOf("\n")>-1?t.value=e.display.prevInput="":e.display.prevInput=o,u&&An(e),e.state.pasteIncoming=e.state.cutIncoming=!1,!0}function Zn(e,t){var n,s,o=e.doc;if(e.somethingSelected()){e.display.prevInput="";var u=o.sel.primary();n=wu&&(u.to().line-u.from().line>100||(s=e.getSelection()).length>1e3);var a=n?"-":s||e.getSelection();e.display.input.value=a,e.state.focused&&Io(e.display.input),r&&i>=9&&(e.display.inputHasSelection=a)}else t||(e.display.prevInput=e.display.input.value="",r&&i>=9&&(e.display.inputHasSelection=null));e.display.inaccurateSelection=n}function er(e){e.options.readOnly!="nocursor"&&(!d||nu()!=e.display.input)&&e.display.input.focus()}function tr(e){e.state.focused||(er(e),Pr(e))}function nr(e){return e.options.readOnly||e.doc.cantEdit}function rr(e){function n(){e.state.focused&&setTimeout(Wo(er,e),0)}function o(t){To(e,t)||vo(t)}function u(n){if(e.somethingSelected())Gn=e.getSelections(),t.inaccurateSelection&&(t.prevInput="",t.inaccurateSelection=!1,t.input.value=Gn.join("\n"),Io(t.input));else{var r=[],i=[];for(var s=0;s=9&&e.display.inputHasSelection&&(e.display.inputHasSelection=null),Qn(e)}),yo(t.input,"keydown",jn(e,Or)),yo(t.input,"keypress",jn(e,Dr)),yo(t.input,"focus",Wo(Pr,e)),yo(t.input,"blur",Wo(Hr,e)),e.options.dragDrop&&(yo(t.scroller,"dragstart",function(t){gr(e,t)}),yo(t.scroller,"dragenter",o),yo(t.scroller,"dragover",o),yo(t.scroller,"drop",jn(e,mr))),yo(t.scroller,"paste",function(n){if(sr(t,n))return;e.state.pasteIncoming=!0,er(e),Qn(e)}),yo(t.input,"paste",function(){if(s&&!e.state.fakedLastChar&&!(new Date-e.state.lastMiddleDown<200)){var n=t.input.selectionStart,r=t.input.selectionEnd;t.input.value+="$",t.input.selectionEnd=r,t.input.selectionStart=n,e.state.fakedLastChar=!0}e.state.pasteIncoming=!0,Qn(e)}),yo(t.input,"cut",u),yo(t.input,"copy",u),l&&yo(t.sizer,"mouseup",function(){nu()==t.input&&t.input.blur(),er(e)})}function ir(e){var t=e.display;if(t.lastWrapHeight==t.wrapper.clientHeight&&t.lastWrapWidth==t.wrapper.clientWidth)return;t.cachedCharWidth=t.cachedTextHeight=t.cachedPaddingH=null,e.setSize()}function sr(e,t){for(var n=mo(t);n!=e.wrapper;n=n.parentNode)if(!n||n.ignoreEvents||n.parentNode==e.sizer&&n!=e.mover)return!0}function or(e,t,n,r){var i=e.display;if(!n){var s=mo(t);if(s==i.scrollbarH||s==i.scrollbarV||s==i.scrollbarFiller||s==i.gutterFiller)return null}var o,u,a=i.lineSpace.getBoundingClientRect();try{o=t.clientX-a.left,u=t.clientY-a.top}catch(t){return null}var f=wn(e,o,u),l;if(r&&f.xRel==1&&(l=Us(e.doc,f.line).text).length==f.ch){var c=Po(l,l.length,e.options.tabSize)-l.length;f=ht(f.line,Math.max(0,Math.round((o-Gt(e.display).left)/Tn(e.display))-c))}return f}function ur(e){if(To(this,e))return;var t=this,n=t.display;n.shift=e.shiftKey;if(sr(n,e)){s||(n.scroller.draggable=!1,setTimeout(function(){n.scroller.draggable=!0},100));return}if(dr(t,e))return;var r=or(t,e);window.focus();switch(go(e)){case 1:r?lr(t,e,r):mo(e)==n.scroller&&co(e);break;case 2:s&&(t.state.lastMiddleDown=+(new Date)),r&&kt(t.doc,r),setTimeout(Wo(er,t),20),co(e);break;case 3:b&&Br(t,e)}}function lr(e,t,n){setTimeout(Wo(tr,e),0);var r=+(new Date),i;fr&&fr.time>r-400&&pt(fr.pos,n)==0?i="triple":ar&&ar.time>r-400&&pt(ar.pos,n)==0?(i="double",fr={time:r,pos:n}):(i="single",ar={time:r,pos:n});var s=e.doc.sel,o=v?t.metaKey:t.ctrlKey;e.options.dragDrop&&cu&&!nr(e)&&i=="single"&&s.contains(n)>-1&&s.somethingSelected()?cr(e,t,n,o):hr(e,t,n,i,o)}function cr(e,t,n,o){var u=e.display,a=jn(e,function(f){s&&(u.scroller.draggable=!1),e.state.draggingText=!1,bo(document,"mouseup",a),bo(u.scroller,"drop",a),Math.abs(t.clientX-f.clientX)+Math.abs(t.clientY-f.clientY)<10&&(co(f),o||kt(e.doc,n),er(e),r&&i==9&&setTimeout(function(){document.body.focus(),er(e)},20))});s&&(u.scroller.draggable=!0),e.state.draggingText=a,u.scroller.dragDrop&&u.scroller.dragDrop(),yo(document,"mouseup",a),yo(u.scroller,"drop",a)}function hr(e,t,n,r,i){function p(t){if(pt(h,t)==0)return;h=t;if(r=="rect"){var i=[],s=e.options.tabSize,l=Po(Us(o,n.line).text,n.ch,s),c=Po(Us(o,t.line).text,t.ch,s),p=Math.min(l,c),d=Math.max(l,c);for(var v=Math.min(n.line,t.line),m=Math.min(e.lastLine(),Math.max(n.line,t.line));v<=m;v++){var g=Us(o,v).text,y=Ho(g,p,s);p==d?i.push(new yt(ht(v,y),ht(v,y))):g.length>y&&i.push(new yt(ht(v,y),ht(v,Ho(g,d,s))))}i.length||i.push(new yt(n,n)),Dt(o,bt(f.ranges.slice(0,a).concat(i),a),{origin:"*mouse",scroll:!1}),e.scrollIntoView(t)}else{var b=u,w=b.anchor,E=t;if(r!="single"){if(r=="double")var S=e.findWordAt(t);else var S=new yt(ht(t.line,0),St(o,ht(t.line+1,0)));pt(S.anchor,w)>0?(E=S.head,w=mt(b.from(),S.anchor)):(E=S.anchor,w=vt(b.to(),S.head))}var i=f.ranges.slice(0);i[a]=new yt(St(o,w),E),Dt(o,bt(i,a),Mo)}}function m(t){var n=++v,i=or(e,t,!0,r=="rect");if(!i)return;if(pt(i,h)!=0){tr(e),p(i);var u=I(s,o);(i.line>=u.to||i.lined.bottom?20:0;a&&setTimeout(jn(e,function(){if(v!=n)return;s.scroller.scrollTop+=a,m(t)}),50)}}function g(t){v=Infinity,co(t),er(e),bo(document,"mousemove",y),bo(document,"mouseup",b),o.history.lastSelOrigin=null}var s=e.display,o=e.doc;co(t);var u,a,f=o.sel;i&&!t.shiftKey?(a=o.sel.contains(n),a>-1?u=o.sel.ranges[a]:u=new yt(n,n)):u=o.sel.primary();if(t.altKey)r="rect",i||(u=new yt(n,n)),n=or(e,t,!0,!0),a=-1;else if(r=="double"){var l=e.findWordAt(n);e.display.shift||o.extend?u=Ct(o,u,l.anchor,l.head):u=l}else if(r=="triple"){var c=new yt(ht(n.line,0),St(o,ht(n.line+1,0)));e.display.shift||o.extend?u=Ct(o,u,c.anchor,c.head):u=c}else u=Ct(o,u,n);i?a>-1?At(o,a,u,Mo):(a=o.sel.ranges.length,Dt(o,bt(o.sel.ranges.concat([u]),a),{scroll:!1,origin:"*mouse"})):(a=0,Dt(o,new gt([u],0),Mo),f=o.sel);var h=n,d=s.wrapper.getBoundingClientRect(),v=0,y=jn(e,function(e){go(e)?m(e):g(e)}),b=jn(e,g);yo(document,"mousemove",y),yo(document,"mouseup",b)}function pr(e,t,n,r,i){try{var s=t.clientX,o=t.clientY}catch(t){return!1}if(s>=Math.floor(e.display.gutters.getBoundingClientRect().right))return!1;r&&co(t);var u=e.display,a=u.lineDiv.getBoundingClientRect();if(o>a.bottom||!Co(e,n))return po(t);o-=a.top-u.viewOffset;for(var f=0;f=s){var c=$s(e.doc,o),h=e.options.gutters[f];return i(e,n,e,c,h,t),po(t)}}}function dr(e,t){return pr(e,t,"gutterClick",!0,So)}function mr(e){var t=this;if(To(t,e)||sr(t.display,e))return;co(e),r&&(vr=+(new Date));var n=or(t,e,!0),i=e.dataTransfer.files;if(!n||nr(t))return;if(i&&i.length&&window.FileReader&&window.File){var s=i.length,o=Array(s),u=0,a=function(e,r){var i=new FileReader;i.onload=jn(t,function(){o[r]=i.result;if(++u==s){n=St(t.doc,n);var e={from:n,to:n,text:yu(o.join("\n")),origin:"paste"};Wr(t.doc,e),_t(t.doc,wt(n,Fr(e)))}}),i.readAsText(e)};for(var f=0;f-1){t.state.draggingText(e),setTimeout(Wo(er,t),20);return}try{var o=e.dataTransfer.getData("Text");if(o){if(t.state.draggingText&&(v?!e.metaKey:!e.ctrlKey))var l=t.listSelections();Pt(t.doc,wt(n,n));if(l)for(var f=0;fu.clientWidth||i&&u.scrollHeight>u.clientHeight))return;if(i&&v&&s)e:for(var f=n.target,l=o.view;f!=u;f=f.parentNode)for(var c=0;c=9&&(t.display.inputHasSelection=null),Qn(t)}function Pr(e){if(e.options.readOnly=="nocursor")return;e.state.focused||(wo(e,"focus",e),e.state.focused=!0,su(e.display.wrapper,"CodeMirror-focused"),!e.curOp&&e.display.selForContextMenu!=e.doc.sel&&(Zn(e),s&&setTimeout(Wo(Zn,e,!0),0))),Kn(e),Wt(e)}function Hr(e){e.state.focused&&(wo(e,"blur",e),e.state.focused=!1,iu(e.display.wrapper,"CodeMirror-focused")),clearInterval(e.display.blinker),setTimeout(function(){e.state.focused||(e.display.shift=!1)},150)}function Br(e,t){function h(){if(n.input.selectionStart!=null){var t=e.somethingSelected(),r=n.input.value="​"+(t?n.input.value:"");n.prevInput=t?"":"​",n.input.selectionStart=1,n.input.selectionEnd=r.length,n.selForContextMenu=e.doc.sel}}function p(){n.inputDiv.style.position="relative",n.input.style.cssText=l,r&&i<9&&(n.scrollbarV.scrollTop=n.scroller.scrollTop=u),Kn(e);if(n.input.selectionStart!=null){(!r||r&&i<9)&&h();var t=0,s=function(){n.selForContextMenu==e.doc.sel&&n.input.selectionStart==0?jn(e,wi.selectAll)(e):t++<10?n.detectingSelectAll=setTimeout(s,500):Zn(e)};n.detectingSelectAll=setTimeout(s,200)}}if(To(e,t,"contextmenu"))return;var n=e.display;if(sr(n,t)||jr(e,t))return;var o=or(e,t),u=n.scroller.scrollTop;if(!o||a)return;var f=e.options.resetSelectionOnContextMenu;f&&e.doc.sel.contains(o)==-1&&jn(e,Dt)(e.doc,wt(o),Oo);var l=n.input.style.cssText;n.inputDiv.style.position="absolute",n.input.style.cssText="position: fixed; width: 30px; height: 30px; top: "+(t.clientY-5)+"px; left: "+(t.clientX-5)+"px; z-index: 1000; background: "+(r?"rgba(255, 255, 255, .05)":"transparent")+"; outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);";if(s)var c=window.scrollY;er(e),s&&window.scrollTo(null,c),Zn(e),e.somethingSelected()||(n.input.value=n.prevInput=" "),n.selForContextMenu=e.doc.sel,clearTimeout(n.detectingSelectAll),r&&i>=9&&h();if(b){vo(t);var d=function(){bo(window,"mouseup",d),setTimeout(p,20)};yo(window,"mouseup",d)}else setTimeout(p,50)}function jr(e,t){return Co(e,"gutterContextMenu")?pr(e,t,"gutterContextMenu",!1,wo):!1}function Ir(e,t){if(pt(e,t.from)<0)return e;if(pt(e,t.to)<=0)return Fr(t);var n=e.line+t.text.length-(t.to.line-t.from.line)-1,r=e.ch;return e.line==t.to.line&&(r+=Fr(t).ch-t.to.ch),ht(n,r)}function qr(e,t){var n=[];for(var r=0;r=0;--i)Xr(e,{from:r[i].from,to:r[i].to,text:i?[""]:t.text});else Xr(e,t)}function Xr(e,t){if(t.text.length==1&&t.text[0]==""&&pt(t.from,t.to)==0)return;var n=qr(e,t);eo(e,t,n,e.cm?e.cm.curOp.id:NaN),Jr(e,t,n,Ui(e,t));var r=[];qs(e,function(e,n){!n&&qo(r,e.history)==-1&&(lo(e.history,t),r.push(e.history)),Jr(e,t,null,Ui(e,t))})}function Vr(e,t,n){if(e.cm&&e.cm.state.suppressEdits)return;var r=e.history,i,s=e.sel,o=t=="undo"?r.done:r.undone,u=t=="undo"?r.undone:r.done;for(var a=0;a=0;--a){var c=i.changes[a];c.origin=t;if(l&&!zr(e,c,!1)){o.length=0;return}f.push(Gs(e,c));var h=a?qr(e,c):Fo(o);Jr(e,c,h,Wi(e,c)),!a&&e.cm&&e.cm.scrollIntoView({from:c.from,to:Fr(c)});var p=[];qs(e,function(e,t){!t&&qo(p,e.history)==-1&&(lo(e.history,c),p.push(e.history)),Jr(e,c,null,Wi(e,c))})}}function $r(e,t){if(t==0)return;e.first+=t,e.sel=new gt(Ro(e.sel.ranges,function(e){return new yt(ht(e.anchor.line+t,e.anchor.ch),ht(e.head.line+t,e.head.ch))}),e.sel.primIndex);if(e.cm){Un(e.cm,e.first,e.first-t,t);for(var n=e.cm.display,r=n.viewFrom;re.lastLine())return;if(t.from.lines&&(t={from:t.from,to:ht(s,Us(e,s).text.length),text:[t.text[0]],origin:t.origin}),t.removed=zs(e,t.from,t.to),n||(n=qr(e,t)),e.cm?Kr(e.cm,t,r):Ds(e,t,r),Pt(e,n,Oo)}function Kr(e,t,n){var r=e.doc,i=e.display,s=t.from,o=t.to,u=!1,a=s.line;e.options.lineWrapping||(a=Vs(ts(Us(r,s.line))),r.iter(a,o.line+1,function(e){if(e==i.maxLine)return u=!0,!0})),r.sel.contains(t.from,t.to)>-1&&No(e),Ds(r,t,n,k(e)),e.options.lineWrapping||(r.iter(a,s.line+t.text.length,function(e){var t=D(e);t>i.maxLineLength&&(i.maxLine=e,i.maxLineLength=t,i.maxLineChanged=!0,u=!1)}),u&&(e.curOp.updateMaxLine=!0)),r.frontier=Math.min(r.frontier,s.line),Xt(e,400);var f=t.text.length-(o.line-s.line)-1;s.line==o.line&&t.text.length==1&&!_s(e.doc,t)?zn(e,s.line,"text"):Un(e,s.line,o.line+1,f);var l=Co(e,"changes"),c=Co(e,"change");if(c||l){var h={from:s,to:o,text:t.text,removed:t.removed,origin:t.origin};c&&So(e,"change",e,h),l&&(e.curOp.changeObjs||(e.curOp.changeObjs=[])).push(h)}e.display.selForContextMenu=null}function Qr(e,t,n,r,i){r||(r=n);if(pt(r,n)<0){var s=r;r=n,n=s}typeof t=="string"&&(t=yu(t)),Wr(e,{from:n,to:r,text:t,origin:i})}function Gr(e,t){if(To(e,"scrollCursorIntoView"))return;var n=e.display,r=n.sizer.getBoundingClientRect(),i=null;t.top+r.top<0?i=!0:t.bottom+r.top>(window.innerHeight||document.documentElement.clientHeight)&&(i=!1);if(i!=null&&!h){var s=Go("div","​",null,"position: absolute; top: "+(t.top-n.viewOffset-Kt(e.display))+"px; height: "+(t.bottom-t.top+Lo)+"px; left: "+t.left+"px; width: 2px;");e.display.lineSpace.appendChild(s),s.scrollIntoView(i),e.display.lineSpace.removeChild(s)}}function Yr(e,t,n,r){r==null&&(r=0);for(var i=0;i<5;i++){var s=!1,o=gn(e,t),u=!n||n==t?o:gn(e,n),a=ei(e,Math.min(o.left,u.left),Math.min(o.top,u.top)-r,Math.max(o.left,u.left),Math.max(o.bottom,u.bottom)+r),f=e.doc.scrollTop,l=e.doc.scrollLeft;a.scrollTop!=null&&(yr(e,a.scrollTop),Math.abs(e.doc.scrollTop-f)>1&&(s=!0)),a.scrollLeft!=null&&(br(e,a.scrollLeft),Math.abs(e.doc.scrollLeft-l)>1&&(s=!0));if(!s)return o}}function Zr(e,t,n,r,i){var s=ei(e,t,n,r,i);s.scrollTop!=null&&yr(e,s.scrollTop),s.scrollLeft!=null&&br(e,s.scrollLeft)}function ei(e,t,n,r,i){var s=e.display,o=xn(e.display);n<0&&(n=0);var u=e.curOp&&e.curOp.scrollTop!=null?e.curOp.scrollTop:s.scroller.scrollTop,a=s.scroller.clientHeight-Lo,f={};i-n>a&&(i=n+a);var l=e.doc.height+Qt(s),c=nl-o;if(nu+a){var p=Math.min(n,(h?l:i)-a);p!=u&&(f.scrollTop=p)}var d=e.curOp&&e.curOp.scrollLeft!=null?e.curOp.scrollLeft:s.scroller.scrollLeft,v=s.scroller.clientWidth-Lo-s.gutters.offsetWidth,m=r-t>v;return m&&(r=t+v),t<10?f.scrollLeft=0:tv+d-3&&(f.scrollLeft=r+(m?0:10)-v),f}function ti(e,t,n){(t!=null||n!=null)&&ri(e),t!=null&&(e.curOp.scrollLeft=(e.curOp.scrollLeft==null?e.doc.scrollLeft:e.curOp.scrollLeft)+t),n!=null&&(e.curOp.scrollTop=(e.curOp.scrollTop==null?e.doc.scrollTop:e.curOp.scrollTop)+n)}function ni(e){ri(e);var t=e.getCursor(),n=t,r=t;e.options.lineWrapping||(n=t.ch?ht(t.line,t.ch-1):t,r=ht(t.line,t.ch+1)),e.curOp.scrollToPos={from:n,to:r,margin:e.options.cursorScrollMargin,isCursor:!0}}function ri(e){var t=e.curOp.scrollToPos;if(t){e.curOp.scrollToPos=null;var n=yn(e,t.from),r=yn(e,t.to),i=ei(e,Math.min(n.left,r.left),Math.min(n.top,r.top)-t.margin,Math.max(n.right,r.right),Math.max(n.bottom,r.bottom)+t.margin);e.scrollTo(i.scrollLeft,i.scrollTop)}}function ii(e,t,n,r){var i=e.doc,s;n==null&&(n="add"),n=="smart"&&(i.mode.indent?s=Jt(e,t):n="prev");var o=e.options.tabSize,u=Us(i,t),a=Po(u.text,null,o);u.stateAfter&&(u.stateAfter=null);var f=u.text.match(/^\s*/)[0],l;if(!r&&!/\S/.test(u.text))l=0,n="not";else if(n=="smart"){l=i.mode.indent(s,u.text.slice(f.length),u.text);if(l==Ao||l>150){if(!r)return;n="prev"}}n=="prev"?t>i.first?l=Po(Us(i,t-1).text,null,o):l=0:n=="add"?l=a+e.options.indentUnit:n=="subtract"?l=a-e.options.indentUnit:typeof n=="number"&&(l=a+n),l=Math.max(0,l);var c="",h=0;if(e.options.indentWithTabs)for(var p=Math.floor(l/o);p;--p)h+=o,c+=" ";h=0;t--)Qr(e.doc,"",r[t].from,r[t].to,"+delete");ni(e)})}function ui(e,t,n,r,i){function l(){var t=s+n;return t=e.first+e.size?f=!1:(s=t,a=Us(e,t))}function c(e){var t=(i?Bu:ju)(a,o,n,!0);if(t==null){if(!!e||!l())return f=!1;i?o=(n<0?Lu:ku)(a):o=n<0?a.text.length:0}else o=t;return!0}var s=t.line,o=t.ch,u=n,a=Us(e,s),f=!0;if(r=="char")c();else if(r=="column")c(!0);else if(r=="word"||r=="group"){var h=null,p=r=="group",d=e.cm&&e.cm.getHelper(t,"wordChars");for(var v=!0;;v=!1){if(n<0&&!c(!v))break;var m=a.text.charAt(o)||"\n",g=$o(m,d)?"w":p&&m=="\n"?"n":!p||/\s/.test(m)?null:"p";p&&!v&&!g&&(g="s");if(h&&h!=g){n<0&&(n=1,c());break}g&&(h=g);if(n>0&&!c(!v))break}}var y=Ft(e,ht(s,o),u,!0);return f||(y.hitSide=!0),y}function ai(e,t,n,r){var i=e.doc,s=t.left,o;if(r=="page"){var u=Math.min(e.display.wrapper.clientHeight,window.innerHeight||document.documentElement.clientHeight);o=t.top+n*(u-(n<0?1.5:.5)*xn(e.display))}else r=="line"&&(o=n>0?t.bottom+3:t.top-3);for(;;){var a=wn(e,s,o);if(!a.outside)break;if(n<0?o<=0:o>=i.height){a.hitSide=!0;break}o+=n*5}return a}function ci(e,t,n,r){S.defaults[e]=t,n&&(li[e]=r?function(e,t,r){r!=hi&&n(e,t,r)}:n)}function Si(e){var t=e.split(/-(?!$)/),e=t[t.length-1],n,r,i,s;for(var o=0;o0||o==0&&s.clearWhenEmpty!==!1)return s;s.replacedWith&&(s.collapsed=!0,s.widgetNode=Go("span",[s.replacedWith],"CodeMirror-widget"),r.handleMouseEvents||(s.widgetNode.ignoreEvents=!0),r.insertLeft&&(s.widgetNode.insertLeft=!0));if(s.collapsed){if(es(e,t.line,t,n,s)||t.line!=n.line&&es(e,n.line,t,n,s))throw new Error("Inserting collapsed marker partially overlapping an existing one");E=!0}s.addToHistory&&eo(e,{from:t,to:n,origin:"markText"},e.sel,NaN);var u=t.line,a=e.cm,f;e.iter(u,n.line+1,function(e){a&&s.collapsed&&!a.options.lineWrapping&&ts(e)==a.display.maxLine&&(f=!0),s.collapsed&&u!=t.line&&Xs(e,0),Ii(e,new Bi(s,u==t.line?t.ch:null,u==n.line?n.ch:null)),++u}),s.collapsed&&e.iter(t.line,n.line+1,function(t){ss(e,t)&&Xs(t,0)}),s.clearOnEnter&&yo(s,"beforeCursorEnter",function(){s.clear()}),s.readOnly&&(w=!0,(e.history.done.length||e.history.undone.length)&&e.clearHistory()),s.collapsed&&(s.id=++Ai,s.atomic=!0);if(a){f&&(a.curOp.updateMaxLine=!0);if(s.collapsed)Un(a,t.line,n.line+1);else if(s.className||s.title||s.startStyle||s.endStyle)for(var l=t.line;l<=n.line;l++)zn(a,l,"text");s.atomic&&Bt(a.doc),So(a,"markerAdded",a,s)}return s}function _i(e,t,n,r,i){r=zo(r),r.shared=!1;var s=[Oi(e,t,n,r,i)],o=s[0],u=r.widgetNode;return qs(e,function(e){u&&(r.widgetNode=u.cloneNode(!0)),s.push(Oi(e,St(e,t),St(e,n),r,i));for(var a=0;a=t:s.to>t);(i||(i=[])).push(new Bi(o,s.from,a?null:s.to))}}return i}function Ri(e,t,n){if(e)for(var r=0,i;r=t:s.to>t);if(u||s.from==t&&o.type=="bookmark"&&(!n||s.marker.insertLeft)){var a=s.from==null||(o.inclusiveLeft?s.from<=t:s.from0&&u)for(var c=0;c0)continue;var l=[a,1],c=pt(f.from,u.from),h=pt(f.to,u.to);(c<0||!o.inclusiveLeft&&!c)&&l.push({from:f.from,to:u.from}),(h>0||!o.inclusiveRight&&!h)&&l.push({from:u.to,to:f.to}),i.splice.apply(i,l),a+=l.length-1}}return i}function Vi(e){var t=e.markedSpans;if(!t)return;for(var n=0;n=0&&c<=0||l<=0&&c>=0)continue;if(l<=0&&(pt(f.to,n)>0||a.marker.inclusiveRight&&i.inclusiveLeft)||l>=0&&(pt(f.from,r)<0||a.marker.inclusiveLeft&&i.inclusiveRight))return!0}}function ts(e){var t;while(t=Yi(e))e=t.find(-1,!0).line;return e}function ns(e){var t,n;while(t=Zi(e))e=t.find(1,!0).line,(n||(n=[])).push(e);return n}function rs(e,t){var n=Us(e,t),r=ts(n);return n==r?t:Vs(r)}function is(e,t){if(t>e.lastLine())return t;var n=Us(e,t),r;if(!ss(e,n))return t;while(r=Zi(n))n=r.find(1,!0).line;return Vs(n)+1}function ss(e,t){var n=E&&t.markedSpans;if(n)for(var r,i=0;it.start)return s}throw new Error("Mode "+e.name+" failed to advance stream.")}function gs(e,t,n,r){function i(e){return{start:l.start,end:l.pos,string:l.current(),type:u||null,state:e?yi(s.mode,f):f}}var s=e.doc,o=s.mode,u;t=St(s,t);var a=Us(s,t.line),f=Jt(e,t.line,n),l=new ki(a.text,e.options.tabSize),c;r&&(c=[]);while((r||l.pose.options.maxHighlightLength?(u=!1,o&&Es(e,t,r,l.pos),l.pos=t.length,c=null):c=ds(ms(n,l,r,h),s);if(h){var p=h[0].name;p&&(c="m-"+(c?p+" "+c:p))}if(!u||f!=c)ae&&i.splice(a,1,e,i[a+1],r),a+=2,f=Math.min(e,r)}if(!t)return;if(u.opaque)i.splice(n,a-n,e,"cm-overlay "+t),a=n+2;else for(;na&&c.from<=a)break}if(c.to>=f)return e(n,r,i,s,o,u);e(n,r.slice(0,c.to-a),i,s,null,u),s=null,r=r.slice(c.to-a),a=c.to}}}function Os(e,t,n,r){var i=!r&&n.widgetNode;i&&(e.map.push(e.pos,e.pos+t,i),e.content.appendChild(i)),e.pos+=t}function Ms(e,t,n){var r=e.markedSpans,i=e.text,s=0;if(!r){for(var o=1;oa)?(b.to!=null&&c>b.to&&(c=b.to,p=""),w.className&&(h+=" "+w.className),w.startStyle&&b.from==a&&(d+=" "+w.startStyle),w.endStyle&&b.to==c&&(p+=" "+w.endStyle),w.title&&!v&&(v=w.title),w.collapsed&&(!m||Qi(m.marker,w)<0)&&(m=b)):b.from>a&&c>b.from&&(c=b.from),w.type=="bookmark"&&b.from==a&&w.widgetNode&&g.push(w)}if(m&&(m.from||0)==a){Os(t,(m.to==null?u+1:m.to)-a,m.marker,m.from==null);if(m.to==null)return}if(!m&&g.length)for(var y=0;y=u)break;var E=Math.min(u,c);for(;;){if(f){var S=a+f.length;if(!m){var x=S>E?f.slice(0,E-a):f;t.addToken(t,x,l?l+h:h,d,a+x.length==c?p:"",v)}if(S>=E){f=f.slice(E-a),a=E;break}a=S,d=""}f=i.slice(s,s=n[o++]),l=Ts(n[o++],t.cm.options)}}}function _s(e,t){return t.from.ch==0&&t.to.ch==0&&Fo(t.text)==""&&(!e.cm||e.cm.options.wholeLineUpdateBefore)}function Ds(e,t,n,r){function i(e){return n?n[e]:null}function s(e,n,i){hs(e,n,i,r),So(e,"change",e,t)}var o=t.from,u=t.to,a=t.text,f=Us(e,o.line),l=Us(e,u.line),c=Fo(a),h=i(a.length-1),p=u.line-o.line;if(_s(e,t)){for(var d=0,v=[];d1&&e.remove(o.line+1,p-1),e.insert(o.line+1,v)}So(e,"change",e,t)}function Ps(e){this.lines=e,this.parent=null;for(var t=0,n=0;t=e.size)throw new Error("There is no line "+(t+e.first)+" in the document.");for(var n=e;!n.lines;)for(var r=0;;++r){var i=n.children[r],s=i.chunkSize();if(t1&&!e.done[e.done.length-2].ranges)return e.done.pop(),Fo(e.done)}function eo(e,t,n,r){var i=e.history;i.undone.length=0;var s=+(new Date),o;if((i.lastOp==r||i.lastOrigin==t.origin&&t.origin&&(t.origin.charAt(0)=="+"&&e.cm&&i.lastModTime>s-e.cm.options.historyEventDelay||t.origin.charAt(0)=="*"))&&(o=Zs(i,i.lastOp==r))){var u=Fo(o.changes);pt(t.from,t.to)==0&&pt(t.from,u.to)==0?u.to=Fr(t):o.changes.push(Gs(e,t))}else{var a=Fo(i.done);(!a||!a.ranges)&&ro(e.sel,i.done),o={changes:[Gs(e,t)],generation:i.generation},i.done.push(o);while(i.done.length>i.undoDepth)i.done.shift(),i.done[0].ranges||i.done.shift()}i.done.push(n),i.generation=++i.maxGeneration,i.lastModTime=i.lastSelTime=s,i.lastOp=i.lastSelOp=r,i.lastOrigin=i.lastSelOrigin=t.origin,u||wo(e,"historyAdded")}function to(e,t,n,r){var i=t.charAt(0);return i=="*"||i=="+"&&n.ranges.length==r.ranges.length&&n.somethingSelected()==r.somethingSelected()&&new Date-e.history.lastSelTime<=(e.cm?e.cm.options.historyEventDelay:500)}function no(e,t,n,r){var i=e.history,s=r&&r.origin;n==i.lastSelOp||s&&i.lastSelOrigin==s&&(i.lastModTime==i.lastSelTime&&i.lastOrigin==s||to(e,s,Fo(i.done),t))?i.done[i.done.length-1]=t:ro(t,i.done),i.lastSelTime=+(new Date),i.lastSelOrigin=s,i.lastSelOp=n,r&&r.clearRedo!==!1&&Ys(i.undone)}function ro(e,t){var n=Fo(t);n&&n.ranges&&n.equals(e)||t.push(e)}function io(e,t,n,r){var i=t["spans_"+e.id],s=0;e.iter(Math.max(e.first,n),Math.min(e.first+e.size,r),function(n){n.markedSpans&&((i||(i=t["spans_"+e.id]={}))[s]=n.markedSpans),++s})}function so(e){if(!e)return null;for(var t=0,n;t-1&&(Fo(u)[c]=f[c],delete f[c])}}return i}function ao(e,t,n,r){n0}function ko(e){e.prototype.on=function(e,t){yo(this,e,t)},e.prototype.off=function(e,t){bo(this,e,t)}}function Do(){this.id=null}function Ho(e,t,n){for(var r=0,i=0;;){var s=e.indexOf(" ",r);s==-1&&(s=e.length);var o=s-r;if(s==e.length||i+o>=t)return r+Math.min(o,t-i);i+=s-r,i+=n-i%n,r=s+1;if(i>=t)return r}}function jo(e){while(Bo.length<=e)Bo.push(Fo(Bo)+" ");return Bo[e]}function Fo(e){return e[e.length-1]}function qo(e,t){for(var n=0;n-1&&Vo(e)?!0:t.test(e):Vo(e)}function Jo(e){for(var t in e)if(e.hasOwnProperty(t)&&e[t])return!1;return!0}function Qo(e){return e.charCodeAt(0)>=768&&Ko.test(e)}function Go(e,t,n,r){var i=document.createElement(e);n&&(i.className=n),r&&(i.style.cssText=r);if(typeof t=="string")i.appendChild(document.createTextNode(t));else if(t)for(var s=0;s0;--t)e.removeChild(e.firstChild);return e}function eu(e,t){return Zo(e).appendChild(t)}function tu(e,t){if(e.contains)return e.contains(t);while(t=t.parentNode)if(t==e)return!0}function nu(){return document.activeElement}function ru(e){return new RegExp("(^|\\s)"+e+"(?:$|\\s)\\s*")}function ou(e,t){var n=e.split(" ");for(var r=0;r2&&!(r&&i<8))}return du?Go("span","​"):Go("span"," ",null,"display: inline-block; width: 1px; margin-right: -1px")}function gu(e){if(mu!=null)return mu;var t=eu(e,document.createTextNode("AخA")),n=Yo(t,0,1).getBoundingClientRect();if(!n||n.left==n.right)return!1;var r=Yo(t,1,2).getBoundingClientRect();return mu=r.right-n.right<3}function Su(e){if(Eu!=null)return Eu;var t=eu(e,Go("span","x")),n=t.getBoundingClientRect(),r=Yo(t,0,1).getBoundingClientRect();return Eu=Math.abs(n.left-r.left)>1}function Tu(e,t,n,r){if(!e)return r(t,n,"ltr");var i=!1;for(var s=0;st||t==n&&o.to==t)r(Math.max(o.from,t),Math.min(o.to,n),o.level==1?"rtl":"ltr"),i=!0}i||r(t,n,"ltr")}function Nu(e){return e.level%2?e.to:e.from}function Cu(e){return e.level%2?e.from:e.to}function ku(e){var t=Ks(e);return t?Nu(t[0]):0}function Lu(e){var t=Ks(e);return t?Cu(Fo(t)):e.text.length}function Au(e,t){var n=Us(e.doc,t),r=ts(n);r!=n&&(t=Vs(r));var i=Ks(r),s=i?i[0].level%2?Lu(r):ku(r):0;return ht(t,s)}function Ou(e,t){var n,r=Us(e.doc,t);while(n=Zi(r))r=n.find(1,!0).line,t=null;var i=Ks(r),s=i?i[0].level%2?ku(r):Lu(r):r.text.length;return ht(t==null?Vs(r):t,s)}function Mu(e,t){var n=Au(e,t.line),r=Us(e.doc,n.line),i=Ks(r);if(!i||i[0].level==0){var s=Math.max(0,r.text.search(/\S/)),o=t.line==n.line&&t.ch<=s&&t.ch;return ht(n.line,o?0:s)}return n}function _u(e,t,n){var r=e[0].level;return t==r?!0:n==r?!1:tt)return n;if(i.from==t||i.to==t){if(r!=null)return _u(e,i.level,e[r].level)?(i.from!=i.to&&(Du=r),n):(i.from!=i.to&&(Du=n),r);r=n}}return r}function Hu(e,t,n,r){if(!r)return t+n;do t+=n;while(t>0&&Qo(e.text.charAt(t)));return t}function Bu(e,t,n,r){var i=Ks(e);if(!i)return ju(e,t,n,r);var s=Pu(i,t),o=i[s],u=Hu(e,t,o.level%2?-n:n,r);for(;;){if(u>o.from&&u0==o.level%2?o.to:o.from);o=i[s+=n];if(!o)return null;n>0==o.level%2?u=Hu(e,o.to,-1,r):u=Hu(e,o.from,1,r)}}function ju(e,t,n,r){var i=t+n;if(r)while(i>0&&Qo(e.text.charAt(i)))i+=n;return i<0||i>e.text.length?null:i}var e=/gecko\/\d/i.test(navigator.userAgent),t=/MSIE \d/.test(navigator.userAgent),n=/Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent),r=t||n,i=r&&(t?document.documentMode||6:n[1]),s=/WebKit\//.test(navigator.userAgent),o=s&&/Qt\/\d+\.\d+/.test(navigator.userAgent),u=/Chrome\//.test(navigator.userAgent),a=/Opera\//.test(navigator.userAgent),f=/Apple Computer/.test(navigator.vendor),l=/KHTML\//.test(navigator.userAgent),c=/Mac OS X 1\d\D([8-9]|\d\d)\D/.test(navigator.userAgent),h=/PhantomJS/.test(navigator.userAgent),p=/AppleWebKit/.test(navigator.userAgent)&&/Mobile\/\w+/.test(navigator.userAgent),d=p||/Android|webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(navigator.userAgent),v=p||/Mac/.test(navigator.platform),m=/win/i.test(navigator.platform),g=a&&navigator.userAgent.match(/Version\/(\d*\.\d*)/);g&&(g=Number(g[1])),g&&g>=15&&(a=!1,s=!0);var y=v&&(o||a&&(g==null||g<12.11)),b=e||r&&i>=9,w=!1,E=!1,ht=S.Pos=function(e,t){if(!(this instanceof ht))return new ht(e,t);this.line=e,this.ch=t},pt=S.cmpPos=function(e,t){return e.line-t.line||e.ch-t.ch};gt.prototype={primary:function(){return this.ranges[this.primIndex]},equals:function(e){if(e==this)return!0;if(e.primIndex!=this.primIndex||e.ranges.length!=this.ranges.length)return!1;for(var t=0;t=0&&pt(e,r.to())<=0)return n}return-1}},yt.prototype={from:function(){return mt(this.anchor,this.head)},to:function(){return vt(this.anchor,this.head)},empty:function(){return this.head.line==this.anchor.line&&this.head.ch==this.anchor.ch}};var on={left:0,right:0,top:0,bottom:0},Sn,Nn=null,Cn=0,Gn=null,ar,fr,vr=0,wr=0,Er=null;r?Er=-0.53:e?Er=15:u?Er=-0.7:f&&(Er=-1/3);var Nr=new Do,Ar=null,Fr=S.changeEnd=function(e){return e.text?ht(e.from.line+e.text.length-1,Fo(e.text).length+(e.text.length==1?e.from.ch:0)):e.to};S.prototype={constructor:S,focus:function(){window.focus(),er(this),Qn(this)},setOption:function(e,t){var n=this.options,r=n[e];if(n[e]==t&&e!="mode")return;n[e]=t,li.hasOwnProperty(e)&&jn(this,li[e])(this,t,r)},getOption:function(e){return this.options[e]},getDoc:function(){return this.doc},addKeyMap:function(e,t){this.state.keyMaps[t?"push":"unshift"](Ci(e))},removeKeyMap:function(e){var t=this.state.keyMaps;for(var n=0;n0&&At(this.doc,r,new yt(s,f[r].to()),Oo)}else i.head.line>n&&(ii(this,i.head.line,e,!0),n=i.head.line,r==this.doc.sel.primIndex&&ni(this))}}),getTokenAt:function(e,t){return gs(this,e,t)},getLineTokens:function(e,t){return gs(this,ht(e),t,!0)},getTokenTypeAt:function(e){e=St(this.doc,e);var t=ws(this,Us(this.doc,e.line)),n=0,r=(t.length-1)/2,i=e.ch,s;if(i==0)s=t[2];else for(;;){var o=n+r>>1;if((o?t[o*2-1]:0)>=i)r=o;else{if(!(t[o*2+1]r&&(e=r,n=!0);var i=Us(this.doc,e);return dn(this,i,{top:0,left:0},t||"page").top+(n?this.doc.height-Js(i):0)},defaultTextHeight:function(){return xn(this.display)},defaultCharWidth:function(){return Tn(this.display)},setGutterMarker:Fn(function(e,t,n){return si(this.doc,e,"gutter",function(e){var r=e.gutterMarkers||(e.gutterMarkers={});return r[t]=n,!n&&Jo(r)&&(e.gutterMarkers=null),!0})}),clearGutter:Fn(function(e){var t=this,n=t.doc,r=n.first;n.iter(function(n){n.gutterMarkers&&n.gutterMarkers[e]&&(n.gutterMarkers[e]=null,zn(t,r,"gutter"),Jo(n.gutterMarkers)&&(n.gutterMarkers=null)),++r})}),addLineWidget:Fn(function(e,t,n){return ls(this,e,t,n)}),removeLineWidget:function(e){e.clear()},lineInfo:function(e){if(typeof e=="number"){if(!Tt(this.doc,e))return null;var t=e;e=Us(this.doc,e);if(!e)return null}else{var t=Vs(e);if(t==null)return null}return{line:t,handle:e,text:e.text,gutterMarkers:e.gutterMarkers,textClass:e.textClass,bgClass:e.bgClass,wrapClass:e.wrapClass,widgets:e.widgets}},getViewport:function(){return{from:this.display.viewFrom,to:this.display.viewTo}},addWidget:function(e,t,n,r,i){var s=this.display;e=gn(this,St(this.doc,e));var o=e.bottom,u=e.left;t.style.position="absolute",s.sizer.appendChild(t);if(r=="over")o=e.top;else if(r=="above"||r=="near"){var a=Math.max(s.wrapper.clientHeight,this.doc.height),f=Math.max(s.sizer.clientWidth,s.lineSpace.clientWidth);(r=="above"||e.bottom+t.offsetHeight>a)&&e.top>t.offsetHeight?o=e.top-t.offsetHeight:e.bottom+t.offsetHeight<=a&&(o=e.bottom),u+t.offsetWidth>f&&(u=f-t.offsetWidth)}t.style.top=o+"px",t.style.left=t.style.right="",i=="right"?(u=s.sizer.clientWidth-t.offsetWidth,t.style.right="0px"):(i=="left"?u=0:i=="middle"&&(u=(s.sizer.clientWidth-t.offsetWidth)/2),t.style.left=u+"px"),n&&Zr(this,u,o,u+t.offsetWidth,o+t.offsetHeight)},triggerOnKeyDown:Fn(Or),triggerOnKeyPress:Fn(Dr),triggerOnKeyUp:_r,execCommand:function(e){if(wi.hasOwnProperty(e))return wi[e](this)},findPosH:function(e,t,n,r){var i=1;t<0&&(i=-1,t=-t);for(var s=0,o=St(this.doc,e);s0&&u(n.charAt(r-1)))--r;while(i.5)&&L(this),wo(this,"refresh",this)}),swapDoc:Fn(function(e){var t=this.doc;return t.cm=null,Rs(this,e),cn(this),Zn(this),this.scrollTo(e.scrollLeft,e.scrollTop),this.curOp.forceScroll=!0,So(this,"swapDoc",this,t),t}),getInputField:function(){return this.display.input},getWrapperElement:function(){return this.display.wrapper},getScrollerElement:function(){return this.display.scroller},getGutterElement:function(){return this.display.gutters}},ko(S);var fi=S.defaults={},li=S.optionHandlers={},hi=S.Init={toString:function(){return"CodeMirror.Init"}};ci("value","",function(e,t){e.setValue(t)},!0),ci("mode",null,function(e,t){e.doc.modeOption=t,T(e)},!0),ci("indentUnit",2,T,!0),ci("indentWithTabs",!1),ci("smartIndent",!0),ci("tabSize",4,function(e){N(e),cn(e),Un(e)},!0),ci("specialChars",/[\t\u0000-\u0019\u00ad\u200b-\u200f\u2028\u2029\ufeff]/g,function(e,t){e.options.specialChars=new RegExp(t.source+(t.test(" ")?"":"| "),"g"),e.refresh()},!0),ci("specialCharPlaceholder",Cs,function(e){e.refresh()},!0),ci("electricChars",!0),ci("rtlMoveVisually",!m),ci("wholeLineUpdateBefore",!0),ci("theme","default",function(e){A(e),O(e)},!0),ci("keyMap","default",function(e,t,n){var r=Ci(t),i=n!=S.Init&&Ci(n);i&&i.detach&&i.detach(e,r),r.attach&&r.attach(e,i||null)}),ci("extraKeys",null),ci("lineWrapping",!1,C,!0),ci("gutters",[],function(e){H(e.options),O(e)},!0),ci("fixedGutter",!0,function(e,t){e.display.gutters.style.left=t?z(e.display)+"px":"0",e.refresh()},!0),ci("coverGutterNextToScrollbar",!1,F,!0),ci("lineNumbers",!1,function(e){H(e.options),O(e)},!0),ci("firstLineNumber",1,O,!0),ci("lineNumberFormatter",function(e){return e},O,!0),ci("showCursorWhenSelecting",!1,Rt,!0),ci("resetSelectionOnContextMenu",!0),ci("readOnly",!1,function(e,t){t=="nocursor"?(Hr(e),e.display.input.blur(),e.display.disabled=!0):(e.display.disabled=!1,t||Zn(e))}),ci("disableInput",!1,function(e,t){t||Zn(e)},!0),ci("dragDrop",!0),ci("cursorBlinkRate",530),ci("cursorScrollMargin",0),ci("cursorHeight",1,Rt,!0),ci("singleCursorHeightPerLine",!0,Rt,!0),ci("workTime",100),ci("workDelay",100),ci("flattenSpans",!0,N,!0),ci("addModeClass",!1,N,!0),ci("pollInterval",100),ci("undoDepth",200,function(e,t){e.doc.history.undoDepth=t}),ci("historyEventDelay",1250),ci("viewportMargin",10,function(e){e.refresh()},!0),ci("maxHighlightLength",1e4,N,!0),ci("moveInputWithCursor",!0,function(e,t){t||(e.display.inputDiv.style.top=e.display.inputDiv.style.left=0)}),ci("tabindex",null,function(e,t){e.display.input.tabIndex=t||""}),ci("autofocus",null);var pi=S.modes={},di=S.mimeModes={};S.defineMode=function(e,t){!S.defaults.mode&&e!="null"&&(S.defaults.mode=e),arguments.length>2&&(t.dependencies=Array.prototype.slice.call(arguments,2)),pi[e]=t},S.defineMIME=function(e,t){di[e]=t},S.resolveMode=function(e){if(typeof e=="string"&&di.hasOwnProperty(e))e=di[e];else if(e&&typeof e.name=="string"&&di.hasOwnProperty(e.name)){var t=di[e.name];typeof t=="string"&&(t={name:t}),e=Uo(t,e),e.name=t.name}else if(typeof e=="string"&&/^[\w\-]+\/[\w\-]+\+xml$/.test(e))return S.resolveMode("application/xml");return typeof e=="string"?{name:e}:e||{name:"null"}},S.getMode=function(e,t){var t=S.resolveMode(t),n=pi[t.name];if(!n)return S.getMode(e,"text/plain");var r=n(e,t);if(vi.hasOwnProperty(t.name)){var i=vi[t.name];for(var s in i){if(!i.hasOwnProperty(s))continue;r.hasOwnProperty(s)&&(r["_"+s]=r[s]),r[s]=i[s]}}r.name=t.name,t.helperType&&(r.helperType=t.helperType);if(t.modeProps)for(var s in t.modeProps)r[s]=t.modeProps[s];return r},S.defineMode("null",function(){return{token:function(e){e.skipToEnd()}}}),S.defineMIME("text/plain","null");var vi=S.modeExtensions={};S.extendMode=function(e,t){var n=vi.hasOwnProperty(e)?vi[e]:vi[e]={};zo(t,n)},S.defineExtension=function(e,t){S.prototype[e]=t},S.defineDocExtension=function(e,t){js.prototype[e]=t},S.defineOption=ci;var mi=[];S.defineInitHook=function(e){mi.push(e)};var gi=S.helpers={};S.registerHelper=function(e,t,n){gi.hasOwnProperty(e)||(gi[e]=S[e]={_global:[]}),gi[e][t]=n},S.registerGlobalHelper=function(e,t,n,r){S.registerHelper(e,t,r),gi[e]._global.push({pred:n,val:r})};var yi=S.copyState=function(e,t){if(t===!0)return t;if(e.copyState)return e.copyState(t);var n={};for(var r in t){var i=t[r];i instanceof Array&&(i=i.concat([])),n[r]=i}return n},bi=S.startState=function(e,t,n){return e.startState?e.startState(t,n):!0};S.innerMode=function(e,t){while(e.innerMode){var n=e.innerMode(t);if(!n||n.mode==e)break;t=n.state,e=n.mode}return n||{mode:e,state:t}};var wi=S.commands={selectAll:function(e){e.setSelection(ht(e.firstLine(),0),ht(e.lastLine()),Oo)},singleSelection:function(e){e.setSelection(e.getCursor("anchor"),e.getCursor("head"),Oo)},killLine:function(e){oi(e,function(t){if(t.empty()){var n=Us(e.doc,t.head.line).text.length;return t.head.ch==n&&t.head.line0)i=new ht(i.line,i.ch+1),e.replaceRange(s.charAt(i.ch-1)+s.charAt(i.ch-2),ht(i.line,i.ch-2),i,"+transpose");else if(i.line>e.doc.first){var o=Us(e.doc,i.line-1).text;o&&e.replaceRange(s.charAt(0)+"\n"+o.charAt(o.length-1),ht(i.line-1,o.length-1),ht(i.line,1),"+transpose")}}n.push(new yt(i,i))}e.setSelections(n)})},newlineAndIndent:function(e){Bn(e,function(){var t=e.listSelections().length;for(var n=0;n=this.string.length},sol:function(){return this.pos==this.lineStart},peek:function(){return this.string.charAt(this.pos)||undefined},next:function(){if(this.post},eatSpace:function(){var e=this.pos;while(/[\s\u00a0]/.test(this.string.charAt(this.pos)))++this.pos;return this.pos>e},skipToEnd:function(){this.pos=this.string.length},skipTo:function(e){var t=this.string.indexOf(e,this.pos);if(t>-1)return this.pos=t,!0},backUp:function(e){this.pos-=e},column:function(){return this.lastColumnPos0?null:(s&&t!==!1&&(this.pos+=s[0].length),s)}var r=function(e){return n?e.toLowerCase():e},i=this.string.substr(this.pos,e.length);if(r(i)==r(e))return t!==!1&&(this.pos+=e.length),!0},current:function(){return this.string.slice(this.start,this.pos)},hideFirstChars:function(e,t){this.lineStart+=e;try{return t()}finally{this.lineStart-=e}}};var Li=S.TextMarker=function(e,t){this.lines=[],this.type=t,this.doc=e};ko(Li),Li.prototype.clear=function(){if(this.explicitlyCleared)return;var e=this.doc.cm,t=e&&!e.curOp;t&&kn(e);if(Co(this,"clear")){var n=this.find();n&&So(this,"clear",n.from,n.to)}var r=null,i=null;for(var s=0;se.display.maxLineLength&&(e.display.maxLine=a,e.display.maxLineLength=f,e.display.maxLineChanged=!0)}r!=null&&e&&this.collapsed&&Un(e,r,i+1),this.lines.length=0,this.explicitlyCleared=!0,this.atomic&&this.doc.cantEdit&&(this.doc.cantEdit=!1,e&&Bt(e.doc)),e&&So(e,"markerCleared",e,this),t&&An(e),this.parent&&this.parent.clear()},Li.prototype.find=function(e,t){e==null&&this.type=="bookmark"&&(e=1);var n,r;for(var i=0;i1||!(this.children[0]instanceof Ps))){var u=[];this.collapse(u),this.children=[new Ps(u)],this.children[0].parent=this}},collapse:function(e){for(var t=0;t50){while(i.lines.length>50){var o=i.lines.splice(i.lines.length-25,25),u=new Ps(o);i.height-=u.height,this.children.splice(r+1,0,u),u.parent=this}this.maybeSpill()}break}e-=s}},maybeSpill:function(){if(this.children.length<=10)return;var e=this;do{var t=e.children.splice(e.children.length-5,5),n=new Hs(t);if(!e.parent){var r=new Hs(e.children);r.parent=e,e.children=[r,n],e=r}else{e.size-=n.size,e.height-=n.height;var i=qo(e.parent.children,e);e.parent.children.splice(i+1,0,n)}n.parent=e.parent}while(e.children.length>10);e.parent.maybeSpill()},iterN:function(e,t,n){for(var r=0;r=0;s--)Wr(this,r[s]);u?_t(this,u):this.cm&&ni(this.cm)}),undo:In(function(){Vr(this,"undo")}),redo:In(function(){Vr(this,"redo")}),undoSelection:In(function(){Vr(this,"undo",!0)}),redoSelection:In(function(){Vr(this,"redo",!0)}),setExtending:function(e){this.extend=e},getExtending:function(){return this.extend},historySize:function(){var e=this.history,t=0,n=0;for(var r=0;r=e.ch)&&t.push(i.marker.parent||i.marker)}return t},findMarks:function(e,t,n){e=St(this,e),t=St(this,t);var r=[],i=e.line;return this.iter(e.line,t.line+1,function(s){var o=s.markedSpans;if(o)for(var u=0;ua.to||a.from==null&&i!=e.line||i==t.line&&a.from>t.ch)&&(!n||n(a.marker))&&r.push(a.marker.parent||a.marker)}++i}),r},getAllMarks:function(){var e=[];return this.iter(function(t){var n=t.markedSpans;if(n)for(var r=0;re)return t=e,!0;e-=i,++n}),St(this,ht(n,t))},indexFromPos:function(e){e=St(this,e);var t=e.ch;return e.linet&&(t=e.from),e.to!=null&&e.to=t)return o+(t-s);o+=u-s,o+=n-o%n,s=u+1}},Bo=[""],Io=function(e){e.select()};p?Io=function(e){e.selectionStart=0,e.selectionEnd=e.value.length}:r&&(Io=function(e){try{e.select()}catch(t){}}),[].indexOf&&(qo=function(e,t){return e.indexOf(t)}),[].map&&(Ro=function(e,t){return e.map(t)});var Xo=/[\u00df\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/,Vo=S.isWordChar=function(e){return/\w/.test(e)||e>"€"&&(e.toUpperCase()!=e.toLowerCase()||Xo.test(e))},Ko=/[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/,Yo;document.createRange?Yo=function(e,t,n){var r=document.createRange();return r.setEnd(e,n),r.setStart(e,t),r}:Yo=function(e,t,n){var r=document.body.createTextRange();try{r.moveToElementText(e.parentNode)}catch(i){return r}return r.collapse(!0),r.moveEnd("character",n),r.moveStart("character",t),r},r&&i<11&&(nu=function(){try{return document.activeElement}catch(e){return document.body}});var iu=S.rmClass=function(e,t){var n=e.className,r=ru(t).exec(n);if(r){var i=n.slice(r.index+r[0].length);e.className=n.slice(0,r.index)+(i?r[1]+i:"")}},su=S.addClass=function(e,t){var n=e.className;ru(t).test(n)||(e.className+=(n?" ":"")+t)},au=!1,cu=function(){if(r&&i<9)return!1;var e=Go("div");return"draggable"in e||"dragDrop"in e}(),hu,du,mu,yu=S.splitLines="\n\nb".split(/\n/).length!=3?function(e){var t=0,n=[],r=e.length;while(t<=r){var i=e.indexOf("\n",t);i==-1&&(i=e.length);var s=e.slice(t,e.charAt(i-1)=="\r"?i-1:i),o=s.indexOf("\r");o!=-1?(n.push(s.slice(0,o)),t+=o+1):(n.push(s),t=i+1)}return n}:function(e){return e.split(/\r\n?|\n/)},bu=window.getSelection?function(e){try{return e.selectionStart!=e.selectionEnd}catch(t){return!1}}:function(e){try{var t=e.ownerDocument.selection.createRange()}catch(n){}return!t||t.parentElement()!=e?!1:t.compareEndPoints("StartToEnd",t)!=0},wu=function(){var e=Go("div");return"oncopy"in e?!0:(e.setAttribute("oncopy","return;"),typeof e.oncopy=="function")}(),Eu=null,xu={3:"Enter",8:"Backspace",9:"Tab",13:"Enter",16:"Shift",17:"Ctrl",18:"Alt",19:"Pause",20:"CapsLock",27:"Esc",32:"Space",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"Left",38:"Up",39:"Right",40:"Down",44:"PrintScrn",45:"Insert",46:"Delete",59:";",61:"=",91:"Mod",92:"Mod",93:"Mod",107:"=",109:"-",127:"Delete",173:"-",186:";",187:"=",188:",",189:"-",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:"'",63232:"Up",63233:"Down",63234:"Left",63235:"Right",63272:"Delete",63273:"Home",63275:"End",63276:"PageUp",63277:"PageDown",63302:"Insert"};S.keyNames=xu,function(){for(var e=0;e<10;e++)xu[e+48]=xu[e+96]=String(e);for(var e=65;e<=90;e++)xu[e]=String.fromCharCode(e);for(var e=1;e<=12;e++)xu[e+111]=xu[e+63235]="F"+e}();var Du,Fu=function(){function n(n){return n<=247?e.charAt(n):1424<=n&&n<=1524?"R":1536<=n&&n<=1773?t.charAt(n-1536):1774<=n&&n<=2220?"r":8192<=n&&n<=8203?"w":n==8204?"b":"L"}function f(e,t,n){this.level=e,this.from=t,this.to=n}var e="bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN",t="rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmm",r=/[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/,i=/[stwN]/,s=/[LRr]/,o=/[Lb1n]/,u=/[1n]/,a="L";return function(e){if(!r.test(e))return!1;var t=e.length,l=[];for(var c=0,h;c"))return v("=>","operator");if(n=="0"&&e.eat(/x/i))return e.eatWhile(/[\da-f]/i),v("number","number");if(/\d/.test(n))return e.match(/^\d*(?:\.\d*)?(?:[eE][+\-]?\d+)?/),v("number","number");if(n=="/")return e.eat("*")?(t.tokenize=y,y(e,t)):e.eat("/")?(e.skipToEnd(),v("comment","comment")):t.lastType=="operator"||t.lastType=="keyword c"||t.lastType=="sof"||/^[\[{}\(,;:]$/.test(t.lastType)?(h(e),e.eatWhile(/[gimy]/),v("regexp","string-2")):(e.eatWhile(l),v("operator","operator",e.current()));if(n=="`")return t.tokenize=b,b(e,t);if(n=="#")return e.skipToEnd(),v("error","error");if(l.test(n))return e.eatWhile(l),v("operator","operator",e.current());if(a.test(n)){e.eatWhile(a);var r=e.current(),i=f.propertyIsEnumerable(r)&&f[r];return i&&t.lastType!="."?v(i.type,i.style,r):v("variable","variable",r)}}function g(e){return function(t,n){var r=!1,i;if(s&&t.peek()=="@"&&t.match(c))return n.tokenize=m,v("jsonld-keyword","meta");while((i=t.next())!=null){if(i==e&&!r)break;r=!r&&i=="\\"}return r||(n.tokenize=m),v("string","string")}}function y(e,t){var n=!1,r;while(r=e.next()){if(r=="/"&&n){t.tokenize=m;break}n=r=="*"}return v("comment","comment")}function b(e,t){var n=!1,r;while((r=e.next())!=null){if(!n&&(r=="`"||r=="$"&&e.eat("{"))){t.tokenize=m;break}n=!n&&r=="\\"}return v("quasi","string-2",e.current())}function E(e,t){t.fatArrowAt&&(t.fatArrowAt=null);var n=e.string.indexOf("=>",e.start);if(n<0)return;var r=0,i=!1;for(var s=n-1;s>=0;--s){var o=e.string.charAt(s),u=w.indexOf(o);if(u>=0&&u<3){if(!r){++s;break}if(--r==0)break}else if(u>=3&&u<6)++r;else if(a.test(o))i=!0;else if(i&&!r){++s;break}}i&&!r&&(t.fatArrowAt=s)}function x(e,t,n,r,i,s){this.indented=e,this.column=t,this.type=n,this.prev=i,this.info=s,r!=null&&(this.align=r)}function T(e,t){for(var n=e.localVars;n;n=n.next)if(n.name==t)return!0;for(var r=e.context;r;r=r.prev)for(var n=r.vars;n;n=n.next)if(n.name==t)return!0}function N(e,t,n,r,i){var s=e.cc;C.state=e,C.stream=i,C.marked=null,C.cc=s,C.style=t,e.lexical.hasOwnProperty("align")||(e.lexical.align=!0);for(;;){var u=s.length?s.pop():o?j:B;if(u(n,r)){while(s.length&&s[s.length-1].lex)s.pop()();return C.marked?C.marked:n=="variable"&&T(e,r)?"variable-2":t}}}function k(){for(var e=arguments.length-1;e>=0;e--)C.cc.push(arguments[e])}function L(){return k.apply(null,arguments),!0}function A(e){function t(t){for(var n=t;n;n=n.next)if(n.name==e)return!0;return!1}var r=C.state;if(r.context){C.marked="def";if(t(r.localVars))return;r.localVars={name:e,next:r.localVars}}else{if(t(r.globalVars))return;n.globalVars&&(r.globalVars={name:e,next:r.globalVars})}}function M(){C.state.context={prev:C.state.context,vars:C.state.localVars},C.state.localVars=O}function _(){C.state.localVars=C.state.context.vars,C.state.context=C.state.context.prev}function D(e,t){var n=function(){var n=C.state,r=n.indented;if(n.lexical.type=="stat")r=n.lexical.indented;else for(var i=n.lexical;i&&i.type==")"&&i.align;i=i.prev)r=i.indented;n.lexical=new x(r,C.stream.column(),e,null,n.lexical,t)};return n.lex=!0,n}function P(){var e=C.state;e.lexical.prev&&(e.lexical.type==")"&&(e.indented=e.lexical.indented),e.lexical=e.lexical.prev)}function H(e){function t(n){return n==e?L():e==";"?k():L(t)}return t}function B(e,t){return e=="var"?L(D("vardef",t.length),it,H(";"),P):e=="keyword a"?L(D("form"),j,B,P):e=="keyword b"?L(D("form"),B,P):e=="{"?L(D("}"),tt,P):e==";"?L():e=="if"?(C.state.lexical.info=="else"&&C.state.cc[C.state.cc.length-1]==P&&C.state.cc.pop()(),L(D("form"),j,B,P,ft)):e=="function"?L(vt):e=="for"?L(D("form"),lt,B,P):e=="variable"?L(D("stat"),J):e=="switch"?L(D("form"),j,D("}","switch"),H("{"),tt,P,P):e=="case"?L(j,H(":")):e=="default"?L(H(":")):e=="catch"?L(D("form"),M,H("("),mt,H(")"),B,P,_):e=="module"?L(D("form"),M,Et,_,P):e=="class"?L(D("form"),gt,P):e=="export"?L(D("form"),St,P):e=="import"?L(D("form"),xt,P):k(D("stat"),j,H(";"),P)}function j(e){return I(e,!1)}function F(e){return I(e,!0)}function I(e,t){if(C.state.fatArrowAt==C.stream.start){var n=t?$:V;if(e=="(")return L(M,D(")"),Z(st,")"),P,H("=>"),n,_);if(e=="variable")return k(M,st,H("=>"),n,_)}var r=t?z:U;return S.hasOwnProperty(e)?L(r):e=="function"?L(vt,r):e=="keyword c"?L(t?R:q):e=="("?L(D(")"),q,Lt,H(")"),P,r):e=="operator"||e=="spread"?L(t?F:j):e=="["?L(D("]"),Ct,P,r):e=="{"?et(Q,"}",null,r):e=="quasi"?k(W,r):L()}function q(e){return e.match(/[;\}\)\],]/)?k():k(j)}function R(e){return e.match(/[;\}\)\],]/)?k():k(F)}function U(e,t){return e==","?L(j):z(e,t,!1)}function z(e,t,n){var r=n==0?U:z,i=n==0?j:F;if(e=="=>")return L(M,n?$:V,_);if(e=="operator")return/\+\+|--/.test(t)?L(r):t=="?"?L(j,H(":"),i):L(i);if(e=="quasi")return k(W,r);if(e==";")return;if(e=="(")return et(F,")","call",r);if(e==".")return L(K,r);if(e=="[")return L(D("]"),q,H("]"),P,r)}function W(e,t){return e!="quasi"?k():t.slice(t.length-2)!="${"?L(W):L(j,X)}function X(e){if(e=="}")return C.marked="string-2",C.state.tokenize=b,L(W)}function V(e){return E(C.stream,C.state),k(e=="{"?B:j)}function $(e){return E(C.stream,C.state),k(e=="{"?B:F)}function J(e){return e==":"?L(P,B):k(U,H(";"),P)}function K(e){if(e=="variable")return C.marked="property",L()}function Q(e,t){if(e=="variable"||C.style=="keyword")return C.marked="property",t=="get"||t=="set"?L(G):L(Y);if(e=="number"||e=="string")return C.marked=s?"property":C.style+" property",L(Y);if(e=="jsonld-keyword")return L(Y);if(e=="[")return L(j,H("]"),Y)}function G(e){return e!="variable"?k(Y):(C.marked="property",L(vt))}function Y(e){if(e==":")return L(F);if(e=="(")return k(vt)}function Z(e,t){function n(r){if(r==","){var i=C.state.lexical;return i.info=="call"&&(i.pos=(i.pos||0)+1),L(e,n)}return r==t?L():L(H(t))}return function(r){return r==t?L():k(e,n)}}function et(e,t,n){for(var r=3;r!?|~^]/,c=/^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)"/,p,d,w="([{}])",S={atom:!0,number:!0,variable:!0,string:!0,regexp:!0,"this":!0,"jsonld-keyword":!0},C={state:null,column:null,marked:null,cc:null},O={name:"this",next:{name:"arguments"}};return P.lex=!0,{startState:function(e){var t={tokenize:m,lastType:"sof",cc:[],lexical:new x((e||0)-r,0,"block",!1),localVars:n.localVars,context:n.localVars&&{vars:n.localVars},indented:0};return n.globalVars&&typeof n.globalVars=="object"&&(t.globalVars=n.globalVars),t},token:function(e,t){e.sol()&&(t.lexical.hasOwnProperty("align")||(t.lexical.align=!1),t.indented=e.indentation(),E(e,t));if(t.tokenize!=y&&e.eatSpace())return null;var n=t.tokenize(e,t);return p=="comment"?n:(t.lastType=p!="operator"||d!="++"&&d!="--"?p:"incdec",N(t,n,p,d,e))},indent:function(t,s){if(t.tokenize==y)return e.Pass;if(t.tokenize!=m)return 0;var o=s&&s.charAt(0),u=t.lexical;if(!/^\s*else\b/.test(s))for(var a=t.cc.length-1;a>=0;--a){var f=t.cc[a];if(f==P)u=u.prev;else if(f!=ft)break}u.type=="stat"&&o=="}"&&(u=u.prev),i&&u.type==")"&&u.prev.type=="stat"&&(u=u.prev);var l=u.type,c=o==l;return l=="vardef"?u.indented+(t.lastType=="operator"||t.lastType==","?u.info+1:0):l=="form"&&o=="{"?u.indented:l=="form"?u.indented+r:l=="stat"?u.indented+(t.lastType=="operator"||t.lastType==","?i||r:0):u.info=="switch"&&!c&&n.doubleIndentSwitch!=0?u.indented+(/^(?:case|default)\b/.test(s)?r:2*r):u.align?u.column+(c?0:1):u.indented+(c?0:r)},electricInput:/^\s*(?:case .*?:|default:|\{|\})$/,blockCommentStart:o?null:"/*",blockCommentEnd:o?null:"*/",lineComment:o?null:"//",fold:"brace",helperType:o?"json":"javascript",jsonldMode:s,jsonMode:o}}),e.registerHelper("wordChars","javascript",/[\w$]/),e.defineMIME("text/javascript","javascript"),e.defineMIME("text/ecmascript","javascript"),e.defineMIME("application/javascript","javascript"),e.defineMIME("application/x-javascript","javascript"),e.defineMIME("application/ecmascript","javascript"),e.defineMIME("application/json",{name:"javascript",json:!0}),e.defineMIME("application/x-json",{name:"javascript",json:!0}),e.defineMIME("application/ld+json",{name:"javascript",jsonld:!0}),e.defineMIME("text/typescript",{name:"javascript",typescript:!0}),e.defineMIME("application/typescript",{name:"javascript",typescript:!0})}),function(e){typeof exports=="object"&&typeof module=="object"?e(require("../../lib/codemirror")):typeof define=="function"&&define.amd?define("libs/codemirror-4.8/addon/hint/xml-hint",["../../lib/codemirror"],e):e(CodeMirror)}(function(e){function n(n,r){var i=r&&r.schemaInfo,s=r&&r.quoteChar||'"';if(!i)return;var o=n.getCursor(),u=n.getTokenAt(o);if(/^<\/?$/.test(u.string)&&u.end==o.ch){var a=n.getTokenAt(t(o.line,o.ch+1));a.start==o.ch&&/\btag\b/.test(a.type)&&(u=a)}var f=e.innerMode(n.getMode(),u.state);if(f.mode.name!="xml")return;var l=[],c=!1,h,p=/\btag\b/.test(u.type)&&!/>$/.test(u.string),d=p&&/^\w/.test(u.string),v;if(d){var m=n.getLine(o.line).slice(Math.max(0,u.start-2),u.start),g=/<\/$/.test(m)?"close":/<$/.test(m)?"open":null;g&&(v=u.start-(g=="close"?2:1))}else p&&u.string=="<"?g="open":p&&u.string=="")}else{var b=i[f.state.tagName],x=b&&b.attrs,T=i["!attrs"];if(!x&&!T)return;if(!x)x=T;else if(T){var N={};for(var C in T)T.hasOwnProperty(C)&&(N[C]=T[C]);for(var C in x)x.hasOwnProperty(C)&&(N[C]=x[C]);x=N}if(u.type=="string"||u.string=="="){var m=n.getRange(t(o.line,Math.max(0,o.ch-60)),t(o.line,u.type=="string"?u.start:u.end)),k=m.match(/([^\s\u00a0=<>\"\']+)=$/),L;if(!k||!x.hasOwnProperty(k[1])||!(L=x[k[1]]))return;typeof L=="function"&&(L=L.call(this,n));if(u.type=="string"){h=u.string;var A=0;/['"]/.test(u.string.charAt(0))&&(s=u.string.charAt(0),h=u.string.slice(1),A++);var O=u.string.length;/['"]/.test(u.string.charAt(O-1))&&(s=u.string.charAt(O-1),h=u.string.substr(A,O-2)),c=!0}for(var E=0;E][<][=] [X]","device-aspect-ratio: X/Y","orientation:portrait","orientation:landscape","device-height: [X]","device-width: [X]"],u={attrs:{}},a={a:{attrs:{href:null,ping:null,type:null,media:o,target:n,hreflang:t}},abbr:u,acronym:u,address:u,applet:u,area:{attrs:{alt:null,coords:null,href:null,target:null,ping:null,media:o,hreflang:t,type:null,shape:["default","rect","circle","poly"]}},article:u,aside:u,audio:{attrs:{src:null,mediagroup:null,crossorigin:["anonymous","use-credentials"],preload:["none","metadata","auto"],autoplay:["","autoplay"],loop:["","loop"],controls:["","controls"]}},b:u,base:{attrs:{href:null,target:n}},basefont:u,bdi:u,bdo:u,big:u,blockquote:{attrs:{cite:null}},body:u,br:u,button:{attrs:{form:null,formaction:null,name:null,value:null,autofocus:["","autofocus"],disabled:["","autofocus"],formenctype:s,formmethod:i,formnovalidate:["","novalidate"],formtarget:n,type:["submit","reset","button"]}},canvas:{attrs:{width:null,height:null}},caption:u,center:u,cite:u,code:u,col:{attrs:{span:null}},colgroup:{attrs:{span:null}},command:{attrs:{type:["command","checkbox","radio"],label:null,icon:null,radiogroup:null,command:null,title:null,disabled:["","disabled"],checked:["","checked"]}},data:{attrs:{value:null}},datagrid:{attrs:{disabled:["","disabled"],multiple:["","multiple"]}},datalist:{attrs:{data:null}},dd:u,del:{attrs:{cite:null,datetime:null}},details:{attrs:{open:["","open"]}},dfn:u,dir:u,div:u,dl:u,dt:u,em:u,embed:{attrs:{src:null,type:null,width:null,height:null}},eventsource:{attrs:{src:null}},fieldset:{attrs:{disabled:["","disabled"],form:null,name:null}},figcaption:u,figure:u,font:u,footer:u,form:{attrs:{action:null,name:null,"accept-charset":r,autocomplete:["on","off"],enctype:s,method:i,novalidate:["","novalidate"],target:n}},frame:u,frameset:u,h1:u,h2:u,h3:u,h4:u,h5:u,h6:u,head:{attrs:{},children:["title","base","link","style","meta","script","noscript","command"]},header:u,hgroup:u,hr:u,html:{attrs:{manifest:null},children:["head","body"]},i:u,iframe:{attrs:{src:null,srcdoc:null,name:null,width:null,height:null,sandbox:["allow-top-navigation","allow-same-origin","allow-forms","allow-scripts"],seamless:["","seamless"]}},img:{attrs:{alt:null,src:null,ismap:null,usemap:null,width:null,height:null,crossorigin:["anonymous","use-credentials"]}},input:{attrs:{alt:null,dirname:null,form:null,formaction:null,height:null,list:null,max:null,maxlength:null,min:null,name:null,pattern:null,placeholder:null,size:null,src:null,step:null,value:null,width:null,accept:["audio/*","video/*","image/*"],autocomplete:["on","off"],autofocus:["","autofocus"],checked:["","checked"],disabled:["","disabled"],formenctype:s,formmethod:i,formnovalidate:["","novalidate"],formtarget:n,multiple:["","multiple"],readonly:["","readonly"],required:["","required"],type:["hidden","text","search","tel","url","email","password","datetime","date","month","week","time","datetime-local","number","range","color","checkbox","radio","file","submit","image","reset","button"]}},ins:{attrs:{cite:null,datetime:null}},kbd:u,keygen:{attrs:{challenge:null,form:null,name:null,autofocus:["","autofocus"],disabled:["","disabled"],keytype:["RSA"]}},label:{attrs:{"for":null,form:null}},legend:u,li:{attrs:{value:null}},link:{attrs:{href:null,type:null,hreflang:t,media:o,sizes:["all","16x16","16x16 32x32","16x16 32x32 64x64"]}},map:{attrs:{name:null}},mark:u,menu:{attrs:{label:null,type:["list","context","toolbar"]}},meta:{attrs:{content:null,charset:r,name:["viewport","application-name","author","description","generator","keywords"],"http-equiv":["content-language","content-type","default-style","refresh"]}},meter:{attrs:{value:null,min:null,low:null,high:null,max:null,optimum:null}},nav:u,noframes:u,noscript:u,object:{attrs:{data:null,type:null,name:null,usemap:null,form:null,width:null,height:null,typemustmatch:["","typemustmatch"]}},ol:{attrs:{reversed:["","reversed"],start:null,type:["1","a","A","i","I"]}},optgroup:{attrs:{disabled:["","disabled"],label:null}},option:{attrs:{disabled:["","disabled"],label:null,selected:["","selected"],value:null}},output:{attrs:{"for":null,form:null,name:null}},p:u,param:{attrs:{name:null,value:null}},pre:u,progress:{attrs:{value:null,max:null}},q:{attrs:{cite:null}},rp:u,rt:u,ruby:u,s:u,samp:u,script:{attrs:{type:["text/javascript"],src:null,async:["","async"],defer:["","defer"],charset:r}},section:u,select:{attrs:{form:null,name:null,size:null,autofocus:["","autofocus"],disabled:["","disabled"],multiple:["","multiple"]}},small:u,source:{attrs:{src:null,type:null,media:null}},span:u,strike:u,strong:u,style:{attrs:{type:["text/css"],media:o,scoped:null}},sub:u,summary:u,sup:u,table:u,tbody:u,td:{attrs:{colspan:null,rowspan:null,headers:null}},textarea:{attrs:{dirname:null,form:null,maxlength:null,name:null,placeholder:null,rows:null,cols:null,autofocus:["","autofocus"],disabled:["","disabled"],readonly:["","readonly"],required:["","required"],wrap:["soft","hard"]}},tfoot:u,th:{attrs:{colspan:null,rowspan:null,headers:null,scope:["row","col","rowgroup","colgroup"]}},thead:u,time:{attrs:{datetime:null}},title:u,tr:u,track:{attrs:{src:null,label:null,"default":null,kind:["subtitles","captions","descriptions","chapters","metadata"],srclang:t}},tt:u,u:u,ul:u,"var":u,video:{attrs:{src:null,poster:null,width:null,height:null,crossorigin:["anonymous","use-credentials"],preload:["auto","metadata","none"],autoplay:["","autoplay"],mediagroup:["movie"],muted:["","muted"],controls:["","controls"]}},wbr:u},f={accesskey:["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","0","1","2","3","4","5","6","7","8","9"],"class":null,contenteditable:["true","false"],contextmenu:null,dir:["ltr","rtl","auto"],draggable:["true","false","auto"],dropzone:["copy","move","link","string:","file:"],hidden:["hidden"],id:null,inert:["inert"],itemid:null,itemprop:null,itemref:null,itemscope:["itemscope"],itemtype:null,lang:["en","es"],spellcheck:["true","false"],style:null,tabindex:["1","2","3","4","5","6","7","8","9"],title:null,translate:["yes","no"],onclick:null,rel:["stylesheet","alternate","author","bookmark","help","license","next","nofollow","noreferrer","prefetch","prev","search","tag"]};l(u);for(var c in a)a.hasOwnProperty(c)&&a[c]!=u&&l(a[c]);e.htmlSchema=a,e.registerHelper("hint","html",h)}),function(e){typeof exports=="object"&&typeof module=="object"?e(require("../../lib/codemirror")):typeof define=="function"&&define.amd?define("libs/codemirror-4.8/addon/hint/show-hint",["../../lib/codemirror"],e):e(CodeMirror)}(function(e){function r(e,t){this.cm=e,this.options=this.buildOptions(t),this.widget=this.onClose=null}function i(e){return typeof e=="string"?e:e.text}function s(e,t){function s(e,r){var s;typeof r!="string"?s=function(e){return r(e,t)}:n.hasOwnProperty(r)?s=n[r]:s=r,i[e]=s}var n={Up:function(){t.moveFocus(-1)},Down:function(){t.moveFocus(1)},PageUp:function(){t.moveFocus(-t.menuSize()+1,!0)},PageDown:function(){t.moveFocus(t.menuSize()-1,!0)},Home:function(){t.setFocus(0)},End:function(){t.setFocus(t.length-1)},Enter:t.pick,Tab:t.pick,Esc:t.close},r=e.options.customKeys,i=r?{}:n;if(r)for(var o in r)r.hasOwnProperty(o)&&s(o,r[o]);var u=e.options.extraKeys;if(u)for(var o in u)u.hasOwnProperty(o)&&s(o,u[o]);return i}function o(e,t){while(t&&t!=e){if(t.nodeName.toUpperCase()==="LI"&&t.parentNode==e)return t;t=t.parentNode}}function u(r,u){this.completion=r,this.data=u;var a=this,f=r.cm,l=this.hints=document.createElement("ul");l.className="CodeMirror-hints",this.selectedHint=u.selectedHint||0;var c=u.list;for(var h=0;h0){var T=S.bottom-S.top,N=m.top-(m.bottom-S.top);if(N-T>0)l.style.top=(y=m.top-T)+"px",b=!1;else if(T>E){l.style.height=E-5+"px",l.style.top=(y=m.bottom-S.top)+"px";var C=f.getCursor();u.from.ch!=C.ch&&(m=f.cursorCoords(C),l.style.left=(g=m.left)+"px",S=l.getBoundingClientRect())}}var k=S.left-w;k>0&&(S.right-S.left>w&&(l.style.width=w-5+"px",k-=S.right-S.left-w),l.style.left=(g=m.left-k)+"px"),f.addKeyMap(this.keyMap=s(r,{moveFocus:function(e,t){a.changeActive(a.selectedHint+e,t)},setFocus:function(e){a.changeActive(e)},menuSize:function(){return a.screenAmount()},length:c.length,close:function(){r.close()},pick:function(){a.pick()},data:u}));if(r.options.closeOnUnfocus){var L;f.on("blur",this.onBlur=function(){L=setTimeout(function(){r.close()},100)}),f.on("focus",this.onFocus=function(){clearTimeout(L)})}var A=f.getScrollInfo();return f.on("scroll",this.onScroll=function(){var e=f.getScrollInfo(),t=f.getWrapperElement().getBoundingClientRect(),n=y+A.top-e.top,i=n-(window.pageYOffset||(document.documentElement||document.body).scrollTop);b||(i+=l.offsetHeight);if(i<=t.top||i>=t.bottom)return r.close();l.style.top=n+"px",l.style.left=g+A.left-e.left+"px"}),e.on(l,"dblclick",function(e){var t=o(l,e.target||e.srcElement);t&&t.hintId!=null&&(a.changeActive(t.hintId),a.pick())}),e.on(l,"click",function(e){var t=o(l,e.target||e.srcElement);t&&t.hintId!=null&&(a.changeActive(t.hintId),r.options.completeOnSingleClick&&a.pick())}),e.on(l,"mousedown",function(){setTimeout(function(){f.focus()},20)}),e.signal(u,"select",c[0],l.firstChild),!0}var t="CodeMirror-hint",n="CodeMirror-hint-active";e.showHint=function(e,t,n){if(!t)return e.showHint(n);n&&n.async&&(t.async=!0);var r={hint:t};if(n)for(var i in n)r[i]=n[i];return e.showHint(r)},e.defineExtension("showHint",function(t){if(this.listSelections().length>1||this.somethingSelected())return;this.state.completionActive&&this.state.completionActive.close();var n=this.state.completionActive=new r(this,t),i=n.options.hint;if(!i)return;e.signal(this,"startCompletion",this);if(!i.async)return n.showHints(i(this,n.options));i(this,function(e){n.showHints(e)},n.options)}),r.prototype={close:function(){if(!this.active())return;this.cm.state.completionActive=null,this.widget&&this.widget.close(),this.onClose&&this.onClose(),e.signal(this.cm,"endCompletion",this.cm)},active:function(){return this.cm.state.completionActive==this},pick:function(t,n){var r=t.list[n];r.hint?r.hint(this.cm,t,r):this.cm.replaceRange(i(r),r.from||t.from,r.to||t.to,"complete"),e.signal(t,"pick",r),this.close()},showHints:function(e){if(!e||!e.list.length||!this.active())return this.close();this.options.completeSingle&&e.list.length==1?this.pick(e,0):this.showWidget(e)},showWidget:function(t){function c(){if(i)return;i=!0,r.close(),r.cm.off("cursorActivity",v),t&&e.signal(t,"close")}function h(){if(i)return;e.signal(t,"update");var n=r.options.hint;n.async?n(r.cm,p,r.options):p(n(r.cm,r.options))}function p(e){t=e;if(i)return;if(!t||!t.list.length)return c();r.widget&&r.widget.close(),r.widget=new u(r,t)}function d(){n&&(l(n),n=0)}function v(){d();var e=r.cm.getCursor(),t=r.cm.getLine(e.line);e.line!=o.line||t.length-e.ch!=a-o.ch||e.ch=this.data.list.length?t=r?this.data.list.length-1:0:t<0&&(t=r?0:this.data.list.length-1);if(this.selectedHint==t)return;var i=this.hints.childNodes[this.selectedHint];i.className=i.className.replace(" "+n,""),i=this.hints.childNodes[this.selectedHint=t],i.className+=" "+n,i.offsetTopthis.hints.scrollTop+this.hints.clientHeight&&(this.hints.scrollTop=i.offsetTop+i.offsetHeight-this.hints.clientHeight+3),e.signal(this.data,"select",this.data.list[this.selectedHint],i)},screenAmount:function(){return Math.floor(this.hints.clientHeight/this.hints.firstChild.offsetHeight)||1}},e.registerHelper("hint","auto",function(t,n){var r=t.getHelpers(t.getCursor(),"hint"),i;if(r.length)for(var s=0;s,]/,closeOnUnfocus:!0,completeOnSingleClick:!1,container:null,customKeys:null,extraKeys:null};e.defineOption("hintOptions",null)}),function(e){typeof exports=="object"&&typeof module=="object"?e(require("../../lib/codemirror")):typeof define=="function"&&define.amd?define("libs/codemirror-4.8/mode/xml/xml",["../../lib/codemirror"],e):e(CodeMirror)}(function(e){e.defineMode("xml",function(t,n){function l(e,t){function n(n){return t.tokenize=n,n(e,t)}var r=e.next();if(r=="<")return e.eat("!")?e.eat("[")?e.match("CDATA[")?n(p("atom","]]>")):null:e.match("--")?n(p("comment","-->")):e.match("DOCTYPE",!0,!0)?(e.eatWhile(/[\w\._\-]/),n(d(1))):null:e.eat("?")?(e.eatWhile(/[\w\._\-]/),t.tokenize=p("meta","?>"),"meta"):(a=e.eat("/")?"closeTag":"openTag",t.tokenize=c,"tag bracket");if(r=="&"){var i;return e.eat("#")?e.eat("x")?i=e.eatWhile(/[a-fA-F\d]/)&&e.eat(";"):i=e.eatWhile(/[\d]/)&&e.eat(";"):i=e.eatWhile(/[\w\.\-:]/)&&e.eat(";"),i?"atom":"error"}return e.eatWhile(/[^&<]/),null}function c(e,t){var n=e.next();if(n==">"||n=="/"&&e.eat(">"))return t.tokenize=l,a=n==">"?"endTag":"selfcloseTag","tag bracket";if(n=="=")return a="equals",null;if(n=="<"){t.tokenize=l,t.state=y,t.tagName=t.tagStart=null;var r=t.tokenize(e,t);return r?r+" tag error":"tag error"}return/[\'\"]/.test(n)?(t.tokenize=h(n),t.stringStartCol=e.column(),t.tokenize(e,t)):(e.match(/^[^\s\u00a0=<>\"\']*[^\s\u00a0=<>\"\'\/]/),"word")}function h(e){var t=function(t,n){while(!t.eol())if(t.next()==e){n.tokenize=c;break}return"string"};return t.isInAttribute=!0,t}function p(e,t){return function(n,r){while(!n.eol()){if(n.match(t)){r.tokenize=l;break}n.next()}return e}}function d(e){return function(t,n){var r;while((r=t.next())!=null){if(r=="<")return n.tokenize=d(e+1),n.tokenize(t,n);if(r==">"){if(e==1){n.tokenize=l;break}return n.tokenize=d(e-1),n.tokenize(t,n)}}return"meta"}}function v(e,t,n){this.prev=e.context,this.tagName=t,this.indent=e.indented,this.startOfLine=n;if(o.doNotIndent.hasOwnProperty(t)||e.context&&e.context.noIndent)this.noIndent=!0}function m(e){e.context&&(e.context=e.context.prev)}function g(e,t){var n;for(;;){if(!e.context)return;n=e.context.tagName;if(!o.contextGrabbers.hasOwnProperty(n)||!o.contextGrabbers[n].hasOwnProperty(t))return;m(e)}}function y(e,t,n){return e=="openTag"?(n.tagStart=t.column(),b):e=="closeTag"?w:y}function b(e,t,n){return e=="word"?(n.tagName=t.current(),f="tag",x):(f="error",b)}function w(e,t,n){if(e=="word"){var r=t.current();return n.context&&n.context.tagName!=r&&o.implicitlyClosed.hasOwnProperty(n.context.tagName)&&m(n),n.context&&n.context.tagName==r?(f="tag",E):(f="tag error",S)}return f="error",S}function E(e,t,n){return e!="endTag"?(f="error",E):(m(n),y)}function S(e,t,n){return f="error",E(e,t,n)}function x(e,t,n){if(e=="word")return f="attribute",T;if(e=="endTag"||e=="selfcloseTag"){var r=n.tagName,i=n.tagStart;return n.tagName=n.tagStart=null,e=="selfcloseTag"||o.autoSelfClosers.hasOwnProperty(r)?g(n,r):(g(n,r),n.context=new v(n,r,i==n.indented)),y}return f="error",x}function T(e,t,n){return e=="equals"?N:(o.allowMissing||(f="error"),x(e,t,n))}function N(e,t,n){return e=="string"?C:e=="word"&&o.allowUnquoted?(f="string",x):(f="error",x(e,t,n))}function C(e,t,n){return e=="string"?C:x(e,t,n)}var r=t.indentUnit,i=n.multilineTagIndentFactor||1,s=n.multilineTagIndentPastTag;s==null&&(s=!0);var o=n.htmlMode?{autoSelfClosers:{area:!0,base:!0,br:!0,col:!0,command:!0,embed:!0,frame:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0,menuitem:!0},implicitlyClosed:{dd:!0,li:!0,optgroup:!0,option:!0,p:!0,rp:!0,rt:!0,tbody:!0,td:!0,tfoot:!0,th:!0,tr:!0},contextGrabbers:{dd:{dd:!0,dt:!0},dt:{dd:!0,dt:!0},li:{li:!0},option:{option:!0,optgroup:!0},optgroup:{optgroup:!0},p:{address:!0,article:!0,aside:!0,blockquote:!0,dir:!0,div:!0,dl:!0,fieldset:!0,footer:!0,form:!0,h1:!0,h2:!0,h3:!0,h4:!0,h5:!0,h6:!0,header:!0,hgroup:!0,hr:!0,menu:!0,nav:!0,ol:!0,p:!0,pre:!0,section:!0,table:!0,ul:!0},rp:{rp:!0,rt:!0},rt:{rp:!0,rt:!0},tbody:{tbody:!0,tfoot:!0},td:{td:!0,th:!0},tfoot:{tbody:!0},th:{td:!0,th:!0},thead:{tbody:!0,tfoot:!0},tr:{tr:!0}},doNotIndent:{pre:!0},allowUnquoted:!0,allowMissing:!0,caseFold:!0}:{autoSelfClosers:{},implicitlyClosed:{},contextGrabbers:{},doNotIndent:{},allowUnquoted:!1,allowMissing:!1,caseFold:!1},u=n.alignCDATA,a,f;return{startState:function(){return{tokenize:l,state:y,indented:0,tagName:null,tagStart:null,context:null}},token:function(e,t){!t.tagName&&e.sol()&&(t.indented=e.indentation());if(e.eatSpace())return null;a=null;var n=t.tokenize(e,t);return(n||a)&&n!="comment"&&(f=null,t.state=t.state(a||n,e,t),f&&(n=f=="error"?n+" error":f)),n},indent:function(t,n,a){var f=t.context;if(t.tokenize.isInAttribute)return t.tagStart==t.indented?t.stringStartCol+1:t.indented+r;if(f&&f.noIndent)return e.Pass;if(t.tokenize!=c&&t.tokenize!=l)return a?a.match(/^(\s*)/)[0].length:0;if(t.tagName)return s?t.tagStart+t.tagName.length+2:t.tagStart+r*i;if(u&&/$/,blockCommentStart:"",configuration:n.htmlMode?"html":"xml",helperType:n.htmlMode?"html":"xml"}}),e.defineMIME("text/xml","xml"),e.defineMIME("application/xml","xml"),e.mimeModes.hasOwnProperty("text/html")||e.defineMIME("text/html",{name:"xml",htmlMode:!0})}),function(e){typeof exports=="object"&&typeof module=="object"?e(require("../../lib/codemirror")):typeof define=="function"&&define.amd?define("libs/codemirror-4.8/addon/runmode/runmode",["../../lib/codemirror"],e):e(CodeMirror)}(function(e){e.runMode=function(t,n,r,i){var s=e.getMode(e.defaults,n),o=/MSIE \d/.test(navigator.userAgent),u=o&&(document.documentMode==null||document.documentMode<9);if(r.nodeType==1){var a=i&&i.tabSize||e.defaults.tabSize,f=r,l=0;f.innerHTML="",r=function(e,t){if(e=="\n"){f.appendChild(document.createTextNode(u?"\r":e)),l=0;return}var n="";for(var r=0;;){var i=e.indexOf(" ",r);if(i==-1){n+=e.slice(r),l+=e.length-r;break}l+=i-r,n+=e.slice(r,i);var s=a-l%a;l+=s;for(var o=0;o/im,s=/]*>\s*([\s\S]+)\s*<\/body>/im,o=typeof location!="undefined"&&location.href,u=o&&location.protocol&&location.protocol.replace(/\:/,""),a=o&&location.hostname,f=o&&(location.port||undefined),l=[],c=e.config&&e.config()||{};t={version:"2.0.5",strip:function(e){if(e){e=e.replace(i,"");var t=e.match(s);t&&(e=t[1])}else e="";return e},jsEscape:function(e){return e.replace(/(['\\])/g,"\\$1").replace(/[\f]/g,"\\f").replace(/[\b]/g,"\\b").replace(/[\n]/g,"\\n").replace(/[\t]/g,"\\t").replace(/[\r]/g,"\\r").replace(/[\u2028]/g,"\\u2028").replace(/[\u2029]/g,"\\u2029")},createXhr:c.createXhr||function(){var e,t,n;if(typeof XMLHttpRequest!="undefined")return new XMLHttpRequest;if(typeof ActiveXObject!="undefined")for(t=0;t<3;t+=1){n=r[t];try{e=new ActiveXObject(n)}catch(i){}if(e){r=[n];break}}return e},parseName:function(e){var t,n,r,i=!1,s=e.indexOf("."),o=e.indexOf("./")===0||e.indexOf("../")===0;return s!==-1&&(!o||s>1)?(t=e.substring(0,s),n=e.substring(s+1,e.length)):t=e,r=n||t,s=r.indexOf("!"),s!==-1&&(i=r.substring(s+1)==="strip",r=r.substring(0,s),n?n=r:t=r),{moduleName:t,ext:n,strip:i}},xdRegExp:/^((\w+)\:)?\/\/([^\/\\]+)/,useXhr:function(e,n,r,i){var s,o,u,a=t.xdRegExp.exec(e);return a?(s=a[2],o=a[3],o=o.split(":"),u=o[1],o=o[0],(!s||s===n)&&(!o||o.toLowerCase()===r.toLowerCase())&&(!u&&!o||u===i)):!0},finishLoad:function(e,n,r,i){r=n?t.strip(r):r,c.isBuild&&(l[e]=r),i(r)},load:function(e,n,r,i){if(i.isBuild&&!i.inlineText){r();return}c.isBuild=i.isBuild;var s=t.parseName(e),l=s.moduleName+(s.ext?"."+s.ext:""),h=n.toUrl(l),p=c.useXhr||t.useXhr;!o||p(h,u,a,f)?t.get(h,function(n){t.finishLoad(e,s.strip,n,r)},function(e){r.error&&r.error(e)}):n([l],function(e){t.finishLoad(s.moduleName+"."+s.ext,s.strip,e,r)})},write:function(e,n,r,i){if(l.hasOwnProperty(n)){var s=t.jsEscape(l[n]);r.asModule(e+"!"+n,"define(function () { return '"+s+"';});\n")}},writeFile:function(e,n,r,i,s){var o=t.parseName(n),u=o.ext?"."+o.ext:"",a=o.moduleName+u,f=r.toUrl(o.moduleName+u)+".js";t.load(a,r,function(n){var r=function(e){return i(f,e)};r.asModule=function(e,t){return i.asModule(e,f,t)},t.write(e,a,r,s)},s)}};if(c.env==="node"||!c.env&&typeof process!="undefined"&&process.versions&&!!process.versions.node)n=require.nodeRequire("fs"),t.get=function(e,t){var r=n.readFileSync(e,"utf8");r.indexOf("")===0&&(r=r.substring(1)),t(r)};else if(c.env==="xhr"||!c.env&&t.createXhr())t.get=function(e,n,r,i){var s=t.createXhr(),o;s.open("GET",e,!0);if(i)for(o in i)i.hasOwnProperty(o)&&s.setRequestHeader(o.toLowerCase(),i[o]);c.onXhr&&c.onXhr(s,e),s.onreadystatechange=function(t){var i,o;s.readyState===4&&(i=s.status,i>399&&i<600?(o=new Error(e+" HTTP status: "+i),o.xhr=s,r(o)):n(s.responseText))},s.send(null)};else if(c.env==="rhino"||!c.env&&typeof Packages!="undefined"&&typeof java!="undefined")t.get=function(e,t){var n,r,i="utf-8",s=new java.io.File(e),o=java.lang.System.getProperty("line.separator"),u=new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(s),i)),a="";try{n=new java.lang.StringBuffer,r=u.readLine(),r&&r.length()&&r.charAt(0)===65279&&(r=r.substring(1)),n.append(r);while((r=u.readLine())!==null)n.append(o),n.append(r);a=String(n.toString())}finally{u.close()}t(a)};return t}),define("text!samples/hello.code",[],function(){return"var <%= name %> = React.createClass({\n render: function () {\n return <%= name %>RT.apply(this);\n }\n});"}),define("text!samples/hello.rt",[],function(){return"

Hello world

\n"}),define("text!samples/todo.code",[],function(){return"var <%= name %> = React.createClass({\n mixins: [React.addons.LinkedStateMixin],\n getInitialState: function () {\n return {edited: '', todos: [], counter: 0};\n },\n add: function () {\n if (this.state.edited.trim().length === 0) {\n return;\n }\n var newTodo = {value: this.state.edited, done: false, key: this.state.counter};\n this.setState({todos: this.state.todos.concat(newTodo), edited: '', counter: this.state.counter + 1});\n },\n remove: function (todo) {\n this.setState({todos: _.reject(this.state.todos, todo)});\n },\n toggleChecked: function (index) {\n var todos = _.cloneDeep(this.state.todos);\n todos[index].done = !todos[index].done;\n this.setState({todos: todos});\n },\n clearDone: function () {\n this.setState({todos: _.filter(this.state.todos, {done: false})});\n },\n render: function () {\n return <%= name %>RT.apply(this);\n }\n});"}),define("text!samples/todo.rt",[],function(){return'
\n {_.filter(this.state.todos, {done:true}).length}\n done,\n {_.filter(this.state.todos, {done:false}).length}\n pending\n
\n
\n \n \n {todo.value}\n
\n \n
\n \n
'}),define("text!samples/rt-if.code",[],function(){return"var <%= name %> = React.createClass({\n getInitialState: function () {\n return {open: false};\n },\n toggle: function() {\n this.setState({open: !this.state.open});\n },\n render: function () {\n return <%= name %>RT.apply(this);\n }\n});"}),define("text!samples/rt-if.rt",[],function(){return'
\n

\n Click to {this.state.open ? \'close\' : \'open\'}\n

\n

This is my paragraph. It opens and\n closes

\n
'}),define("text!samples/rt-props.code",[],function(){return"var <%= name %> = React.createClass({\n mixins: [React.addons.LinkedStateMixin],\n getInitialState: function() {\n return { key: 'color', val: 'blue' };\n },\n getProps: function() {\n var ret = { style: {\n color: 'black',\n backgroundColor: 'white',\n borderColor: 'black'\n }};\n ret.style[this.state.key] = this.state.val;\n return ret;\n },\n render: function () {\n return <%= name %>RT.apply(this);\n }\n});"}),define("text!samples/rt-props.rt",[],function(){return'
\n Style:\n
\n Value:\n

\n
Sample
\n
'}),define("text!samples/rt-repeat.code",[],function(){return"var <%= name %> = React.createClass({\n getInitialState: function () {\n return {\n items: ['One', 'Two', 'Three']\n };\n },\n render: function () {\n return <%= name %>RT.apply(this);\n }\n});"}),define("text!samples/rt-repeat.rt",[],function(){return'
\n
    \n
  • {item}
  • \n
\n
'}),define("text!samples/weather.code",[],function(){return"var <%= name %> = React.createClass({\n mixins: [React.addons.LinkedStateMixin],\n getInitialState: function() {\n this.cityIds = [5391959,293397,2643743];\n this.fetchWeather();\n return { loading: true, cityToAdd: '', info: [] };\n },\n addCity: function() {\n if (this.state.cityToAdd.trim() == '') {\n return;\n }\n this.setState({ loading: true, cityToAdd: '' });\n $.get('http://api.openweathermap.org/data/2.5/weather?q=' + this.state.cityToAdd, this.findCityCallback);\n },\n findCityCallback: function(result) {\n if (result.id && !_.contains(this.cityIds, result.id)) {\n this.cityIds.unshift(result.id);\n this.fetchWeather();\n } else {\n this.setState({ loading: false });\n }\n },\n refresh: function() {\n this.setState({ loading:true });\n this.fetchWeather();\n },\n fetchWeather: function() {\n $.get('http://api.openweathermap.org/data/2.5/group?id=' + this.cityIds.join(',') + '&units=metric', this.fetchWeatherCallback);\n },\n fetchWeatherCallback: function(result) {\n this.setState({ loading:false, info: result.list });\n },\n render: function () {\n return <%= name %>RT.apply(this);\n }\n});"}),define("text!samples/weather.rt",[],function(){return'
\n

Cities weather report

\n \n \n
\n -- Loading --\n
\n
\n {cityIndex+1})\n \n {city.name}, {city.sys.country}\n
\n \n
'}),define("text!samples/rt-require.rt",[],function(){return'\n\n
\n myComp is just a regular tag\n
\n'}),define("examples",["lodash","react","./examples.rt","text!./samples/hello.code","text!./samples/hello.rt","text!./samples/todo.code","text!./samples/todo.rt","text!./samples/rt-if.code","text!./samples/rt-if.rt","text!./samples/rt-props.code","text!./samples/rt-props.rt","text!./samples/rt-repeat.code","text!./samples/rt-repeat.rt","text!./samples/weather.code","text!./samples/weather.rt","text!./samples/rt-require.rt"],function(e,t,n,r,i,s,o,u,a,f,l,c,h,p,d,v){var m={hello:[r,i],todo:[s,o],props:[f,l],rtIf:[u,a],repeat:[c,h],weather:[p,d]};Object.keys(m).forEach(function(t){m[t]={name:t,templateProps:e.template(m[t][0],{name:t}),templateHTML:m[t][1]}});var g=t.createClass({displayName:"Examples",mixins:[t.addons.LinkedStateMixin],getInitialState:function(){var e=window.reactTemplates.convertTemplateToReact(v,{modules:"amd",name:"template"}),t=window.reactTemplates.convertTemplateToReact(v,{modules:"commonjs",name:"template"}),n=window.reactTemplates.convertTemplateToReact(v,{modules:"es6",name:"template"});return{rtRequire:{value:v},amd:{value:e},cjs:{value:t},es6:{value:n},samples:m}},render:n});return g}),requirejs.config({paths:{lodash:"//cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.min",jquery:"//code.jquery.com/jquery-1.11.0.min",firebase:"https://cdn.firebase.com/js/client/2.0.5/firebase",react:"//fb.me/react-with-addons-0.12.2",text:"libs/requirejs-plugins/text",json:"libs/requirejs-plugins/json"},shim:{lodash:{exports:"_"},firebase:{exports:"Firebase"},jquery:{exports:"$"},react:{exports:"React"}},map:{"*":{"react/addons":"react"}}}),requirejs(["jquery","react","./examples"],function(e,t,n){var r=t.createElement(n);t.render(r,document.getElementById("home-section"))}),define("home-main.js",function(){}); \ No newline at end of file diff --git a/playground/dist/rt-main.browser.js b/playground/dist/rt-main.browser.js index 5d744f4..b93c483 100644 --- a/playground/dist/rt-main.browser.js +++ b/playground/dist/rt-main.browser.js @@ -1532,7 +1532,7 @@ exports.update = function(arr, parent) { // module.exports = $.extend(exports); }).call(this,require("buffer").Buffer) -},{"buffer":82,"htmlparser2":44}],8:[function(require,module,exports){ +},{"buffer":83,"htmlparser2":44}],8:[function(require,module,exports){ /** * Module dependencies */ @@ -3460,8 +3460,8 @@ function renderComment(elem) { } },{"domelementtype":28,"entities":29}],28:[function(require,module,exports){ -module.exports=require(26) -},{"/Users/idok/Projects/react-templates/node_modules/cheerio/node_modules/CSSselect/node_modules/domutils/node_modules/domelementtype/index.js":26}],29:[function(require,module,exports){ +arguments[4][26][0].apply(exports,arguments) +},{"dup":26}],29:[function(require,module,exports){ var encode = require("./lib/encode.js"), decode = require("./lib/decode.js"); @@ -3835,7 +3835,7 @@ FeedHandler.prototype.onend = function(){ module.exports = FeedHandler; -},{"./index.js":44,"util":105}],39:[function(require,module,exports){ +},{"./index.js":44,"util":106}],39:[function(require,module,exports){ var Tokenizer = require("./Tokenizer.js"); /* @@ -4187,7 +4187,7 @@ Parser.prototype.done = Parser.prototype.end; module.exports = Parser; -},{"./Tokenizer.js":42,"events":86,"util":105}],40:[function(require,module,exports){ +},{"./Tokenizer.js":42,"events":87,"util":106}],40:[function(require,module,exports){ module.exports = ProxyHandler; function ProxyHandler(cbs){ @@ -4251,7 +4251,7 @@ Object.keys(EVENTS).forEach(function(name){ throw Error("wrong number of arguments!"); } }); -},{"../":44,"./WritableStream.js":43,"util":105}],42:[function(require,module,exports){ +},{"../":44,"./WritableStream.js":43,"util":106}],42:[function(require,module,exports){ module.exports = Tokenizer; var decodeCodePoint = require("entities/lib/decode_codepoint.js"), @@ -5181,7 +5181,7 @@ WritableStream.prototype._write = function(chunk, encoding, cb){ this._parser.write(chunk); cb(); }; -},{"./Parser.js":39,"readable-stream":81,"stream":102,"util":105}],44:[function(require,module,exports){ +},{"./Parser.js":39,"readable-stream":82,"stream":103,"util":106}],44:[function(require,module,exports){ var Parser = require("./Parser.js"), DomHandler = require("domhandler"); @@ -5252,8 +5252,8 @@ module.exports = { }; },{"./CollectingHandler.js":37,"./FeedHandler.js":38,"./Parser.js":39,"./ProxyHandler.js":40,"./Stream.js":41,"./Tokenizer.js":42,"./WritableStream.js":43,"domelementtype":45,"domhandler":46,"domutils":49}],45:[function(require,module,exports){ -module.exports=require(26) -},{"/Users/idok/Projects/react-templates/node_modules/cheerio/node_modules/CSSselect/node_modules/domutils/node_modules/domelementtype/index.js":26}],46:[function(require,module,exports){ +arguments[4][26][0].apply(exports,arguments) +},{"dup":26}],46:[function(require,module,exports){ var ElementType = require("domelementtype"); var re_whitespace = /\s+/g; @@ -5507,7 +5507,7 @@ Object.keys(domLvl1).forEach(function(key) { },{}],49:[function(require,module,exports){ arguments[4][19][0].apply(exports,arguments) -},{"./lib/helpers":50,"./lib/legacy":51,"./lib/manipulation":52,"./lib/querying":53,"./lib/stringify":54,"./lib/traversal":55,"/Users/idok/Projects/react-templates/node_modules/cheerio/node_modules/CSSselect/node_modules/domutils/index.js":19}],50:[function(require,module,exports){ +},{"./lib/helpers":50,"./lib/legacy":51,"./lib/manipulation":52,"./lib/querying":53,"./lib/stringify":54,"./lib/traversal":55,"dup":19}],50:[function(require,module,exports){ // removeSubsets // Given an array of nodes, remove any member that is contained by another. exports.removeSubsets = function(nodes) { @@ -5651,26 +5651,26 @@ exports.uniqueSort = function(nodes) { }; },{}],51:[function(require,module,exports){ -module.exports=require(21) -},{"/Users/idok/Projects/react-templates/node_modules/cheerio/node_modules/CSSselect/node_modules/domutils/lib/legacy.js":21,"domelementtype":45}],52:[function(require,module,exports){ -module.exports=require(22) -},{"/Users/idok/Projects/react-templates/node_modules/cheerio/node_modules/CSSselect/node_modules/domutils/lib/manipulation.js":22}],53:[function(require,module,exports){ -module.exports=require(23) -},{"/Users/idok/Projects/react-templates/node_modules/cheerio/node_modules/CSSselect/node_modules/domutils/lib/querying.js":23,"domelementtype":45}],54:[function(require,module,exports){ -module.exports=require(24) -},{"/Users/idok/Projects/react-templates/node_modules/cheerio/node_modules/CSSselect/node_modules/domutils/lib/stringify.js":24,"domelementtype":45}],55:[function(require,module,exports){ -module.exports=require(25) -},{"/Users/idok/Projects/react-templates/node_modules/cheerio/node_modules/CSSselect/node_modules/domutils/lib/traversal.js":25}],56:[function(require,module,exports){ -module.exports=require(31) -},{"../maps/decode.json":57,"/Users/idok/Projects/react-templates/node_modules/cheerio/node_modules/entities/lib/decode_codepoint.js":31}],57:[function(require,module,exports){ -module.exports=require(33) -},{"/Users/idok/Projects/react-templates/node_modules/cheerio/node_modules/entities/maps/decode.json":33}],58:[function(require,module,exports){ -module.exports=require(34) -},{"/Users/idok/Projects/react-templates/node_modules/cheerio/node_modules/entities/maps/entities.json":34}],59:[function(require,module,exports){ -module.exports=require(35) -},{"/Users/idok/Projects/react-templates/node_modules/cheerio/node_modules/entities/maps/legacy.json":35}],60:[function(require,module,exports){ -module.exports=require(36) -},{"/Users/idok/Projects/react-templates/node_modules/cheerio/node_modules/entities/maps/xml.json":36}],61:[function(require,module,exports){ +arguments[4][21][0].apply(exports,arguments) +},{"domelementtype":45,"dup":21}],52:[function(require,module,exports){ +arguments[4][22][0].apply(exports,arguments) +},{"dup":22}],53:[function(require,module,exports){ +arguments[4][23][0].apply(exports,arguments) +},{"domelementtype":45,"dup":23}],54:[function(require,module,exports){ +arguments[4][24][0].apply(exports,arguments) +},{"domelementtype":45,"dup":24}],55:[function(require,module,exports){ +arguments[4][25][0].apply(exports,arguments) +},{"dup":25}],56:[function(require,module,exports){ +arguments[4][31][0].apply(exports,arguments) +},{"../maps/decode.json":57,"dup":31}],57:[function(require,module,exports){ +arguments[4][33][0].apply(exports,arguments) +},{"dup":33}],58:[function(require,module,exports){ +arguments[4][34][0].apply(exports,arguments) +},{"dup":34}],59:[function(require,module,exports){ +arguments[4][35][0].apply(exports,arguments) +},{"dup":35}],60:[function(require,module,exports){ +arguments[4][36][0].apply(exports,arguments) +},{"dup":36}],61:[function(require,module,exports){ (function (global){ /** * @license @@ -12486,11 +12486,11 @@ module.exports={ "node": ">= 0.6" }, "dependencies": { - "CSSselect": "~0.4.0", + "CSSselect": "^0.4.1", + "dom-serializer": "~0.0.0", "entities": "~1.1.1", "htmlparser2": "~3.8.1", - "dom-serializer": "~0.0.0", - "lodash": "~2.4.1" + "lodash": "^2.4.1" }, "devDependencies": { "benchmark": "~1.0.0", @@ -12546,6 +12546,7 @@ module.exports={ (function (global){ /* Copyright (C) 2012-2014 Yusuke Suzuki + Copyright (C) 2015 Ingvar Stepanyan Copyright (C) 2014 Ivan Nikulin Copyright (C) 2012-2013 Michael Ficarra Copyright (C) 2012-2013 Mathias Bynens @@ -12605,79 +12606,15 @@ module.exports={ extra, parse, sourceMap, + sourceCode, + preserveBlankLines, FORMAT_MINIFY, FORMAT_DEFAULTS; estraverse = require('estraverse'); esutils = require('esutils'); - Syntax = { - AssignmentExpression: 'AssignmentExpression', - ArrayExpression: 'ArrayExpression', - ArrayPattern: 'ArrayPattern', - ArrowFunctionExpression: 'ArrowFunctionExpression', - BlockStatement: 'BlockStatement', - BinaryExpression: 'BinaryExpression', - BreakStatement: 'BreakStatement', - CallExpression: 'CallExpression', - CatchClause: 'CatchClause', - ClassBody: 'ClassBody', - ClassDeclaration: 'ClassDeclaration', - ClassExpression: 'ClassExpression', - ComprehensionBlock: 'ComprehensionBlock', - ComprehensionExpression: 'ComprehensionExpression', - ConditionalExpression: 'ConditionalExpression', - ContinueStatement: 'ContinueStatement', - DirectiveStatement: 'DirectiveStatement', - DoWhileStatement: 'DoWhileStatement', - DebuggerStatement: 'DebuggerStatement', - EmptyStatement: 'EmptyStatement', - ExportBatchSpecifier: 'ExportBatchSpecifier', - ExportDeclaration: 'ExportDeclaration', - ExportSpecifier: 'ExportSpecifier', - ExpressionStatement: 'ExpressionStatement', - ForStatement: 'ForStatement', - ForInStatement: 'ForInStatement', - ForOfStatement: 'ForOfStatement', - FunctionDeclaration: 'FunctionDeclaration', - FunctionExpression: 'FunctionExpression', - GeneratorExpression: 'GeneratorExpression', - Identifier: 'Identifier', - IfStatement: 'IfStatement', - ImportDeclaration: 'ImportDeclaration', - ImportDefaultSpecifier: 'ImportDefaultSpecifier', - ImportNamespaceSpecifier: 'ImportNamespaceSpecifier', - ImportSpecifier: 'ImportSpecifier', - Literal: 'Literal', - LabeledStatement: 'LabeledStatement', - LogicalExpression: 'LogicalExpression', - MemberExpression: 'MemberExpression', - MethodDefinition: 'MethodDefinition', - ModuleSpecifier: 'ModuleSpecifier', - NewExpression: 'NewExpression', - ObjectExpression: 'ObjectExpression', - ObjectPattern: 'ObjectPattern', - Program: 'Program', - Property: 'Property', - ReturnStatement: 'ReturnStatement', - SequenceExpression: 'SequenceExpression', - SpreadElement: 'SpreadElement', - SwitchStatement: 'SwitchStatement', - SwitchCase: 'SwitchCase', - TaggedTemplateExpression: 'TaggedTemplateExpression', - TemplateElement: 'TemplateElement', - TemplateLiteral: 'TemplateLiteral', - ThisExpression: 'ThisExpression', - ThrowStatement: 'ThrowStatement', - TryStatement: 'TryStatement', - UnaryExpression: 'UnaryExpression', - UpdateExpression: 'UpdateExpression', - VariableDeclaration: 'VariableDeclaration', - VariableDeclarator: 'VariableDeclarator', - WhileStatement: 'WhileStatement', - WithStatement: 'WithStatement', - YieldExpression: 'YieldExpression' - }; + Syntax = estraverse.Syntax; // Generation is done by generateExpression. function isExpression(node) { @@ -12692,6 +12629,7 @@ module.exports={ Precedence = { Sequence: 0, Yield: 1, + Await: 1, Assignment: 1, Conditional: 2, ArrowFunction: 2, @@ -12797,7 +12735,8 @@ module.exports={ compact: false, parentheses: true, semicolons: true, - safeConcatenation: false + safeConcatenation: false, + preserveBlankLines: false }, moz: { comprehensionExpressionStartsWithAssignment: false, @@ -12808,7 +12747,8 @@ module.exports={ sourceMapWithCode: false, directive: false, raw: true, - verbatim: null + verbatim: null, + sourceCode: null }; } @@ -13257,7 +13197,11 @@ module.exports={ return '//' + comment.value; } else { // Always use LineTerminator - return '//' + comment.value + '\n'; + var result = '//' + comment.value; + if (!preserveBlankLines) { + result += '\n'; + } + return result; } } if (extra.format.indent.adjustMultilineComment && /[\n\r]/.test(comment.value)) { @@ -13267,56 +13211,111 @@ module.exports={ } function addComments(stmt, result) { - var i, len, comment, save, tailingToStatement, specialBase, fragment; + var i, len, comment, save, tailingToStatement, specialBase, fragment, + extRange, range, prevRange, prefix, infix, suffix, count; if (stmt.leadingComments && stmt.leadingComments.length > 0) { save = result; - comment = stmt.leadingComments[0]; - result = []; - if (safeConcatenation && stmt.type === Syntax.Program && stmt.body.length === 0) { - result.push('\n'); - } - result.push(generateComment(comment)); - if (!endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) { - result.push('\n'); - } + if (preserveBlankLines) { + comment = stmt.leadingComments[0]; + result = []; - for (i = 1, len = stmt.leadingComments.length; i < len; ++i) { - comment = stmt.leadingComments[i]; - fragment = [generateComment(comment)]; - if (!endsWithLineTerminator(toSourceNodeWhenNeeded(fragment).toString())) { - fragment.push('\n'); + extRange = comment.extendedRange; + range = comment.range; + + prefix = sourceCode.substring(extRange[0], range[0]); + count = (prefix.match(/\n/g) || []).length; + if (count > 0) { + result.push(stringRepeat('\n', count)); + result.push(addIndent(generateComment(comment))); + } else { + result.push(prefix); + result.push(generateComment(comment)); + } + + prevRange = range; + + for (i = 1, len = stmt.leadingComments.length; i < len; i++) { + comment = stmt.leadingComments[i]; + range = comment.range; + + infix = sourceCode.substring(prevRange[1], range[0]); + count = (infix.match(/\n/g) || []).length; + result.push(stringRepeat('\n', count)); + result.push(addIndent(generateComment(comment))); + + prevRange = range; + } + + suffix = sourceCode.substring(range[1], extRange[1]); + count = (suffix.match(/\n/g) || []).length; + result.push(stringRepeat('\n', count)); + } else { + comment = stmt.leadingComments[0]; + result = []; + if (safeConcatenation && stmt.type === Syntax.Program && stmt.body.length === 0) { + result.push('\n'); + } + result.push(generateComment(comment)); + if (!endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) { + result.push('\n'); + } + + for (i = 1, len = stmt.leadingComments.length; i < len; ++i) { + comment = stmt.leadingComments[i]; + fragment = [generateComment(comment)]; + if (!endsWithLineTerminator(toSourceNodeWhenNeeded(fragment).toString())) { + fragment.push('\n'); + } + result.push(addIndent(fragment)); } - result.push(addIndent(fragment)); } result.push(addIndent(save)); } if (stmt.trailingComments) { - tailingToStatement = !endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString()); - specialBase = stringRepeat(' ', calculateSpaces(toSourceNodeWhenNeeded([base, result, indent]).toString())); - for (i = 0, len = stmt.trailingComments.length; i < len; ++i) { - comment = stmt.trailingComments[i]; - if (tailingToStatement) { - // We assume target like following script - // - // var t = 20; /** - // * This is comment of t - // */ - if (i === 0) { - // first case - result = [result, indent]; - } else { - result = [result, specialBase]; - } - result.push(generateComment(comment, specialBase)); + + if (preserveBlankLines) { + comment = stmt.trailingComments[0]; + extRange = comment.extendedRange; + range = comment.range; + + prefix = sourceCode.substring(extRange[0], range[0]); + count = (prefix.match(/\n/g) || []).length; + + if (count > 0) { + result.push(stringRepeat('\n', count)); + result.push(addIndent(generateComment(comment))); } else { - result = [result, addIndent(generateComment(comment))]; + result.push(prefix); + result.push(generateComment(comment)); } - if (i !== len - 1 && !endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) { - result = [result, '\n']; + } else { + tailingToStatement = !endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString()); + specialBase = stringRepeat(' ', calculateSpaces(toSourceNodeWhenNeeded([base, result, indent]).toString())); + for (i = 0, len = stmt.trailingComments.length; i < len; ++i) { + comment = stmt.trailingComments[i]; + if (tailingToStatement) { + // We assume target like following script + // + // var t = 20; /** + // * This is comment of t + // */ + if (i === 0) { + // first case + result = [result, indent]; + } else { + result = [result, specialBase]; + } + result.push(generateComment(comment, specialBase)); + } else { + result = [result, addIndent(generateComment(comment))]; + } + if (i !== len - 1 && !endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) { + result = [result, '\n']; + } } } } @@ -13324,6 +13323,20 @@ module.exports={ return result; } + function generateBlankLines(start, end, result) { + var j, newlineCount = 0; + + for (j = start; j < end; j++) { + if (sourceCode[j] === '\n') { + newlineCount++; + } + } + + for (j = 1; j < newlineCount; j++) { + result.push(newline); + } + } + function parenthesize(text, current, should) { if (current < should) { return ['(', text, ')']; @@ -13399,6 +13412,25 @@ module.exports={ return toSourceNodeWhenNeeded(node.name, node); } + function generateAsyncPrefix(node, spaceRequired) { + return node.async ? 'async' + (spaceRequired ? noEmptySpace() : space) : ''; + } + + function generateStarSuffix(node) { + var isGenerator = node.generator && !extra.moz.starlessGenerator; + return isGenerator ? '*' + space : ''; + } + + function generateMethodPrefix(prop) { + var func = prop.value; + if (func.async) { + return generateAsyncPrefix(func, !prop.computed); + } else { + // avoid space before method name + return generateStarSuffix(func) ? '*' : ''; + } + } + CodeGenerator.prototype.generatePattern = function (node, precedence, flags) { if (node.type === Syntax.Identifier) { return generateIdentifier(node); @@ -13415,9 +13447,10 @@ module.exports={ !node.rest && (!node.defaults || node.defaults.length === 0) && node.params.length === 1 && node.params[0].type === Syntax.Identifier) { // arg => { } case - result = [generateIdentifier(node.params[0])]; + result = [generateAsyncPrefix(node, true), generateIdentifier(node.params[0])]; } else { - result = ['(']; + result = node.type === Syntax.ArrowFunctionExpression ? [generateAsyncPrefix(node, false)] : []; + result.push('('); if (node.defaults) { hasDefault = true; } @@ -13536,22 +13569,81 @@ module.exports={ CodeGenerator.Statement = { BlockStatement: function (stmt, flags) { - var result = ['{', newline], that = this; + var range, content, result = ['{', newline], that = this; withIndent(function () { + // handle functions without any code + if (stmt.body.length === 0 && preserveBlankLines) { + range = stmt.range; + if (range[1] - range[0] > 2) { + content = sourceCode.substring(range[0] + 1, range[1] - 1); + if (content[0] === '\n') { + result = ['{']; + } + result.push(content); + } + } + var i, iz, fragment, bodyFlags; bodyFlags = S_TFFF; if (flags & F_FUNC_BODY) { bodyFlags |= F_DIRECTIVE_CTX; } + for (i = 0, iz = stmt.body.length; i < iz; ++i) { + if (preserveBlankLines) { + // handle spaces before the first line + if (i === 0) { + if (stmt.body[0].leadingComments) { + range = stmt.body[0].leadingComments[0].extendedRange; + content = sourceCode.substring(range[0], range[1]); + if (content[0] === '\n') { + result = ['{']; + } + } + if (!stmt.body[0].leadingComments) { + generateBlankLines(stmt.range[0], stmt.body[0].range[0], result); + } + } + + // handle spaces between lines + if (i > 0) { + if (!stmt.body[i - 1].trailingComments && !stmt.body[i].leadingComments) { + generateBlankLines(stmt.body[i - 1].range[1], stmt.body[i].range[0], result); + } + } + } + if (i === iz - 1) { bodyFlags |= F_SEMICOLON_OPT; } - fragment = addIndent(that.generateStatement(stmt.body[i], bodyFlags)); + + if (stmt.body[i].leadingComments && preserveBlankLines) { + fragment = that.generateStatement(stmt.body[i], bodyFlags); + } else { + fragment = addIndent(that.generateStatement(stmt.body[i], bodyFlags)); + } + result.push(fragment); if (!endsWithLineTerminator(toSourceNodeWhenNeeded(fragment).toString())) { - result.push(newline); + if (preserveBlankLines && i < iz - 1) { + // don't add a new line if there are leading coments + // in the next statement + if (!stmt.body[i + 1].leadingComments) { + result.push(newline); + } + } else { + result.push(newline); + } + } + + if (preserveBlankLines) { + // handle spaces after the last line + if (i === iz - 1) { + if (!stmt.body[i].trailingComments) { + generateBlankLines(stmt.body[i].range[1], stmt.range[1], result); + } + } } } }); @@ -13722,13 +13814,55 @@ module.exports={ ExpressionStatement: function (stmt, flags) { var result, fragment; + function isClassPrefixed(fragment) { + var code; + if (fragment.slice(0, 5) !== 'class') { + return false; + } + code = fragment.charCodeAt(5); + return code === 0x7B /* '{' */ || esutils.code.isWhiteSpace(code) || esutils.code.isLineTerminator(code); + } + + function isFunctionPrefixed(fragment) { + var code; + if (fragment.slice(0, 8) !== 'function') { + return false; + } + code = fragment.charCodeAt(8); + return code === 0x28 /* '(' */ || esutils.code.isWhiteSpace(code) || code === 0x2A /* '*' */ || esutils.code.isLineTerminator(code); + } + + function isAsyncPrefixed(fragment) { + var code, i, iz; + if (fragment.slice(0, 5) !== 'async') { + return false; + } + if (!esutils.code.isWhiteSpace(fragment.charCodeAt(5))) { + return false; + } + for (i = 6, iz = fragment.length; i < iz; ++i) { + if (!esutils.code.isWhiteSpace(fragment.charCodeAt(i))) { + break; + } + } + if (i === iz) { + return false; + } + if (fragment.slice(i, i + 8) !== 'function') { + return false; + } + code = fragment.charCodeAt(i + 8); + return code === 0x28 /* '(' */ || esutils.code.isWhiteSpace(code) || code === 0x2A /* '*' */ || esutils.code.isLineTerminator(code); + } + result = [this.generateExpression(stmt.expression, Precedence.Sequence, E_TTT)]; // 12.4 '{', 'function', 'class' is not allowed in this position. // wrap expression with parentheses fragment = toSourceNodeWhenNeeded(result).toString(); - if (fragment.charAt(0) === '{' || // ObjectExpression - (fragment.slice(0, 5) === 'class' && ' {'.indexOf(fragment.charAt(5)) >= 0) || // class - (fragment.slice(0, 8) === 'function' && '* ('.indexOf(fragment.charAt(8)) >= 0) || // function or generator + if (fragment.charCodeAt(0) === 0x7B /* '{' */ || // ObjectExpression + isClassPrefixed(fragment) || + isFunctionPrefixed(fragment) || + isAsyncPrefixed(fragment) || (directive && (flags & F_DIRECTIVE_CTX) && stmt.expression.type === Syntax.Literal && typeof stmt.expression.value === 'string')) { result = ['(', result, ')' + this.semicolon(flags)]; } else { @@ -14086,20 +14220,52 @@ module.exports={ if (!safeConcatenation && i === iz - 1) { bodyFlags |= F_SEMICOLON_OPT; } + + if (preserveBlankLines) { + // handle spaces before the first line + if (i === 0) { + if (!stmt.body[0].leadingComments) { + generateBlankLines(stmt.range[0], stmt.body[i].range[0], result); + } + } + + // handle spaces between lines + if (i > 0) { + if (!stmt.body[i - 1].trailingComments && !stmt.body[i].leadingComments) { + generateBlankLines(stmt.body[i - 1].range[1], stmt.body[i].range[0], result); + } + } + } + fragment = addIndent(this.generateStatement(stmt.body[i], bodyFlags)); result.push(fragment); if (i + 1 < iz && !endsWithLineTerminator(toSourceNodeWhenNeeded(fragment).toString())) { - result.push(newline); + if (preserveBlankLines) { + if (!stmt.body[i + 1].leadingComments) { + result.push(newline); + } + } else { + result.push(newline); + } + } + + if (preserveBlankLines) { + // handle spaces after the last line + if (i === iz - 1) { + if (!stmt.body[i].trailingComments) { + generateBlankLines(stmt.body[i].range[1], stmt.range[1], result); + } + } } } return result; }, FunctionDeclaration: function (stmt, flags) { - var isGenerator = stmt.generator && !extra.moz.starlessGenerator; return [ - (isGenerator ? 'function*' : 'function'), - (isGenerator ? space : noEmptySpace()), + generateAsyncPrefix(stmt, true), + 'function', + generateStarSuffix(stmt) || noEmptySpace(), generateIdentifier(stmt.id), this.generateFunctionBody(stmt) ]; @@ -14356,6 +14522,14 @@ module.exports={ return parenthesize(result, Precedence.Yield, precedence); }, + AwaitExpression: function (expr, precedence, flags) { + var result = join( + expr.delegate ? 'await*' : 'await', + this.generateExpression(expr.argument, Precedence.Await, E_TTT) + ); + return parenthesize(result, Precedence.Await, precedence); + }, + UpdateExpression: function (expr, precedence, flags) { if (expr.prefix) { return parenthesize( @@ -14378,14 +14552,18 @@ module.exports={ }, FunctionExpression: function (expr, precedence, flags) { - var result, isGenerator; - isGenerator = expr.generator && !extra.moz.starlessGenerator; - result = isGenerator ? 'function*' : 'function'; - + var result = [ + generateAsyncPrefix(expr, true), + 'function' + ]; if (expr.id) { - return [result, (isGenerator) ? space : noEmptySpace(), generateIdentifier(expr.id), this.generateFunctionBody(expr)]; + result.push(generateStarSuffix(expr) || noEmptySpace()); + result.push(generateIdentifier(expr.id)); + } else { + result.push(generateStarSuffix(expr) || space); } - return [result + space, this.generateFunctionBody(expr)]; + result.push(this.generateFunctionBody(expr)); + return result; }, ExportBatchSpecifier: function (expr, precedence, flags) { @@ -14452,29 +14630,22 @@ module.exports={ } else { result = []; } - if (expr.kind === 'get' || expr.kind === 'set') { - result = join(result, [ + fragment = [ join(expr.kind, this.generatePropertyKey(expr.key, expr.computed)), this.generateFunctionBody(expr.value) - ]); + ]; } else { fragment = [ + generateMethodPrefix(expr), this.generatePropertyKey(expr.key, expr.computed), this.generateFunctionBody(expr.value) ]; - if (expr.value.generator) { - result.push('*'); - result.push(fragment); - } else { - result = join(result, fragment); - } } - return result; + return join(result, fragment); }, Property: function (expr, precedence, flags) { - var result; if (expr.kind === 'get' || expr.kind === 'set') { return [ expr.kind, noEmptySpace(), @@ -14488,13 +14659,11 @@ module.exports={ } if (expr.method) { - result = []; - if (expr.value.generator) { - result.push('*'); - } - result.push(this.generatePropertyKey(expr.key, expr.computed)); - result.push(this.generateFunctionBody(expr.value)); - return result; + return [ + generateMethodPrefix(expr), + this.generatePropertyKey(expr.key, expr.computed), + this.generateFunctionBody(expr.value) + ]; } return [ @@ -14869,6 +15038,8 @@ module.exports={ directive = options.directive; parse = json ? null : options.parse; sourceMap = options.sourceMap; + sourceCode = options.sourceCode; + preserveBlankLines = options.format.preserveBlankLines && sourceCode !== null; extra = options; if (sourceMap) { @@ -14933,7 +15104,7 @@ module.exports={ /* vim: set sw=4 ts=4 et tw=80 : */ }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"./package.json":79,"estraverse":64,"esutils":68,"source-map":69}],64:[function(require,module,exports){ +},{"./package.json":80,"estraverse":64,"esutils":68,"source-map":69}],64:[function(require,module,exports){ /* Copyright (C) 2012-2013 Yusuke Suzuki Copyright (C) 2012 Ariya Hidayat @@ -16211,7 +16382,7 @@ exports.SourceMapGenerator = require('./source-map/source-map-generator').Source exports.SourceMapConsumer = require('./source-map/source-map-consumer').SourceMapConsumer; exports.SourceNode = require('./source-map/source-node').SourceNode; -},{"./source-map/source-map-consumer":74,"./source-map/source-map-generator":75,"./source-map/source-node":76}],70:[function(require,module,exports){ +},{"./source-map/source-map-consumer":75,"./source-map/source-map-generator":76,"./source-map/source-node":77}],70:[function(require,module,exports){ /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors @@ -16310,7 +16481,7 @@ define(function (require, exports, module) { }); -},{"./util":77,"amdefine":78}],71:[function(require,module,exports){ +},{"./util":78,"amdefine":79}],71:[function(require,module,exports){ /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors @@ -16454,7 +16625,7 @@ define(function (require, exports, module) { }); -},{"./base64":72,"amdefine":78}],72:[function(require,module,exports){ +},{"./base64":72,"amdefine":79}],72:[function(require,module,exports){ /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors @@ -16498,7 +16669,7 @@ define(function (require, exports, module) { }); -},{"amdefine":78}],73:[function(require,module,exports){ +},{"amdefine":79}],73:[function(require,module,exports){ /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors @@ -16580,7 +16751,95 @@ define(function (require, exports, module) { }); -},{"amdefine":78}],74:[function(require,module,exports){ +},{"amdefine":79}],74:[function(require,module,exports){ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2014 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ +if (typeof define !== 'function') { + var define = require('amdefine')(module, require); +} +define(function (require, exports, module) { + + var util = require('./util'); + + /** + * Determine whether mappingB is after mappingA with respect to generated + * position. + */ + function generatedPositionAfter(mappingA, mappingB) { + // Optimized for most common case + var lineA = mappingA.generatedLine; + var lineB = mappingB.generatedLine; + var columnA = mappingA.generatedColumn; + var columnB = mappingB.generatedColumn; + return lineB > lineA || lineB == lineA && columnB >= columnA || + util.compareByGeneratedPositions(mappingA, mappingB) <= 0; + } + + /** + * A data structure to provide a sorted view of accumulated mappings in a + * performance conscious manner. It trades a neglibable overhead in general + * case for a large speedup in case of mappings being added in order. + */ + function MappingList() { + this._array = []; + this._sorted = true; + // Serves as infimum + this._last = {generatedLine: -1, generatedColumn: 0}; + } + + /** + * Iterate through internal items. This method takes the same arguments that + * `Array.prototype.forEach` takes. + * + * NOTE: The order of the mappings is NOT guaranteed. + */ + MappingList.prototype.unsortedForEach = + function MappingList_forEach(aCallback, aThisArg) { + this._array.forEach(aCallback, aThisArg); + }; + + /** + * Add the given source mapping. + * + * @param Object aMapping + */ + MappingList.prototype.add = function MappingList_add(aMapping) { + var mapping; + if (generatedPositionAfter(this._last, aMapping)) { + this._last = aMapping; + this._array.push(aMapping); + } else { + this._sorted = false; + this._array.push(aMapping); + } + }; + + /** + * Returns the flat, sorted array of mappings. The mappings are sorted by + * generated position. + * + * WARNING: This method returns internal data without copying, for + * performance. The return value must NOT be mutated, and should be treated as + * an immutable borrow. If you want to take ownership, you must make your own + * copy. + */ + MappingList.prototype.toArray = function MappingList_toArray() { + if (!this._sorted) { + this._array.sort(util.compareByGeneratedPositions); + this._sorted = true; + } + return this._array; + }; + + exports.MappingList = MappingList; + +}); + +},{"./util":78,"amdefine":79}],75:[function(require,module,exports){ /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors @@ -16685,9 +16944,8 @@ define(function (require, exports, module) { smc.sourceRoot); smc.file = aSourceMap._file; - smc.__generatedMappings = aSourceMap._mappings.slice() - .sort(util.compareByGeneratedPositions); - smc.__originalMappings = aSourceMap._mappings.slice() + smc.__generatedMappings = aSourceMap._mappings.toArray().slice(); + smc.__originalMappings = aSourceMap._mappings.toArray().slice() .sort(util.compareByOriginalPositions); return smc; @@ -17158,7 +17416,7 @@ define(function (require, exports, module) { }); -},{"./array-set":70,"./base64-vlq":71,"./binary-search":73,"./util":77,"amdefine":78}],75:[function(require,module,exports){ +},{"./array-set":70,"./base64-vlq":71,"./binary-search":73,"./util":78,"amdefine":79}],76:[function(require,module,exports){ /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors @@ -17173,6 +17431,7 @@ define(function (require, exports, module) { var base64VLQ = require('./base64-vlq'); var util = require('./util'); var ArraySet = require('./array-set').ArraySet; + var MappingList = require('./mapping-list').MappingList; /** * An instance of the SourceMapGenerator represents a source map which is @@ -17188,9 +17447,10 @@ define(function (require, exports, module) { } this._file = util.getArg(aArgs, 'file', null); this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null); + this._skipValidation = util.getArg(aArgs, 'skipValidation', false); this._sources = new ArraySet(); this._names = new ArraySet(); - this._mappings = []; + this._mappings = new MappingList(); this._sourcesContents = null; } @@ -17260,7 +17520,9 @@ define(function (require, exports, module) { var source = util.getArg(aArgs, 'source', null); var name = util.getArg(aArgs, 'name', null); - this._validateMapping(generated, original, source, name); + if (!this._skipValidation) { + this._validateMapping(generated, original, source, name); + } if (source != null && !this._sources.has(source)) { this._sources.add(source); @@ -17270,7 +17532,7 @@ define(function (require, exports, module) { this._names.add(name); } - this._mappings.push({ + this._mappings.add({ generatedLine: generated.line, generatedColumn: generated.column, originalLine: original != null && original.line, @@ -17347,7 +17609,7 @@ define(function (require, exports, module) { var newNames = new ArraySet(); // Find mappings for the "sourceFile" - this._mappings.forEach(function (mapping) { + this._mappings.unsortedForEach(function (mapping) { if (mapping.source === sourceFile && mapping.originalLine != null) { // Check if it can be mapped by the source map, then update the mapping. var original = aSourceMapConsumer.originalPositionFor({ @@ -17453,15 +17715,10 @@ define(function (require, exports, module) { var result = ''; var mapping; - // The mappings must be guaranteed to be in sorted order before we start - // serializing them or else the generated line numbers (which are defined - // via the ';' separators) will be all messed up. Note: it might be more - // performant to maintain the sorting as we insert them, rather than as we - // serialize them, but the big O is the same either way. - this._mappings.sort(util.compareByGeneratedPositions); + var mappings = this._mappings.toArray(); - for (var i = 0, len = this._mappings.length; i < len; i++) { - mapping = this._mappings[i]; + for (var i = 0, len = mappings.length; i < len; i++) { + mapping = mappings[i]; if (mapping.generatedLine !== previousGeneratedLine) { previousGeneratedColumn = 0; @@ -17472,7 +17729,7 @@ define(function (require, exports, module) { } else { if (i > 0) { - if (!util.compareByGeneratedPositions(mapping, this._mappings[i - 1])) { + if (!util.compareByGeneratedPositions(mapping, mappings[i - 1])) { continue; } result += ','; @@ -17561,7 +17818,7 @@ define(function (require, exports, module) { }); -},{"./array-set":70,"./base64-vlq":71,"./util":77,"amdefine":78}],76:[function(require,module,exports){ +},{"./array-set":70,"./base64-vlq":71,"./mapping-list":74,"./util":78,"amdefine":79}],77:[function(require,module,exports){ /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors @@ -17580,8 +17837,8 @@ define(function (require, exports, module) { // operating systems these days (capturing the result). var REGEX_NEWLINE = /(\r?\n)/; - // Matches a Windows-style newline, or any character. - var REGEX_CHARACTER = /\r\n|[\s\S]/g; + // Newline character code for charCodeAt() comparisons + var NEWLINE_CODE = 10; // Private symbol for identifying `SourceNode`s when multiple versions of // the source-map library are loaded. This MUST NOT CHANGE across @@ -17939,12 +18196,12 @@ define(function (require, exports, module) { lastOriginalSource = null; sourceMappingActive = false; } - chunk.match(REGEX_CHARACTER).forEach(function (ch, idx, array) { - if (REGEX_NEWLINE.test(ch)) { + for (var idx = 0, length = chunk.length; idx < length; idx++) { + if (chunk.charCodeAt(idx) === NEWLINE_CODE) { generated.line++; generated.column = 0; // Mappings end at eol - if (idx + 1 === array.length) { + if (idx + 1 === length) { lastOriginalSource = null; sourceMappingActive = false; } else if (sourceMappingActive) { @@ -17962,9 +18219,9 @@ define(function (require, exports, module) { }); } } else { - generated.column += ch.length; + generated.column++; } - }); + } }); this.walkSourceContents(function (sourceFile, sourceContent) { map.setSourceContent(sourceFile, sourceContent); @@ -17977,7 +18234,7 @@ define(function (require, exports, module) { }); -},{"./source-map-generator":75,"./util":77,"amdefine":78}],77:[function(require,module,exports){ +},{"./source-map-generator":76,"./util":78,"amdefine":79}],78:[function(require,module,exports){ /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors @@ -18298,7 +18555,7 @@ define(function (require, exports, module) { }); -},{"amdefine":78}],78:[function(require,module,exports){ +},{"amdefine":79}],79:[function(require,module,exports){ (function (process,__filename){ /** vim: et:ts=4:sw=4:sts=4 * @license amdefine 0.1.0 Copyright (c) 2011, The Dojo Foundation All Rights Reserved. @@ -18601,7 +18858,7 @@ function amdefine(module, requireFn) { module.exports = amdefine; }).call(this,require('_process'),"/node_modules/escodegen/node_modules/source-map/node_modules/amdefine/amdefine.js") -},{"_process":90,"path":89}],79:[function(require,module,exports){ +},{"_process":91,"path":90}],80:[function(require,module,exports){ module.exports={ "name": "escodegen", "description": "ECMAScript code generator", @@ -18617,10 +18874,9 @@ module.exports={ "README.md", "bin", "escodegen.js", - "gulpfile.js", "package.json" ], - "version": "1.4.3", + "version": "1.6.1", "engines": { "node": ">=0.10.0" }, @@ -18635,25 +18891,26 @@ module.exports={ "url": "http://github.com/estools/escodegen.git" }, "dependencies": { - "esprima": "^1.2.2", - "estraverse": "^1.9.0", + "estraverse": "^1.9.1", "esutils": "^1.1.6", - "optionator": "^0.4.0", + "esprima": "^1.2.2", + "optionator": "^0.5.0", "source-map": "~0.1.40" }, "optionalDependencies": { "source-map": "~0.1.40" }, "devDependencies": { - "esprima-moz": "*", - "semver": "^4.1.0", + "acorn-6to5": "^0.11.1-25", "bluebird": "^2.3.11", - "chai": "^1.10.0", - "gulp-mocha": "^2.0.0", - "gulp-eslint": "^0.2.0", - "gulp": "^3.8.10", "bower-registry-client": "^0.2.1", - "commonjs-everywhere": "^0.9.7" + "chai": "^1.10.0", + "commonjs-everywhere": "^0.9.7", + "esprima-moz": "*", + "gulp": "^3.8.10", + "gulp-eslint": "^0.2.0", + "gulp-mocha": "^2.0.0", + "semver": "^4.1.0" }, "licenses": [ { @@ -18669,32 +18926,31 @@ module.exports={ "build-min": "cjsify -ma path: tools/entry-point.js > escodegen.browser.min.js", "build": "cjsify -a path: tools/entry-point.js > escodegen.browser.js" }, - "gitHead": "ee238d803cb10af46c7ce5a1aef9b57cf006c317", + "gitHead": "1ca664f68dcf220b76c9dc562b2337c5e0b4227d", "bugs": { "url": "https://github.com/estools/escodegen/issues" }, - "_id": "escodegen@1.4.3", - "_shasum": "2b2422bf18c95e2542effaabc0c998712d490291", - "_from": "escodegen@1.4.3", + "_id": "escodegen@1.6.1", + "_shasum": "367de17d8510540d12bc6dcb8b3f918391265815", + "_from": "escodegen@1.6.1", "_npmVersion": "2.0.0-alpha-5", "_npmUser": { "name": "constellation", "email": "utatane.tea@gmail.com" }, "dist": { - "shasum": "2b2422bf18c95e2542effaabc0c998712d490291", - "tarball": "http://registry.npmjs.org/escodegen/-/escodegen-1.4.3.tgz" + "shasum": "367de17d8510540d12bc6dcb8b3f918391265815", + "tarball": "http://registry.npmjs.org/escodegen/-/escodegen-1.6.1.tgz" }, "directories": {}, - "_resolved": "https://registry.npmjs.org/escodegen/-/escodegen-1.4.3.tgz", + "_resolved": "https://registry.npmjs.org/escodegen/-/escodegen-1.6.1.tgz", "readme": "ERROR: No README data found!" } -},{}],80:[function(require,module,exports){ +},{}],81:[function(require,module,exports){ /* Copyright (C) 2013 Ariya Hidayat Copyright (C) 2013 Thaddee Tyl - Copyright (C) 2013 Mathias Bynens Copyright (C) 2012 Ariya Hidayat Copyright (C) 2012 Mathias Bynens Copyright (C) 2012 Joost-Wim Boekesteijn @@ -18726,22 +18982,28 @@ module.exports={ /*jslint bitwise:true plusplus:true */ /*global esprima:true, define:true, exports:true, window: true, -throwErrorTolerant: true, throwError: true, generateStatement: true, peek: true, -parseAssignmentExpression: true, parseBlock: true, parseExpression: true, +parseAssignmentExpression: true, parseBlock: true, +parseClassExpression: true, parseClassDeclaration: true, parseExpression: true, +parseForStatement: true, parseFunctionDeclaration: true, parseFunctionExpression: true, parseFunctionSourceElements: true, parseVariableIdentifier: true, -parseLeftHandSideExpression: true, -parseUnaryExpression: true, -parseStatement: true, parseSourceElement: true */ +parseImportSpecifier: true, +parseLeftHandSideExpression: true, parseParams: true, validateParam: true, +parseSpreadOrAssignmentExpression: true, +parseStatement: true, parseSourceElement: true, parseConciseBody: true, +advanceXJSChild: true, isXJSIdentifierStart: true, isXJSIdentifierPart: true, +scanXJSStringLiteral: true, scanXJSIdentifier: true, +parseXJSAttributeValue: true, parseXJSChild: true, parseXJSElement: true, parseXJSExpressionContainer: true, parseXJSEmptyExpression: true, +parseTypeAnnotation: true, parseTypeAnnotatableIdentifier: true, +parseYieldExpression: true, parseAwaitExpression: true +*/ (function (root, factory) { 'use strict'; // Universal Module Definition (UMD) to support AMD, CommonJS/Node.js, // Rhino, and plain browser loading. - - /* istanbul ignore next */ if (typeof define === 'function' && define.amd) { define(['exports'], factory); } else if (typeof exports !== 'undefined') { @@ -18760,6 +19022,8 @@ parseStatement: true, parseSourceElement: true */ Messages, Regex, SyntaxTreeDelegate, + XHTMLEntities, + ClassPropertyType, source, strict, index, @@ -18780,7 +19044,10 @@ parseStatement: true, parseSourceElement: true */ NumericLiteral: 6, Punctuator: 7, StringLiteral: 8, - RegularExpression: 9 + RegularExpression: 9, + Template: 10, + XJSIdentifier: 11, + XJSText: 12 }; TokenName = {}; @@ -18792,6 +19059,8 @@ parseStatement: true, parseSourceElement: true */ TokenName[Token.NumericLiteral] = 'Numeric'; TokenName[Token.Punctuator] = 'Punctuator'; TokenName[Token.StringLiteral] = 'String'; + TokenName[Token.XJSIdentifier] = 'XJSIdentifier'; + TokenName[Token.XJSText] = 'XJSText'; TokenName[Token.RegularExpression] = 'RegularExpression'; // A function following one of those tokens is an expression. @@ -18806,46 +19075,91 @@ parseStatement: true, parseSourceElement: true */ '<=', '<', '>', '!=', '!==']; Syntax = { - AssignmentExpression: 'AssignmentExpression', ArrayExpression: 'ArrayExpression', - BlockStatement: 'BlockStatement', + ArrayPattern: 'ArrayPattern', + ArrowFunctionExpression: 'ArrowFunctionExpression', + AssignmentExpression: 'AssignmentExpression', BinaryExpression: 'BinaryExpression', + BlockStatement: 'BlockStatement', BreakStatement: 'BreakStatement', CallExpression: 'CallExpression', CatchClause: 'CatchClause', + ClassBody: 'ClassBody', + ClassDeclaration: 'ClassDeclaration', + ClassExpression: 'ClassExpression', + ClassProperty: 'ClassProperty', + ComprehensionBlock: 'ComprehensionBlock', + ComprehensionExpression: 'ComprehensionExpression', ConditionalExpression: 'ConditionalExpression', ContinueStatement: 'ContinueStatement', - DoWhileStatement: 'DoWhileStatement', DebuggerStatement: 'DebuggerStatement', + DoWhileStatement: 'DoWhileStatement', EmptyStatement: 'EmptyStatement', + ExportDeclaration: 'ExportDeclaration', + ExportBatchSpecifier: 'ExportBatchSpecifier', + ExportSpecifier: 'ExportSpecifier', ExpressionStatement: 'ExpressionStatement', - ForStatement: 'ForStatement', ForInStatement: 'ForInStatement', + ForOfStatement: 'ForOfStatement', + ForStatement: 'ForStatement', FunctionDeclaration: 'FunctionDeclaration', FunctionExpression: 'FunctionExpression', Identifier: 'Identifier', IfStatement: 'IfStatement', - Literal: 'Literal', + ImportDeclaration: 'ImportDeclaration', + ImportDefaultSpecifier: 'ImportDefaultSpecifier', + ImportNamespaceSpecifier: 'ImportNamespaceSpecifier', + ImportSpecifier: 'ImportSpecifier', LabeledStatement: 'LabeledStatement', + Literal: 'Literal', LogicalExpression: 'LogicalExpression', MemberExpression: 'MemberExpression', + MethodDefinition: 'MethodDefinition', + ModuleSpecifier: 'ModuleSpecifier', NewExpression: 'NewExpression', ObjectExpression: 'ObjectExpression', + ObjectPattern: 'ObjectPattern', + ObjectTypeAnnotation: 'ObjectTypeAnnotation', + OptionalParameter: 'OptionalParameter', + ParametricTypeAnnotation: 'ParametricTypeAnnotation', + ParametricallyTypedIdentifier: 'ParametricallyTypedIdentifier', Program: 'Program', Property: 'Property', ReturnStatement: 'ReturnStatement', SequenceExpression: 'SequenceExpression', - SwitchStatement: 'SwitchStatement', + SpreadElement: 'SpreadElement', + SpreadProperty: 'SpreadProperty', SwitchCase: 'SwitchCase', + SwitchStatement: 'SwitchStatement', + TaggedTemplateExpression: 'TaggedTemplateExpression', + TemplateElement: 'TemplateElement', + TemplateLiteral: 'TemplateLiteral', ThisExpression: 'ThisExpression', ThrowStatement: 'ThrowStatement', TryStatement: 'TryStatement', + TypeAnnotatedIdentifier: 'TypeAnnotatedIdentifier', + TypeAnnotation: 'TypeAnnotation', UnaryExpression: 'UnaryExpression', + UnionTypeAnnotation: 'UnionTypeAnnotation', UpdateExpression: 'UpdateExpression', VariableDeclaration: 'VariableDeclaration', VariableDeclarator: 'VariableDeclarator', + VoidTypeAnnotation: 'VoidTypeAnnotation', WhileStatement: 'WhileStatement', - WithStatement: 'WithStatement' + WithStatement: 'WithStatement', + XJSIdentifier: 'XJSIdentifier', + XJSNamespacedName: 'XJSNamespacedName', + XJSMemberExpression: 'XJSMemberExpression', + XJSEmptyExpression: 'XJSEmptyExpression', + XJSExpressionContainer: 'XJSExpressionContainer', + XJSElement: 'XJSElement', + XJSClosingElement: 'XJSClosingElement', + XJSOpeningElement: 'XJSOpeningElement', + XJSAttribute: 'XJSAttribute', + XJSSpreadAttribute: 'XJSSpreadAttribute', + XJSText: 'XJSText', + YieldExpression: 'YieldExpression', + AwaitExpression: 'AwaitExpression' }; PropertyKind = { @@ -18854,6 +19168,11 @@ parseStatement: true, parseSourceElement: true */ Set: 4 }; + ClassPropertyType = { + 'static': 'static', + prototype: 'prototype' + }; + // Error messages should be identical to V8. Messages = { UnexpectedToken: 'Unexpected token %0', @@ -18861,11 +19180,13 @@ parseStatement: true, parseSourceElement: true */ UnexpectedString: 'Unexpected string', UnexpectedIdentifier: 'Unexpected identifier', UnexpectedReserved: 'Unexpected reserved word', + UnexpectedTemplate: 'Unexpected quasi %0', UnexpectedEOS: 'Unexpected end of input', NewlineAfterThrow: 'Illegal newline after throw', InvalidRegExp: 'Invalid regular expression', UnterminatedRegExp: 'Invalid regular expression: missing /', InvalidLHSInAssignment: 'Invalid left-hand side in assignment', + InvalidLHSInFormalsList: 'Invalid left-hand side in formals list', InvalidLHSInForIn: 'Invalid left-hand side in for-in', MultipleDefaultsInSwitch: 'More than one default clause in switch statement', NoCatchOrFinally: 'Missing catch or finally after try', @@ -18873,12 +19194,20 @@ parseStatement: true, parseSourceElement: true */ Redeclaration: '%0 \'%1\' has already been declared', IllegalContinue: 'Illegal continue statement', IllegalBreak: 'Illegal break statement', + IllegalDuplicateClassProperty: 'Illegal duplicate property in class definition', IllegalReturn: 'Illegal return statement', + IllegalSpread: 'Illegal spread element', StrictModeWith: 'Strict mode code may not include a with statement', StrictCatchVariable: 'Catch variable may not be eval or arguments in strict mode', StrictVarName: 'Variable name may not be eval or arguments in strict mode', StrictParamName: 'Parameter name eval or arguments is not allowed in strict mode', StrictParamDupe: 'Strict mode function may not have duplicate parameter names', + ParameterAfterRestParameter: 'Rest parameter must be final parameter of an argument list', + DefaultRestParameter: 'Rest parameter can not have a default value', + ElementAfterSpreadElement: 'Spread must be the final element of an element list', + PropertyAfterSpreadProperty: 'A rest property must be the final property of an object literal', + ObjectPatternAsRestParameter: 'Invalid rest parameter', + ObjectPatternAsSpread: 'Invalid spread argument', StrictFunctionName: 'Function name may not be eval or arguments in strict mode', StrictOctalLiteral: 'Octal literals are not allowed in strict mode.', StrictDelete: 'Delete of an unqualified identifier in strict mode.', @@ -18888,13 +19217,24 @@ parseStatement: true, parseSourceElement: true */ StrictLHSAssignment: 'Assignment to eval or arguments is not allowed in strict mode', StrictLHSPostfix: 'Postfix increment/decrement may not have eval or arguments operand in strict mode', StrictLHSPrefix: 'Prefix increment/decrement may not have eval or arguments operand in strict mode', - StrictReservedWord: 'Use of future reserved word in strict mode' + StrictReservedWord: 'Use of future reserved word in strict mode', + MissingFromClause: 'Missing from clause', + NoAsAfterImportNamespace: 'Missing as after import *', + InvalidModuleSpecifier: 'Invalid module specifier', + NoUnintializedConst: 'Const must be initialized', + ComprehensionRequiresBlock: 'Comprehension must have at least one block', + ComprehensionError: 'Comprehension Error', + EachNotAllowed: 'Each is not supported', + InvalidXJSAttributeValue: 'XJS value should be either an expression or a quoted XJS text', + ExpectedXJSClosingTag: 'Expected corresponding XJS closing tag for %0', + AdjacentXJSElements: 'Adjacent XJS elements must be wrapped in an enclosing tag' }; // See also tools/generate-unicode-regex.py. Regex = { - NonAsciiIdentifierStart: new RegExp('[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0\u08A2-\u08AC\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097F\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C33\u0C35-\u0C39\u0C3D\u0C58\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F0\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191C\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA697\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA793\uA7A0-\uA7AA\uA7F8-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA80-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uABC0-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]'), - NonAsciiIdentifierPart: new RegExp('[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u0527\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0\u08A2-\u08AC\u08E4-\u08FE\u0900-\u0963\u0966-\u096F\u0971-\u0977\u0979-\u097F\u0981-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C01-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C33\u0C35-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58\u0C59\u0C60-\u0C63\u0C66-\u0C6F\u0C82\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D02\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D60-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F0\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191C\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1D00-\u1DE6\u1DFC-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA697\uA69F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA793\uA7A0-\uA7AA\uA7F8-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A\uAA7B\uAA80-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uABC0-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE26\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]') + NonAsciiIdentifierStart: new RegExp('[\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0\u08a2-\u08ac\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097f\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2e2f\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa80-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc]'), + NonAsciiIdentifierPart: new RegExp('[\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0300-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u0483-\u0487\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u05d0-\u05ea\u05f0-\u05f2\u0610-\u061a\u0620-\u0669\u066e-\u06d3\u06d5-\u06dc\u06df-\u06e8\u06ea-\u06fc\u06ff\u0710-\u074a\u074d-\u07b1\u07c0-\u07f5\u07fa\u0800-\u082d\u0840-\u085b\u08a0\u08a2-\u08ac\u08e4-\u08fe\u0900-\u0963\u0966-\u096f\u0971-\u0977\u0979-\u097f\u0981-\u0983\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bc-\u09c4\u09c7\u09c8\u09cb-\u09ce\u09d7\u09dc\u09dd\u09df-\u09e3\u09e6-\u09f1\u0a01-\u0a03\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a59-\u0a5c\u0a5e\u0a66-\u0a75\u0a81-\u0a83\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abc-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ad0\u0ae0-\u0ae3\u0ae6-\u0aef\u0b01-\u0b03\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3c-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b5c\u0b5d\u0b5f-\u0b63\u0b66-\u0b6f\u0b71\u0b82\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd0\u0bd7\u0be6-\u0bef\u0c01-\u0c03\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c58\u0c59\u0c60-\u0c63\u0c66-\u0c6f\u0c82\u0c83\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbc-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0cde\u0ce0-\u0ce3\u0ce6-\u0cef\u0cf1\u0cf2\u0d02\u0d03\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d-\u0d44\u0d46-\u0d48\u0d4a-\u0d4e\u0d57\u0d60-\u0d63\u0d66-\u0d6f\u0d7a-\u0d7f\u0d82\u0d83\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0df2\u0df3\u0e01-\u0e3a\u0e40-\u0e4e\u0e50-\u0e59\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb9\u0ebb-\u0ebd\u0ec0-\u0ec4\u0ec6\u0ec8-\u0ecd\u0ed0-\u0ed9\u0edc-\u0edf\u0f00\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e-\u0f47\u0f49-\u0f6c\u0f71-\u0f84\u0f86-\u0f97\u0f99-\u0fbc\u0fc6\u1000-\u1049\u1050-\u109d\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u135d-\u135f\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176c\u176e-\u1770\u1772\u1773\u1780-\u17d3\u17d7\u17dc\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u1820-\u1877\u1880-\u18aa\u18b0-\u18f5\u1900-\u191c\u1920-\u192b\u1930-\u193b\u1946-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u19d0-\u19d9\u1a00-\u1a1b\u1a20-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1aa7\u1b00-\u1b4b\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1bf3\u1c00-\u1c37\u1c40-\u1c49\u1c4d-\u1c7d\u1cd0-\u1cd2\u1cd4-\u1cf6\u1d00-\u1de6\u1dfc-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u200c\u200d\u203f\u2040\u2054\u2071\u207f\u2090-\u209c\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d7f-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2de0-\u2dff\u2e2f\u3005-\u3007\u3021-\u302f\u3031-\u3035\u3038-\u303c\u3041-\u3096\u3099\u309a\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua62b\ua640-\ua66f\ua674-\ua67d\ua67f-\ua697\ua69f-\ua6f1\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua827\ua840-\ua873\ua880-\ua8c4\ua8d0-\ua8d9\ua8e0-\ua8f7\ua8fb\ua900-\ua92d\ua930-\ua953\ua960-\ua97c\ua980-\ua9c0\ua9cf-\ua9d9\uaa00-\uaa36\uaa40-\uaa4d\uaa50-\uaa59\uaa60-\uaa76\uaa7a\uaa7b\uaa80-\uaac2\uaadb-\uaadd\uaae0-\uaaef\uaaf2-\uaaf6\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabea\uabec\uabed\uabf0-\uabf9\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe00-\ufe0f\ufe20-\ufe26\ufe33\ufe34\ufe4d-\ufe4f\ufe70-\ufe74\ufe76-\ufefc\uff10-\uff19\uff21-\uff3a\uff3f\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc]'), + LeadingZeros: new RegExp('^0+(?!$)') }; // Ensure the condition is true, otherwise throw an error. @@ -18903,7 +19243,6 @@ parseStatement: true, parseSourceElement: true */ // Do NOT use this to enforce a certain condition on any user input. function assert(condition, message) { - /* istanbul ignore if */ if (!condition) { throw new Error('ASSERT: ' + message); } @@ -18925,32 +19264,36 @@ parseStatement: true, parseSourceElement: true */ // 7.2 White Space function isWhiteSpace(ch) { - return (ch === 0x20) || (ch === 0x09) || (ch === 0x0B) || (ch === 0x0C) || (ch === 0xA0) || - (ch >= 0x1680 && [0x1680, 0x180E, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, 0x202F, 0x205F, 0x3000, 0xFEFF].indexOf(ch) >= 0); + return (ch === 32) || // space + (ch === 9) || // tab + (ch === 0xB) || + (ch === 0xC) || + (ch === 0xA0) || + (ch >= 0x1680 && '\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\uFEFF'.indexOf(String.fromCharCode(ch)) > 0); } // 7.3 Line Terminators function isLineTerminator(ch) { - return (ch === 0x0A) || (ch === 0x0D) || (ch === 0x2028) || (ch === 0x2029); + return (ch === 10) || (ch === 13) || (ch === 0x2028) || (ch === 0x2029); } // 7.6 Identifier Names and Identifiers function isIdentifierStart(ch) { - return (ch === 0x24) || (ch === 0x5F) || // $ (dollar) and _ (underscore) - (ch >= 0x41 && ch <= 0x5A) || // A..Z - (ch >= 0x61 && ch <= 0x7A) || // a..z - (ch === 0x5C) || // \ (backslash) + return (ch === 36) || (ch === 95) || // $ (dollar) and _ (underscore) + (ch >= 65 && ch <= 90) || // A..Z + (ch >= 97 && ch <= 122) || // a..z + (ch === 92) || // \ (backslash) ((ch >= 0x80) && Regex.NonAsciiIdentifierStart.test(String.fromCharCode(ch))); } function isIdentifierPart(ch) { - return (ch === 0x24) || (ch === 0x5F) || // $ (dollar) and _ (underscore) - (ch >= 0x41 && ch <= 0x5A) || // A..Z - (ch >= 0x61 && ch <= 0x7A) || // a..z - (ch >= 0x30 && ch <= 0x39) || // 0..9 - (ch === 0x5C) || // \ (backslash) + return (ch === 36) || (ch === 95) || // $ (dollar) and _ (underscore) + (ch >= 65 && ch <= 90) || // A..Z + (ch >= 97 && ch <= 122) || // a..z + (ch >= 48 && ch <= 57) || // 0..9 + (ch === 92) || // \ (backslash) ((ch >= 0x80) && Regex.NonAsciiIdentifierPart.test(String.fromCharCode(ch))); } @@ -18999,7 +19342,8 @@ parseStatement: true, parseSourceElement: true */ } // 'const' is specialized as Keyword in V8. - // 'yield' and 'let' are for compatiblity with SpiderMonkey and ES.next. + // 'yield' is only treated as a keyword in strict mode. + // 'let' is for compatiblity with SpiderMonkey and ES.next. // Some others are from future reserved words. switch (id.length) { @@ -19013,7 +19357,7 @@ parseStatement: true, parseSourceElement: true */ (id === 'void') || (id === 'with') || (id === 'enum'); case 5: return (id === 'while') || (id === 'break') || (id === 'catch') || - (id === 'throw') || (id === 'const') || (id === 'yield') || + (id === 'throw') || (id === 'const') || (id === 'class') || (id === 'super'); case 6: return (id === 'return') || (id === 'typeof') || (id === 'delete') || @@ -19031,178 +19375,77 @@ parseStatement: true, parseSourceElement: true */ // 7.4 Comments - function addComment(type, value, start, end, loc) { - var comment, attacher; + function skipComment() { + var ch, blockComment, lineComment; - assert(typeof start === 'number', 'Comment must have valid position'); - - // Because the way the actual token is scanned, often the comments - // (if any) are skipped twice during the lexical analysis. - // Thus, we need to skip adding a comment if the comment array already - // handled it. - if (state.lastCommentStart >= start) { - return; - } - state.lastCommentStart = start; - - comment = { - type: type, - value: value - }; - if (extra.range) { - comment.range = [start, end]; - } - if (extra.loc) { - comment.loc = loc; - } - extra.comments.push(comment); - if (extra.attachComment) { - extra.leadingComments.push(comment); - extra.trailingComments.push(comment); - } - } - - function skipSingleLineComment(offset) { - var start, loc, ch, comment; - - start = index - offset; - loc = { - start: { - line: lineNumber, - column: index - lineStart - offset - } - }; + blockComment = false; + lineComment = false; while (index < length) { ch = source.charCodeAt(index); - ++index; - if (isLineTerminator(ch)) { - if (extra.comments) { - comment = source.slice(start + offset, index - 1); - loc.end = { - line: lineNumber, - column: index - lineStart - 1 - }; - addComment('Line', comment, start, index - 1, loc); + + if (lineComment) { + ++index; + if (isLineTerminator(ch)) { + lineComment = false; + if (ch === 13 && source.charCodeAt(index) === 10) { + ++index; + } + ++lineNumber; + lineStart = index; } + } else if (blockComment) { + if (isLineTerminator(ch)) { + if (ch === 13) { + ++index; + } + if (ch !== 13 || source.charCodeAt(index) === 10) { + ++lineNumber; + ++index; + lineStart = index; + if (index >= length) { + throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); + } + } + } else { + ch = source.charCodeAt(index++); + if (index >= length) { + throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); + } + // Block comment ends with '*/' (char #42, char #47). + if (ch === 42) { + ch = source.charCodeAt(index); + if (ch === 47) { + ++index; + blockComment = false; + } + } + } + } else if (ch === 47) { + ch = source.charCodeAt(index + 1); + // Line comment starts with '//' (char #47, char #47). + if (ch === 47) { + index += 2; + lineComment = true; + } else if (ch === 42) { + // Block comment starts with '/*' (char #47, char #42). + index += 2; + blockComment = true; + if (index >= length) { + throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); + } + } else { + break; + } + } else if (isWhiteSpace(ch)) { + ++index; + } else if (isLineTerminator(ch)) { + ++index; if (ch === 13 && source.charCodeAt(index) === 10) { ++index; } ++lineNumber; lineStart = index; - return; - } - } - - if (extra.comments) { - comment = source.slice(start + offset, index); - loc.end = { - line: lineNumber, - column: index - lineStart - }; - addComment('Line', comment, start, index, loc); - } - } - - function skipMultiLineComment() { - var start, loc, ch, comment; - - if (extra.comments) { - start = index - 2; - loc = { - start: { - line: lineNumber, - column: index - lineStart - 2 - } - }; - } - - while (index < length) { - ch = source.charCodeAt(index); - if (isLineTerminator(ch)) { - if (ch === 0x0D && source.charCodeAt(index + 1) === 0x0A) { - ++index; - } - ++lineNumber; - ++index; - lineStart = index; - if (index >= length) { - throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); - } - } else if (ch === 0x2A) { - // Block comment ends with '*/'. - if (source.charCodeAt(index + 1) === 0x2F) { - ++index; - ++index; - if (extra.comments) { - comment = source.slice(start + 2, index - 2); - loc.end = { - line: lineNumber, - column: index - lineStart - }; - addComment('Block', comment, start, index, loc); - } - return; - } - ++index; - } else { - ++index; - } - } - - throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); - } - - function skipComment() { - var ch, start; - - start = (index === 0); - while (index < length) { - ch = source.charCodeAt(index); - - if (isWhiteSpace(ch)) { - ++index; - } else if (isLineTerminator(ch)) { - ++index; - if (ch === 0x0D && source.charCodeAt(index) === 0x0A) { - ++index; - } - ++lineNumber; - lineStart = index; - start = true; - } else if (ch === 0x2F) { // U+002F is '/' - ch = source.charCodeAt(index + 1); - if (ch === 0x2F) { - ++index; - ++index; - skipSingleLineComment(2); - start = true; - } else if (ch === 0x2A) { // U+002A is '*' - ++index; - ++index; - skipMultiLineComment(); - } else { - break; - } - } else if (start && ch === 0x2D) { // U+002D is '-' - // U+003E is '>' - if ((source.charCodeAt(index + 1) === 0x2D) && (source.charCodeAt(index + 2) === 0x3E)) { - // '-->' is a single-line comment - index += 3; - skipSingleLineComment(3); - } else { - break; - } - } else if (ch === 0x3C) { // U+003C is '<' - if (source.slice(index + 1, index + 4) === '!--') { - ++index; // `<` - ++index; // `!` - ++index; // `-` - ++index; // `-` - skipSingleLineComment(4); - } else { - break; - } } else { break; } @@ -19224,15 +19467,47 @@ parseStatement: true, parseSourceElement: true */ return String.fromCharCode(code); } + function scanUnicodeCodePointEscape() { + var ch, code, cu1, cu2; + + ch = source[index]; + code = 0; + + // At least, one hex digit is required. + if (ch === '}') { + throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); + } + + while (index < length) { + ch = source[index++]; + if (!isHexDigit(ch)) { + break; + } + code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase()); + } + + if (code > 0x10FFFF || ch !== '}') { + throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); + } + + // UTF-16 Encoding + if (code <= 0xFFFF) { + return String.fromCharCode(code); + } + cu1 = ((code - 0x10000) >> 10) + 0xD800; + cu2 = ((code - 0x10000) & 1023) + 0xDC00; + return String.fromCharCode(cu1, cu2); + } + function getEscapedIdentifier() { var ch, id; ch = source.charCodeAt(index++); id = String.fromCharCode(ch); - // '\u' (U+005C, U+0075) denotes an escaped character. - if (ch === 0x5C) { - if (source.charCodeAt(index) !== 0x75) { + // '\u' (char #92, char #117) denotes an escaped character. + if (ch === 92) { + if (source.charCodeAt(index) !== 117) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } ++index; @@ -19251,10 +19526,10 @@ parseStatement: true, parseSourceElement: true */ ++index; id += String.fromCharCode(ch); - // '\u' (U+005C, U+0075) denotes an escaped character. - if (ch === 0x5C) { + // '\u' (char #92, char #117) denotes an escaped character. + if (ch === 92) { id = id.substr(0, id.length - 1); - if (source.charCodeAt(index) !== 0x75) { + if (source.charCodeAt(index) !== 117) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } ++index; @@ -19275,8 +19550,8 @@ parseStatement: true, parseSourceElement: true */ start = index++; while (index < length) { ch = source.charCodeAt(index); - if (ch === 0x5C) { - // Blackslash (U+005C) marks Unicode escape sequence. + if (ch === 92) { + // Blackslash (char #92) marks Unicode escape sequence. index = start; return getEscapedIdentifier(); } @@ -19295,8 +19570,8 @@ parseStatement: true, parseSourceElement: true */ start = index; - // Backslash (U+005C) starts an escaped character. - id = (source.charCodeAt(index) === 0x5C) ? getEscapedIdentifier() : getIdentifier(); + // Backslash (char #92) starts an escaped character. + id = (source.charCodeAt(index) === 92) ? getEscapedIdentifier() : getIdentifier(); // There is no keyword or literal with only one character. // Thus, it must be an identifier. @@ -19317,8 +19592,7 @@ parseStatement: true, parseSourceElement: true */ value: id, lineNumber: lineNumber, lineStart: lineStart, - start: start, - end: index + range: [start, index] }; } @@ -19335,25 +19609,23 @@ parseStatement: true, parseSourceElement: true */ ch4; switch (code) { - // Check for most common single-character punctuators. - case 0x2E: // . dot - case 0x28: // ( open bracket - case 0x29: // ) close bracket - case 0x3B: // ; semicolon - case 0x2C: // , comma - case 0x7B: // { open curly brace - case 0x7D: // } close curly brace - case 0x5B: // [ - case 0x5D: // ] - case 0x3A: // : - case 0x3F: // ? - case 0x7E: // ~ + case 40: // ( open bracket + case 41: // ) close bracket + case 59: // ; semicolon + case 44: // , comma + case 123: // { open curly brace + case 125: // } close curly brace + case 91: // [ + case 93: // ] + case 58: // : + case 63: // ? + case 126: // ~ ++index; if (extra.tokenize) { - if (code === 0x28) { + if (code === 40) { extra.openParenToken = extra.tokens.length; - } else if (code === 0x7B) { + } else if (code === 123) { extra.openCurlyToken = extra.tokens.length; } } @@ -19362,42 +19634,40 @@ parseStatement: true, parseSourceElement: true */ value: String.fromCharCode(code), lineNumber: lineNumber, lineStart: lineStart, - start: start, - end: index + range: [start, index] }; default: code2 = source.charCodeAt(index + 1); - // '=' (U+003D) marks an assignment or comparison operator. - if (code2 === 0x3D) { + // '=' (char #61) marks an assignment or comparison operator. + if (code2 === 61) { switch (code) { - case 0x2B: // + - case 0x2D: // - - case 0x2F: // / - case 0x3C: // < - case 0x3E: // > - case 0x5E: // ^ - case 0x7C: // | - case 0x25: // % - case 0x26: // & - case 0x2A: // * + case 37: // % + case 38: // & + case 42: // *: + case 43: // + + case 45: // - + case 47: // / + case 60: // < + case 62: // > + case 94: // ^ + case 124: // | index += 2; return { type: Token.Punctuator, value: String.fromCharCode(code) + String.fromCharCode(code2), lineNumber: lineNumber, lineStart: lineStart, - start: start, - end: index + range: [start, index] }; - case 0x21: // ! - case 0x3D: // = + case 33: // ! + case 61: // = index += 2; // !== and === - if (source.charCodeAt(index) === 0x3D) { + if (source.charCodeAt(index) === 61) { ++index; } return { @@ -19405,61 +19675,106 @@ parseStatement: true, parseSourceElement: true */ value: source.slice(start, index), lineNumber: lineNumber, lineStart: lineStart, - start: start, - end: index + range: [start, index] }; + default: + break; } } + break; } + // Peek more characters. + + ch2 = source[index + 1]; + ch3 = source[index + 2]; + ch4 = source[index + 3]; + // 4-character punctuator: >>>= - ch4 = source.substr(index, 4); - - if (ch4 === '>>>=') { - index += 4; - return { - type: Token.Punctuator, - value: ch4, - lineNumber: lineNumber, - lineStart: lineStart, - start: start, - end: index - }; + if (ch1 === '>' && ch2 === '>' && ch3 === '>') { + if (ch4 === '=') { + index += 4; + return { + type: Token.Punctuator, + value: '>>>=', + lineNumber: lineNumber, + lineStart: lineStart, + range: [start, index] + }; + } } // 3-character punctuators: === !== >>> <<= >>= - ch3 = ch4.substr(0, 3); - - if (ch3 === '>>>' || ch3 === '<<=' || ch3 === '>>=') { + if (ch1 === '>' && ch2 === '>' && ch3 === '>') { index += 3; return { type: Token.Punctuator, - value: ch3, + value: '>>>', lineNumber: lineNumber, lineStart: lineStart, - start: start, - end: index + range: [start, index] + }; + } + + if (ch1 === '<' && ch2 === '<' && ch3 === '=') { + index += 3; + return { + type: Token.Punctuator, + value: '<<=', + lineNumber: lineNumber, + lineStart: lineStart, + range: [start, index] + }; + } + + if (ch1 === '>' && ch2 === '>' && ch3 === '=') { + index += 3; + return { + type: Token.Punctuator, + value: '>>=', + lineNumber: lineNumber, + lineStart: lineStart, + range: [start, index] + }; + } + + if (ch1 === '.' && ch2 === '.' && ch3 === '.') { + index += 3; + return { + type: Token.Punctuator, + value: '...', + lineNumber: lineNumber, + lineStart: lineStart, + range: [start, index] }; } // Other 2-character punctuators: ++ -- << >> && || - ch2 = ch3.substr(0, 2); - if ((ch1 === ch2[1] && ('+-<>&|'.indexOf(ch1) >= 0)) || ch2 === '=>') { + if (ch1 === ch2 && ('+-<>&|'.indexOf(ch1) >= 0)) { index += 2; return { type: Token.Punctuator, - value: ch2, + value: ch1 + ch2, lineNumber: lineNumber, lineStart: lineStart, - start: start, - end: index + range: [start, index] + }; + } + + if (ch1 === '=' && ch2 === '>') { + index += 2; + return { + type: Token.Punctuator, + value: '=>', + lineNumber: lineNumber, + lineStart: lineStart, + range: [start, index] }; } - // 1-character punctuators: < > = ! + - * % & | ^ / if ('<>=!+-*%&|^/'.indexOf(ch1) >= 0) { ++index; return { @@ -19467,8 +19782,18 @@ parseStatement: true, parseSourceElement: true */ value: ch1, lineNumber: lineNumber, lineStart: lineStart, - start: start, - end: index + range: [start, index] + }; + } + + if (ch1 === '.') { + ++index; + return { + type: Token.Punctuator, + value: ch1, + lineNumber: lineNumber, + lineStart: lineStart, + range: [start, index] }; } @@ -19500,13 +19825,22 @@ parseStatement: true, parseSourceElement: true */ value: parseInt('0x' + number, 16), lineNumber: lineNumber, lineStart: lineStart, - start: start, - end: index + range: [start, index] }; } - function scanOctalLiteral(start) { - var number = '0' + source[index++]; + function scanOctalLiteral(prefix, start) { + var number, octal; + + if (isOctalDigit(prefix)) { + octal = true; + number = '0' + source[index++]; + } else { + octal = false; + ++index; + number = ''; + } + while (index < length) { if (!isOctalDigit(source[index])) { break; @@ -19514,6 +19848,11 @@ parseStatement: true, parseSourceElement: true */ number += source[index++]; } + if (!octal && number.length === 0) { + // only 0o or 0O + throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); + } + if (isIdentifierStart(source.charCodeAt(index)) || isDecimalDigit(source.charCodeAt(index))) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } @@ -19521,16 +19860,15 @@ parseStatement: true, parseSourceElement: true */ return { type: Token.NumericLiteral, value: parseInt(number, 8), - octal: true, + octal: octal, lineNumber: lineNumber, lineStart: lineStart, - start: start, - end: index + range: [start, index] }; } function scanNumericLiteral() { - var number, start, ch; + var number, start, ch, octal; ch = source[index]; assert(isDecimalDigit(ch.charCodeAt(0)) || (ch === '.'), @@ -19544,15 +19882,47 @@ parseStatement: true, parseSourceElement: true */ // Hex number starts with '0x'. // Octal number starts with '0'. + // Octal number in ES6 starts with '0o'. + // Binary number in ES6 starts with '0b'. if (number === '0') { if (ch === 'x' || ch === 'X') { ++index; return scanHexLiteral(start); } - if (isOctalDigit(ch)) { - return scanOctalLiteral(start); - } + if (ch === 'b' || ch === 'B') { + ++index; + number = ''; + while (index < length) { + ch = source[index]; + if (ch !== '0' && ch !== '1') { + break; + } + number += source[index++]; + } + + if (number.length === 0) { + // only 0b or 0B + throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); + } + + if (index < length) { + ch = source.charCodeAt(index); + if (isIdentifierStart(ch) || isDecimalDigit(ch)) { + throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); + } + } + return { + type: Token.NumericLiteral, + value: parseInt(number, 2), + lineNumber: lineNumber, + lineStart: lineStart, + range: [start, index] + }; + } + if (ch === 'o' || ch === 'O' || isOctalDigit(ch)) { + return scanOctalLiteral(ch, start); + } // decimal number starts with '0' such as '09' is illegal. if (ch && isDecimalDigit(ch.charCodeAt(0))) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); @@ -19598,17 +19968,14 @@ parseStatement: true, parseSourceElement: true */ value: parseFloat(number), lineNumber: lineNumber, lineStart: lineStart, - start: start, - end: index + range: [start, index] }; } // 7.8.4 String Literals function scanStringLiteral() { - var str = '', quote, start, ch, code, unescaped, restore, octal = false, startLineNumber, startLineStart; - startLineNumber = lineNumber; - startLineStart = lineStart; + var str = '', quote, start, ch, code, unescaped, restore, octal = false; quote = source[index]; assert((quote === '\'' || quote === '"'), @@ -19627,17 +19994,6 @@ parseStatement: true, parseSourceElement: true */ ch = source[index++]; if (!ch || !isLineTerminator(ch.charCodeAt(0))) { switch (ch) { - case 'u': - case 'x': - restore = index; - unescaped = scanHexEscape(ch); - if (unescaped) { - str += unescaped; - } else { - index = restore; - str += ch; - } - break; case 'n': str += '\n'; break; @@ -19647,6 +20003,22 @@ parseStatement: true, parseSourceElement: true */ case 't': str += '\t'; break; + case 'u': + case 'x': + if (source[index] === '{') { + ++index; + str += scanUnicodeCodePointEscape(); + } else { + restore = index; + unescaped = scanHexEscape(ch); + if (unescaped) { + str += unescaped; + } else { + index = restore; + str += ch; + } + } + break; case 'b': str += '\b'; break; @@ -19706,56 +20078,189 @@ parseStatement: true, parseSourceElement: true */ type: Token.StringLiteral, value: str, octal: octal, - startLineNumber: startLineNumber, - startLineStart: startLineStart, lineNumber: lineNumber, lineStart: lineStart, - start: start, - end: index + range: [start, index] }; } - function testRegExp(pattern, flags) { - var value; - try { - value = new RegExp(pattern, flags); - } catch (e) { - throwError({}, Messages.InvalidRegExp); + function scanTemplate() { + var cooked = '', ch, start, terminated, tail, restore, unescaped, code, octal; + + terminated = false; + tail = false; + start = index; + + ++index; + + while (index < length) { + ch = source[index++]; + if (ch === '`') { + tail = true; + terminated = true; + break; + } else if (ch === '$') { + if (source[index] === '{') { + ++index; + terminated = true; + break; + } + cooked += ch; + } else if (ch === '\\') { + ch = source[index++]; + if (!isLineTerminator(ch.charCodeAt(0))) { + switch (ch) { + case 'n': + cooked += '\n'; + break; + case 'r': + cooked += '\r'; + break; + case 't': + cooked += '\t'; + break; + case 'u': + case 'x': + if (source[index] === '{') { + ++index; + cooked += scanUnicodeCodePointEscape(); + } else { + restore = index; + unescaped = scanHexEscape(ch); + if (unescaped) { + cooked += unescaped; + } else { + index = restore; + cooked += ch; + } + } + break; + case 'b': + cooked += '\b'; + break; + case 'f': + cooked += '\f'; + break; + case 'v': + cooked += '\v'; + break; + + default: + if (isOctalDigit(ch)) { + code = '01234567'.indexOf(ch); + + // \0 is not octal escape sequence + if (code !== 0) { + octal = true; + } + + if (index < length && isOctalDigit(source[index])) { + octal = true; + code = code * 8 + '01234567'.indexOf(source[index++]); + + // 3 digits are only allowed when string starts + // with 0, 1, 2, 3 + if ('0123'.indexOf(ch) >= 0 && + index < length && + isOctalDigit(source[index])) { + code = code * 8 + '01234567'.indexOf(source[index++]); + } + } + cooked += String.fromCharCode(code); + } else { + cooked += ch; + } + break; + } + } else { + ++lineNumber; + if (ch === '\r' && source[index] === '\n') { + ++index; + } + lineStart = index; + } + } else if (isLineTerminator(ch.charCodeAt(0))) { + ++lineNumber; + if (ch === '\r' && source[index] === '\n') { + ++index; + } + lineStart = index; + cooked += '\n'; + } else { + cooked += ch; + } } - return value; + + if (!terminated) { + throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); + } + + return { + type: Token.Template, + value: { + cooked: cooked, + raw: source.slice(start + 1, index - ((tail) ? 1 : 2)) + }, + tail: tail, + octal: octal, + lineNumber: lineNumber, + lineStart: lineStart, + range: [start, index] + }; } - function scanRegExpBody() { - var ch, str, classMarker, terminated, body; + function scanTemplateElement(option) { + var startsWith, template; + lookahead = null; + skipComment(); + + startsWith = (option.head) ? '`' : '}'; + + if (source[index] !== startsWith) { + throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); + } + + template = scanTemplate(); + + peek(); + + return template; + } + + function scanRegExp() { + var str, ch, start, pattern, flags, value, classMarker = false, restore, terminated = false, tmp; + + lookahead = null; + skipComment(); + + start = index; ch = source[index]; assert(ch === '/', 'Regular expression literal must start with a slash'); str = source[index++]; - classMarker = false; - terminated = false; while (index < length) { ch = source[index++]; str += ch; - if (ch === '\\') { - ch = source[index++]; - // ECMA-262 7.8.5 - if (isLineTerminator(ch.charCodeAt(0))) { - throwError({}, Messages.UnterminatedRegExp); - } - str += ch; - } else if (isLineTerminator(ch.charCodeAt(0))) { - throwError({}, Messages.UnterminatedRegExp); - } else if (classMarker) { + if (classMarker) { if (ch === ']') { classMarker = false; } } else { - if (ch === '/') { + if (ch === '\\') { + ch = source[index++]; + // ECMA-262 7.8.5 + if (isLineTerminator(ch.charCodeAt(0))) { + throwError({}, Messages.UnterminatedRegExp); + } + str += ch; + } else if (ch === '/') { terminated = true; break; } else if (ch === '[') { classMarker = true; + } else if (isLineTerminator(ch.charCodeAt(0))) { + throwError({}, Messages.UnterminatedRegExp); } } } @@ -19765,17 +20270,8 @@ parseStatement: true, parseSourceElement: true */ } // Exclude leading and trailing slash. - body = str.substr(1, str.length - 2); - return { - value: body, - literal: str - }; - } + pattern = str.substr(1, str.length - 2); - function scanRegExpFlags() { - var ch, str, flags, restore; - - str = ''; flags = ''; while (index < length) { ch = source[index]; @@ -19800,10 +20296,8 @@ parseStatement: true, parseSourceElement: true */ flags += 'u'; str += '\\u'; } - throwErrorTolerant({}, Messages.UnexpectedToken, 'ILLEGAL'); } else { str += '\\'; - throwErrorTolerant({}, Messages.UnexpectedToken, 'ILLEGAL'); } } else { flags += ch; @@ -19811,84 +20305,59 @@ parseStatement: true, parseSourceElement: true */ } } - return { - value: flags, - literal: str - }; - } + tmp = pattern; + if (flags.indexOf('u') >= 0) { + // Replace each astral symbol and every Unicode code point + // escape sequence that represents such a symbol with a single + // ASCII symbol to avoid throwing on regular expressions that + // are only valid in combination with the `/u` flag. + tmp = tmp + .replace(/\\u\{([0-9a-fA-F]{5,6})\}/g, 'x') + .replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g, 'x'); + } - function scanRegExp() { - var start, body, flags, pattern, value; + // First, detect invalid regular expressions. + try { + value = new RegExp(tmp); + } catch (e) { + throwError({}, Messages.InvalidRegExp); + } - lookahead = null; - skipComment(); - start = index; + // Return a regular expression object for this pattern-flag pair, or + // `null` in case the current environment doesn't support the flags it + // uses. + try { + value = new RegExp(pattern, flags); + } catch (exception) { + value = null; + } - body = scanRegExpBody(); - flags = scanRegExpFlags(); - value = testRegExp(body.value, flags.value); + peek(); if (extra.tokenize) { return { type: Token.RegularExpression, value: value, + regex: { + pattern: pattern, + flags: flags + }, lineNumber: lineNumber, lineStart: lineStart, - start: start, - end: index + range: [start, index] }; } - return { - literal: body.literal + flags.literal, + literal: str, value: value, - start: start, - end: index + regex: { + pattern: pattern, + flags: flags + }, + range: [start, index] }; } - function collectRegex() { - var pos, loc, regex, token; - - skipComment(); - - pos = index; - loc = { - start: { - line: lineNumber, - column: index - lineStart - } - }; - - regex = scanRegExp(); - loc.end = { - line: lineNumber, - column: index - lineStart - }; - - /* istanbul ignore next */ - if (!extra.tokenize) { - // Pop the previous token, which is likely '/' or '/=' - if (extra.tokens.length > 0) { - token = extra.tokens[extra.tokens.length - 1]; - if (token.range[0] === pos && token.type === 'Punctuator') { - if (token.value === '/' || token.value === '/=') { - extra.tokens.pop(); - } - } - } - - extra.tokens.push({ - type: 'RegularExpression', - value: regex.literal, - range: [pos, index], - loc: loc - }); - } - - return regex; - } - function isIdentifierName(token) { return token.type === Token.Identifier || token.type === Token.Keyword || @@ -19904,12 +20373,9 @@ parseStatement: true, parseSourceElement: true */ prevToken = extra.tokens[extra.tokens.length - 1]; if (!prevToken) { // Nothing before that: it cannot be a division. - return collectRegex(); + return scanRegExp(); } if (prevToken.type === 'Punctuator') { - if (prevToken.value === ']') { - return scanPunctuator(); - } if (prevToken.value === ')') { checkToken = extra.tokens[extra.openParenToken - 1]; if (checkToken && @@ -19918,7 +20384,7 @@ parseStatement: true, parseSourceElement: true */ checkToken.value === 'while' || checkToken.value === 'for' || checkToken.value === 'with')) { - return collectRegex(); + return scanRegExp(); } return scanPunctuator(); } @@ -19937,7 +20403,7 @@ parseStatement: true, parseSourceElement: true */ // Named function. checkToken = extra.tokens[extra.openCurlyToken - 5]; if (!checkToken) { - return collectRegex(); + return scanRegExp(); } } else { return scanPunctuator(); @@ -19949,12 +20415,12 @@ parseStatement: true, parseSourceElement: true */ return scanPunctuator(); } // It is a declaration. - return collectRegex(); + return scanRegExp(); } - return collectRegex(); + return scanRegExp(); } if (prevToken.type === 'Keyword') { - return collectRegex(); + return scanRegExp(); } return scanPunctuator(); } @@ -19962,38 +20428,52 @@ parseStatement: true, parseSourceElement: true */ function advance() { var ch; - skipComment(); + if (!state.inXJSChild) { + skipComment(); + } if (index >= length) { return { type: Token.EOF, lineNumber: lineNumber, lineStart: lineStart, - start: index, - end: index + range: [index, index] }; } + if (state.inXJSChild) { + return advanceXJSChild(); + } + ch = source.charCodeAt(index); + // Very common: ( and ) and ; + if (ch === 40 || ch === 41 || ch === 58) { + return scanPunctuator(); + } + + // String literal starts with single quote (#39) or double quote (#34). + if (ch === 39 || ch === 34) { + if (state.inXJSTag) { + return scanXJSStringLiteral(); + } + return scanStringLiteral(); + } + + if (state.inXJSTag && isXJSIdentifierStart(ch)) { + return scanXJSIdentifier(); + } + + if (ch === 96) { + return scanTemplate(); + } if (isIdentifierStart(ch)) { return scanIdentifier(); } - // Very common: ( and ) and ; - if (ch === 0x28 || ch === 0x29 || ch === 0x3B) { - return scanPunctuator(); - } - - // String literal starts with single quote (U+0027) or double quote (U+0022). - if (ch === 0x27 || ch === 0x22) { - return scanStringLiteral(); - } - - - // Dot (.) U+002E can also start a floating-point number, hence the need + // Dot (.) char #46 can also start a floating-point number, hence the need // to check the next character. - if (ch === 0x2E) { + if (ch === 46) { if (isDecimalDigit(source.charCodeAt(index + 1))) { return scanNumericLiteral(); } @@ -20004,55 +20484,25 @@ parseStatement: true, parseSourceElement: true */ return scanNumericLiteral(); } - // Slash (/) U+002F can also start a regex. - if (extra.tokenize && ch === 0x2F) { + // Slash (/) char #47 can also start a regex. + if (extra.tokenize && ch === 47) { return advanceSlash(); } return scanPunctuator(); } - function collectToken() { - var loc, token, range, value; - - skipComment(); - loc = { - start: { - line: lineNumber, - column: index - lineStart - } - }; - - token = advance(); - loc.end = { - line: lineNumber, - column: index - lineStart - }; - - if (token.type !== Token.EOF) { - value = source.slice(token.start, token.end); - extra.tokens.push({ - type: TokenName[token.type], - value: value, - range: [token.start, token.end], - loc: loc - }); - } - - return token; - } - function lex() { var token; token = lookahead; - index = token.end; + index = token.range[1]; lineNumber = token.lineNumber; lineStart = token.lineStart; - lookahead = (typeof extra.tokens !== 'undefined') ? collectToken() : advance(); + lookahead = advance(); - index = token.end; + index = token.range[1]; lineNumber = token.lineNumber; lineStart = token.lineStart; @@ -20065,98 +20515,140 @@ parseStatement: true, parseSourceElement: true */ pos = index; line = lineNumber; start = lineStart; - lookahead = (typeof extra.tokens !== 'undefined') ? collectToken() : advance(); + lookahead = advance(); index = pos; lineNumber = line; lineStart = start; } - function Position(line, column) { - this.line = line; - this.column = column; + function lookahead2() { + var adv, pos, line, start, result; + + // If we are collecting the tokens, don't grab the next one yet. + adv = (typeof extra.advance === 'function') ? extra.advance : advance; + + pos = index; + line = lineNumber; + start = lineStart; + + // Scan for the next immediate token. + if (lookahead === null) { + lookahead = adv(); + } + index = lookahead.range[1]; + lineNumber = lookahead.lineNumber; + lineStart = lookahead.lineStart; + + // Grab the token right after. + result = adv(); + index = pos; + lineNumber = line; + lineStart = start; + + return result; } - function SourceLocation(startLine, startColumn, line, column) { - this.start = new Position(startLine, startColumn); - this.end = new Position(line, column); + function rewind(token) { + index = token.range[0]; + lineNumber = token.lineNumber; + lineStart = token.lineStart; + lookahead = token; + } + + function markerCreate() { + if (!extra.loc && !extra.range) { + return undefined; + } + skipComment(); + return {offset: index, line: lineNumber, col: index - lineStart}; + } + + function markerCreatePreserveWhitespace() { + if (!extra.loc && !extra.range) { + return undefined; + } + return {offset: index, line: lineNumber, col: index - lineStart}; + } + + function processComment(node) { + var lastChild, + trailingComments, + bottomRight = extra.bottomRightStack, + last = bottomRight[bottomRight.length - 1]; + + if (node.type === Syntax.Program) { + if (node.body.length > 0) { + return; + } + } + + if (extra.trailingComments.length > 0) { + if (extra.trailingComments[0].range[0] >= node.range[1]) { + trailingComments = extra.trailingComments; + extra.trailingComments = []; + } else { + extra.trailingComments.length = 0; + } + } else { + if (last && last.trailingComments && last.trailingComments[0].range[0] >= node.range[1]) { + trailingComments = last.trailingComments; + delete last.trailingComments; + } + } + + // Eating the stack. + if (last) { + while (last && last.range[0] >= node.range[0]) { + lastChild = last; + last = bottomRight.pop(); + } + } + + if (lastChild) { + if (lastChild.leadingComments && lastChild.leadingComments[lastChild.leadingComments.length - 1].range[1] <= node.range[0]) { + node.leadingComments = lastChild.leadingComments; + delete lastChild.leadingComments; + } + } else if (extra.leadingComments.length > 0 && extra.leadingComments[extra.leadingComments.length - 1].range[1] <= node.range[0]) { + node.leadingComments = extra.leadingComments; + extra.leadingComments = []; + } + + if (trailingComments) { + node.trailingComments = trailingComments; + } + + bottomRight.push(node); + } + + function markerApply(marker, node) { + if (extra.range) { + node.range = [marker.offset, index]; + } + if (extra.loc) { + node.loc = { + start: { + line: marker.line, + column: marker.col + }, + end: { + line: lineNumber, + column: index - lineStart + } + }; + node = delegate.postProcess(node); + } + if (extra.attachComment) { + processComment(node); + } + return node; } SyntaxTreeDelegate = { name: 'SyntaxTree', - processComment: function (node) { - var lastChild, trailingComments; - - if (node.type === Syntax.Program) { - if (node.body.length > 0) { - return; - } - } - - if (extra.trailingComments.length > 0) { - if (extra.trailingComments[0].range[0] >= node.range[1]) { - trailingComments = extra.trailingComments; - extra.trailingComments = []; - } else { - extra.trailingComments.length = 0; - } - } else { - if (extra.bottomRightStack.length > 0 && - extra.bottomRightStack[extra.bottomRightStack.length - 1].trailingComments && - extra.bottomRightStack[extra.bottomRightStack.length - 1].trailingComments[0].range[0] >= node.range[1]) { - trailingComments = extra.bottomRightStack[extra.bottomRightStack.length - 1].trailingComments; - delete extra.bottomRightStack[extra.bottomRightStack.length - 1].trailingComments; - } - } - - // Eating the stack. - while (extra.bottomRightStack.length > 0 && extra.bottomRightStack[extra.bottomRightStack.length - 1].range[0] >= node.range[0]) { - lastChild = extra.bottomRightStack.pop(); - } - - if (lastChild) { - if (lastChild.leadingComments && lastChild.leadingComments[lastChild.leadingComments.length - 1].range[1] <= node.range[0]) { - node.leadingComments = lastChild.leadingComments; - delete lastChild.leadingComments; - } - } else if (extra.leadingComments.length > 0 && extra.leadingComments[extra.leadingComments.length - 1].range[1] <= node.range[0]) { - node.leadingComments = extra.leadingComments; - extra.leadingComments = []; - } - - - if (trailingComments) { - node.trailingComments = trailingComments; - } - - extra.bottomRightStack.push(node); - }, - - markEnd: function (node, startToken) { - if (extra.range) { - node.range = [startToken.start, index]; - } - if (extra.loc) { - node.loc = new SourceLocation( - startToken.startLineNumber === undefined ? startToken.lineNumber : startToken.startLineNumber, - startToken.start - (startToken.startLineStart === undefined ? startToken.lineStart : startToken.startLineStart), - lineNumber, - index - lineStart - ); - this.postProcess(node); - } - - if (extra.attachComment) { - this.processComment(node); - } - return node; - }, - postProcess: function (node) { - if (extra.source) { - node.loc.source = extra.source; - } return node; }, @@ -20280,35 +20772,198 @@ parseStatement: true, parseSourceElement: true */ }; }, - createFunctionDeclaration: function (id, params, defaults, body) { + createForOfStatement: function (left, right, body) { return { + type: Syntax.ForOfStatement, + left: left, + right: right, + body: body + }; + }, + + createFunctionDeclaration: function (id, params, defaults, body, rest, generator, expression, + isAsync, returnType, parametricType) { + var funDecl = { type: Syntax.FunctionDeclaration, id: id, params: params, defaults: defaults, body: body, - rest: null, - generator: false, - expression: false + rest: rest, + generator: generator, + expression: expression, + returnType: returnType, + parametricType: parametricType }; + + if (isAsync) { + funDecl.async = true; + } + + return funDecl; }, - createFunctionExpression: function (id, params, defaults, body) { - return { + createFunctionExpression: function (id, params, defaults, body, rest, generator, expression, + isAsync, returnType, parametricType) { + var funExpr = { type: Syntax.FunctionExpression, id: id, params: params, defaults: defaults, body: body, - rest: null, - generator: false, - expression: false + rest: rest, + generator: generator, + expression: expression, + returnType: returnType, + parametricType: parametricType }; + + if (isAsync) { + funExpr.async = true; + } + + return funExpr; }, createIdentifier: function (name) { return { type: Syntax.Identifier, + name: name, + // Only here to initialize the shape of the object to ensure + // that the 'typeAnnotation' key is ordered before others that + // are added later (like 'loc' and 'range'). This just helps + // keep the shape of Identifier nodes consistent with everything + // else. + typeAnnotation: undefined + }; + }, + + createTypeAnnotation: function (typeIdentifier, parametricType, params, returnType, nullable) { + return { + type: Syntax.TypeAnnotation, + id: typeIdentifier, + parametricType: parametricType, + params: params, + returnType: returnType, + nullable: nullable + }; + }, + + createParametricTypeAnnotation: function (parametricTypes) { + return { + type: Syntax.ParametricTypeAnnotation, + params: parametricTypes + }; + }, + + createVoidTypeAnnotation: function () { + return { + type: Syntax.VoidTypeAnnotation + }; + }, + + createObjectTypeAnnotation: function (properties, nullable) { + return { + type: Syntax.ObjectTypeAnnotation, + properties: properties, + nullable: nullable + }; + }, + + createUnionTypeAnnotation: function (types) { + return { + type: Syntax.UnionTypeAnnotation, + types: types + }; + }, + + createTypeAnnotatedIdentifier: function (identifier, annotation, isOptionalParam) { + return { + type: Syntax.TypeAnnotatedIdentifier, + id: identifier, + annotation: annotation + }; + }, + + createOptionalParameter: function (identifier) { + return { + type: Syntax.OptionalParameter, + id: identifier + }; + }, + + createXJSAttribute: function (name, value) { + return { + type: Syntax.XJSAttribute, + name: name, + value: value || null + }; + }, + + createXJSSpreadAttribute: function (argument) { + return { + type: Syntax.XJSSpreadAttribute, + argument: argument + }; + }, + + createXJSIdentifier: function (name) { + return { + type: Syntax.XJSIdentifier, + name: name + }; + }, + + createXJSNamespacedName: function (namespace, name) { + return { + type: Syntax.XJSNamespacedName, + namespace: namespace, + name: name + }; + }, + + createXJSMemberExpression: function (object, property) { + return { + type: Syntax.XJSMemberExpression, + object: object, + property: property + }; + }, + + createXJSElement: function (openingElement, closingElement, children) { + return { + type: Syntax.XJSElement, + openingElement: openingElement, + closingElement: closingElement, + children: children + }; + }, + + createXJSEmptyExpression: function () { + return { + type: Syntax.XJSEmptyExpression + }; + }, + + createXJSExpressionContainer: function (expression) { + return { + type: Syntax.XJSExpressionContainer, + expression: expression + }; + }, + + createXJSOpeningElement: function (name, attributes, selfClosing) { + return { + type: Syntax.XJSOpeningElement, + name: name, + selfClosing: selfClosing, + attributes: attributes + }; + }, + + createXJSClosingElement: function (name) { + return { + type: Syntax.XJSClosingElement, name: name }; }, @@ -20331,11 +20986,15 @@ parseStatement: true, parseSourceElement: true */ }, createLiteral: function (token) { - return { + var object = { type: Syntax.Literal, value: token.value, - raw: source.slice(token.start, token.end) + raw: source.slice(token.range[0], token.range[1]) }; + if (token.regex) { + object.regex = token.regex; + } + return object; }, createMemberExpression: function (accessor, object, property) { @@ -20378,12 +21037,15 @@ parseStatement: true, parseSourceElement: true */ }; }, - createProperty: function (kind, key, value) { + createProperty: function (kind, key, value, method, shorthand, computed) { return { type: Syntax.Property, key: key, value: value, - kind: kind + kind: kind, + method: method, + shorthand: shorthand, + computed: computed }; }, @@ -20487,7 +21149,196 @@ parseStatement: true, parseSourceElement: true */ object: object, body: body }; + }, + + createTemplateElement: function (value, tail) { + return { + type: Syntax.TemplateElement, + value: value, + tail: tail + }; + }, + + createTemplateLiteral: function (quasis, expressions) { + return { + type: Syntax.TemplateLiteral, + quasis: quasis, + expressions: expressions + }; + }, + + createSpreadElement: function (argument) { + return { + type: Syntax.SpreadElement, + argument: argument + }; + }, + + createSpreadProperty: function (argument) { + return { + type: Syntax.SpreadProperty, + argument: argument + }; + }, + + createTaggedTemplateExpression: function (tag, quasi) { + return { + type: Syntax.TaggedTemplateExpression, + tag: tag, + quasi: quasi + }; + }, + + createArrowFunctionExpression: function (params, defaults, body, rest, expression, isAsync) { + var arrowExpr = { + type: Syntax.ArrowFunctionExpression, + id: null, + params: params, + defaults: defaults, + body: body, + rest: rest, + generator: false, + expression: expression + }; + + if (isAsync) { + arrowExpr.async = true; + } + + return arrowExpr; + }, + + createMethodDefinition: function (propertyType, kind, key, value) { + return { + type: Syntax.MethodDefinition, + key: key, + value: value, + kind: kind, + 'static': propertyType === ClassPropertyType.static + }; + }, + + createClassProperty: function (propertyIdentifier) { + return { + type: Syntax.ClassProperty, + id: propertyIdentifier + }; + }, + + createClassBody: function (body) { + return { + type: Syntax.ClassBody, + body: body + }; + }, + + createClassExpression: function (id, superClass, body, parametricType) { + return { + type: Syntax.ClassExpression, + id: id, + superClass: superClass, + body: body, + parametricType: parametricType + }; + }, + + createClassDeclaration: function (id, superClass, body, parametricType, superParametricType) { + return { + type: Syntax.ClassDeclaration, + id: id, + superClass: superClass, + body: body, + parametricType: parametricType, + superParametricType: superParametricType + }; + }, + + createModuleSpecifier: function (token) { + return { + type: Syntax.ModuleSpecifier, + value: token.value, + raw: source.slice(token.range[0], token.range[1]) + }; + }, + + createExportSpecifier: function (id, name) { + return { + type: Syntax.ExportSpecifier, + id: id, + name: name + }; + }, + + createExportBatchSpecifier: function () { + return { + type: Syntax.ExportBatchSpecifier + }; + }, + + createImportDefaultSpecifier: function (id) { + return { + type: Syntax.ImportDefaultSpecifier, + id: id + }; + }, + + createImportNamespaceSpecifier: function (id) { + return { + type: Syntax.ImportNamespaceSpecifier, + id: id + }; + }, + + createExportDeclaration: function (isDefault, declaration, specifiers, source) { + return { + type: Syntax.ExportDeclaration, + 'default': !!isDefault, + declaration: declaration, + specifiers: specifiers, + source: source + }; + }, + + createImportSpecifier: function (id, name) { + return { + type: Syntax.ImportSpecifier, + id: id, + name: name + }; + }, + + createImportDeclaration: function (specifiers, source) { + return { + type: Syntax.ImportDeclaration, + specifiers: specifiers, + source: source + }; + }, + + createYieldExpression: function (argument, delegate) { + return { + type: Syntax.YieldExpression, + argument: argument, + delegate: delegate + }; + }, + + createAwaitExpression: function (argument) { + return { + type: Syntax.AwaitExpression, + argument: argument + }; + }, + + createComprehensionExpression: function (filter, blocks, body) { + return { + type: Syntax.ComprehensionExpression, + filter: filter, + blocks: blocks, + body: body + }; } + }; // Return true if there is a line terminator before the next token. @@ -20522,9 +21373,9 @@ parseStatement: true, parseSourceElement: true */ if (typeof token.lineNumber === 'number') { error = new Error('Line ' + token.lineNumber + ': ' + msg); - error.index = token.start; + error.index = token.range[0]; error.lineNumber = token.lineNumber; - error.column = token.start - lineStart + 1; + error.column = token.range[0] - lineStart + 1; } else { error = new Error('Line ' + lineNumber + ': ' + msg); error.index = index; @@ -20560,7 +21411,7 @@ parseStatement: true, parseSourceElement: true */ throwError(token, Messages.UnexpectedNumber); } - if (token.type === Token.StringLiteral) { + if (token.type === Token.StringLiteral || token.type === Token.XJSText) { throwError(token, Messages.UnexpectedString); } @@ -20578,6 +21429,10 @@ parseStatement: true, parseSourceElement: true */ throwError(token, Messages.UnexpectedToken, token.value); } + if (token.type === Token.Template) { + throwError(token, Messages.UnexpectedTemplate, token.value.raw); + } + // BooleanLiteral, NullLiteral, or Punctuator. throwError(token, Messages.UnexpectedToken, token.value); } @@ -20595,13 +21450,21 @@ parseStatement: true, parseSourceElement: true */ // Expect the next token to match the specified keyword. // If not, an exception will be thrown. - function expectKeyword(keyword) { + function expectKeyword(keyword, contextual) { var token = lex(); - if (token.type !== Token.Keyword || token.value !== keyword) { + if (token.type !== (contextual ? Token.Identifier : Token.Keyword) || + token.value !== keyword) { throwUnexpected(token); } } + // Expect the next token to match the specified contextual keyword. + // If not, an exception will be thrown. + + function expectContextualKeyword(keyword) { + return expectKeyword(keyword, true); + } + // Return true if the next token matches the specified punctuator. function match(value) { @@ -20610,8 +21473,15 @@ parseStatement: true, parseSourceElement: true */ // Return true if the next token matches the specified keyword - function matchKeyword(keyword) { - return lookahead.type === Token.Keyword && lookahead.value === keyword; + function matchKeyword(keyword, contextual) { + var expectedType = contextual ? Token.Identifier : Token.Keyword; + return lookahead.type === expectedType && lookahead.value === keyword; + } + + // Return true if the next token matches the specified contextual keyword + + function matchContextualKeyword(keyword) { + return matchKeyword(keyword, true); } // Return true if the next token is an assignment operator @@ -20637,11 +21507,36 @@ parseStatement: true, parseSourceElement: true */ op === '|='; } - function consumeSemicolon() { - var line; + // Note that 'yield' is treated as a keyword in strict mode, but a + // contextual keyword (identifier) in non-strict mode, so we need to + // use matchKeyword('yield', false) and matchKeyword('yield', true) + // (i.e. matchContextualKeyword) appropriately. + function matchYield() { + return state.yieldAllowed && matchKeyword('yield', !strict); + } - // Catch the very common case first: immediately a semicolon (U+003B). - if (source.charCodeAt(index) === 0x3B || match(';')) { + function matchAsync() { + var backtrackToken = lookahead, matches = false; + + if (matchContextualKeyword('async')) { + lex(); // Make sure peekLineTerminator() starts after 'async'. + matches = !peekLineTerminator(); + rewind(backtrackToken); // Revert the lex(). + } + + return matches; + } + + function matchAwait() { + return state.awaitAllowed && matchContextualKeyword('await'); + } + + function consumeSemicolon() { + var line, oldIndex = index, oldLineNumber = lineNumber, + oldLineStart = lineStart, oldLookahead = lookahead; + + // Catch the very common case first: immediately a semicolon (char #59). + if (source.charCodeAt(index) === 59) { lex(); return; } @@ -20649,6 +21544,15 @@ parseStatement: true, parseSourceElement: true */ line = lineNumber; skipComment(); if (lineNumber !== line) { + index = oldIndex; + lineNumber = oldLineNumber; + lineStart = oldLineStart; + lookahead = oldLookahead; + return; + } + + if (match(';')) { + lex(); return; } @@ -20663,52 +21567,144 @@ parseStatement: true, parseSourceElement: true */ return expr.type === Syntax.Identifier || expr.type === Syntax.MemberExpression; } + function isAssignableLeftHandSide(expr) { + return isLeftHandSide(expr) || expr.type === Syntax.ObjectPattern || expr.type === Syntax.ArrayPattern; + } + // 11.1.4 Array Initialiser function parseArrayInitialiser() { - var elements = [], startToken; + var elements = [], blocks = [], filter = null, tmp, possiblecomprehension = true, body, + marker = markerCreate(); - startToken = lookahead; expect('['); - while (!match(']')) { - if (match(',')) { + if (lookahead.value === 'for' && + lookahead.type === Token.Keyword) { + if (!possiblecomprehension) { + throwError({}, Messages.ComprehensionError); + } + matchKeyword('for'); + tmp = parseForStatement({ignoreBody: true}); + tmp.of = tmp.type === Syntax.ForOfStatement; + tmp.type = Syntax.ComprehensionBlock; + if (tmp.left.kind) { // can't be let or const + throwError({}, Messages.ComprehensionError); + } + blocks.push(tmp); + } else if (lookahead.value === 'if' && + lookahead.type === Token.Keyword) { + if (!possiblecomprehension) { + throwError({}, Messages.ComprehensionError); + } + expectKeyword('if'); + expect('('); + filter = parseExpression(); + expect(')'); + } else if (lookahead.value === ',' && + lookahead.type === Token.Punctuator) { + possiblecomprehension = false; // no longer allowed. lex(); elements.push(null); } else { - elements.push(parseAssignmentExpression()); - - if (!match(']')) { - expect(','); + tmp = parseSpreadOrAssignmentExpression(); + elements.push(tmp); + if (tmp && tmp.type === Syntax.SpreadElement) { + if (!match(']')) { + throwError({}, Messages.ElementAfterSpreadElement); + } + } else if (!(match(']') || matchKeyword('for') || matchKeyword('if'))) { + expect(','); // this lexes. + possiblecomprehension = false; } } } - lex(); + expect(']'); - return delegate.markEnd(delegate.createArrayExpression(elements), startToken); + if (filter && !blocks.length) { + throwError({}, Messages.ComprehensionRequiresBlock); + } + + if (blocks.length) { + if (elements.length !== 1) { + throwError({}, Messages.ComprehensionError); + } + return markerApply(marker, delegate.createComprehensionExpression(filter, blocks, elements[0])); + } + return markerApply(marker, delegate.createArrayExpression(elements)); } // 11.1.5 Object Initialiser - function parsePropertyFunction(param, first) { - var previousStrict, body, startToken; + function parsePropertyFunction(options) { + var previousStrict, previousYieldAllowed, previousAwaitAllowed, + params, defaults, body, marker = markerCreate(); previousStrict = strict; - startToken = lookahead; - body = parseFunctionSourceElements(); - if (first && strict && isRestrictedWord(param[0].name)) { - throwErrorTolerant(first, Messages.StrictParamName); + previousYieldAllowed = state.yieldAllowed; + state.yieldAllowed = options.generator; + previousAwaitAllowed = state.awaitAllowed; + state.awaitAllowed = options.async; + params = options.params || []; + defaults = options.defaults || []; + + body = parseConciseBody(); + if (options.name && strict && isRestrictedWord(params[0].name)) { + throwErrorTolerant(options.name, Messages.StrictParamName); } strict = previousStrict; - return delegate.markEnd(delegate.createFunctionExpression(null, param, [], body), startToken); + state.yieldAllowed = previousYieldAllowed; + state.awaitAllowed = previousAwaitAllowed; + + return markerApply(marker, delegate.createFunctionExpression( + null, + params, + defaults, + body, + options.rest || null, + options.generator, + body.type !== Syntax.BlockStatement, + options.async, + options.returnType, + options.parametricType + )); } - function parseObjectPropertyKey() { - var token, startToken; - startToken = lookahead; - token = lex(); + function parsePropertyMethodFunction(options) { + var previousStrict, tmp, method; + + previousStrict = strict; + strict = true; + + tmp = parseParams(); + + if (tmp.stricted) { + throwErrorTolerant(tmp.stricted, tmp.message); + } + + method = parsePropertyFunction({ + params: tmp.params, + defaults: tmp.defaults, + rest: tmp.rest, + generator: options.generator, + async: options.async, + returnType: tmp.returnType, + parametricType: options.parametricType + }); + + strict = previousStrict; + + return method; + } + + + function parseObjectPropertyKey() { + var marker = markerCreate(), + token = lex(), + propertyKey, + result; // Note: This function is called only from parseObjectProperty(), where // EOF and Punctuator tokens are already filtered out. @@ -20717,95 +21713,219 @@ parseStatement: true, parseSourceElement: true */ if (strict && token.octal) { throwErrorTolerant(token, Messages.StrictOctalLiteral); } - return delegate.markEnd(delegate.createLiteral(token), startToken); + return markerApply(marker, delegate.createLiteral(token)); } - return delegate.markEnd(delegate.createIdentifier(token.value), startToken); + if (token.type === Token.Punctuator && token.value === '[') { + // For computed properties we should skip the [ and ], and + // capture in marker only the assignment expression itself. + marker = markerCreate(); + propertyKey = parseAssignmentExpression(); + result = markerApply(marker, propertyKey); + expect(']'); + return result; + } + + return markerApply(marker, delegate.createIdentifier(token.value)); } function parseObjectProperty() { - var token, key, id, value, param, startToken; + var token, key, id, value, param, expr, computed, + marker = markerCreate(); token = lookahead; - startToken = lookahead; - - if (token.type === Token.Identifier) { + computed = (token.value === '['); + if (token.type === Token.Identifier || computed || matchAsync()) { id = parseObjectPropertyKey(); + if (match(':')) { + lex(); + + return markerApply( + marker, + delegate.createProperty( + 'init', + id, + parseAssignmentExpression(), + false, + false, + computed + ) + ); + } + + if (match('(')) { + return markerApply( + marker, + delegate.createProperty( + 'init', + id, + parsePropertyMethodFunction({ + generator: false, + async: false + }), + true, + false, + computed + ) + ); + } + // Property Assignment: Getter and Setter. - if (token.value === 'get' && !match(':')) { + if (token.value === 'get') { + computed = (lookahead.value === '['); key = parseObjectPropertyKey(); + expect('('); expect(')'); - value = parsePropertyFunction([]); - return delegate.markEnd(delegate.createProperty('get', key, value), startToken); + + return markerApply( + marker, + delegate.createProperty( + 'get', + key, + parsePropertyFunction({ + generator: false, + async: false + }), + false, + false, + computed + ) + ); } - if (token.value === 'set' && !match(':')) { + + if (token.value === 'set') { + computed = (lookahead.value === '['); key = parseObjectPropertyKey(); + expect('('); token = lookahead; - if (token.type !== Token.Identifier) { - expect(')'); - throwErrorTolerant(token, Messages.UnexpectedToken, token.value); - value = parsePropertyFunction([]); - } else { - param = [ parseVariableIdentifier() ]; - expect(')'); - value = parsePropertyFunction(param, token); - } - return delegate.markEnd(delegate.createProperty('set', key, value), startToken); + param = [ parseTypeAnnotatableIdentifier() ]; + expect(')'); + + return markerApply( + marker, + delegate.createProperty( + 'set', + key, + parsePropertyFunction({ + params: param, + generator: false, + async: false, + name: token + }), + false, + false, + computed + ) + ); } - expect(':'); - value = parseAssignmentExpression(); - return delegate.markEnd(delegate.createProperty('init', id, value), startToken); + + if (token.value === 'async') { + computed = (lookahead.value === '['); + key = parseObjectPropertyKey(); + + return markerApply( + marker, + delegate.createProperty( + 'init', + key, + parsePropertyMethodFunction({ + generator: false, + async: true + }), + true, + false, + computed + ) + ); + } + + if (computed) { + // Computed properties can only be used with full notation. + throwUnexpected(lookahead); + } + + return markerApply( + marker, + delegate.createProperty('init', id, id, false, true, false) + ); } + if (token.type === Token.EOF || token.type === Token.Punctuator) { - throwUnexpected(token); - } else { - key = parseObjectPropertyKey(); - expect(':'); - value = parseAssignmentExpression(); - return delegate.markEnd(delegate.createProperty('init', key, value), startToken); + if (!match('*')) { + throwUnexpected(token); + } + lex(); + + computed = (lookahead.type === Token.Punctuator && lookahead.value === '['); + + id = parseObjectPropertyKey(); + + if (!match('(')) { + throwUnexpected(lex()); + } + + return markerApply(marker, delegate.createProperty('init', id, parsePropertyMethodFunction({ generator: true }), true, false, computed)); } + key = parseObjectPropertyKey(); + if (match(':')) { + lex(); + return markerApply(marker, delegate.createProperty('init', key, parseAssignmentExpression(), false, false, false)); + } + if (match('(')) { + return markerApply(marker, delegate.createProperty('init', key, parsePropertyMethodFunction({ generator: false }), true, false, false)); + } + throwUnexpected(lex()); + } + + function parseObjectSpreadProperty() { + var marker = markerCreate(); + expect('...'); + return markerApply(marker, delegate.createSpreadProperty(parseAssignmentExpression())); } function parseObjectInitialiser() { - var properties = [], property, name, key, kind, map = {}, toString = String, startToken; - - startToken = lookahead; + var properties = [], property, name, key, kind, map = {}, toString = String, + marker = markerCreate(); expect('{'); while (!match('}')) { - property = parseObjectProperty(); - - if (property.key.type === Syntax.Identifier) { - name = property.key.name; + if (match('...')) { + property = parseObjectSpreadProperty(); } else { - name = toString(property.key.value); - } - kind = (property.kind === 'init') ? PropertyKind.Data : (property.kind === 'get') ? PropertyKind.Get : PropertyKind.Set; + property = parseObjectProperty(); - key = '$' + name; - if (Object.prototype.hasOwnProperty.call(map, key)) { - if (map[key] === PropertyKind.Data) { - if (strict && kind === PropertyKind.Data) { - throwErrorTolerant({}, Messages.StrictDuplicateProperty); - } else if (kind !== PropertyKind.Data) { - throwErrorTolerant({}, Messages.AccessorDataProperty); - } + if (property.key.type === Syntax.Identifier) { + name = property.key.name; } else { - if (kind === PropertyKind.Data) { - throwErrorTolerant({}, Messages.AccessorDataProperty); - } else if (map[key] & kind) { - throwErrorTolerant({}, Messages.AccessorGetSet); - } + name = toString(property.key.value); + } + kind = (property.kind === 'init') ? PropertyKind.Data : (property.kind === 'get') ? PropertyKind.Get : PropertyKind.Set; + + key = '$' + name; + if (Object.prototype.hasOwnProperty.call(map, key)) { + if (map[key] === PropertyKind.Data) { + if (strict && kind === PropertyKind.Data) { + throwErrorTolerant({}, Messages.StrictDuplicateProperty); + } else if (kind !== PropertyKind.Data) { + throwErrorTolerant({}, Messages.AccessorDataProperty); + } + } else { + if (kind === PropertyKind.Data) { + throwErrorTolerant({}, Messages.AccessorDataProperty); + } else if (map[key] & kind) { + throwErrorTolerant({}, Messages.AccessorGetSet); + } + } + map[key] |= kind; + } else { + map[key] = kind; } - map[key] |= kind; - } else { - map[key] = kind; } properties.push(property); @@ -20817,7 +21937,32 @@ parseStatement: true, parseSourceElement: true */ expect('}'); - return delegate.markEnd(delegate.createObjectExpression(properties), startToken); + return markerApply(marker, delegate.createObjectExpression(properties)); + } + + function parseTemplateElement(option) { + var marker = markerCreate(), + token = scanTemplateElement(option); + if (strict && token.octal) { + throwError(token, Messages.StrictOctalLiteral); + } + return markerApply(marker, delegate.createTemplateElement({ raw: token.value.raw, cooked: token.value.cooked }, token.tail)); + } + + function parseTemplateLiteral() { + var quasi, quasis, expressions, marker = markerCreate(); + + quasi = parseTemplateElement({ head: true }); + quasis = [ quasi ]; + expressions = []; + + while (!quasi.tail) { + expressions.push(parseExpression()); + quasi = parseTemplateElement({ head: false }); + quasis.push(quasi); + } + + return markerApply(marker, delegate.createTemplateLiteral(quasis, expressions)); } // 11.1.6 The Grouping Operator @@ -20827,6 +21972,8 @@ parseStatement: true, parseSourceElement: true */ expect('('); + ++state.parenthesizedCount; + expr = parseExpression(); expect(')'); @@ -20834,14 +21981,73 @@ parseStatement: true, parseSourceElement: true */ return expr; } + function matchAsyncFuncExprOrDecl() { + var token; + + if (matchAsync()) { + token = lookahead2(); + if (token.type === Token.Keyword && token.value === 'function') { + return true; + } + } + + return false; + } // 11.1 Primary Expressions function parsePrimaryExpression() { - var type, token, expr, startToken; + var marker, type, token, expr; - if (match('(')) { - return parseGroupExpression(); + type = lookahead.type; + + if (type === Token.Identifier) { + marker = markerCreate(); + return markerApply(marker, delegate.createIdentifier(lex().value)); + } + + if (type === Token.StringLiteral || type === Token.NumericLiteral) { + if (strict && lookahead.octal) { + throwErrorTolerant(lookahead, Messages.StrictOctalLiteral); + } + marker = markerCreate(); + return markerApply(marker, delegate.createLiteral(lex())); + } + + if (type === Token.Keyword) { + if (matchKeyword('this')) { + marker = markerCreate(); + lex(); + return markerApply(marker, delegate.createThisExpression()); + } + + if (matchKeyword('function')) { + return parseFunctionExpression(); + } + + if (matchKeyword('class')) { + return parseClassExpression(); + } + + if (matchKeyword('super')) { + marker = markerCreate(); + lex(); + return markerApply(marker, delegate.createIdentifier('super')); + } + } + + if (type === Token.BooleanLiteral) { + marker = markerCreate(); + token = lex(); + token.value = (token.value === 'true'); + return markerApply(marker, delegate.createLiteral(token)); + } + + if (type === Token.NullLiteral) { + marker = markerCreate(); + token = lex(); + token.value = null; + return markerApply(marker, delegate.createLiteral(token)); } if (match('[')) { @@ -20852,61 +22058,44 @@ parseStatement: true, parseSourceElement: true */ return parseObjectInitialiser(); } - type = lookahead.type; - startToken = lookahead; - - if (type === Token.Identifier) { - expr = delegate.createIdentifier(lex().value); - } else if (type === Token.StringLiteral || type === Token.NumericLiteral) { - if (strict && lookahead.octal) { - throwErrorTolerant(lookahead, Messages.StrictOctalLiteral); - } - expr = delegate.createLiteral(lex()); - } else if (type === Token.Keyword) { - if (matchKeyword('function')) { - return parseFunctionExpression(); - } - if (matchKeyword('this')) { - lex(); - expr = delegate.createThisExpression(); - } else { - throwUnexpected(lex()); - } - } else if (type === Token.BooleanLiteral) { - token = lex(); - token.value = (token.value === 'true'); - expr = delegate.createLiteral(token); - } else if (type === Token.NullLiteral) { - token = lex(); - token.value = null; - expr = delegate.createLiteral(token); - } else if (match('/') || match('/=')) { - if (typeof extra.tokens !== 'undefined') { - expr = delegate.createLiteral(collectRegex()); - } else { - expr = delegate.createLiteral(scanRegExp()); - } - peek(); - } else { - throwUnexpected(lex()); + if (match('(')) { + return parseGroupExpression(); } - return delegate.markEnd(expr, startToken); + if (match('/') || match('/=')) { + marker = markerCreate(); + return markerApply(marker, delegate.createLiteral(scanRegExp())); + } + + if (type === Token.Template) { + return parseTemplateLiteral(); + } + + if (match('<')) { + return parseXJSElement(); + } + + throwUnexpected(lex()); } // 11.2 Left-Hand-Side Expressions function parseArguments() { - var args = []; + var args = [], arg; expect('('); if (!match(')')) { while (index < length) { - args.push(parseAssignmentExpression()); + arg = parseSpreadOrAssignmentExpression(); + args.push(arg); + if (match(')')) { break; + } else if (arg.type === Syntax.SpreadElement) { + throwError({}, Messages.ElementAfterSpreadElement); } + expect(','); } } @@ -20916,17 +22105,24 @@ parseStatement: true, parseSourceElement: true */ return args; } - function parseNonComputedProperty() { - var token, startToken; + function parseSpreadOrAssignmentExpression() { + if (match('...')) { + var marker = markerCreate(); + lex(); + return markerApply(marker, delegate.createSpreadElement(parseAssignmentExpression())); + } + return parseAssignmentExpression(); + } - startToken = lookahead; - token = lex(); + function parseNonComputedProperty() { + var marker = markerCreate(), + token = lex(); if (!isIdentifierName(token)) { throwUnexpected(token); } - return delegate.markEnd(delegate.createIdentifier(token.value), startToken); + return markerApply(marker, delegate.createIdentifier(token.value)); } function parseNonComputedMember() { @@ -20948,63 +22144,49 @@ parseStatement: true, parseSourceElement: true */ } function parseNewExpression() { - var callee, args, startToken; + var callee, args, marker = markerCreate(); - startToken = lookahead; expectKeyword('new'); callee = parseLeftHandSideExpression(); args = match('(') ? parseArguments() : []; - return delegate.markEnd(delegate.createNewExpression(callee, args), startToken); + return markerApply(marker, delegate.createNewExpression(callee, args)); } function parseLeftHandSideExpressionAllowCall() { - var previousAllowIn, expr, args, property, startToken; + var expr, args, marker = markerCreate(); - startToken = lookahead; - - previousAllowIn = state.allowIn; - state.allowIn = true; expr = matchKeyword('new') ? parseNewExpression() : parsePrimaryExpression(); - state.allowIn = previousAllowIn; - for (;;) { - if (match('.')) { - property = parseNonComputedMember(); - expr = delegate.createMemberExpression('.', expr, property); - } else if (match('(')) { + while (match('.') || match('[') || match('(') || lookahead.type === Token.Template) { + if (match('(')) { args = parseArguments(); - expr = delegate.createCallExpression(expr, args); + expr = markerApply(marker, delegate.createCallExpression(expr, args)); } else if (match('[')) { - property = parseComputedMember(); - expr = delegate.createMemberExpression('[', expr, property); + expr = markerApply(marker, delegate.createMemberExpression('[', expr, parseComputedMember())); + } else if (match('.')) { + expr = markerApply(marker, delegate.createMemberExpression('.', expr, parseNonComputedMember())); } else { - break; + expr = markerApply(marker, delegate.createTaggedTemplateExpression(expr, parseTemplateLiteral())); } - delegate.markEnd(expr, startToken); } return expr; } function parseLeftHandSideExpression() { - var previousAllowIn, expr, property, startToken; + var expr, marker = markerCreate(); - startToken = lookahead; - - previousAllowIn = state.allowIn; expr = matchKeyword('new') ? parseNewExpression() : parsePrimaryExpression(); - state.allowIn = previousAllowIn; - while (match('.') || match('[')) { + while (match('.') || match('[') || lookahead.type === Token.Template) { if (match('[')) { - property = parseComputedMember(); - expr = delegate.createMemberExpression('[', expr, property); + expr = markerApply(marker, delegate.createMemberExpression('[', expr, parseComputedMember())); + } else if (match('.')) { + expr = markerApply(marker, delegate.createMemberExpression('.', expr, parseNonComputedMember())); } else { - property = parseNonComputedMember(); - expr = delegate.createMemberExpression('.', expr, property); + expr = markerApply(marker, delegate.createTaggedTemplateExpression(expr, parseTemplateLiteral())); } - delegate.markEnd(expr, startToken); } return expr; @@ -21013,24 +22195,26 @@ parseStatement: true, parseSourceElement: true */ // 11.3 Postfix Expressions function parsePostfixExpression() { - var expr, token, startToken = lookahead; + var marker = markerCreate(), + expr = parseLeftHandSideExpressionAllowCall(), + token; - expr = parseLeftHandSideExpressionAllowCall(); + if (lookahead.type !== Token.Punctuator) { + return expr; + } - if (lookahead.type === Token.Punctuator) { - if ((match('++') || match('--')) && !peekLineTerminator()) { - // 11.3.1, 11.3.2 - if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) { - throwErrorTolerant({}, Messages.StrictLHSPostfix); - } - - if (!isLeftHandSide(expr)) { - throwErrorTolerant({}, Messages.InvalidLHSInAssignment); - } - - token = lex(); - expr = delegate.markEnd(delegate.createPostfixExpression(token.value, expr), startToken); + if ((match('++') || match('--')) && !peekLineTerminator()) { + // 11.3.1, 11.3.2 + if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) { + throwErrorTolerant({}, Messages.StrictLHSPostfix); } + + if (!isLeftHandSide(expr)) { + throwError({}, Messages.InvalidLHSInAssignment); + } + + token = lex(); + expr = markerApply(marker, delegate.createPostfixExpression(token.value, expr)); } return expr; @@ -21039,12 +22223,14 @@ parseStatement: true, parseSourceElement: true */ // 11.4 Unary Operators function parseUnaryExpression() { - var token, expr, startToken; + var marker, token, expr; if (lookahead.type !== Token.Punctuator && lookahead.type !== Token.Keyword) { - expr = parsePostfixExpression(); - } else if (match('++') || match('--')) { - startToken = lookahead; + return parsePostfixExpression(); + } + + if (match('++') || match('--')) { + marker = markerCreate(); token = lex(); expr = parseUnaryExpression(); // 11.4.4, 11.4.5 @@ -21053,31 +22239,31 @@ parseStatement: true, parseSourceElement: true */ } if (!isLeftHandSide(expr)) { - throwErrorTolerant({}, Messages.InvalidLHSInAssignment); + throwError({}, Messages.InvalidLHSInAssignment); } - expr = delegate.createUnaryExpression(token.value, expr); - expr = delegate.markEnd(expr, startToken); - } else if (match('+') || match('-') || match('~') || match('!')) { - startToken = lookahead; + return markerApply(marker, delegate.createUnaryExpression(token.value, expr)); + } + + if (match('+') || match('-') || match('~') || match('!')) { + marker = markerCreate(); token = lex(); expr = parseUnaryExpression(); - expr = delegate.createUnaryExpression(token.value, expr); - expr = delegate.markEnd(expr, startToken); - } else if (matchKeyword('delete') || matchKeyword('void') || matchKeyword('typeof')) { - startToken = lookahead; + return markerApply(marker, delegate.createUnaryExpression(token.value, expr)); + } + + if (matchKeyword('delete') || matchKeyword('void') || matchKeyword('typeof')) { + marker = markerCreate(); token = lex(); expr = parseUnaryExpression(); - expr = delegate.createUnaryExpression(token.value, expr); - expr = delegate.markEnd(expr, startToken); + expr = markerApply(marker, delegate.createUnaryExpression(token.value, expr)); if (strict && expr.operator === 'delete' && expr.argument.type === Syntax.Identifier) { throwErrorTolerant({}, Messages.StrictDelete); } - } else { - expr = parsePostfixExpression(); + return expr; } - return expr; + return parsePostfixExpression(); } function binaryPrecedence(token, allowIn) { @@ -21160,25 +22346,29 @@ parseStatement: true, parseSourceElement: true */ // 11.11 Binary Logical Operators function parseBinaryExpression() { - var marker, markers, expr, token, prec, stack, right, operator, left, i; + var expr, token, prec, previousAllowIn, stack, right, operator, left, i, + marker, markers; - marker = lookahead; + previousAllowIn = state.allowIn; + state.allowIn = true; + + marker = markerCreate(); left = parseUnaryExpression(); token = lookahead; - prec = binaryPrecedence(token, state.allowIn); + prec = binaryPrecedence(token, previousAllowIn); if (prec === 0) { return left; } token.prec = prec; lex(); - markers = [marker, lookahead]; + markers = [marker, markerCreate()]; right = parseUnaryExpression(); stack = [left, token, right]; - while ((prec = binaryPrecedence(lookahead, state.allowIn)) > 0) { + while ((prec = binaryPrecedence(lookahead, previousAllowIn)) > 0) { // Reduce: make a binary expression from the three topmost entries. while ((stack.length > 2) && (prec <= stack[stack.length - 2].prec)) { @@ -21187,20 +22377,23 @@ parseStatement: true, parseSourceElement: true */ left = stack.pop(); expr = delegate.createBinaryExpression(operator, left, right); markers.pop(); - marker = markers[markers.length - 1]; - delegate.markEnd(expr, marker); + marker = markers.pop(); + markerApply(marker, expr); stack.push(expr); + markers.push(marker); } // Shift. token = lex(); token.prec = prec; stack.push(token); - markers.push(lookahead); + markers.push(markerCreate()); expr = parseUnaryExpression(); stack.push(expr); } + state.allowIn = previousAllowIn; + // Final reduce to clean-up the stack. i = stack.length - 1; expr = stack[i]; @@ -21209,7 +22402,7 @@ parseStatement: true, parseSourceElement: true */ expr = delegate.createBinaryExpression(stack[i - 1].value, stack[i - 2], expr); i -= 2; marker = markers.pop(); - delegate.markEnd(expr, marker); + markerApply(marker, expr); } return expr; @@ -21219,10 +22412,7 @@ parseStatement: true, parseSourceElement: true */ // 11.12 Conditional Operator function parseConditionalExpression() { - var expr, previousAllowIn, consequent, alternate, startToken; - - startToken = lookahead; - + var expr, previousAllowIn, consequent, alternate, marker = markerCreate(); expr = parseBinaryExpression(); if (match('?')) { @@ -21234,8 +22424,7 @@ parseStatement: true, parseSourceElement: true */ expect(':'); alternate = parseAssignmentExpression(); - expr = delegate.createConditionalExpression(expr, consequent, alternate); - delegate.markEnd(expr, startToken); + expr = markerApply(marker, delegate.createConditionalExpression(expr, consequent, alternate)); } return expr; @@ -21243,55 +22432,320 @@ parseStatement: true, parseSourceElement: true */ // 11.13 Assignment Operators + function reinterpretAsAssignmentBindingPattern(expr) { + var i, len, property, element; + + if (expr.type === Syntax.ObjectExpression) { + expr.type = Syntax.ObjectPattern; + for (i = 0, len = expr.properties.length; i < len; i += 1) { + property = expr.properties[i]; + if (property.type === Syntax.SpreadProperty) { + if (i < len - 1) { + throwError({}, Messages.PropertyAfterSpreadProperty); + } + reinterpretAsAssignmentBindingPattern(property.argument); + } else { + if (property.kind !== 'init') { + throwError({}, Messages.InvalidLHSInAssignment); + } + reinterpretAsAssignmentBindingPattern(property.value); + } + } + } else if (expr.type === Syntax.ArrayExpression) { + expr.type = Syntax.ArrayPattern; + for (i = 0, len = expr.elements.length; i < len; i += 1) { + element = expr.elements[i]; + if (element) { + reinterpretAsAssignmentBindingPattern(element); + } + } + } else if (expr.type === Syntax.Identifier) { + if (isRestrictedWord(expr.name)) { + throwError({}, Messages.InvalidLHSInAssignment); + } + } else if (expr.type === Syntax.SpreadElement) { + reinterpretAsAssignmentBindingPattern(expr.argument); + if (expr.argument.type === Syntax.ObjectPattern) { + throwError({}, Messages.ObjectPatternAsSpread); + } + } else { + if (expr.type !== Syntax.MemberExpression && expr.type !== Syntax.CallExpression && expr.type !== Syntax.NewExpression) { + throwError({}, Messages.InvalidLHSInAssignment); + } + } + } + + + function reinterpretAsDestructuredParameter(options, expr) { + var i, len, property, element; + + if (expr.type === Syntax.ObjectExpression) { + expr.type = Syntax.ObjectPattern; + for (i = 0, len = expr.properties.length; i < len; i += 1) { + property = expr.properties[i]; + if (property.type === Syntax.SpreadProperty) { + if (i < len - 1) { + throwError({}, Messages.PropertyAfterSpreadProperty); + } + reinterpretAsDestructuredParameter(options, property.argument); + } else { + if (property.kind !== 'init') { + throwError({}, Messages.InvalidLHSInFormalsList); + } + reinterpretAsDestructuredParameter(options, property.value); + } + } + } else if (expr.type === Syntax.ArrayExpression) { + expr.type = Syntax.ArrayPattern; + for (i = 0, len = expr.elements.length; i < len; i += 1) { + element = expr.elements[i]; + if (element) { + reinterpretAsDestructuredParameter(options, element); + } + } + } else if (expr.type === Syntax.Identifier) { + validateParam(options, expr, expr.name); + } else { + if (expr.type !== Syntax.MemberExpression) { + throwError({}, Messages.InvalidLHSInFormalsList); + } + } + } + + function reinterpretAsCoverFormalsList(expressions) { + var i, len, param, params, defaults, defaultCount, options, rest; + + params = []; + defaults = []; + defaultCount = 0; + rest = null; + options = { + paramSet: {} + }; + + for (i = 0, len = expressions.length; i < len; i += 1) { + param = expressions[i]; + if (param.type === Syntax.Identifier) { + params.push(param); + defaults.push(null); + validateParam(options, param, param.name); + } else if (param.type === Syntax.ObjectExpression || param.type === Syntax.ArrayExpression) { + reinterpretAsDestructuredParameter(options, param); + params.push(param); + defaults.push(null); + } else if (param.type === Syntax.SpreadElement) { + assert(i === len - 1, 'It is guaranteed that SpreadElement is last element by parseExpression'); + reinterpretAsDestructuredParameter(options, param.argument); + rest = param.argument; + } else if (param.type === Syntax.AssignmentExpression) { + params.push(param.left); + defaults.push(param.right); + ++defaultCount; + validateParam(options, param.left, param.left.name); + } else { + return null; + } + } + + if (options.message === Messages.StrictParamDupe) { + throwError( + strict ? options.stricted : options.firstRestricted, + options.message + ); + } + + if (defaultCount === 0) { + defaults = []; + } + + return { + params: params, + defaults: defaults, + rest: rest, + stricted: options.stricted, + firstRestricted: options.firstRestricted, + message: options.message + }; + } + + function parseArrowFunctionExpression(options, marker) { + var previousStrict, previousYieldAllowed, previousAwaitAllowed, body; + + expect('=>'); + + previousStrict = strict; + previousYieldAllowed = state.yieldAllowed; + state.yieldAllowed = false; + previousAwaitAllowed = state.awaitAllowed; + state.awaitAllowed = !!options.async; + body = parseConciseBody(); + + if (strict && options.firstRestricted) { + throwError(options.firstRestricted, options.message); + } + if (strict && options.stricted) { + throwErrorTolerant(options.stricted, options.message); + } + + strict = previousStrict; + state.yieldAllowed = previousYieldAllowed; + state.awaitAllowed = previousAwaitAllowed; + + return markerApply(marker, delegate.createArrowFunctionExpression( + options.params, + options.defaults, + body, + options.rest, + body.type !== Syntax.BlockStatement, + !!options.async + )); + } + function parseAssignmentExpression() { - var token, left, right, node, startToken; + var marker, expr, token, params, oldParenthesizedCount, + backtrackToken = lookahead, possiblyAsync = false; + + if (matchYield()) { + return parseYieldExpression(); + } + + if (matchAwait()) { + return parseAwaitExpression(); + } + + oldParenthesizedCount = state.parenthesizedCount; + + marker = markerCreate(); + + if (matchAsyncFuncExprOrDecl()) { + return parseFunctionExpression(); + } + + if (matchAsync()) { + // We can't be completely sure that this 'async' token is + // actually a contextual keyword modifying a function + // expression, so we might have to un-lex() it later by + // calling rewind(backtrackToken). + possiblyAsync = true; + lex(); + } + + if (match('(')) { + token = lookahead2(); + if ((token.type === Token.Punctuator && token.value === ')') || token.value === '...') { + params = parseParams(); + if (!match('=>')) { + throwUnexpected(lex()); + } + params.async = possiblyAsync; + return parseArrowFunctionExpression(params, marker); + } + } token = lookahead; - startToken = lookahead; - node = left = parseConditionalExpression(); + // If the 'async' keyword is not followed by a '(' character or an + // identifier, then it can't be an arrow function modifier, and we + // should interpret it as a normal identifer. + if (possiblyAsync && !match('(') && token.type !== Token.Identifier) { + possiblyAsync = false; + rewind(backtrackToken); + } + + expr = parseConditionalExpression(); + + if (match('=>') && + (state.parenthesizedCount === oldParenthesizedCount || + state.parenthesizedCount === (oldParenthesizedCount + 1))) { + if (expr.type === Syntax.Identifier) { + params = reinterpretAsCoverFormalsList([ expr ]); + } else if (expr.type === Syntax.SequenceExpression) { + params = reinterpretAsCoverFormalsList(expr.expressions); + } + if (params) { + params.async = possiblyAsync; + return parseArrowFunctionExpression(params, marker); + } + } + + // If we haven't returned by now, then the 'async' keyword was not + // a function modifier, and we should rewind and interpret it as a + // normal identifier. + if (possiblyAsync) { + possiblyAsync = false; + rewind(backtrackToken); + expr = parseConditionalExpression(); + } if (matchAssign()) { - // LeftHandSideExpression - if (!isLeftHandSide(left)) { - throwErrorTolerant({}, Messages.InvalidLHSInAssignment); - } - // 11.13.1 - if (strict && left.type === Syntax.Identifier && isRestrictedWord(left.name)) { + if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) { throwErrorTolerant(token, Messages.StrictLHSAssignment); } - token = lex(); - right = parseAssignmentExpression(); - node = delegate.markEnd(delegate.createAssignmentExpression(token.value, left, right), startToken); + // ES.next draf 11.13 Runtime Semantics step 1 + if (match('=') && (expr.type === Syntax.ObjectExpression || expr.type === Syntax.ArrayExpression)) { + reinterpretAsAssignmentBindingPattern(expr); + } else if (!isLeftHandSide(expr)) { + throwError({}, Messages.InvalidLHSInAssignment); + } + + expr = markerApply(marker, delegate.createAssignmentExpression(lex().value, expr, parseAssignmentExpression())); } - return node; + return expr; } // 11.14 Comma Operator function parseExpression() { - var expr, startToken = lookahead; + var marker, expr, expressions, sequence, coverFormalsList, spreadFound, oldParenthesizedCount; + oldParenthesizedCount = state.parenthesizedCount; + + marker = markerCreate(); expr = parseAssignmentExpression(); + expressions = [ expr ]; if (match(',')) { - expr = delegate.createSequenceExpression([ expr ]); - while (index < length) { if (!match(',')) { break; } + lex(); - expr.expressions.push(parseAssignmentExpression()); + expr = parseSpreadOrAssignmentExpression(); + expressions.push(expr); + + if (expr.type === Syntax.SpreadElement) { + spreadFound = true; + if (!match(')')) { + throwError({}, Messages.ElementAfterSpreadElement); + } + break; + } } - delegate.markEnd(expr, startToken); + sequence = markerApply(marker, delegate.createSequenceExpression(expressions)); } - return expr; + if (match('=>')) { + // Do not allow nested parentheses on the LHS of the =>. + if (state.parenthesizedCount === oldParenthesizedCount || state.parenthesizedCount === (oldParenthesizedCount + 1)) { + expr = expr.type === Syntax.SequenceExpression ? expr.expressions : expressions; + coverFormalsList = reinterpretAsCoverFormalsList(expr); + if (coverFormalsList) { + return parseArrowFunctionExpression(coverFormalsList, marker); + } + } + throwUnexpected(lex()); + } + + if (spreadFound && lookahead2().value !== '=>') { + throwError({}, Messages.IllegalSpread); + } + + return sequence || expr; } // 12.1 Block @@ -21315,45 +22769,212 @@ parseStatement: true, parseSourceElement: true */ } function parseBlock() { - var block, startToken; + var block, marker = markerCreate(); - startToken = lookahead; expect('{'); block = parseStatementList(); expect('}'); - return delegate.markEnd(delegate.createBlockStatement(block), startToken); + return markerApply(marker, delegate.createBlockStatement(block)); } // 12.2 Variable Statement - function parseVariableIdentifier() { - var token, startToken; + function parseObjectTypeAnnotation(nullable) { + var isMethod, marker, properties = [], property, propertyKey, + propertyTypeAnnotation; - startToken = lookahead; - token = lex(); + expect('{'); + + while (!match('}')) { + marker = markerCreate(); + propertyKey = parseObjectPropertyKey(); + isMethod = match('('); + propertyTypeAnnotation = parseTypeAnnotation(); + properties.push(markerApply(marker, delegate.createProperty( + 'init', + propertyKey, + propertyTypeAnnotation, + isMethod, + false + ))); + + if (!match('}')) { + if (match(',') || match(';')) { + lex(); + } else { + throwUnexpected(lookahead); + } + } + } + + expect('}'); + + return delegate.createObjectTypeAnnotation(properties, nullable); + } + + function parseVoidTypeAnnotation() { + var marker = markerCreate(); + expectKeyword('void'); + return markerApply(marker, delegate.createVoidTypeAnnotation()); + } + + function parseParametricTypeAnnotation() { + var marker = markerCreate(), typeIdentifier, paramTypes = []; + + expect('<'); + while (!match('>')) { + paramTypes.push(parseVariableIdentifier()); + if (!match('>')) { + expect(','); + } + } + expect('>'); + + return markerApply(marker, delegate.createParametricTypeAnnotation( + paramTypes + )); + } + + function parseTypeAnnotationWithoutUnions() { + var typeIdentifier = null, params = null, returnType = null, + nullable = false, marker = markerCreate(), returnTypeMarker = null, + parametricType, annotation; + + if (match('?')) { + lex(); + nullable = true; + } + + if (match('{')) { + return markerApply(marker, parseObjectTypeAnnotation(nullable)); + } + + if (lookahead.type === Token.Identifier) { + typeIdentifier = parseVariableIdentifier(); + if (match('<')) { + parametricType = parseParametricTypeAnnotation(); + } + } else if (match('(')) { + lex(); + params = []; + while (lookahead.type === Token.Identifier || match('?')) { + params.push(parseTypeAnnotatableIdentifier( + true, /* requireTypeAnnotation */ + true /* canBeOptionalParam */ + )); + if (!match(')')) { + expect(','); + } + } + expect(')'); + + returnTypeMarker = markerCreate(); + expect('=>'); + + returnType = parseTypeAnnotation(true); + } else { + if (!matchKeyword('void')) { + throwUnexpected(lookahead); + } else { + return markerApply(marker, parseVoidTypeAnnotation()); + } + } + + return markerApply(marker, delegate.createTypeAnnotation( + typeIdentifier, + parametricType, + params, + returnType, + nullable + )); + } + + function parseUnionTypeAnnotation(types) { + while (match('|')) { + lex(); + types.push(parseTypeAnnotationWithoutUnions()); + } + + return delegate.createUnionTypeAnnotation( + types + ); + } + + function parseTypeAnnotation(dontExpectColon) { + var type, marker = markerCreate(); + if (!dontExpectColon) { + expect(':'); + } + + type = parseTypeAnnotationWithoutUnions(marker); + + if (match('|')) { + type = parseUnionTypeAnnotation([type]); + } + + return markerApply(marker, type); + } + + function parseVariableIdentifier() { + var marker = markerCreate(), + token = lex(); if (token.type !== Token.Identifier) { throwUnexpected(token); } - return delegate.markEnd(delegate.createIdentifier(token.value), startToken); + return markerApply(marker, delegate.createIdentifier(token.value)); + } + + function parseTypeAnnotatableIdentifier(requireTypeAnnotation, canBeOptionalParam) { + var marker = markerCreate(), + ident = parseVariableIdentifier(), + isOptionalParam = false; + + if (canBeOptionalParam && match('?')) { + expect('?'); + isOptionalParam = true; + } + + if (requireTypeAnnotation || match(':')) { + ident = markerApply(marker, delegate.createTypeAnnotatedIdentifier( + ident, + parseTypeAnnotation() + )); + } + + if (isOptionalParam) { + ident = markerApply(marker, delegate.createOptionalParameter(ident)); + } + + return ident; } function parseVariableDeclaration(kind) { - var init = null, id, startToken; - - startToken = lookahead; - id = parseVariableIdentifier(); - - // 12.2.1 - if (strict && isRestrictedWord(id.name)) { - throwErrorTolerant({}, Messages.StrictVarName); + var id, + marker = markerCreate(), + init = null; + if (match('{')) { + id = parseObjectInitialiser(); + reinterpretAsAssignmentBindingPattern(id); + } else if (match('[')) { + id = parseArrayInitialiser(); + reinterpretAsAssignmentBindingPattern(id); + } else { + id = state.allowKeyword ? parseNonComputedProperty() : parseTypeAnnotatableIdentifier(); + // 12.2.1 + if (strict && isRestrictedWord(id.name)) { + throwErrorTolerant({}, Messages.StrictVarName); + } } if (kind === 'const') { + if (!match('=')) { + throwError({}, Messages.NoUnintializedConst); + } expect('='); init = parseAssignmentExpression(); } else if (match('=')) { @@ -21361,7 +22982,7 @@ parseStatement: true, parseSourceElement: true */ init = parseAssignmentExpression(); } - return delegate.markEnd(delegate.createVariableDeclarator(id, init), startToken); + return markerApply(marker, delegate.createVariableDeclarator(id, init)); } function parseVariableDeclarationList(kind) { @@ -21379,7 +23000,7 @@ parseStatement: true, parseSourceElement: true */ } function parseVariableStatement() { - var declarations; + var declarations, marker = markerCreate(); expectKeyword('var'); @@ -21387,7 +23008,7 @@ parseStatement: true, parseSourceElement: true */ consumeSemicolon(); - return delegate.createVariableDeclaration(declarations, 'var'); + return markerApply(marker, delegate.createVariableDeclaration(declarations, 'var')); } // kind may be `const` or `let` @@ -21395,9 +23016,7 @@ parseStatement: true, parseSourceElement: true */ // see http://wiki.ecmascript.org/doku.php?id=harmony:const // and http://wiki.ecmascript.org/doku.php?id=harmony:let function parseConstLetDeclaration(kind) { - var declarations, startToken; - - startToken = lookahead; + var declarations, marker = markerCreate(); expectKeyword(kind); @@ -21405,28 +23024,270 @@ parseStatement: true, parseSourceElement: true */ consumeSemicolon(); - return delegate.markEnd(delegate.createVariableDeclaration(declarations, kind), startToken); + return markerApply(marker, delegate.createVariableDeclaration(declarations, kind)); + } + + // people.mozilla.org/~jorendorff/es6-draft.html + + function parseModuleSpecifier() { + var marker = markerCreate(), + specifier; + + if (lookahead.type !== Token.StringLiteral) { + throwError({}, Messages.InvalidModuleSpecifier); + } + specifier = delegate.createModuleSpecifier(lookahead); + lex(); + return markerApply(marker, specifier); + } + + function parseExportBatchSpecifier() { + var marker = markerCreate(); + expect('*'); + return markerApply(marker, delegate.createExportBatchSpecifier()); + } + + function parseExportSpecifier() { + var id, name = null, marker = markerCreate(), from; + if (matchKeyword('default')) { + lex(); + id = markerApply(marker, delegate.createIdentifier('default')); + // export {default} from "something"; + } else { + id = parseVariableIdentifier(); + } + if (matchContextualKeyword('as')) { + lex(); + name = parseNonComputedProperty(); + } + + return markerApply(marker, delegate.createExportSpecifier(id, name)); + } + + function parseExportDeclaration() { + var backtrackToken, id, previousAllowKeyword, declaration = null, + isExportFromIdentifier, + src = null, specifiers = [], + marker = markerCreate(); + + expectKeyword('export'); + + if (matchKeyword('default')) { + // covers: + // export default ... + lex(); + if (matchKeyword('function') || matchKeyword('class')) { + backtrackToken = lookahead; + lex(); + if (isIdentifierName(lookahead)) { + // covers: + // export default function foo () {} + // export default class foo {} + id = parseNonComputedProperty(); + rewind(backtrackToken); + return markerApply(marker, delegate.createExportDeclaration(true, parseSourceElement(), [id], null)); + } + // covers: + // export default function () {} + // export default class {} + rewind(backtrackToken); + switch (lookahead.value) { + case 'class': + return markerApply(marker, delegate.createExportDeclaration(true, parseClassExpression(), [], null)); + case 'function': + return markerApply(marker, delegate.createExportDeclaration(true, parseFunctionExpression(), [], null)); + } + } + + if (matchContextualKeyword('from')) { + throwError({}, Messages.UnexpectedToken, lookahead.value); + } + + // covers: + // export default {}; + // export default []; + if (match('{')) { + declaration = parseObjectInitialiser(); + } else if (match('[')) { + declaration = parseArrayInitialiser(); + } else { + declaration = parseAssignmentExpression(); + } + consumeSemicolon(); + return markerApply(marker, delegate.createExportDeclaration(true, declaration, [], null)); + } + + // non-default export + if (lookahead.type === Token.Keyword) { + // covers: + // export var f = 1; + switch (lookahead.value) { + case 'let': + case 'const': + case 'var': + case 'class': + case 'function': + return markerApply(marker, delegate.createExportDeclaration(false, parseSourceElement(), specifiers, null)); + } + } + + if (match('*')) { + // covers: + // export * from "foo"; + specifiers.push(parseExportBatchSpecifier()); + + if (!matchContextualKeyword('from')) { + throwError({}, lookahead.value ? + Messages.UnexpectedToken : Messages.MissingFromClause, lookahead.value); + } + lex(); + src = parseModuleSpecifier(); + consumeSemicolon(); + + return markerApply(marker, delegate.createExportDeclaration(false, null, specifiers, src)); + } + + expect('{'); + do { + isExportFromIdentifier = isExportFromIdentifier || matchKeyword('default'); + specifiers.push(parseExportSpecifier()); + } while (match(',') && lex()); + expect('}'); + + if (matchContextualKeyword('from')) { + // covering: + // export {default} from "foo"; + // export {foo} from "foo"; + lex(); + src = parseModuleSpecifier(); + consumeSemicolon(); + } else if (isExportFromIdentifier) { + // covering: + // export {default}; // missing fromClause + throwError({}, lookahead.value ? + Messages.UnexpectedToken : Messages.MissingFromClause, lookahead.value); + } else { + // cover + // export {foo}; + consumeSemicolon(); + } + return markerApply(marker, delegate.createExportDeclaration(false, declaration, specifiers, src)); + } + + + function parseImportSpecifier() { + // import {} ...; + var id, name = null, marker = markerCreate(); + + id = parseNonComputedProperty(); + if (matchContextualKeyword('as')) { + lex(); + name = parseVariableIdentifier(); + } + + return markerApply(marker, delegate.createImportSpecifier(id, name)); + } + + function parseNamedImports() { + var specifiers = []; + // {foo, bar as bas} + expect('{'); + do { + specifiers.push(parseImportSpecifier()); + } while (match(',') && lex()); + expect('}'); + return specifiers; + } + + function parseImportDefaultSpecifier() { + // import ...; + var id, marker = markerCreate(); + + id = parseNonComputedProperty(); + + return markerApply(marker, delegate.createImportDefaultSpecifier(id)); + } + + function parseImportNamespaceSpecifier() { + // import <* as foo> ...; + var id, marker = markerCreate(); + + expect('*'); + if (!matchContextualKeyword('as')) { + throwError({}, Messages.NoAsAfterImportNamespace); + } + lex(); + id = parseNonComputedProperty(); + + return markerApply(marker, delegate.createImportNamespaceSpecifier(id)); + } + + function parseImportDeclaration() { + var specifiers, src, marker = markerCreate(); + + expectKeyword('import'); + specifiers = []; + + if (lookahead.type === Token.StringLiteral) { + // covers: + // import "foo"; + src = parseModuleSpecifier(); + consumeSemicolon(); + return markerApply(marker, delegate.createImportDeclaration(specifiers, src)); + } + + if (!matchKeyword('default') && isIdentifierName(lookahead)) { + // covers: + // import foo + // import foo, ... + specifiers.push(parseImportDefaultSpecifier()); + if (match(',')) { + lex(); + } + } + if (match('*')) { + // covers: + // import foo, * as foo + // import * as foo + specifiers.push(parseImportNamespaceSpecifier()); + } else if (match('{')) { + // covers: + // import foo, {bar} + // import {bar} + specifiers = specifiers.concat(parseNamedImports()); + } + + if (!matchContextualKeyword('from')) { + throwError({}, lookahead.value ? + Messages.UnexpectedToken : Messages.MissingFromClause, lookahead.value); + } + lex(); + src = parseModuleSpecifier(); + consumeSemicolon(); + + return markerApply(marker, delegate.createImportDeclaration(specifiers, src)); } // 12.3 Empty Statement function parseEmptyStatement() { + var marker = markerCreate(); expect(';'); - return delegate.createEmptyStatement(); + return markerApply(marker, delegate.createEmptyStatement()); } // 12.4 Expression Statement function parseExpressionStatement() { - var expr = parseExpression(); + var marker = markerCreate(), expr = parseExpression(); consumeSemicolon(); - return delegate.createExpressionStatement(expr); + return markerApply(marker, delegate.createExpressionStatement(expr)); } // 12.5 If statement function parseIfStatement() { - var test, consequent, alternate; + var test, consequent, alternate, marker = markerCreate(); expectKeyword('if'); @@ -21445,13 +23306,13 @@ parseStatement: true, parseSourceElement: true */ alternate = null; } - return delegate.createIfStatement(test, consequent, alternate); + return markerApply(marker, delegate.createIfStatement(test, consequent, alternate)); } // 12.6 Iteration Statements function parseDoWhileStatement() { - var body, test, oldInIteration; + var body, test, oldInIteration, marker = markerCreate(); expectKeyword('do'); @@ -21474,11 +23335,11 @@ parseStatement: true, parseSourceElement: true */ lex(); } - return delegate.createDoWhileStatement(body, test); + return markerApply(marker, delegate.createDoWhileStatement(body, test)); } function parseWhileStatement() { - var test, body, oldInIteration; + var test, body, oldInIteration, marker = markerCreate(); expectKeyword('while'); @@ -21495,54 +23356,65 @@ parseStatement: true, parseSourceElement: true */ state.inIteration = oldInIteration; - return delegate.createWhileStatement(test, body); + return markerApply(marker, delegate.createWhileStatement(test, body)); } function parseForVariableDeclaration() { - var token, declarations, startToken; + var marker = markerCreate(), + token = lex(), + declarations = parseVariableDeclarationList(); - startToken = lookahead; - token = lex(); - declarations = parseVariableDeclarationList(); - - return delegate.markEnd(delegate.createVariableDeclaration(declarations, token.value), startToken); + return markerApply(marker, delegate.createVariableDeclaration(declarations, token.value)); } - function parseForStatement() { - var init, test, update, left, right, body, oldInIteration; - + function parseForStatement(opts) { + var init, test, update, left, right, body, operator, oldInIteration, + marker = markerCreate(); init = test = update = null; - expectKeyword('for'); + // http://wiki.ecmascript.org/doku.php?id=proposals:iterators_and_generators&s=each + if (matchContextualKeyword('each')) { + throwError({}, Messages.EachNotAllowed); + } + expect('('); if (match(';')) { lex(); } else { - if (matchKeyword('var') || matchKeyword('let')) { + if (matchKeyword('var') || matchKeyword('let') || matchKeyword('const')) { state.allowIn = false; init = parseForVariableDeclaration(); state.allowIn = true; - if (init.declarations.length === 1 && matchKeyword('in')) { - lex(); - left = init; - right = parseExpression(); - init = null; + if (init.declarations.length === 1) { + if (matchKeyword('in') || matchContextualKeyword('of')) { + operator = lookahead; + if (!((operator.value === 'in' || init.kind !== 'var') && init.declarations[0].init)) { + lex(); + left = init; + right = parseExpression(); + init = null; + } + } } } else { state.allowIn = false; init = parseExpression(); state.allowIn = true; - if (matchKeyword('in')) { + if (matchContextualKeyword('of')) { + operator = lex(); + left = init; + right = parseExpression(); + init = null; + } else if (matchKeyword('in')) { // LeftHandSideExpression - if (!isLeftHandSide(init)) { - throwErrorTolerant({}, Messages.InvalidLHSInForIn); + if (!isAssignableLeftHandSide(init)) { + throwError({}, Messages.InvalidLHSInForIn); } - - lex(); + operator = lex(); left = init; right = parseExpression(); init = null; @@ -21571,31 +23443,38 @@ parseStatement: true, parseSourceElement: true */ oldInIteration = state.inIteration; state.inIteration = true; - body = parseStatement(); + if (!(opts !== undefined && opts.ignoreBody)) { + body = parseStatement(); + } state.inIteration = oldInIteration; - return (typeof left === 'undefined') ? - delegate.createForStatement(init, test, update, body) : - delegate.createForInStatement(left, right, body); + if (typeof left === 'undefined') { + return markerApply(marker, delegate.createForStatement(init, test, update, body)); + } + + if (operator.value === 'in') { + return markerApply(marker, delegate.createForInStatement(left, right, body)); + } + return markerApply(marker, delegate.createForOfStatement(left, right, body)); } // 12.7 The continue statement function parseContinueStatement() { - var label = null, key; + var label = null, key, marker = markerCreate(); expectKeyword('continue'); // Optimize the most common form: 'continue;'. - if (source.charCodeAt(index) === 0x3B) { + if (source.charCodeAt(index) === 59) { lex(); if (!state.inIteration) { throwError({}, Messages.IllegalContinue); } - return delegate.createContinueStatement(null); + return markerApply(marker, delegate.createContinueStatement(null)); } if (peekLineTerminator()) { @@ -21603,7 +23482,7 @@ parseStatement: true, parseSourceElement: true */ throwError({}, Messages.IllegalContinue); } - return delegate.createContinueStatement(null); + return markerApply(marker, delegate.createContinueStatement(null)); } if (lookahead.type === Token.Identifier) { @@ -21621,25 +23500,25 @@ parseStatement: true, parseSourceElement: true */ throwError({}, Messages.IllegalContinue); } - return delegate.createContinueStatement(label); + return markerApply(marker, delegate.createContinueStatement(label)); } // 12.8 The break statement function parseBreakStatement() { - var label = null, key; + var label = null, key, marker = markerCreate(); expectKeyword('break'); - // Catch the very common case first: immediately a semicolon (U+003B). - if (source.charCodeAt(index) === 0x3B) { + // Catch the very common case first: immediately a semicolon (char #59). + if (source.charCodeAt(index) === 59) { lex(); if (!(state.inIteration || state.inSwitch)) { throwError({}, Messages.IllegalBreak); } - return delegate.createBreakStatement(null); + return markerApply(marker, delegate.createBreakStatement(null)); } if (peekLineTerminator()) { @@ -21647,7 +23526,7 @@ parseStatement: true, parseSourceElement: true */ throwError({}, Messages.IllegalBreak); } - return delegate.createBreakStatement(null); + return markerApply(marker, delegate.createBreakStatement(null)); } if (lookahead.type === Token.Identifier) { @@ -21665,13 +23544,13 @@ parseStatement: true, parseSourceElement: true */ throwError({}, Messages.IllegalBreak); } - return delegate.createBreakStatement(label); + return markerApply(marker, delegate.createBreakStatement(label)); } // 12.9 The return statement function parseReturnStatement() { - var argument = null; + var argument = null, marker = markerCreate(); expectKeyword('return'); @@ -21680,16 +23559,16 @@ parseStatement: true, parseSourceElement: true */ } // 'return' followed by a space and an identifier is very common. - if (source.charCodeAt(index) === 0x20) { + if (source.charCodeAt(index) === 32) { if (isIdentifierStart(source.charCodeAt(index + 1))) { argument = parseExpression(); consumeSemicolon(); - return delegate.createReturnStatement(argument); + return markerApply(marker, delegate.createReturnStatement(argument)); } } if (peekLineTerminator()) { - return delegate.createReturnStatement(null); + return markerApply(marker, delegate.createReturnStatement(null)); } if (!match(';')) { @@ -21700,17 +23579,15 @@ parseStatement: true, parseSourceElement: true */ consumeSemicolon(); - return delegate.createReturnStatement(argument); + return markerApply(marker, delegate.createReturnStatement(argument)); } // 12.10 The with statement function parseWithStatement() { - var object, body; + var object, body, marker = markerCreate(); if (strict) { - // TODO(ikarienator): Should we update the test cases instead? - skipComment(); throwErrorTolerant({}, Messages.StrictModeWith); } @@ -21724,15 +23601,17 @@ parseStatement: true, parseSourceElement: true */ body = parseStatement(); - return delegate.createWithStatement(object, body); + return markerApply(marker, delegate.createWithStatement(object, body)); } // 12.10 The swith statement function parseSwitchCase() { - var test, consequent = [], statement, startToken; + var test, + consequent = [], + sourceElement, + marker = markerCreate(); - startToken = lookahead; if (matchKeyword('default')) { lex(); test = null; @@ -21746,15 +23625,18 @@ parseStatement: true, parseSourceElement: true */ if (match('}') || matchKeyword('default') || matchKeyword('case')) { break; } - statement = parseStatement(); - consequent.push(statement); + sourceElement = parseSourceElement(); + if (typeof sourceElement === 'undefined') { + break; + } + consequent.push(sourceElement); } - return delegate.markEnd(delegate.createSwitchCase(test, consequent), startToken); + return markerApply(marker, delegate.createSwitchCase(test, consequent)); } function parseSwitchStatement() { - var discriminant, cases, clause, oldInSwitch, defaultFound; + var discriminant, cases, clause, oldInSwitch, defaultFound, marker = markerCreate(); expectKeyword('switch'); @@ -21770,7 +23652,7 @@ parseStatement: true, parseSourceElement: true */ if (match('}')) { lex(); - return delegate.createSwitchStatement(discriminant, cases); + return markerApply(marker, delegate.createSwitchStatement(discriminant, cases)); } oldInSwitch = state.inSwitch; @@ -21795,13 +23677,13 @@ parseStatement: true, parseSourceElement: true */ expect('}'); - return delegate.createSwitchStatement(discriminant, cases); + return markerApply(marker, delegate.createSwitchStatement(discriminant, cases)); } // 12.13 The throw statement function parseThrowStatement() { - var argument; + var argument, marker = markerCreate(); expectKeyword('throw'); @@ -21813,15 +23695,14 @@ parseStatement: true, parseSourceElement: true */ consumeSemicolon(); - return delegate.createThrowStatement(argument); + return markerApply(marker, delegate.createThrowStatement(argument)); } // 12.14 The try statement function parseCatchClause() { - var param, body, startToken; + var param, body, marker = markerCreate(); - startToken = lookahead; expectKeyword('catch'); expect('('); @@ -21829,19 +23710,19 @@ parseStatement: true, parseSourceElement: true */ throwUnexpected(lookahead); } - param = parseVariableIdentifier(); + param = parseExpression(); // 12.14.1 - if (strict && isRestrictedWord(param.name)) { + if (strict && param.type === Syntax.Identifier && isRestrictedWord(param.name)) { throwErrorTolerant({}, Messages.StrictCatchVariable); } expect(')'); body = parseBlock(); - return delegate.markEnd(delegate.createCatchClause(param, body), startToken); + return markerApply(marker, delegate.createCatchClause(param, body)); } function parseTryStatement() { - var block, handlers = [], finalizer = null; + var block, handlers = [], finalizer = null, marker = markerCreate(); expectKeyword('try'); @@ -21860,44 +23741,41 @@ parseStatement: true, parseSourceElement: true */ throwError({}, Messages.NoCatchOrFinally); } - return delegate.createTryStatement(block, [], handlers, finalizer); + return markerApply(marker, delegate.createTryStatement(block, [], handlers, finalizer)); } // 12.15 The debugger statement function parseDebuggerStatement() { + var marker = markerCreate(); expectKeyword('debugger'); consumeSemicolon(); - return delegate.createDebuggerStatement(); + return markerApply(marker, delegate.createDebuggerStatement()); } // 12 Statements function parseStatement() { var type = lookahead.type, + marker, expr, labeledBody, - key, - startToken; + key; if (type === Token.EOF) { throwUnexpected(lookahead); } - if (type === Token.Punctuator && lookahead.value === '{') { - return parseBlock(); - } - - startToken = lookahead; - if (type === Token.Punctuator) { switch (lookahead.value) { case ';': - return delegate.markEnd(parseEmptyStatement(), startToken); + return parseEmptyStatement(); + case '{': + return parseBlock(); case '(': - return delegate.markEnd(parseExpressionStatement(), startToken); + return parseExpressionStatement(); default: break; } @@ -21906,38 +23784,45 @@ parseStatement: true, parseSourceElement: true */ if (type === Token.Keyword) { switch (lookahead.value) { case 'break': - return delegate.markEnd(parseBreakStatement(), startToken); + return parseBreakStatement(); case 'continue': - return delegate.markEnd(parseContinueStatement(), startToken); + return parseContinueStatement(); case 'debugger': - return delegate.markEnd(parseDebuggerStatement(), startToken); + return parseDebuggerStatement(); case 'do': - return delegate.markEnd(parseDoWhileStatement(), startToken); + return parseDoWhileStatement(); case 'for': - return delegate.markEnd(parseForStatement(), startToken); + return parseForStatement(); case 'function': - return delegate.markEnd(parseFunctionDeclaration(), startToken); + return parseFunctionDeclaration(); + case 'class': + return parseClassDeclaration(); case 'if': - return delegate.markEnd(parseIfStatement(), startToken); + return parseIfStatement(); case 'return': - return delegate.markEnd(parseReturnStatement(), startToken); + return parseReturnStatement(); case 'switch': - return delegate.markEnd(parseSwitchStatement(), startToken); + return parseSwitchStatement(); case 'throw': - return delegate.markEnd(parseThrowStatement(), startToken); + return parseThrowStatement(); case 'try': - return delegate.markEnd(parseTryStatement(), startToken); + return parseTryStatement(); case 'var': - return delegate.markEnd(parseVariableStatement(), startToken); + return parseVariableStatement(); case 'while': - return delegate.markEnd(parseWhileStatement(), startToken); + return parseWhileStatement(); case 'with': - return delegate.markEnd(parseWithStatement(), startToken); + return parseWithStatement(); default: break; } } + if (matchAsyncFuncExprOrDecl()) { + return parseFunctionDeclaration(); + } + + marker = markerCreate(); expr = parseExpression(); // 12.12 Labelled Statements @@ -21952,21 +23837,28 @@ parseStatement: true, parseSourceElement: true */ state.labelSet[key] = true; labeledBody = parseStatement(); delete state.labelSet[key]; - return delegate.markEnd(delegate.createLabeledStatement(expr, labeledBody), startToken); + return markerApply(marker, delegate.createLabeledStatement(expr, labeledBody)); } consumeSemicolon(); - return delegate.markEnd(delegate.createExpressionStatement(expr), startToken); + return markerApply(marker, delegate.createExpressionStatement(expr)); } // 13 Function Definition + function parseConciseBody() { + if (match('{')) { + return parseFunctionSourceElements(); + } + return parseAssignmentExpression(); + } + function parseFunctionSourceElements() { var sourceElement, sourceElements = [], token, directive, firstRestricted, - oldLabelSet, oldInIteration, oldInSwitch, oldInFunctionBody, startToken; + oldLabelSet, oldInIteration, oldInSwitch, oldInFunctionBody, oldParenthesizedCount, + marker = markerCreate(); - startToken = lookahead; expect('{'); while (index < length) { @@ -21981,7 +23873,7 @@ parseStatement: true, parseSourceElement: true */ // this is not directive break; } - directive = source.slice(token.start + 1, token.end - 1); + directive = source.slice(token.range[0] + 1, token.range[1] - 1); if (directive === 'use strict') { strict = true; if (firstRestricted) { @@ -21998,11 +23890,13 @@ parseStatement: true, parseSourceElement: true */ oldInIteration = state.inIteration; oldInSwitch = state.inSwitch; oldInFunctionBody = state.inFunctionBody; + oldParenthesizedCount = state.parenthesizedCount; state.labelSet = {}; state.inIteration = false; state.inSwitch = false; state.inFunctionBody = true; + state.parenthesizedCount = 0; while (index < length) { if (match('}')) { @@ -22021,44 +23915,107 @@ parseStatement: true, parseSourceElement: true */ state.inIteration = oldInIteration; state.inSwitch = oldInSwitch; state.inFunctionBody = oldInFunctionBody; + state.parenthesizedCount = oldParenthesizedCount; - return delegate.markEnd(delegate.createBlockStatement(sourceElements), startToken); + return markerApply(marker, delegate.createBlockStatement(sourceElements)); + } + + function validateParam(options, param, name) { + var key = '$' + name; + if (strict) { + if (isRestrictedWord(name)) { + options.stricted = param; + options.message = Messages.StrictParamName; + } + if (Object.prototype.hasOwnProperty.call(options.paramSet, key)) { + options.stricted = param; + options.message = Messages.StrictParamDupe; + } + } else if (!options.firstRestricted) { + if (isRestrictedWord(name)) { + options.firstRestricted = param; + options.message = Messages.StrictParamName; + } else if (isStrictModeReservedWord(name)) { + options.firstRestricted = param; + options.message = Messages.StrictReservedWord; + } else if (Object.prototype.hasOwnProperty.call(options.paramSet, key)) { + options.firstRestricted = param; + options.message = Messages.StrictParamDupe; + } + } + options.paramSet[key] = true; + } + + function parseParam(options) { + var token, rest, param, def; + + token = lookahead; + if (token.value === '...') { + token = lex(); + rest = true; + } + + if (match('[')) { + param = parseArrayInitialiser(); + reinterpretAsDestructuredParameter(options, param); + } else if (match('{')) { + if (rest) { + throwError({}, Messages.ObjectPatternAsRestParameter); + } + param = parseObjectInitialiser(); + reinterpretAsDestructuredParameter(options, param); + } else { + // Typing rest params is awkward, so punting on that for now + param = + rest + ? parseVariableIdentifier() + : parseTypeAnnotatableIdentifier( + false, /* requireTypeAnnotation */ + true /* canBeOptionalParam */ + ); + + validateParam(options, token, token.value); + } + + if (match('=')) { + if (rest) { + throwErrorTolerant(lookahead, Messages.DefaultRestParameter); + } + lex(); + def = parseAssignmentExpression(); + ++options.defaultCount; + } + + if (rest) { + if (!match(')')) { + throwError({}, Messages.ParameterAfterRestParameter); + } + options.rest = param; + return false; + } + + options.params.push(param); + options.defaults.push(def); + return !match(')'); } function parseParams(firstRestricted) { - var param, params = [], token, stricted, paramSet, key, message; + var options, marker = markerCreate(); + + options = { + params: [], + defaultCount: 0, + defaults: [], + rest: null, + firstRestricted: firstRestricted + }; + expect('('); if (!match(')')) { - paramSet = {}; + options.paramSet = {}; while (index < length) { - token = lookahead; - param = parseVariableIdentifier(); - key = '$' + token.value; - if (strict) { - if (isRestrictedWord(token.value)) { - stricted = token; - message = Messages.StrictParamName; - } - if (Object.prototype.hasOwnProperty.call(paramSet, key)) { - stricted = token; - message = Messages.StrictParamDupe; - } - } else if (!firstRestricted) { - if (isRestrictedWord(token.value)) { - firstRestricted = token; - message = Messages.StrictParamName; - } else if (isStrictModeReservedWord(token.value)) { - firstRestricted = token; - message = Messages.StrictReservedWord; - } else if (Object.prototype.hasOwnProperty.call(paramSet, key)) { - firstRestricted = token; - message = Messages.StrictParamDupe; - } - } - params.push(param); - paramSet[key] = true; - if (match(')')) { + if (!parseParam(options)) { break; } expect(','); @@ -22067,22 +24024,44 @@ parseStatement: true, parseSourceElement: true */ expect(')'); - return { - params: params, - stricted: stricted, - firstRestricted: firstRestricted, - message: message - }; + if (options.defaultCount === 0) { + options.defaults = []; + } + + if (match(':')) { + options.returnType = parseTypeAnnotation(); + } + + return markerApply(marker, options); } function parseFunctionDeclaration() { - var id, params = [], body, token, stricted, tmp, firstRestricted, message, previousStrict, startToken; + var id, body, token, tmp, firstRestricted, message, generator, isAsync, + previousStrict, previousYieldAllowed, previousAwaitAllowed, + marker = markerCreate(), parametricType; - startToken = lookahead; + isAsync = false; + if (matchAsync()) { + lex(); + isAsync = true; + } expectKeyword('function'); + + generator = false; + if (match('*')) { + lex(); + generator = true; + } + token = lookahead; + id = parseVariableIdentifier(); + + if (match('<')) { + parametricType = parseParametricTypeAnnotation(); + } + if (strict) { if (isRestrictedWord(token.value)) { throwErrorTolerant(token, Messages.StrictFunctionName); @@ -22098,72 +24077,376 @@ parseStatement: true, parseSourceElement: true */ } tmp = parseParams(firstRestricted); - params = tmp.params; - stricted = tmp.stricted; firstRestricted = tmp.firstRestricted; if (tmp.message) { message = tmp.message; } previousStrict = strict; + previousYieldAllowed = state.yieldAllowed; + state.yieldAllowed = generator; + previousAwaitAllowed = state.awaitAllowed; + state.awaitAllowed = isAsync; + body = parseFunctionSourceElements(); + if (strict && firstRestricted) { throwError(firstRestricted, message); } - if (strict && stricted) { - throwErrorTolerant(stricted, message); + if (strict && tmp.stricted) { + throwErrorTolerant(tmp.stricted, message); } strict = previousStrict; + state.yieldAllowed = previousYieldAllowed; + state.awaitAllowed = previousAwaitAllowed; - return delegate.markEnd(delegate.createFunctionDeclaration(id, params, [], body), startToken); + return markerApply( + marker, + delegate.createFunctionDeclaration( + id, + tmp.params, + tmp.defaults, + body, + tmp.rest, + generator, + false, + isAsync, + tmp.returnType, + parametricType + ) + ); } function parseFunctionExpression() { - var token, id = null, stricted, firstRestricted, message, tmp, params = [], body, previousStrict, startToken; + var token, id = null, firstRestricted, message, tmp, body, generator, isAsync, + previousStrict, previousYieldAllowed, previousAwaitAllowed, + marker = markerCreate(), parametricType; + + isAsync = false; + if (matchAsync()) { + lex(); + isAsync = true; + } - startToken = lookahead; expectKeyword('function'); + generator = false; + + if (match('*')) { + lex(); + generator = true; + } + if (!match('(')) { - token = lookahead; - id = parseVariableIdentifier(); - if (strict) { - if (isRestrictedWord(token.value)) { - throwErrorTolerant(token, Messages.StrictFunctionName); - } - } else { - if (isRestrictedWord(token.value)) { - firstRestricted = token; - message = Messages.StrictFunctionName; - } else if (isStrictModeReservedWord(token.value)) { - firstRestricted = token; - message = Messages.StrictReservedWord; + if (!match('<')) { + token = lookahead; + id = parseVariableIdentifier(); + + if (strict) { + if (isRestrictedWord(token.value)) { + throwErrorTolerant(token, Messages.StrictFunctionName); + } + } else { + if (isRestrictedWord(token.value)) { + firstRestricted = token; + message = Messages.StrictFunctionName; + } else if (isStrictModeReservedWord(token.value)) { + firstRestricted = token; + message = Messages.StrictReservedWord; + } } } + + if (match('<')) { + parametricType = parseParametricTypeAnnotation(); + } } tmp = parseParams(firstRestricted); - params = tmp.params; - stricted = tmp.stricted; firstRestricted = tmp.firstRestricted; if (tmp.message) { message = tmp.message; } previousStrict = strict; + previousYieldAllowed = state.yieldAllowed; + state.yieldAllowed = generator; + previousAwaitAllowed = state.awaitAllowed; + state.awaitAllowed = isAsync; + body = parseFunctionSourceElements(); + if (strict && firstRestricted) { throwError(firstRestricted, message); } - if (strict && stricted) { - throwErrorTolerant(stricted, message); + if (strict && tmp.stricted) { + throwErrorTolerant(tmp.stricted, message); } strict = previousStrict; + state.yieldAllowed = previousYieldAllowed; + state.awaitAllowed = previousAwaitAllowed; - return delegate.markEnd(delegate.createFunctionExpression(id, params, [], body), startToken); + return markerApply( + marker, + delegate.createFunctionExpression( + id, + tmp.params, + tmp.defaults, + body, + tmp.rest, + generator, + false, + isAsync, + tmp.returnType, + parametricType + ) + ); } - // 14 Program + function parseYieldExpression() { + var delegateFlag, expr, marker = markerCreate(); + + expectKeyword('yield', !strict); + + delegateFlag = false; + if (match('*')) { + lex(); + delegateFlag = true; + } + + expr = parseAssignmentExpression(); + + return markerApply(marker, delegate.createYieldExpression(expr, delegateFlag)); + } + + function parseAwaitExpression() { + var expr, marker = markerCreate(); + expectContextualKeyword('await'); + expr = parseAssignmentExpression(); + return markerApply(marker, delegate.createAwaitExpression(expr)); + } + + // 14 Classes + + function parseMethodDefinition(existingPropNames) { + var token, key, param, propType, isValidDuplicateProp = false, + isAsync, marker = markerCreate(), token2, parametricType, + parametricTypeMarker, annotationMarker; + + if (lookahead.value === 'static') { + propType = ClassPropertyType.static; + lex(); + } else { + propType = ClassPropertyType.prototype; + } + + if (match('*')) { + lex(); + return markerApply(marker, delegate.createMethodDefinition( + propType, + '', + parseObjectPropertyKey(), + parsePropertyMethodFunction({ generator: true }) + )); + } + + token = lookahead; + //parametricTypeMarker = markerCreate(); + key = parseObjectPropertyKey(); + + if (token.value === 'get' && !match('(')) { + key = parseObjectPropertyKey(); + + // It is a syntax error if any other properties have a name + // duplicating this one unless they are a setter + if (existingPropNames[propType].hasOwnProperty(key.name)) { + isValidDuplicateProp = + // There isn't already a getter for this prop + existingPropNames[propType][key.name].get === undefined + // There isn't already a data prop by this name + && existingPropNames[propType][key.name].data === undefined + // The only existing prop by this name is a setter + && existingPropNames[propType][key.name].set !== undefined; + if (!isValidDuplicateProp) { + throwError(key, Messages.IllegalDuplicateClassProperty); + } + } else { + existingPropNames[propType][key.name] = {}; + } + existingPropNames[propType][key.name].get = true; + + expect('('); + expect(')'); + return markerApply(marker, delegate.createMethodDefinition( + propType, + 'get', + key, + parsePropertyFunction({ generator: false }) + )); + } + if (token.value === 'set' && !match('(')) { + key = parseObjectPropertyKey(); + + // It is a syntax error if any other properties have a name + // duplicating this one unless they are a getter + if (existingPropNames[propType].hasOwnProperty(key.name)) { + isValidDuplicateProp = + // There isn't already a setter for this prop + existingPropNames[propType][key.name].set === undefined + // There isn't already a data prop by this name + && existingPropNames[propType][key.name].data === undefined + // The only existing prop by this name is a getter + && existingPropNames[propType][key.name].get !== undefined; + if (!isValidDuplicateProp) { + throwError(key, Messages.IllegalDuplicateClassProperty); + } + } else { + existingPropNames[propType][key.name] = {}; + } + existingPropNames[propType][key.name].set = true; + + expect('('); + token = lookahead; + param = [ parseTypeAnnotatableIdentifier() ]; + expect(')'); + return markerApply(marker, delegate.createMethodDefinition( + propType, + 'set', + key, + parsePropertyFunction({ params: param, generator: false, name: token }) + )); + } + + if (match('<')) { + parametricType = parseParametricTypeAnnotation(); + } + + isAsync = token.value === 'async' && !match('('); + if (isAsync) { + key = parseObjectPropertyKey(); + } + + // It is a syntax error if any other properties have the same name as a + // non-getter, non-setter method + if (existingPropNames[propType].hasOwnProperty(key.name)) { + throwError(key, Messages.IllegalDuplicateClassProperty); + } else { + existingPropNames[propType][key.name] = {}; + } + existingPropNames[propType][key.name].data = true; + + return markerApply(marker, delegate.createMethodDefinition( + propType, + '', + key, + parsePropertyMethodFunction({ + generator: false, + async: isAsync, + parametricType: parametricType + }) + )); + } + + function parseClassProperty(existingPropNames) { + var marker = markerCreate(), propertyIdentifier; + + propertyIdentifier = parseTypeAnnotatableIdentifier(); + expect(';'); + + return markerApply(marker, delegate.createClassProperty( + propertyIdentifier + )); + } + + function parseClassElement(existingProps) { + if (match(';')) { + lex(); + return; + } + + var doubleLookahead = lookahead2(); + if (doubleLookahead.type === Token.Punctuator) { + if (doubleLookahead.value === ':') { + return parseClassProperty(existingProps); + } + } + + return parseMethodDefinition(existingProps); + } + + function parseClassBody() { + var classElement, classElements = [], existingProps = {}, marker = markerCreate(); + + existingProps[ClassPropertyType.static] = {}; + existingProps[ClassPropertyType.prototype] = {}; + + expect('{'); + + while (index < length) { + if (match('}')) { + break; + } + classElement = parseClassElement(existingProps); + + if (typeof classElement !== 'undefined') { + classElements.push(classElement); + } + } + + expect('}'); + + return markerApply(marker, delegate.createClassBody(classElements)); + } + + function parseClassExpression() { + var id, previousYieldAllowed, superClass = null, marker = markerCreate(), + parametricType; + + expectKeyword('class'); + + if (!matchKeyword('extends') && !match('{')) { + id = parseVariableIdentifier(); + } + + if (match('<')) { + parametricType = parseParametricTypeAnnotation(); + } + + if (matchKeyword('extends')) { + expectKeyword('extends'); + previousYieldAllowed = state.yieldAllowed; + state.yieldAllowed = false; + superClass = parseAssignmentExpression(); + state.yieldAllowed = previousYieldAllowed; + } + + return markerApply(marker, delegate.createClassExpression(id, superClass, parseClassBody(), parametricType)); + } + + function parseClassDeclaration() { + var id, previousYieldAllowed, superClass = null, marker = markerCreate(), + parametricType, superParametricType; + + expectKeyword('class'); + + id = parseVariableIdentifier(); + + if (match('<')) { + parametricType = parseParametricTypeAnnotation(); + } + + if (matchKeyword('extends')) { + expectKeyword('extends'); + previousYieldAllowed = state.yieldAllowed; + state.yieldAllowed = false; + superClass = parseAssignmentExpression(); + state.yieldAllowed = previousYieldAllowed; + } + + return markerApply(marker, delegate.createClassDeclaration(id, superClass, parseClassBody(), parametricType, superParametricType)); + } + + // 15 Program function parseSourceElement() { if (lookahead.type === Token.Keyword) { @@ -22183,7 +24466,20 @@ parseStatement: true, parseSourceElement: true */ } } - function parseSourceElements() { + function parseProgramElement() { + if (lookahead.type === Token.Keyword) { + switch (lookahead.value) { + case 'export': + return parseExportDeclaration(); + case 'import': + return parseImportDeclaration(); + } + } + + return parseSourceElement(); + } + + function parseProgramElements() { var sourceElement, sourceElements = [], token, directive, firstRestricted; while (index < length) { @@ -22192,13 +24488,13 @@ parseStatement: true, parseSourceElement: true */ break; } - sourceElement = parseSourceElement(); + sourceElement = parseProgramElement(); sourceElements.push(sourceElement); if (sourceElement.expression.type !== Syntax.Literal) { // this is not directive break; } - directive = source.slice(token.start + 1, token.end - 1); + directive = source.slice(token.range[0] + 1, token.range[1] - 1); if (directive === 'use strict') { strict = true; if (firstRestricted) { @@ -22212,8 +24508,7 @@ parseStatement: true, parseSourceElement: true */ } while (index < length) { - sourceElement = parseSourceElement(); - /* istanbul ignore if */ + sourceElement = parseProgramElement(); if (typeof sourceElement === 'undefined') { break; } @@ -22223,15 +24518,917 @@ parseStatement: true, parseSourceElement: true */ } function parseProgram() { - var body, startToken; + var body, marker = markerCreate(); + strict = false; + peek(); + body = parseProgramElements(); + return markerApply(marker, delegate.createProgram(body)); + } + + // The following functions are needed only when the option to preserve + // the comments is active. + + function addComment(type, value, start, end, loc) { + var comment; + + assert(typeof start === 'number', 'Comment must have valid position'); + + // Because the way the actual token is scanned, often the comments + // (if any) are skipped twice during the lexical analysis. + // Thus, we need to skip adding a comment if the comment array already + // handled it. + if (state.lastCommentStart >= start) { + return; + } + state.lastCommentStart = start; + + comment = { + type: type, + value: value + }; + if (extra.range) { + comment.range = [start, end]; + } + if (extra.loc) { + comment.loc = loc; + } + extra.comments.push(comment); + if (extra.attachComment) { + extra.leadingComments.push(comment); + extra.trailingComments.push(comment); + } + } + + function scanComment() { + var comment, ch, loc, start, blockComment, lineComment; + + comment = ''; + blockComment = false; + lineComment = false; + + while (index < length) { + ch = source[index]; + + if (lineComment) { + ch = source[index++]; + if (isLineTerminator(ch.charCodeAt(0))) { + loc.end = { + line: lineNumber, + column: index - lineStart - 1 + }; + lineComment = false; + addComment('Line', comment, start, index - 1, loc); + if (ch === '\r' && source[index] === '\n') { + ++index; + } + ++lineNumber; + lineStart = index; + comment = ''; + } else if (index >= length) { + lineComment = false; + comment += ch; + loc.end = { + line: lineNumber, + column: length - lineStart + }; + addComment('Line', comment, start, length, loc); + } else { + comment += ch; + } + } else if (blockComment) { + if (isLineTerminator(ch.charCodeAt(0))) { + if (ch === '\r') { + ++index; + comment += '\r'; + } + if (ch !== '\r' || source[index] === '\n') { + comment += source[index]; + ++lineNumber; + ++index; + lineStart = index; + if (index >= length) { + throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); + } + } + } else { + ch = source[index++]; + if (index >= length) { + throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); + } + comment += ch; + if (ch === '*') { + ch = source[index]; + if (ch === '/') { + comment = comment.substr(0, comment.length - 1); + blockComment = false; + ++index; + loc.end = { + line: lineNumber, + column: index - lineStart + }; + addComment('Block', comment, start, index, loc); + comment = ''; + } + } + } + } else if (ch === '/') { + ch = source[index + 1]; + if (ch === '/') { + loc = { + start: { + line: lineNumber, + column: index - lineStart + } + }; + start = index; + index += 2; + lineComment = true; + if (index >= length) { + loc.end = { + line: lineNumber, + column: index - lineStart + }; + lineComment = false; + addComment('Line', comment, start, index, loc); + } + } else if (ch === '*') { + start = index; + index += 2; + blockComment = true; + loc = { + start: { + line: lineNumber, + column: index - lineStart - 2 + } + }; + if (index >= length) { + throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); + } + } else { + break; + } + } else if (isWhiteSpace(ch.charCodeAt(0))) { + ++index; + } else if (isLineTerminator(ch.charCodeAt(0))) { + ++index; + if (ch === '\r' && source[index] === '\n') { + ++index; + } + ++lineNumber; + lineStart = index; + } else { + break; + } + } + } + + // 16 XJS + + XHTMLEntities = { + quot: '\u0022', + amp: '&', + apos: '\u0027', + lt: '<', + gt: '>', + nbsp: '\u00A0', + iexcl: '\u00A1', + cent: '\u00A2', + pound: '\u00A3', + curren: '\u00A4', + yen: '\u00A5', + brvbar: '\u00A6', + sect: '\u00A7', + uml: '\u00A8', + copy: '\u00A9', + ordf: '\u00AA', + laquo: '\u00AB', + not: '\u00AC', + shy: '\u00AD', + reg: '\u00AE', + macr: '\u00AF', + deg: '\u00B0', + plusmn: '\u00B1', + sup2: '\u00B2', + sup3: '\u00B3', + acute: '\u00B4', + micro: '\u00B5', + para: '\u00B6', + middot: '\u00B7', + cedil: '\u00B8', + sup1: '\u00B9', + ordm: '\u00BA', + raquo: '\u00BB', + frac14: '\u00BC', + frac12: '\u00BD', + frac34: '\u00BE', + iquest: '\u00BF', + Agrave: '\u00C0', + Aacute: '\u00C1', + Acirc: '\u00C2', + Atilde: '\u00C3', + Auml: '\u00C4', + Aring: '\u00C5', + AElig: '\u00C6', + Ccedil: '\u00C7', + Egrave: '\u00C8', + Eacute: '\u00C9', + Ecirc: '\u00CA', + Euml: '\u00CB', + Igrave: '\u00CC', + Iacute: '\u00CD', + Icirc: '\u00CE', + Iuml: '\u00CF', + ETH: '\u00D0', + Ntilde: '\u00D1', + Ograve: '\u00D2', + Oacute: '\u00D3', + Ocirc: '\u00D4', + Otilde: '\u00D5', + Ouml: '\u00D6', + times: '\u00D7', + Oslash: '\u00D8', + Ugrave: '\u00D9', + Uacute: '\u00DA', + Ucirc: '\u00DB', + Uuml: '\u00DC', + Yacute: '\u00DD', + THORN: '\u00DE', + szlig: '\u00DF', + agrave: '\u00E0', + aacute: '\u00E1', + acirc: '\u00E2', + atilde: '\u00E3', + auml: '\u00E4', + aring: '\u00E5', + aelig: '\u00E6', + ccedil: '\u00E7', + egrave: '\u00E8', + eacute: '\u00E9', + ecirc: '\u00EA', + euml: '\u00EB', + igrave: '\u00EC', + iacute: '\u00ED', + icirc: '\u00EE', + iuml: '\u00EF', + eth: '\u00F0', + ntilde: '\u00F1', + ograve: '\u00F2', + oacute: '\u00F3', + ocirc: '\u00F4', + otilde: '\u00F5', + ouml: '\u00F6', + divide: '\u00F7', + oslash: '\u00F8', + ugrave: '\u00F9', + uacute: '\u00FA', + ucirc: '\u00FB', + uuml: '\u00FC', + yacute: '\u00FD', + thorn: '\u00FE', + yuml: '\u00FF', + OElig: '\u0152', + oelig: '\u0153', + Scaron: '\u0160', + scaron: '\u0161', + Yuml: '\u0178', + fnof: '\u0192', + circ: '\u02C6', + tilde: '\u02DC', + Alpha: '\u0391', + Beta: '\u0392', + Gamma: '\u0393', + Delta: '\u0394', + Epsilon: '\u0395', + Zeta: '\u0396', + Eta: '\u0397', + Theta: '\u0398', + Iota: '\u0399', + Kappa: '\u039A', + Lambda: '\u039B', + Mu: '\u039C', + Nu: '\u039D', + Xi: '\u039E', + Omicron: '\u039F', + Pi: '\u03A0', + Rho: '\u03A1', + Sigma: '\u03A3', + Tau: '\u03A4', + Upsilon: '\u03A5', + Phi: '\u03A6', + Chi: '\u03A7', + Psi: '\u03A8', + Omega: '\u03A9', + alpha: '\u03B1', + beta: '\u03B2', + gamma: '\u03B3', + delta: '\u03B4', + epsilon: '\u03B5', + zeta: '\u03B6', + eta: '\u03B7', + theta: '\u03B8', + iota: '\u03B9', + kappa: '\u03BA', + lambda: '\u03BB', + mu: '\u03BC', + nu: '\u03BD', + xi: '\u03BE', + omicron: '\u03BF', + pi: '\u03C0', + rho: '\u03C1', + sigmaf: '\u03C2', + sigma: '\u03C3', + tau: '\u03C4', + upsilon: '\u03C5', + phi: '\u03C6', + chi: '\u03C7', + psi: '\u03C8', + omega: '\u03C9', + thetasym: '\u03D1', + upsih: '\u03D2', + piv: '\u03D6', + ensp: '\u2002', + emsp: '\u2003', + thinsp: '\u2009', + zwnj: '\u200C', + zwj: '\u200D', + lrm: '\u200E', + rlm: '\u200F', + ndash: '\u2013', + mdash: '\u2014', + lsquo: '\u2018', + rsquo: '\u2019', + sbquo: '\u201A', + ldquo: '\u201C', + rdquo: '\u201D', + bdquo: '\u201E', + dagger: '\u2020', + Dagger: '\u2021', + bull: '\u2022', + hellip: '\u2026', + permil: '\u2030', + prime: '\u2032', + Prime: '\u2033', + lsaquo: '\u2039', + rsaquo: '\u203A', + oline: '\u203E', + frasl: '\u2044', + euro: '\u20AC', + image: '\u2111', + weierp: '\u2118', + real: '\u211C', + trade: '\u2122', + alefsym: '\u2135', + larr: '\u2190', + uarr: '\u2191', + rarr: '\u2192', + darr: '\u2193', + harr: '\u2194', + crarr: '\u21B5', + lArr: '\u21D0', + uArr: '\u21D1', + rArr: '\u21D2', + dArr: '\u21D3', + hArr: '\u21D4', + forall: '\u2200', + part: '\u2202', + exist: '\u2203', + empty: '\u2205', + nabla: '\u2207', + isin: '\u2208', + notin: '\u2209', + ni: '\u220B', + prod: '\u220F', + sum: '\u2211', + minus: '\u2212', + lowast: '\u2217', + radic: '\u221A', + prop: '\u221D', + infin: '\u221E', + ang: '\u2220', + and: '\u2227', + or: '\u2228', + cap: '\u2229', + cup: '\u222A', + 'int': '\u222B', + there4: '\u2234', + sim: '\u223C', + cong: '\u2245', + asymp: '\u2248', + ne: '\u2260', + equiv: '\u2261', + le: '\u2264', + ge: '\u2265', + sub: '\u2282', + sup: '\u2283', + nsub: '\u2284', + sube: '\u2286', + supe: '\u2287', + oplus: '\u2295', + otimes: '\u2297', + perp: '\u22A5', + sdot: '\u22C5', + lceil: '\u2308', + rceil: '\u2309', + lfloor: '\u230A', + rfloor: '\u230B', + lang: '\u2329', + rang: '\u232A', + loz: '\u25CA', + spades: '\u2660', + clubs: '\u2663', + hearts: '\u2665', + diams: '\u2666' + }; + + function getQualifiedXJSName(object) { + if (object.type === Syntax.XJSIdentifier) { + return object.name; + } + if (object.type === Syntax.XJSNamespacedName) { + return object.namespace.name + ':' + object.name.name; + } + if (object.type === Syntax.XJSMemberExpression) { + return ( + getQualifiedXJSName(object.object) + '.' + + getQualifiedXJSName(object.property) + ); + } + } + + function isXJSIdentifierStart(ch) { + // exclude backslash (\) + return (ch !== 92) && isIdentifierStart(ch); + } + + function isXJSIdentifierPart(ch) { + // exclude backslash (\) and add hyphen (-) + return (ch !== 92) && (ch === 45 || isIdentifierPart(ch)); + } + + function scanXJSIdentifier() { + var ch, start, value = ''; + + start = index; + while (index < length) { + ch = source.charCodeAt(index); + if (!isXJSIdentifierPart(ch)) { + break; + } + value += source[index++]; + } + + return { + type: Token.XJSIdentifier, + value: value, + lineNumber: lineNumber, + lineStart: lineStart, + range: [start, index] + }; + } + + function scanXJSEntity() { + var ch, str = '', start = index, count = 0, code; + ch = source[index]; + assert(ch === '&', 'Entity must start with an ampersand'); + index++; + while (index < length && count++ < 10) { + ch = source[index++]; + if (ch === ';') { + break; + } + str += ch; + } + + // Well-formed entity (ending was found). + if (ch === ';') { + // Numeric entity. + if (str[0] === '#') { + if (str[1] === 'x') { + code = +('0' + str.substr(1)); + } else { + // Removing leading zeros in order to avoid treating as octal in old browsers. + code = +str.substr(1).replace(Regex.LeadingZeros, ''); + } + + if (!isNaN(code)) { + return String.fromCharCode(code); + } + } else if (XHTMLEntities[str]) { + return XHTMLEntities[str]; + } + } + + // Treat non-entity sequences as regular text. + index = start + 1; + return '&'; + } + + function scanXJSText(stopChars) { + var ch, str = '', start; + start = index; + while (index < length) { + ch = source[index]; + if (stopChars.indexOf(ch) !== -1) { + break; + } + if (ch === '&') { + str += scanXJSEntity(); + } else { + index++; + if (ch === '\r' && source[index] === '\n') { + str += ch; + ch = source[index]; + index++; + } + if (isLineTerminator(ch.charCodeAt(0))) { + ++lineNumber; + lineStart = index; + } + str += ch; + } + } + return { + type: Token.XJSText, + value: str, + lineNumber: lineNumber, + lineStart: lineStart, + range: [start, index] + }; + } + + function scanXJSStringLiteral() { + var innerToken, quote, start; + + quote = source[index]; + assert((quote === '\'' || quote === '"'), + 'String literal must starts with a quote'); + + start = index; + ++index; + + innerToken = scanXJSText([quote]); + + if (quote !== source[index]) { + throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); + } + + ++index; + + innerToken.range = [start, index]; + + return innerToken; + } + + /** + * Between XJS opening and closing tags (e.g. HERE), anything that + * is not another XJS tag and is not an expression wrapped by {} is text. + */ + function advanceXJSChild() { + var ch = source.charCodeAt(index); + + // { (123) and < (60) + if (ch !== 123 && ch !== 60) { + return scanXJSText(['<', '{']); + } + + return scanPunctuator(); + } + + function parseXJSIdentifier() { + var token, marker = markerCreate(); + + if (lookahead.type !== Token.XJSIdentifier) { + throwUnexpected(lookahead); + } + + token = lex(); + return markerApply(marker, delegate.createXJSIdentifier(token.value)); + } + + function parseXJSNamespacedName() { + var namespace, name, marker = markerCreate(); + + namespace = parseXJSIdentifier(); + expect(':'); + name = parseXJSIdentifier(); + + return markerApply(marker, delegate.createXJSNamespacedName(namespace, name)); + } + + function parseXJSMemberExpression() { + var marker = markerCreate(), + expr = parseXJSIdentifier(); + + while (match('.')) { + lex(); + expr = markerApply(marker, delegate.createXJSMemberExpression(expr, parseXJSIdentifier())); + } + + return expr; + } + + function parseXJSElementName() { + if (lookahead2().value === ':') { + return parseXJSNamespacedName(); + } + if (lookahead2().value === '.') { + return parseXJSMemberExpression(); + } + + return parseXJSIdentifier(); + } + + function parseXJSAttributeName() { + if (lookahead2().value === ':') { + return parseXJSNamespacedName(); + } + + return parseXJSIdentifier(); + } + + function parseXJSAttributeValue() { + var value, marker; + if (match('{')) { + value = parseXJSExpressionContainer(); + if (value.expression.type === Syntax.XJSEmptyExpression) { + throwError( + value, + 'XJS attributes must only be assigned a non-empty ' + + 'expression' + ); + } + } else if (match('<')) { + value = parseXJSElement(); + } else if (lookahead.type === Token.XJSText) { + marker = markerCreate(); + value = markerApply(marker, delegate.createLiteral(lex())); + } else { + throwError({}, Messages.InvalidXJSAttributeValue); + } + return value; + } + + function parseXJSEmptyExpression() { + var marker = markerCreatePreserveWhitespace(); + while (source.charAt(index) !== '}') { + index++; + } + return markerApply(marker, delegate.createXJSEmptyExpression()); + } + + function parseXJSExpressionContainer() { + var expression, origInXJSChild, origInXJSTag, marker = markerCreate(); + + origInXJSChild = state.inXJSChild; + origInXJSTag = state.inXJSTag; + state.inXJSChild = false; + state.inXJSTag = false; + + expect('{'); + + if (match('}')) { + expression = parseXJSEmptyExpression(); + } else { + expression = parseExpression(); + } + + state.inXJSChild = origInXJSChild; + state.inXJSTag = origInXJSTag; + + expect('}'); + + return markerApply(marker, delegate.createXJSExpressionContainer(expression)); + } + + function parseXJSSpreadAttribute() { + var expression, origInXJSChild, origInXJSTag, marker = markerCreate(); + + origInXJSChild = state.inXJSChild; + origInXJSTag = state.inXJSTag; + state.inXJSChild = false; + state.inXJSTag = false; + + expect('{'); + expect('...'); + + expression = parseAssignmentExpression(); + + state.inXJSChild = origInXJSChild; + state.inXJSTag = origInXJSTag; + + expect('}'); + + return markerApply(marker, delegate.createXJSSpreadAttribute(expression)); + } + + function parseXJSAttribute() { + var name, marker; + + if (match('{')) { + return parseXJSSpreadAttribute(); + } + + marker = markerCreate(); + + name = parseXJSAttributeName(); + + // HTML empty attribute + if (match('=')) { + lex(); + return markerApply(marker, delegate.createXJSAttribute(name, parseXJSAttributeValue())); + } + + return markerApply(marker, delegate.createXJSAttribute(name)); + } + + function parseXJSChild() { + var token, marker; + if (match('{')) { + token = parseXJSExpressionContainer(); + } else if (lookahead.type === Token.XJSText) { + marker = markerCreatePreserveWhitespace(); + token = markerApply(marker, delegate.createLiteral(lex())); + } else { + token = parseXJSElement(); + } + return token; + } + + function parseXJSClosingElement() { + var name, origInXJSChild, origInXJSTag, marker = markerCreate(); + origInXJSChild = state.inXJSChild; + origInXJSTag = state.inXJSTag; + state.inXJSChild = false; + state.inXJSTag = true; + expect('<'); + expect('/'); + name = parseXJSElementName(); + // Because advance() (called by lex() called by expect()) expects there + // to be a valid token after >, it needs to know whether to look for a + // standard JS token or an XJS text node + state.inXJSChild = origInXJSChild; + state.inXJSTag = origInXJSTag; + expect('>'); + return markerApply(marker, delegate.createXJSClosingElement(name)); + } + + function parseXJSOpeningElement() { + var name, attribute, attributes = [], selfClosing = false, origInXJSChild, origInXJSTag, marker = markerCreate(); + + origInXJSChild = state.inXJSChild; + origInXJSTag = state.inXJSTag; + state.inXJSChild = false; + state.inXJSTag = true; + + expect('<'); + + name = parseXJSElementName(); + + while (index < length && + lookahead.value !== '/' && + lookahead.value !== '>') { + attributes.push(parseXJSAttribute()); + } + + state.inXJSTag = origInXJSTag; + + if (lookahead.value === '/') { + expect('/'); + // Because advance() (called by lex() called by expect()) expects + // there to be a valid token after >, it needs to know whether to + // look for a standard JS token or an XJS text node + state.inXJSChild = origInXJSChild; + expect('>'); + selfClosing = true; + } else { + state.inXJSChild = true; + expect('>'); + } + return markerApply(marker, delegate.createXJSOpeningElement(name, attributes, selfClosing)); + } + + function parseXJSElement() { + var openingElement, closingElement = null, children = [], origInXJSChild, origInXJSTag, marker = markerCreate(); + + origInXJSChild = state.inXJSChild; + origInXJSTag = state.inXJSTag; + openingElement = parseXJSOpeningElement(); + + if (!openingElement.selfClosing) { + while (index < length) { + state.inXJSChild = false; // Call lookahead2() with inXJSChild = false because one
two
; + // + // the default error message is a bit incomprehensible. Since it's + // rarely (never?) useful to write a less-than sign after an XJS + // element, we disallow it here in the parser in order to provide a + // better error message. (In the rare case that the less-than operator + // was intended, the left tag can be wrapped in parentheses.) + if (!origInXJSChild && match('<')) { + throwError(lookahead, Messages.AdjacentXJSElements); + } + + return markerApply(marker, delegate.createXJSElement(openingElement, closingElement, children)); + } + + function collectToken() { + var start, loc, token, range, value, entry; + + if (!state.inXJSChild) { + skipComment(); + } + + start = index; + loc = { + start: { + line: lineNumber, + column: index - lineStart + } + }; + + token = extra.advance(); + loc.end = { + line: lineNumber, + column: index - lineStart + }; + + if (token.type !== Token.EOF) { + range = [token.range[0], token.range[1]]; + value = source.slice(token.range[0], token.range[1]); + entry = { + type: TokenName[token.type], + value: value, + range: range, + loc: loc + }; + if (token.regex) { + entry.regex = { + pattern: token.regex.pattern, + flags: token.regex.flags + }; + } + extra.tokens.push(entry); + } + + return token; + } + + function collectRegex() { + var pos, loc, regex, token; skipComment(); - peek(); - startToken = lookahead; - strict = false; - body = parseSourceElements(); - return delegate.markEnd(delegate.createProgram(body), startToken); + pos = index; + loc = { + start: { + line: lineNumber, + column: index - lineStart + } + }; + + regex = extra.scanRegExp(); + loc.end = { + line: lineNumber, + column: index - lineStart + }; + + if (!extra.tokenize) { + // Pop the previous token, which is likely '/' or '/=' + if (extra.tokens.length > 0) { + token = extra.tokens[extra.tokens.length - 1]; + if (token.range[0] === pos && token.type === 'Punctuator') { + if (token.value === '/' || token.value === '/=') { + extra.tokens.pop(); + } + } + } + + extra.tokens.push({ + type: 'RegularExpression', + value: regex.literal, + regex: regex.regex, + range: [pos, index], + loc: loc + }); + } + + return regex; } function filterTokenLocation() { @@ -22243,6 +25440,12 @@ parseStatement: true, parseSourceElement: true */ type: entry.type, value: entry.value }; + if (entry.regex) { + token.regex = { + pattern: entry.regex.pattern, + flags: entry.regex.flags + }; + } if (extra.range) { token.range = entry.range; } @@ -22255,6 +25458,52 @@ parseStatement: true, parseSourceElement: true */ extra.tokens = tokens; } + function patch() { + if (extra.comments) { + extra.skipComment = skipComment; + skipComment = scanComment; + } + + if (typeof extra.tokens !== 'undefined') { + extra.advance = advance; + extra.scanRegExp = scanRegExp; + + advance = collectToken; + scanRegExp = collectRegex; + } + } + + function unpatch() { + if (typeof extra.skipComment === 'function') { + skipComment = extra.skipComment; + } + + if (typeof extra.scanRegExp === 'function') { + advance = extra.advance; + scanRegExp = extra.scanRegExp; + } + } + + // This is used to modify the delegate. + + function extend(object, properties) { + var entry, result = {}; + + for (entry in object) { + if (object.hasOwnProperty(entry)) { + result[entry] = object[entry]; + } + } + + for (entry in properties) { + if (properties.hasOwnProperty(entry)) { + result[entry] = properties[entry]; + } + } + + return result; + } + function tokenize(code, options) { var toString, token, @@ -22273,6 +25522,7 @@ parseStatement: true, parseSourceElement: true */ length = source.length; lookahead = null; state = { + allowKeyword: true, allowIn: true, labelSet: {}, inFunctionBody: false, @@ -22304,6 +25554,19 @@ parseStatement: true, parseSourceElement: true */ extra.errors = []; } + if (length > 0) { + if (typeof source[0] === 'undefined') { + // Try first to convert to a string. This is good as fast path + // for old IE which understands string indexing for string + // literals only and not for string object. + if (code instanceof String) { + source = code.valueOf(); + } + } + } + + patch(); + try { peek(); if (lookahead.type === Token.EOF) { @@ -22338,6 +25601,7 @@ parseStatement: true, parseSourceElement: true */ } catch (e) { throw e; } finally { + unpatch(); extra = {}; } return tokens; @@ -22359,12 +25623,18 @@ parseStatement: true, parseSourceElement: true */ length = source.length; lookahead = null; state = { + allowKeyword: false, allowIn: true, labelSet: {}, + parenthesizedCount: 0, inFunctionBody: false, inIteration: false, inSwitch: false, - lastCommentStart: -1 + inXJSChild: false, + inXJSTag: false, + lastCommentStart: -1, + yieldAllowed: false, + awaitAllowed: false }; extra = {}; @@ -22374,7 +25644,12 @@ parseStatement: true, parseSourceElement: true */ extra.attachComment = (typeof options.attachComment === 'boolean') && options.attachComment; if (extra.loc && options.source !== null && options.source !== undefined) { - extra.source = toString(options.source); + delegate = extend(delegate, { + 'postProcess': function (node) { + node.loc.source = toString(options.source); + return node; + } + }); } if (typeof options.tokens === 'boolean' && options.tokens) { @@ -22395,6 +25670,18 @@ parseStatement: true, parseSourceElement: true */ } } + if (length > 0) { + if (typeof source[0] === 'undefined') { + // Try first to convert to a string. This is good as fast path + // for old IE which understands string indexing for string + // literals only and not for string object. + if (code instanceof String) { + source = code.valueOf(); + } + } + } + + patch(); try { program = parseProgram(); if (typeof extra.comments !== 'undefined') { @@ -22410,6 +25697,7 @@ parseStatement: true, parseSourceElement: true */ } catch (e) { throw e; } finally { + unpatch(); extra = {}; } @@ -22417,14 +25705,13 @@ parseStatement: true, parseSourceElement: true */ } // Sync with *.json manifests. - exports.version = '1.2.2'; + exports.version = '7001.0001.0000-dev-harmony-fb'; exports.tokenize = tokenize; exports.parse = parse; // Deep copy. - /* istanbul ignore next */ exports.Syntax = (function () { var name, types = {}; @@ -22448,9 +25735,9 @@ parseStatement: true, parseSourceElement: true */ })); /* vim: set sw=4 ts=4 et tw=80 : */ -},{}],81:[function(require,module,exports){ - },{}],82:[function(require,module,exports){ + +},{}],83:[function(require,module,exports){ /*! * The buffer module from node.js, for the browser. * @@ -22463,11 +25750,12 @@ var ieee754 = require('ieee754') var isArray = require('is-array') exports.Buffer = Buffer -exports.SlowBuffer = Buffer +exports.SlowBuffer = SlowBuffer exports.INSPECT_MAX_BYTES = 50 Buffer.poolSize = 8192 // not used by this implementation var kMaxLength = 0x3fffffff +var rootParent = {} /** * If `Buffer.TYPED_ARRAY_SUPPORT`: @@ -22527,8 +25815,6 @@ function Buffer (subject, encoding, noZero) { if (type === 'number') length = subject > 0 ? subject >>> 0 : 0 else if (type === 'string') { - if (encoding === 'base64') - subject = base64clean(subject) length = Buffer.byteLength(subject, encoding) } else if (type === 'object' && subject !== null) { // assume object is array-like if (subject.type === 'Buffer' && isArray(subject.data)) @@ -22537,7 +25823,7 @@ function Buffer (subject, encoding, noZero) { } else throw new TypeError('must start with number, buffer, array or string') - if (this.length > kMaxLength) + if (length > kMaxLength) throw new RangeError('Attempt to allocate Buffer larger than maximum ' + 'size: 0x' + kMaxLength.toString(16) + ' bytes') @@ -22573,6 +25859,18 @@ function Buffer (subject, encoding, noZero) { } } + if (length > 0 && length <= Buffer.poolSize) + buf.parent = rootParent + + return buf +} + +function SlowBuffer(subject, encoding, noZero) { + if (!(this instanceof SlowBuffer)) + return new SlowBuffer(subject, encoding, noZero) + + var buf = new Buffer(subject, encoding, noZero) + delete buf.parent return buf } @@ -22723,7 +26021,7 @@ Buffer.prototype.toString = function (encoding, start, end) { } Buffer.prototype.equals = function (b) { - if(!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') return Buffer.compare(this, b) === 0 } @@ -22783,7 +26081,7 @@ function hexWrite (buf, string, offset, length) { } function utf8Write (buf, string, offset, length) { - var charsWritten = blitBuffer(utf8ToBytes(string), buf, offset, length) + var charsWritten = blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) return charsWritten } @@ -22802,7 +26100,7 @@ function base64Write (buf, string, offset, length) { } function utf16leWrite (buf, string, offset, length) { - var charsWritten = blitBuffer(utf16leToBytes(string), buf, offset, length, 2) + var charsWritten = blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length, 2) return charsWritten } @@ -22822,6 +26120,10 @@ Buffer.prototype.write = function (string, offset, length, encoding) { } offset = Number(offset) || 0 + + if (length < 0 || offset < 0 || offset > this.length) + throw new RangeError('attempt to write outside buffer bounds'); + var remaining = this.length - offset if (!length) { length = remaining @@ -22900,13 +26202,19 @@ function asciiSlice (buf, start, end) { end = Math.min(buf.length, end) for (var i = start; i < end; i++) { - ret += String.fromCharCode(buf[i]) + ret += String.fromCharCode(buf[i] & 0x7F) } return ret } function binarySlice (buf, start, end) { - return asciiSlice(buf, start, end) + var ret = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; i++) { + ret += String.fromCharCode(buf[i]) + } + return ret } function hexSlice (buf, start, end) { @@ -22955,16 +26263,21 @@ Buffer.prototype.slice = function (start, end) { if (end < start) end = start + var newBuf if (Buffer.TYPED_ARRAY_SUPPORT) { - return Buffer._augment(this.subarray(start, end)) + newBuf = Buffer._augment(this.subarray(start, end)) } else { var sliceLen = end - start - var newBuf = new Buffer(sliceLen, undefined, true) + newBuf = new Buffer(sliceLen, undefined, true) for (var i = 0; i < sliceLen; i++) { newBuf[i] = this[i + start] } - return newBuf } + + if (newBuf.length) + newBuf.parent = this.parent || this + + return newBuf } /* @@ -22977,6 +26290,35 @@ function checkOffset (offset, ext, length) { throw new RangeError('Trying to access beyond buffer length') } +Buffer.prototype.readUIntLE = function (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) + checkOffset(offset, byteLength, this.length) + + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) + val += this[offset + i] * mul + + return val +} + +Buffer.prototype.readUIntBE = function (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) + checkOffset(offset, byteLength, this.length) + + var val = this[offset + --byteLength] + var mul = 1 + while (byteLength > 0 && (mul *= 0x100)) + val += this[offset + --byteLength] * mul; + + return val +} + Buffer.prototype.readUInt8 = function (offset, noAssert) { if (!noAssert) checkOffset(offset, 1, this.length) @@ -23015,6 +26357,44 @@ Buffer.prototype.readUInt32BE = function (offset, noAssert) { this[offset + 3]) } +Buffer.prototype.readIntLE = function (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) + checkOffset(offset, byteLength, this.length) + + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) + val += this[offset + i] * mul + mul *= 0x80 + + if (val >= mul) + val -= Math.pow(2, 8 * byteLength) + + return val +} + +Buffer.prototype.readIntBE = function (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) + checkOffset(offset, byteLength, this.length) + + var i = byteLength + var mul = 1 + var val = this[offset + --i] + while (i > 0 && (mul *= 0x100)) + val += this[offset + --i] * mul + mul *= 0x80 + + if (val >= mul) + val -= Math.pow(2, 8 * byteLength) + + return val +} + Buffer.prototype.readInt8 = function (offset, noAssert) { if (!noAssert) checkOffset(offset, 1, this.length) @@ -23083,8 +26463,40 @@ Buffer.prototype.readDoubleBE = function (offset, noAssert) { function checkInt (buf, value, offset, ext, max, min) { if (!Buffer.isBuffer(buf)) throw new TypeError('buffer must be a Buffer instance') - if (value > max || value < min) throw new TypeError('value is out of bounds') - if (offset + ext > buf.length) throw new TypeError('index out of range') + if (value > max || value < min) throw new RangeError('value is out of bounds') + if (offset + ext > buf.length) throw new RangeError('index out of range') +} + +Buffer.prototype.writeUIntLE = function (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) + checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0) + + var mul = 1 + var i = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) + this[offset + i] = (value / mul) >>> 0 & 0xFF + + return offset + byteLength +} + +Buffer.prototype.writeUIntBE = function (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) + checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0) + + var i = byteLength - 1 + var mul = 1 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) + this[offset + i] = (value / mul) >>> 0 & 0xFF + + return offset + byteLength } Buffer.prototype.writeUInt8 = function (value, offset, noAssert) { @@ -23164,6 +26576,50 @@ Buffer.prototype.writeUInt32BE = function (value, offset, noAssert) { return offset + 4 } +Buffer.prototype.writeIntLE = function (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + checkInt(this, + value, + offset, + byteLength, + Math.pow(2, 8 * byteLength - 1) - 1, + -Math.pow(2, 8 * byteLength - 1)) + } + + var i = 0 + var mul = 1 + var sub = value < 0 ? 1 : 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + + return offset + byteLength +} + +Buffer.prototype.writeIntBE = function (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + checkInt(this, + value, + offset, + byteLength, + Math.pow(2, 8 * byteLength - 1) - 1, + -Math.pow(2, 8 * byteLength - 1)) + } + + var i = byteLength - 1 + var mul = 1 + var sub = value < 0 ? 1 : 0 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + + return offset + byteLength +} + Buffer.prototype.writeInt8 = function (value, offset, noAssert) { value = +value offset = offset >>> 0 @@ -23229,8 +26685,9 @@ Buffer.prototype.writeInt32BE = function (value, offset, noAssert) { } function checkIEEE754 (buf, value, offset, ext, max, min) { - if (value > max || value < min) throw new TypeError('value is out of bounds') - if (offset + ext > buf.length) throw new TypeError('index out of range') + if (value > max || value < min) throw new RangeError('value is out of bounds') + if (offset + ext > buf.length) throw new RangeError('index out of range') + if (offset < 0) throw new RangeError('index out of range') } function writeFloat (buf, value, offset, littleEndian, noAssert) { @@ -23269,18 +26726,19 @@ Buffer.prototype.copy = function (target, target_start, start, end) { if (!start) start = 0 if (!end && end !== 0) end = this.length + if (target_start >= target.length) target_start = target.length if (!target_start) target_start = 0 + if (end > 0 && end < start) end = start // Copy 0 bytes; we're done - if (end === start) return - if (target.length === 0 || source.length === 0) return + if (end === start) return 0 + if (target.length === 0 || source.length === 0) return 0 // Fatal error conditions - if (end < start) throw new TypeError('sourceEnd < sourceStart') - if (target_start < 0 || target_start >= target.length) - throw new TypeError('targetStart out of bounds') - if (start < 0 || start >= source.length) throw new TypeError('sourceStart out of bounds') - if (end < 0 || end > source.length) throw new TypeError('sourceEnd out of bounds') + if (target_start < 0) + throw new RangeError('targetStart out of bounds') + if (start < 0 || start >= source.length) throw new RangeError('sourceStart out of bounds') + if (end < 0) throw new RangeError('sourceEnd out of bounds') // Are we oob? if (end > this.length) @@ -23297,6 +26755,8 @@ Buffer.prototype.copy = function (target, target_start, start, end) { } else { target._set(this.subarray(start, start + len), target_start) } + + return len } // fill(value, start=0, end=buffer.length) @@ -23305,14 +26765,14 @@ Buffer.prototype.fill = function (value, start, end) { if (!start) start = 0 if (!end) end = this.length - if (end < start) throw new TypeError('end < start') + if (end < start) throw new RangeError('end < start') // Fill 0 bytes; we're done if (end === start) return if (this.length === 0) return - if (start < 0 || start >= this.length) throw new TypeError('start out of bounds') - if (end < 0 || end > this.length) throw new TypeError('end out of bounds') + if (start < 0 || start >= this.length) throw new RangeError('start out of bounds') + if (end < 0 || end > this.length) throw new RangeError('end out of bounds') var i if (typeof value === 'number') { @@ -23378,11 +26838,15 @@ Buffer._augment = function (arr) { arr.compare = BP.compare arr.copy = BP.copy arr.slice = BP.slice + arr.readUIntLE = BP.readUIntLE + arr.readUIntBE = BP.readUIntBE arr.readUInt8 = BP.readUInt8 arr.readUInt16LE = BP.readUInt16LE arr.readUInt16BE = BP.readUInt16BE arr.readUInt32LE = BP.readUInt32LE arr.readUInt32BE = BP.readUInt32BE + arr.readIntLE = BP.readIntLE + arr.readIntBE = BP.readIntBE arr.readInt8 = BP.readInt8 arr.readInt16LE = BP.readInt16LE arr.readInt16BE = BP.readInt16BE @@ -23393,10 +26857,14 @@ Buffer._augment = function (arr) { arr.readDoubleLE = BP.readDoubleLE arr.readDoubleBE = BP.readDoubleBE arr.writeUInt8 = BP.writeUInt8 + arr.writeUIntLE = BP.writeUIntLE + arr.writeUIntBE = BP.writeUIntBE arr.writeUInt16LE = BP.writeUInt16LE arr.writeUInt16BE = BP.writeUInt16BE arr.writeUInt32LE = BP.writeUInt32LE arr.writeUInt32BE = BP.writeUInt32BE + arr.writeIntLE = BP.writeIntLE + arr.writeIntBE = BP.writeIntBE arr.writeInt8 = BP.writeInt8 arr.writeInt16LE = BP.writeInt16LE arr.writeInt16BE = BP.writeInt16BE @@ -23413,11 +26881,13 @@ Buffer._augment = function (arr) { return arr } -var INVALID_BASE64_RE = /[^+\/0-9A-z]/g +var INVALID_BASE64_RE = /[^+\/0-9A-z\-]/g function base64clean (str) { // Node strips out invalid characters like \n and \t from the string, base64-js does not str = stringtrim(str).replace(INVALID_BASE64_RE, '') + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not while (str.length % 4 !== 0) { str = str + '=' @@ -23441,22 +26911,100 @@ function toHex (n) { return n.toString(16) } -function utf8ToBytes (str) { - var byteArray = [] - for (var i = 0; i < str.length; i++) { - var b = str.charCodeAt(i) - if (b <= 0x7F) { - byteArray.push(b) - } else { - var start = i - if (b >= 0xD800 && b <= 0xDFFF) i++ - var h = encodeURIComponent(str.slice(start, i+1)).substr(1).split('%') - for (var j = 0; j < h.length; j++) { - byteArray.push(parseInt(h[j], 16)) +function utf8ToBytes(string, units) { + var codePoint, length = string.length + var leadSurrogate = null + units = units || Infinity + var bytes = [] + var i = 0 + + for (; i 0xD7FF && codePoint < 0xE000) { + + // last char was a lead + if (leadSurrogate) { + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + leadSurrogate = codePoint + continue + } + + // valid surrogate pair + else { + codePoint = leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00 | 0x10000 + leadSurrogate = null + } + } + + // no lead yet + else { + + // unexpected trail + if (codePoint > 0xDBFF) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } + + // unpaired lead + else if (i + 1 === length) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } + + // valid lead + else { + leadSurrogate = codePoint + continue + } } } + + // valid bmp char, but last char was a lead + else if (leadSurrogate) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + leadSurrogate = null + } + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint) + } + else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ); + } + else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ); + } + else if (codePoint < 0x200000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ); + } + else { + throw new Error('Invalid code point') + } } - return byteArray + + return bytes } function asciiToBytes (str) { @@ -23468,10 +27016,13 @@ function asciiToBytes (str) { return byteArray } -function utf16leToBytes (str) { +function utf16leToBytes (str, units) { var c, hi, lo var byteArray = [] for (var i = 0; i < str.length; i++) { + + if ((units -= 2) < 0) break + c = str.charCodeAt(i) hi = c >> 8 lo = c % 256 @@ -23483,7 +27034,7 @@ function utf16leToBytes (str) { } function base64ToBytes (str) { - return base64.toByteArray(str) + return base64.toByteArray(base64clean(str)) } function blitBuffer (src, dst, offset, length, unitSize) { @@ -23504,7 +27055,7 @@ function decodeUtf8Char (str) { } } -},{"base64-js":83,"ieee754":84,"is-array":85}],83:[function(require,module,exports){ +},{"base64-js":84,"ieee754":85,"is-array":86}],84:[function(require,module,exports){ var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; ;(function (exports) { @@ -23519,12 +27070,16 @@ var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; var NUMBER = '0'.charCodeAt(0) var LOWER = 'a'.charCodeAt(0) var UPPER = 'A'.charCodeAt(0) + var PLUS_URL_SAFE = '-'.charCodeAt(0) + var SLASH_URL_SAFE = '_'.charCodeAt(0) function decode (elt) { var code = elt.charCodeAt(0) - if (code === PLUS) + if (code === PLUS || + code === PLUS_URL_SAFE) return 62 // '+' - if (code === SLASH) + if (code === SLASH || + code === SLASH_URL_SAFE) return 63 // '/' if (code < NUMBER) return -1 //no match @@ -23626,7 +27181,7 @@ var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; exports.fromByteArray = uint8ToBase64 }(typeof exports === 'undefined' ? (this.base64js = {}) : exports)) -},{}],84:[function(require,module,exports){ +},{}],85:[function(require,module,exports){ exports.read = function(buffer, offset, isLE, mLen, nBytes) { var e, m, eLen = nBytes * 8 - mLen - 1, @@ -23712,7 +27267,7 @@ exports.write = function(buffer, value, offset, isLE, mLen, nBytes) { buffer[offset + i - d] |= s * 128; }; -},{}],85:[function(require,module,exports){ +},{}],86:[function(require,module,exports){ /** * isArray @@ -23747,7 +27302,7 @@ module.exports = isArray || function (val) { return !! val && '[object Array]' == str.call(val); }; -},{}],86:[function(require,module,exports){ +},{}],87:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -24050,7 +27605,7 @@ function isUndefined(arg) { return arg === void 0; } -},{}],87:[function(require,module,exports){ +},{}],88:[function(require,module,exports){ if (typeof Object.create === 'function') { // implementation from standard node.js 'util' module module.exports = function inherits(ctor, superCtor) { @@ -24075,12 +27630,12 @@ if (typeof Object.create === 'function') { } } -},{}],88:[function(require,module,exports){ +},{}],89:[function(require,module,exports){ module.exports = Array.isArray || function (arr) { return Object.prototype.toString.call(arr) == '[object Array]'; }; -},{}],89:[function(require,module,exports){ +},{}],90:[function(require,module,exports){ (function (process){ // Copyright Joyent, Inc. and other Node contributors. // @@ -24308,73 +27863,43 @@ var substr = 'ab'.substr(-1) === 'b' ; }).call(this,require('_process')) -},{"_process":90}],90:[function(require,module,exports){ +},{"_process":91}],91:[function(require,module,exports){ // shim for using process in browser var process = module.exports = {}; +var queue = []; +var draining = false; -process.nextTick = (function () { - var canSetImmediate = typeof window !== 'undefined' - && window.setImmediate; - var canMutationObserver = typeof window !== 'undefined' - && window.MutationObserver; - var canPost = typeof window !== 'undefined' - && window.postMessage && window.addEventListener - ; - - if (canSetImmediate) { - return function (f) { return window.setImmediate(f) }; +function drainQueue() { + if (draining) { + return; } - - var queue = []; - - if (canMutationObserver) { - var hiddenDiv = document.createElement("div"); - var observer = new MutationObserver(function () { - var queueList = queue.slice(); - queue.length = 0; - queueList.forEach(function (fn) { - fn(); - }); - }); - - observer.observe(hiddenDiv, { attributes: true }); - - return function nextTick(fn) { - if (!queue.length) { - hiddenDiv.setAttribute('yes', 'no'); - } - queue.push(fn); - }; + draining = true; + var currentQueue; + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + var i = -1; + while (++i < len) { + currentQueue[i](); + } + len = queue.length; } - - if (canPost) { - window.addEventListener('message', function (ev) { - var source = ev.source; - if ((source === window || source === null) && ev.data === 'process-tick') { - ev.stopPropagation(); - if (queue.length > 0) { - var fn = queue.shift(); - fn(); - } - } - }, true); - - return function nextTick(fn) { - queue.push(fn); - window.postMessage('process-tick', '*'); - }; + draining = false; +} +process.nextTick = function (fun) { + queue.push(fun); + if (!draining) { + setTimeout(drainQueue, 0); } - - return function nextTick(fn) { - setTimeout(fn, 0); - }; -})(); +}; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; +process.version = ''; // empty string to avoid regexp issues function noop() {} @@ -24395,11 +27920,12 @@ process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; +process.umask = function() { return 0; }; -},{}],91:[function(require,module,exports){ +},{}],92:[function(require,module,exports){ module.exports = require("./lib/_stream_duplex.js") -},{"./lib/_stream_duplex.js":92}],92:[function(require,module,exports){ +},{"./lib/_stream_duplex.js":93}],93:[function(require,module,exports){ (function (process){ // Copyright Joyent, Inc. and other Node contributors. // @@ -24492,7 +28018,7 @@ function forEach (xs, f) { } }).call(this,require('_process')) -},{"./_stream_readable":94,"./_stream_writable":96,"_process":90,"core-util-is":97,"inherits":87}],93:[function(require,module,exports){ +},{"./_stream_readable":95,"./_stream_writable":97,"_process":91,"core-util-is":98,"inherits":88}],94:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -24540,7 +28066,7 @@ PassThrough.prototype._transform = function(chunk, encoding, cb) { cb(null, chunk); }; -},{"./_stream_transform":95,"core-util-is":97,"inherits":87}],94:[function(require,module,exports){ +},{"./_stream_transform":96,"core-util-is":98,"inherits":88}],95:[function(require,module,exports){ (function (process){ // Copyright Joyent, Inc. and other Node contributors. // @@ -25526,7 +29052,7 @@ function indexOf (xs, x) { } }).call(this,require('_process')) -},{"_process":90,"buffer":82,"core-util-is":97,"events":86,"inherits":87,"isarray":88,"stream":102,"string_decoder/":103}],95:[function(require,module,exports){ +},{"_process":91,"buffer":83,"core-util-is":98,"events":87,"inherits":88,"isarray":89,"stream":103,"string_decoder/":104}],96:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -25738,7 +29264,7 @@ function done(stream, er) { return stream.push(null); } -},{"./_stream_duplex":92,"core-util-is":97,"inherits":87}],96:[function(require,module,exports){ +},{"./_stream_duplex":93,"core-util-is":98,"inherits":88}],97:[function(require,module,exports){ (function (process){ // Copyright Joyent, Inc. and other Node contributors. // @@ -26128,7 +29654,7 @@ function endWritable(stream, state, cb) { } }).call(this,require('_process')) -},{"./_stream_duplex":92,"_process":90,"buffer":82,"core-util-is":97,"inherits":87,"stream":102}],97:[function(require,module,exports){ +},{"./_stream_duplex":93,"_process":91,"buffer":83,"core-util-is":98,"inherits":88,"stream":103}],98:[function(require,module,exports){ (function (Buffer){ // Copyright Joyent, Inc. and other Node contributors. // @@ -26238,10 +29764,10 @@ function objectToString(o) { return Object.prototype.toString.call(o); } }).call(this,require("buffer").Buffer) -},{"buffer":82}],98:[function(require,module,exports){ +},{"buffer":83}],99:[function(require,module,exports){ module.exports = require("./lib/_stream_passthrough.js") -},{"./lib/_stream_passthrough.js":93}],99:[function(require,module,exports){ +},{"./lib/_stream_passthrough.js":94}],100:[function(require,module,exports){ var Stream = require('stream'); // hack to fix a circular dependency issue when used with browserify exports = module.exports = require('./lib/_stream_readable.js'); exports.Stream = Stream; @@ -26251,13 +29777,13 @@ exports.Duplex = require('./lib/_stream_duplex.js'); exports.Transform = require('./lib/_stream_transform.js'); exports.PassThrough = require('./lib/_stream_passthrough.js'); -},{"./lib/_stream_duplex.js":92,"./lib/_stream_passthrough.js":93,"./lib/_stream_readable.js":94,"./lib/_stream_transform.js":95,"./lib/_stream_writable.js":96,"stream":102}],100:[function(require,module,exports){ +},{"./lib/_stream_duplex.js":93,"./lib/_stream_passthrough.js":94,"./lib/_stream_readable.js":95,"./lib/_stream_transform.js":96,"./lib/_stream_writable.js":97,"stream":103}],101:[function(require,module,exports){ module.exports = require("./lib/_stream_transform.js") -},{"./lib/_stream_transform.js":95}],101:[function(require,module,exports){ +},{"./lib/_stream_transform.js":96}],102:[function(require,module,exports){ module.exports = require("./lib/_stream_writable.js") -},{"./lib/_stream_writable.js":96}],102:[function(require,module,exports){ +},{"./lib/_stream_writable.js":97}],103:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -26386,7 +29912,7 @@ Stream.prototype.pipe = function(dest, options) { return dest; }; -},{"events":86,"inherits":87,"readable-stream/duplex.js":91,"readable-stream/passthrough.js":98,"readable-stream/readable.js":99,"readable-stream/transform.js":100,"readable-stream/writable.js":101}],103:[function(require,module,exports){ +},{"events":87,"inherits":88,"readable-stream/duplex.js":92,"readable-stream/passthrough.js":99,"readable-stream/readable.js":100,"readable-stream/transform.js":101,"readable-stream/writable.js":102}],104:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -26609,14 +30135,14 @@ function base64DetectIncompleteChar(buffer) { this.charLength = this.charReceived ? 3 : 0; } -},{"buffer":82}],104:[function(require,module,exports){ +},{"buffer":83}],105:[function(require,module,exports){ module.exports = function isBuffer(arg) { return arg && typeof arg === 'object' && typeof arg.copy === 'function' && typeof arg.fill === 'function' && typeof arg.readUInt8 === 'function'; } -},{}],105:[function(require,module,exports){ +},{}],106:[function(require,module,exports){ (function (process,global){ // Copyright Joyent, Inc. and other Node contributors. // @@ -27206,9 +30732,11253 @@ function hasOwnProperty(obj, prop) { } }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"./support/isBuffer":104,"_process":90,"inherits":87}],106:[function(require,module,exports){ -module.exports=require(61) -},{"/Users/idok/Projects/react-templates/node_modules/cheerio/node_modules/lodash/dist/lodash.js":61}],107:[function(require,module,exports){ +},{"./support/isBuffer":105,"_process":91,"inherits":88}],107:[function(require,module,exports){ +(function (global){ +/** + * @license + * lodash 3.2.0 (Custom Build) + * Build: `lodash modern -d -o ./index.js` + * Copyright 2012-2015 The Dojo Foundation + * Based on Underscore.js 1.7.0 + * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + * Available under MIT license + */ +;(function() { + + /** Used as a safe reference for `undefined` in pre-ES5 environments. */ + var undefined; + + /** Used as the semantic version number. */ + var VERSION = '3.2.0'; + + /** Used to compose bitmasks for wrapper metadata. */ + var BIND_FLAG = 1, + BIND_KEY_FLAG = 2, + CURRY_BOUND_FLAG = 4, + CURRY_FLAG = 8, + CURRY_RIGHT_FLAG = 16, + PARTIAL_FLAG = 32, + PARTIAL_RIGHT_FLAG = 64, + REARG_FLAG = 128, + ARY_FLAG = 256; + + /** Used as default options for `_.trunc`. */ + var DEFAULT_TRUNC_LENGTH = 30, + DEFAULT_TRUNC_OMISSION = '...'; + + /** Used to detect when a function becomes hot. */ + var HOT_COUNT = 150, + HOT_SPAN = 16; + + /** Used to indicate the type of lazy iteratees. */ + var LAZY_FILTER_FLAG = 0, + LAZY_MAP_FLAG = 1, + LAZY_WHILE_FLAG = 2; + + /** Used as the `TypeError` message for "Functions" methods. */ + var FUNC_ERROR_TEXT = 'Expected a function'; + + /** Used as the internal argument placeholder. */ + var PLACEHOLDER = '__lodash_placeholder__'; + + /** `Object#toString` result references. */ + var argsTag = '[object Arguments]', + arrayTag = '[object Array]', + boolTag = '[object Boolean]', + dateTag = '[object Date]', + errorTag = '[object Error]', + funcTag = '[object Function]', + mapTag = '[object Map]', + numberTag = '[object Number]', + objectTag = '[object Object]', + regexpTag = '[object RegExp]', + setTag = '[object Set]', + stringTag = '[object String]', + weakMapTag = '[object WeakMap]'; + + var arrayBufferTag = '[object ArrayBuffer]', + float32Tag = '[object Float32Array]', + float64Tag = '[object Float64Array]', + int8Tag = '[object Int8Array]', + int16Tag = '[object Int16Array]', + int32Tag = '[object Int32Array]', + uint8Tag = '[object Uint8Array]', + uint8ClampedTag = '[object Uint8ClampedArray]', + uint16Tag = '[object Uint16Array]', + uint32Tag = '[object Uint32Array]'; + + /** Used to match empty string literals in compiled template source. */ + var reEmptyStringLeading = /\b__p \+= '';/g, + reEmptyStringMiddle = /\b(__p \+=) '' \+/g, + reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g; + + /** Used to match HTML entities and HTML characters. */ + var reEscapedHtml = /&(?:amp|lt|gt|quot|#39|#96);/g, + reUnescapedHtml = /[&<>"'`]/g, + reHasEscapedHtml = RegExp(reEscapedHtml.source), + reHasUnescapedHtml = RegExp(reUnescapedHtml.source); + + /** Used to match template delimiters. */ + var reEscape = /<%-([\s\S]+?)%>/g, + reEvaluate = /<%([\s\S]+?)%>/g, + reInterpolate = /<%=([\s\S]+?)%>/g; + + /** + * Used to match ES template delimiters. + * See the [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-template-literal-lexical-components) + * for more details. + */ + var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g; + + /** Used to match `RegExp` flags from their coerced string values. */ + var reFlags = /\w*$/; + + /** Used to detect named functions. */ + var reFuncName = /^\s*function[ \n\r\t]+\w/; + + /** Used to detect hexadecimal string values. */ + var reHexPrefix = /^0[xX]/; + + /** Used to detect host constructors (Safari > 5). */ + var reHostCtor = /^\[object .+?Constructor\]$/; + + /** Used to match latin-1 supplementary letters (excluding mathematical operators). */ + var reLatin1 = /[\xc0-\xd6\xd8-\xde\xdf-\xf6\xf8-\xff]/g; + + /** Used to ensure capturing order of template delimiters. */ + var reNoMatch = /($^)/; + + /** + * Used to match `RegExp` special characters. + * See this [article on `RegExp` characters](http://www.regular-expressions.info/characters.html#special) + * for more details. + */ + var reRegExpChars = /[.*+?^${}()|[\]\/\\]/g, + reHasRegExpChars = RegExp(reRegExpChars.source); + + /** Used to detect functions containing a `this` reference. */ + var reThis = /\bthis\b/; + + /** Used to match unescaped characters in compiled string literals. */ + var reUnescapedString = /['\n\r\u2028\u2029\\]/g; + + /** Used to match words to create compound words. */ + var reWords = (function() { + var upper = '[A-Z\\xc0-\\xd6\\xd8-\\xde]', + lower = '[a-z\\xdf-\\xf6\\xf8-\\xff]+'; + + return RegExp(upper + '{2,}(?=' + upper + lower + ')|' + upper + '?' + lower + '|' + upper + '+|[0-9]+', 'g'); + }()); + + /** Used to detect and test for whitespace. */ + var whitespace = ( + // Basic whitespace characters. + ' \t\x0b\f\xa0\ufeff' + + + // Line terminators. + '\n\r\u2028\u2029' + + + // Unicode category "Zs" space separators. + '\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000' + ); + + /** Used to assign default `context` object properties. */ + var contextProps = [ + 'Array', 'ArrayBuffer', 'Date', 'Error', 'Float32Array', 'Float64Array', + 'Function', 'Int8Array', 'Int16Array', 'Int32Array', 'Math', 'Number', + 'Object', 'RegExp', 'Set', 'String', '_', 'clearTimeout', 'document', + 'isFinite', 'parseInt', 'setTimeout', 'TypeError', 'Uint8Array', + 'Uint8ClampedArray', 'Uint16Array', 'Uint32Array', 'WeakMap', + 'window', 'WinRTError' + ]; + + /** Used to make template sourceURLs easier to identify. */ + var templateCounter = -1; + + /** Used to identify `toStringTag` values of typed arrays. */ + var typedArrayTags = {}; + typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = + typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = + typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = + typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = + typedArrayTags[uint32Tag] = true; + typedArrayTags[argsTag] = typedArrayTags[arrayTag] = + typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = + typedArrayTags[dateTag] = typedArrayTags[errorTag] = + typedArrayTags[funcTag] = typedArrayTags[mapTag] = + typedArrayTags[numberTag] = typedArrayTags[objectTag] = + typedArrayTags[regexpTag] = typedArrayTags[setTag] = + typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false; + + /** Used to identify `toStringTag` values supported by `_.clone`. */ + var cloneableTags = {}; + cloneableTags[argsTag] = cloneableTags[arrayTag] = + cloneableTags[arrayBufferTag] = cloneableTags[boolTag] = + cloneableTags[dateTag] = cloneableTags[float32Tag] = + cloneableTags[float64Tag] = cloneableTags[int8Tag] = + cloneableTags[int16Tag] = cloneableTags[int32Tag] = + cloneableTags[numberTag] = cloneableTags[objectTag] = + cloneableTags[regexpTag] = cloneableTags[stringTag] = + cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = + cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true; + cloneableTags[errorTag] = cloneableTags[funcTag] = + cloneableTags[mapTag] = cloneableTags[setTag] = + cloneableTags[weakMapTag] = false; + + /** Used as an internal `_.debounce` options object by `_.throttle`. */ + var debounceOptions = { + 'leading': false, + 'maxWait': 0, + 'trailing': false + }; + + /** Used to map latin-1 supplementary letters to basic latin letters. */ + var deburredLetters = { + '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A', + '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a', + '\xc7': 'C', '\xe7': 'c', + '\xd0': 'D', '\xf0': 'd', + '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E', + '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e', + '\xcC': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I', + '\xeC': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i', + '\xd1': 'N', '\xf1': 'n', + '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O', + '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o', + '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U', + '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u', + '\xdd': 'Y', '\xfd': 'y', '\xff': 'y', + '\xc6': 'Ae', '\xe6': 'ae', + '\xde': 'Th', '\xfe': 'th', + '\xdf': 'ss' + }; + + /** Used to map characters to HTML entities. */ + var htmlEscapes = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + "'": ''', + '`': '`' + }; + + /** Used to map HTML entities to characters. */ + var htmlUnescapes = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + ''': "'", + '`': '`' + }; + + /** Used to determine if values are of the language type `Object`. */ + var objectTypes = { + 'function': true, + 'object': true + }; + + /** Used to escape characters for inclusion in compiled string literals. */ + var stringEscapes = { + '\\': '\\', + "'": "'", + '\n': 'n', + '\r': 'r', + '\u2028': 'u2028', + '\u2029': 'u2029' + }; + + /** + * Used as a reference to the global object. + * + * The `this` value is used if it is the global object to avoid Greasemonkey's + * restricted `window` object, otherwise the `window` object is used. + */ + var root = (objectTypes[typeof window] && window !== (this && this.window)) ? window : this; + + /** Detect free variable `exports`. */ + var freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports; + + /** Detect free variable `module`. */ + var freeModule = objectTypes[typeof module] && module && !module.nodeType && module; + + /** Detect free variable `global` from Node.js or Browserified code and use it as `root`. */ + var freeGlobal = freeExports && freeModule && typeof global == 'object' && global; + if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal || freeGlobal.self === freeGlobal)) { + root = freeGlobal; + } + + /** Detect the popular CommonJS extension `module.exports`. */ + var moduleExports = freeModule && freeModule.exports === freeExports && freeExports; + + /*--------------------------------------------------------------------------*/ + + /** + * The base implementation of `compareAscending` which compares values and + * sorts them in ascending order without guaranteeing a stable sort. + * + * @private + * @param {*} value The value to compare to `other`. + * @param {*} other The value to compare to `value`. + * @returns {number} Returns the sort order indicator for `value`. + */ + function baseCompareAscending(value, other) { + if (value !== other) { + var valIsReflexive = value === value, + othIsReflexive = other === other; + + if (value > other || !valIsReflexive || (typeof value == 'undefined' && othIsReflexive)) { + return 1; + } + if (value < other || !othIsReflexive || (typeof other == 'undefined' && valIsReflexive)) { + return -1; + } + } + return 0; + } + + /** + * The base implementation of `_.indexOf` without support for binary searches. + * + * @private + * @param {Array} array The array to search. + * @param {*} value The value to search for. + * @param {number} [fromIndex=0] The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function baseIndexOf(array, value, fromIndex) { + if (value !== value) { + return indexOfNaN(array, fromIndex); + } + var index = (fromIndex || 0) - 1, + length = array.length; + + while (++index < length) { + if (array[index] === value) { + return index; + } + } + return -1; + } + + /** + * The base implementation of `_.sortBy` and `_.sortByAll` which uses `comparer` + * to define the sort order of `array` and replaces criteria objects with their + * corresponding values. + * + * @private + * @param {Array} array The array to sort. + * @param {Function} comparer The function to define sort order. + * @returns {Array} Returns `array`. + */ + function baseSortBy(array, comparer) { + var length = array.length; + + array.sort(comparer); + while (length--) { + array[length] = array[length].value; + } + return array; + } + + /** + * Converts `value` to a string if it is not one. An empty string is returned + * for `null` or `undefined` values. + * + * @private + * @param {*} value The value to process. + * @returns {string} Returns the string. + */ + function baseToString(value) { + if (typeof value == 'string') { + return value; + } + return value == null ? '' : (value + ''); + } + + /** + * Used by `_.max` and `_.min` as the default callback for string values. + * + * @private + * @param {string} string The string to inspect. + * @returns {number} Returns the code unit of the first character of the string. + */ + function charAtCallback(string) { + return string.charCodeAt(0); + } + + /** + * Used by `_.trim` and `_.trimLeft` to get the index of the first character + * of `string` that is not found in `chars`. + * + * @private + * @param {string} string The string to inspect. + * @param {string} chars The characters to find. + * @returns {number} Returns the index of the first character not found in `chars`. + */ + function charsLeftIndex(string, chars) { + var index = -1, + length = string.length; + + while (++index < length && chars.indexOf(string.charAt(index)) > -1) {} + return index; + } + + /** + * Used by `_.trim` and `_.trimRight` to get the index of the last character + * of `string` that is not found in `chars`. + * + * @private + * @param {string} string The string to inspect. + * @param {string} chars The characters to find. + * @returns {number} Returns the index of the last character not found in `chars`. + */ + function charsRightIndex(string, chars) { + var index = string.length; + + while (index-- && chars.indexOf(string.charAt(index)) > -1) {} + return index; + } + + /** + * Used by `_.sortBy` to compare transformed elements of a collection and stable + * sort them in ascending order. + * + * @private + * @param {Object} object The object to compare to `other`. + * @param {Object} other The object to compare to `object`. + * @returns {number} Returns the sort order indicator for `object`. + */ + function compareAscending(object, other) { + return baseCompareAscending(object.criteria, other.criteria) || (object.index - other.index); + } + + /** + * Used by `_.sortByAll` to compare multiple properties of each element + * in a collection and stable sort them in ascending order. + * + * @private + * @param {Object} object The object to compare to `other`. + * @param {Object} other The object to compare to `object`. + * @returns {number} Returns the sort order indicator for `object`. + */ + function compareMultipleAscending(object, other) { + var index = -1, + objCriteria = object.criteria, + othCriteria = other.criteria, + length = objCriteria.length; + + while (++index < length) { + var result = baseCompareAscending(objCriteria[index], othCriteria[index]); + if (result) { + return result; + } + } + // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications + // that causes it, under certain circumstances, to provide the same value for + // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247 + // for more details. + // + // This also ensures a stable sort in V8 and other engines. + // See https://code.google.com/p/v8/issues/detail?id=90 for more details. + return object.index - other.index; + } + + /** + * Used by `_.deburr` to convert latin-1 supplementary letters to basic latin letters. + * + * @private + * @param {string} letter The matched letter to deburr. + * @returns {string} Returns the deburred letter. + */ + function deburrLetter(letter) { + return deburredLetters[letter]; + } + + /** + * Used by `_.escape` to convert characters to HTML entities. + * + * @private + * @param {string} chr The matched character to escape. + * @returns {string} Returns the escaped character. + */ + function escapeHtmlChar(chr) { + return htmlEscapes[chr]; + } + + /** + * Used by `_.template` to escape characters for inclusion in compiled + * string literals. + * + * @private + * @param {string} chr The matched character to escape. + * @returns {string} Returns the escaped character. + */ + function escapeStringChar(chr) { + return '\\' + stringEscapes[chr]; + } + + /** + * Gets the index at which the first occurrence of `NaN` is found in `array`. + * If `fromRight` is provided elements of `array` are iterated from right to left. + * + * @private + * @param {Array} array The array to search. + * @param {number} [fromIndex] The index to search from. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {number} Returns the index of the matched `NaN`, else `-1`. + */ + function indexOfNaN(array, fromIndex, fromRight) { + var length = array.length, + index = fromRight ? (fromIndex || length) : ((fromIndex || 0) - 1); + + while ((fromRight ? index-- : ++index < length)) { + var other = array[index]; + if (other !== other) { + return index; + } + } + return -1; + } + + /** + * Checks if `value` is object-like. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + */ + function isObjectLike(value) { + return (value && typeof value == 'object') || false; + } + + /** + * Used by `trimmedLeftIndex` and `trimmedRightIndex` to determine if a + * character code is whitespace. + * + * @private + * @param {number} charCode The character code to inspect. + * @returns {boolean} Returns `true` if `charCode` is whitespace, else `false`. + */ + function isSpace(charCode) { + return ((charCode <= 160 && (charCode >= 9 && charCode <= 13) || charCode == 32 || charCode == 160) || charCode == 5760 || charCode == 6158 || + (charCode >= 8192 && (charCode <= 8202 || charCode == 8232 || charCode == 8233 || charCode == 8239 || charCode == 8287 || charCode == 12288 || charCode == 65279))); + } + + /** + * Replaces all `placeholder` elements in `array` with an internal placeholder + * and returns an array of their indexes. + * + * @private + * @param {Array} array The array to modify. + * @param {*} placeholder The placeholder to replace. + * @returns {Array} Returns the new array of placeholder indexes. + */ + function replaceHolders(array, placeholder) { + var index = -1, + length = array.length, + resIndex = -1, + result = []; + + while (++index < length) { + if (array[index] === placeholder) { + array[index] = PLACEHOLDER; + result[++resIndex] = index; + } + } + return result; + } + + /** + * An implementation of `_.uniq` optimized for sorted arrays without support + * for callback shorthands and `this` binding. + * + * @private + * @param {Array} array The array to inspect. + * @param {Function} [iteratee] The function invoked per iteration. + * @returns {Array} Returns the new duplicate-value-free array. + */ + function sortedUniq(array, iteratee) { + var seen, + index = -1, + length = array.length, + resIndex = -1, + result = []; + + while (++index < length) { + var value = array[index], + computed = iteratee ? iteratee(value, index, array) : value; + + if (!index || seen !== computed) { + seen = computed; + result[++resIndex] = value; + } + } + return result; + } + + /** + * Used by `_.trim` and `_.trimLeft` to get the index of the first non-whitespace + * character of `string`. + * + * @private + * @param {string} string The string to inspect. + * @returns {number} Returns the index of the first non-whitespace character. + */ + function trimmedLeftIndex(string) { + var index = -1, + length = string.length; + + while (++index < length && isSpace(string.charCodeAt(index))) {} + return index; + } + + /** + * Used by `_.trim` and `_.trimRight` to get the index of the last non-whitespace + * character of `string`. + * + * @private + * @param {string} string The string to inspect. + * @returns {number} Returns the index of the last non-whitespace character. + */ + function trimmedRightIndex(string) { + var index = string.length; + + while (index-- && isSpace(string.charCodeAt(index))) {} + return index; + } + + /** + * Used by `_.unescape` to convert HTML entities to characters. + * + * @private + * @param {string} chr The matched character to unescape. + * @returns {string} Returns the unescaped character. + */ + function unescapeHtmlChar(chr) { + return htmlUnescapes[chr]; + } + + /*--------------------------------------------------------------------------*/ + + /** + * Create a new pristine `lodash` function using the given `context` object. + * + * @static + * @memberOf _ + * @category Utility + * @param {Object} [context=root] The context object. + * @returns {Function} Returns a new `lodash` function. + * @example + * + * _.mixin({ 'add': function(a, b) { return a + b; } }); + * + * var lodash = _.runInContext(); + * lodash.mixin({ 'sub': function(a, b) { return a - b; } }); + * + * _.isFunction(_.add); + * // => true + * _.isFunction(_.sub); + * // => false + * + * lodash.isFunction(lodash.add); + * // => false + * lodash.isFunction(lodash.sub); + * // => true + * + * // using `context` to mock `Date#getTime` use in `_.now` + * var mock = _.runInContext({ + * 'Date': function() { + * return { 'getTime': getTimeMock }; + * } + * }); + * + * // or creating a suped-up `defer` in Node.js + * var defer = _.runInContext({ 'setTimeout': setImmediate }).defer; + */ + function runInContext(context) { + // Avoid issues with some ES3 environments that attempt to use values, named + // after built-in constructors like `Object`, for the creation of literals. + // ES5 clears this up by stating that literals must use built-in constructors. + // See https://es5.github.io/#x11.1.5 for more details. + context = context ? _.defaults(root.Object(), context, _.pick(root, contextProps)) : root; + + /** Native constructor references. */ + var Array = context.Array, + Date = context.Date, + Error = context.Error, + Function = context.Function, + Math = context.Math, + Number = context.Number, + Object = context.Object, + RegExp = context.RegExp, + String = context.String, + TypeError = context.TypeError; + + /** Used for native method references. */ + var arrayProto = Array.prototype, + objectProto = Object.prototype; + + /** Used to detect DOM support. */ + var document = (document = context.window) && document.document; + + /** Used to resolve the decompiled source of functions. */ + var fnToString = Function.prototype.toString; + + /** Used to the length of n-tuples for `_.unzip`. */ + var getLength = baseProperty('length'); + + /** Used to check objects for own properties. */ + var hasOwnProperty = objectProto.hasOwnProperty; + + /** Used to generate unique IDs. */ + var idCounter = 0; + + /** + * Used to resolve the `toStringTag` of values. + * See the [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.prototype.tostring) + * for more details. + */ + var objToString = objectProto.toString; + + /** Used to restore the original `_` reference in `_.noConflict`. */ + var oldDash = context._; + + /** Used to detect if a method is native. */ + var reNative = RegExp('^' + + escapeRegExp(objToString) + .replace(/toString|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' + ); + + /** Native method references. */ + var ArrayBuffer = isNative(ArrayBuffer = context.ArrayBuffer) && ArrayBuffer, + bufferSlice = isNative(bufferSlice = ArrayBuffer && new ArrayBuffer(0).slice) && bufferSlice, + ceil = Math.ceil, + clearTimeout = context.clearTimeout, + floor = Math.floor, + getPrototypeOf = isNative(getPrototypeOf = Object.getPrototypeOf) && getPrototypeOf, + push = arrayProto.push, + propertyIsEnumerable = objectProto.propertyIsEnumerable, + Set = isNative(Set = context.Set) && Set, + setTimeout = context.setTimeout, + splice = arrayProto.splice, + Uint8Array = isNative(Uint8Array = context.Uint8Array) && Uint8Array, + WeakMap = isNative(WeakMap = context.WeakMap) && WeakMap; + + /** Used to clone array buffers. */ + var Float64Array = (function() { + // Safari 5 errors when using an array buffer to initialize a typed array + // where the array buffer's `byteLength` is not a multiple of the typed + // array's `BYTES_PER_ELEMENT`. + try { + var func = isNative(func = context.Float64Array) && func, + result = new func(new ArrayBuffer(10), 0, 1) && func; + } catch(e) {} + return result; + }()); + + /* Native method references for those with the same name as other `lodash` methods. */ + var nativeIsArray = isNative(nativeIsArray = Array.isArray) && nativeIsArray, + nativeCreate = isNative(nativeCreate = Object.create) && nativeCreate, + nativeIsFinite = context.isFinite, + nativeKeys = isNative(nativeKeys = Object.keys) && nativeKeys, + nativeMax = Math.max, + nativeMin = Math.min, + nativeNow = isNative(nativeNow = Date.now) && nativeNow, + nativeNumIsFinite = isNative(nativeNumIsFinite = Number.isFinite) && nativeNumIsFinite, + nativeParseInt = context.parseInt, + nativeRandom = Math.random; + + /** Used as references for `-Infinity` and `Infinity`. */ + var NEGATIVE_INFINITY = Number.NEGATIVE_INFINITY, + POSITIVE_INFINITY = Number.POSITIVE_INFINITY; + + /** Used as references for the maximum length and index of an array. */ + var MAX_ARRAY_LENGTH = Math.pow(2, 32) - 1, + MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1, + HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1; + + /** Used as the size, in bytes, of each `Float64Array` element. */ + var FLOAT64_BYTES_PER_ELEMENT = Float64Array ? Float64Array.BYTES_PER_ELEMENT : 0; + + /** + * Used as the maximum length of an array-like value. + * See the [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.max_safe_integer) + * for more details. + */ + var MAX_SAFE_INTEGER = Math.pow(2, 53) - 1; + + /** Used to store function metadata. */ + var metaMap = WeakMap && new WeakMap; + + /*------------------------------------------------------------------------*/ + + /** + * Creates a `lodash` object which wraps `value` to enable implicit chaining. + * Methods that operate on and return arrays, collections, and functions can + * be chained together. Methods that return a boolean or single value will + * automatically end the chain returning the unwrapped value. Explicit chaining + * may be enabled using `_.chain`. The execution of chained methods is lazy, + * that is, execution is deferred until `_#value` is implicitly or explicitly + * called. + * + * Lazy evaluation allows several methods to support shortcut fusion. Shortcut + * fusion is an optimization that merges iteratees to avoid creating intermediate + * arrays and reduce the number of iteratee executions. + * + * Chaining is supported in custom builds as long as the `_#value` method is + * directly or indirectly included in the build. + * + * In addition to lodash methods, wrappers also have the following `Array` methods: + * `concat`, `join`, `pop`, `push`, `reverse`, `shift`, `slice`, `sort`, `splice`, + * and `unshift` + * + * The wrapper methods that support shortcut fusion are: + * `compact`, `drop`, `dropRight`, `dropRightWhile`, `dropWhile`, `filter`, + * `first`, `initial`, `last`, `map`, `pluck`, `reject`, `rest`, `reverse`, + * `slice`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, `toArray`, + * and `where` + * + * The chainable wrapper methods are: + * `after`, `ary`, `assign`, `at`, `before`, `bind`, `bindAll`, `bindKey`, + * `callback`, `chain`, `chunk`, `commit`, `compact`, `concat`, `constant`, + * `countBy`, `create`, `curry`, `debounce`, `defaults`, `defer`, `delay`, + * `difference`, `drop`, `dropRight`, `dropRightWhile`, `dropWhile`, `fill`, + * `filter`, `flatten`, `flattenDeep`, `flow`, `flowRight`, `forEach`, + * `forEachRight`, `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `functions`, + * `groupBy`, `indexBy`, `initial`, `intersection`, `invert`, `invoke`, `keys`, + * `keysIn`, `map`, `mapValues`, `matches`, `memoize`, `merge`, `mixin`, + * `negate`, `noop`, `omit`, `once`, `pairs`, `partial`, `partialRight`, + * `partition`, `pick`, `plant`, `pluck`, `property`, `propertyOf`, `pull`, + * `pullAt`, `push`, `range`, `rearg`, `reject`, `remove`, `rest`, `reverse`, + * `shuffle`, `slice`, `sort`, `sortBy`, `sortByAll`, `splice`, `spread`, + * `take`, `takeRight`, `takeRightWhile`, `takeWhile`, `tap`, `throttle`, + * `thru`, `times`, `toArray`, `toPlainObject`, `transform`, `union`, `uniq`, + * `unshift`, `unzip`, `values`, `valuesIn`, `where`, `without`, `wrap`, `xor`, + * `zip`, and `zipObject` + * + * The wrapper methods that are **not** chainable by default are: + * `attempt`, `camelCase`, `capitalize`, `clone`, `cloneDeep`, `deburr`, + * `endsWith`, `escape`, `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, + * `findLast`, `findLastIndex`, `findLastKey`, `findWhere`, `first`, `has`, + * `identity`, `includes`, `indexOf`, `isArguments`, `isArray`, `isBoolean`, + * `isDate`, `isElement`, `isEmpty`, `isEqual`, `isError`, `isFinite`, + * `isFunction`, `isMatch`, `isNative`, `isNaN`, `isNull`, `isNumber`, + * `isObject`, `isPlainObject`, `isRegExp`, `isString`, `isUndefined`, + * `isTypedArray`, `join`, `kebabCase`, `last`, `lastIndexOf`, `max`, `min`, + * `noConflict`, `now`, `pad`, `padLeft`, `padRight`, `parseInt`, `pop`, + * `random`, `reduce`, `reduceRight`, `repeat`, `result`, `runInContext`, + * `shift`, `size`, `snakeCase`, `some`, `sortedIndex`, `sortedLastIndex`, + * `startCase`, `startsWith`, `template`, `trim`, `trimLeft`, `trimRight`, + * `trunc`, `unescape`, `uniqueId`, `value`, and `words` + * + * The wrapper method `sample` will return a wrapped value when `n` is provided, + * otherwise an unwrapped value is returned. + * + * @name _ + * @constructor + * @category Chain + * @param {*} value The value to wrap in a `lodash` instance. + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var wrapped = _([1, 2, 3]); + * + * // returns an unwrapped value + * wrapped.reduce(function(sum, n) { return sum + n; }); + * // => 6 + * + * // returns a wrapped value + * var squares = wrapped.map(function(n) { return n * n; }); + * + * _.isArray(squares); + * // => false + * + * _.isArray(squares.value()); + * // => true + */ + function lodash(value) { + if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) { + if (value instanceof LodashWrapper) { + return value; + } + if (hasOwnProperty.call(value, '__chain__') && hasOwnProperty.call(value, '__wrapped__')) { + return wrapperClone(value); + } + } + return new LodashWrapper(value); + } + + /** + * The base constructor for creating `lodash` wrapper objects. + * + * @private + * @param {*} value The value to wrap. + * @param {boolean} [chainAll] Enable chaining for all wrapper methods. + * @param {Array} [actions=[]] Actions to peform to resolve the unwrapped value. + */ + function LodashWrapper(value, chainAll, actions) { + this.__wrapped__ = value; + this.__actions__ = actions || []; + this.__chain__ = !!chainAll; + } + + /** + * An object environment feature flags. + * + * @static + * @memberOf _ + * @type Object + */ + var support = lodash.support = {}; + + (function(x) { + + /** + * Detect if functions can be decompiled by `Function#toString` + * (all but Firefox OS certified apps, older Opera mobile browsers, and + * the PlayStation 3; forced `false` for Windows 8 apps). + * + * @memberOf _.support + * @type boolean + */ + support.funcDecomp = !isNative(context.WinRTError) && reThis.test(runInContext); + + /** + * Detect if `Function#name` is supported (all but IE). + * + * @memberOf _.support + * @type boolean + */ + support.funcNames = typeof Function.name == 'string'; + + /** + * Detect if the DOM is supported. + * + * @memberOf _.support + * @type boolean + */ + try { + support.dom = document.createDocumentFragment().nodeType === 11; + } catch(e) { + support.dom = false; + } + + /** + * Detect if `arguments` object indexes are non-enumerable. + * + * In Firefox < 4, IE < 9, PhantomJS, and Safari < 5.1 `arguments` object + * indexes are non-enumerable. Chrome < 25 and Node.js < 0.11.0 treat + * `arguments` object indexes as non-enumerable and fail `hasOwnProperty` + * checks for indexes that exceed their function's formal parameters with + * associated values of `0`. + * + * @memberOf _.support + * @type boolean + */ + try { + support.nonEnumArgs = !propertyIsEnumerable.call(arguments, 1); + } catch(e) { + support.nonEnumArgs = true; + } + }(0, 0)); + + /** + * By default, the template delimiters used by lodash are like those in + * embedded Ruby (ERB). Change the following template settings to use + * alternative delimiters. + * + * @static + * @memberOf _ + * @type Object + */ + lodash.templateSettings = { + + /** + * Used to detect `data` property values to be HTML-escaped. + * + * @memberOf _.templateSettings + * @type RegExp + */ + 'escape': reEscape, + + /** + * Used to detect code to be evaluated. + * + * @memberOf _.templateSettings + * @type RegExp + */ + 'evaluate': reEvaluate, + + /** + * Used to detect `data` property values to inject. + * + * @memberOf _.templateSettings + * @type RegExp + */ + 'interpolate': reInterpolate, + + /** + * Used to reference the data object in the template text. + * + * @memberOf _.templateSettings + * @type string + */ + 'variable': '', + + /** + * Used to import variables into the compiled template. + * + * @memberOf _.templateSettings + * @type Object + */ + 'imports': { + + /** + * A reference to the `lodash` function. + * + * @memberOf _.templateSettings.imports + * @type Function + */ + '_': lodash + } + }; + + /*------------------------------------------------------------------------*/ + + /** + * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation. + * + * @private + * @param {*} value The value to wrap. + */ + function LazyWrapper(value) { + this.__wrapped__ = value; + this.__actions__ = null; + this.__dir__ = 1; + this.__dropCount__ = 0; + this.__filtered__ = false; + this.__iteratees__ = null; + this.__takeCount__ = POSITIVE_INFINITY; + this.__views__ = null; + } + + /** + * Creates a clone of the lazy wrapper object. + * + * @private + * @name clone + * @memberOf LazyWrapper + * @returns {Object} Returns the cloned `LazyWrapper` object. + */ + function lazyClone() { + var actions = this.__actions__, + iteratees = this.__iteratees__, + views = this.__views__, + result = new LazyWrapper(this.__wrapped__); + + result.__actions__ = actions ? arrayCopy(actions) : null; + result.__dir__ = this.__dir__; + result.__dropCount__ = this.__dropCount__; + result.__filtered__ = this.__filtered__; + result.__iteratees__ = iteratees ? arrayCopy(iteratees) : null; + result.__takeCount__ = this.__takeCount__; + result.__views__ = views ? arrayCopy(views) : null; + return result; + } + + /** + * Reverses the direction of lazy iteration. + * + * @private + * @name reverse + * @memberOf LazyWrapper + * @returns {Object} Returns the new reversed `LazyWrapper` object. + */ + function lazyReverse() { + if (this.__filtered__) { + var result = new LazyWrapper(this); + result.__dir__ = -1; + result.__filtered__ = true; + } else { + result = this.clone(); + result.__dir__ *= -1; + } + return result; + } + + /** + * Extracts the unwrapped value from its lazy wrapper. + * + * @private + * @name value + * @memberOf LazyWrapper + * @returns {*} Returns the unwrapped value. + */ + function lazyValue() { + var array = this.__wrapped__.value(); + if (!isArray(array)) { + return baseWrapperValue(array, this.__actions__); + } + var dir = this.__dir__, + isRight = dir < 0, + view = getView(0, array.length, this.__views__), + start = view.start, + end = view.end, + length = end - start, + dropCount = this.__dropCount__, + takeCount = nativeMin(length, this.__takeCount__), + index = isRight ? end : start - 1, + iteratees = this.__iteratees__, + iterLength = iteratees ? iteratees.length : 0, + resIndex = 0, + result = []; + + outer: + while (length-- && resIndex < takeCount) { + index += dir; + + var iterIndex = -1, + value = array[index]; + + while (++iterIndex < iterLength) { + var data = iteratees[iterIndex], + iteratee = data.iteratee, + computed = iteratee(value, index, array), + type = data.type; + + if (type == LAZY_MAP_FLAG) { + value = computed; + } else if (!computed) { + if (type == LAZY_FILTER_FLAG) { + continue outer; + } else { + break outer; + } + } + } + if (dropCount) { + dropCount--; + } else { + result[resIndex++] = value; + } + } + return result; + } + + /*------------------------------------------------------------------------*/ + + /** + * Creates a cache object to store key/value pairs. + * + * @private + * @static + * @name Cache + * @memberOf _.memoize + */ + function MapCache() { + this.__data__ = {}; + } + + /** + * Removes `key` and its value from the cache. + * + * @private + * @name delete + * @memberOf _.memoize.Cache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed successfully, else `false`. + */ + function mapDelete(key) { + return this.has(key) && delete this.__data__[key]; + } + + /** + * Gets the cached value for `key`. + * + * @private + * @name get + * @memberOf _.memoize.Cache + * @param {string} key The key of the value to get. + * @returns {*} Returns the cached value. + */ + function mapGet(key) { + return key == '__proto__' ? undefined : this.__data__[key]; + } + + /** + * Checks if a cached value for `key` exists. + * + * @private + * @name has + * @memberOf _.memoize.Cache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function mapHas(key) { + return key != '__proto__' && hasOwnProperty.call(this.__data__, key); + } + + /** + * Adds `value` to `key` of the cache. + * + * @private + * @name set + * @memberOf _.memoize.Cache + * @param {string} key The key of the value to cache. + * @param {*} value The value to cache. + * @returns {Object} Returns the cache object. + */ + function mapSet(key, value) { + if (key != '__proto__') { + this.__data__[key] = value; + } + return this; + } + + /*------------------------------------------------------------------------*/ + + /** + * + * Creates a cache object to store unique values. + * + * @private + * @param {Array} [values] The values to cache. + */ + function SetCache(values) { + var length = values ? values.length : 0; + + this.data = { 'hash': nativeCreate(null), 'set': new Set }; + while (length--) { + this.push(values[length]); + } + } + + /** + * Checks if `value` is in `cache` mimicking the return signature of + * `_.indexOf` by returning `0` if the value is found, else `-1`. + * + * @private + * @param {Object} cache The cache to search. + * @param {*} value The value to search for. + * @returns {number} Returns `0` if `value` is found, else `-1`. + */ + function cacheIndexOf(cache, value) { + var data = cache.data, + result = (typeof value == 'string' || isObject(value)) ? data.set.has(value) : data.hash[value]; + + return result ? 0 : -1; + } + + /** + * Adds `value` to the cache. + * + * @private + * @name push + * @memberOf SetCache + * @param {*} value The value to cache. + */ + function cachePush(value) { + var data = this.data; + if (typeof value == 'string' || isObject(value)) { + data.set.add(value); + } else { + data.hash[value] = true; + } + } + + /*------------------------------------------------------------------------*/ + + /** + * Copies the values of `source` to `array`. + * + * @private + * @param {Array} source The array to copy values from. + * @param {Array} [array=[]] The array to copy values to. + * @returns {Array} Returns `array`. + */ + function arrayCopy(source, array) { + var index = -1, + length = source.length; + + array || (array = Array(length)); + while (++index < length) { + array[index] = source[index]; + } + return array; + } + + /** + * A specialized version of `_.forEach` for arrays without support for callback + * shorthands or `this` binding. + * + * @private + * @param {Array} array The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns `array`. + */ + function arrayEach(array, iteratee) { + var index = -1, + length = array.length; + + while (++index < length) { + if (iteratee(array[index], index, array) === false) { + break; + } + } + return array; + } + + /** + * A specialized version of `_.forEachRight` for arrays without support for + * callback shorthands or `this` binding. + * + * @private + * @param {Array} array The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns `array`. + */ + function arrayEachRight(array, iteratee) { + var length = array.length; + + while (length--) { + if (iteratee(array[length], length, array) === false) { + break; + } + } + return array; + } + + /** + * A specialized version of `_.every` for arrays without support for callback + * shorthands or `this` binding. + * + * @private + * @param {Array} array The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if all elements pass the predicate check, + * else `false`. + */ + function arrayEvery(array, predicate) { + var index = -1, + length = array.length; + + while (++index < length) { + if (!predicate(array[index], index, array)) { + return false; + } + } + return true; + } + + /** + * A specialized version of `_.filter` for arrays without support for callback + * shorthands or `this` binding. + * + * @private + * @param {Array} array The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + */ + function arrayFilter(array, predicate) { + var index = -1, + length = array.length, + resIndex = -1, + result = []; + + while (++index < length) { + var value = array[index]; + if (predicate(value, index, array)) { + result[++resIndex] = value; + } + } + return result; + } + + /** + * A specialized version of `_.map` for arrays without support for callback + * shorthands or `this` binding. + * + * @private + * @param {Array} array The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + */ + function arrayMap(array, iteratee) { + var index = -1, + length = array.length, + result = Array(length); + + while (++index < length) { + result[index] = iteratee(array[index], index, array); + } + return result; + } + + /** + * A specialized version of `_.max` for arrays without support for iteratees. + * + * @private + * @param {Array} array The array to iterate over. + * @returns {*} Returns the maximum value. + */ + function arrayMax(array) { + var index = -1, + length = array.length, + result = NEGATIVE_INFINITY; + + while (++index < length) { + var value = array[index]; + if (value > result) { + result = value; + } + } + return result; + } + + /** + * A specialized version of `_.min` for arrays without support for iteratees. + * + * @private + * @param {Array} array The array to iterate over. + * @returns {*} Returns the minimum value. + */ + function arrayMin(array) { + var index = -1, + length = array.length, + result = POSITIVE_INFINITY; + + while (++index < length) { + var value = array[index]; + if (value < result) { + result = value; + } + } + return result; + } + + /** + * A specialized version of `_.reduce` for arrays without support for callback + * shorthands or `this` binding. + * + * @private + * @param {Array} array The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @param {boolean} [initFromArray] Specify using the first element of `array` + * as the initial value. + * @returns {*} Returns the accumulated value. + */ + function arrayReduce(array, iteratee, accumulator, initFromArray) { + var index = -1, + length = array.length; + + if (initFromArray && length) { + accumulator = array[++index]; + } + while (++index < length) { + accumulator = iteratee(accumulator, array[index], index, array); + } + return accumulator; + } + + /** + * A specialized version of `_.reduceRight` for arrays without support for + * callback shorthands or `this` binding. + * + * @private + * @param {Array} array The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @param {boolean} [initFromArray] Specify using the last element of `array` + * as the initial value. + * @returns {*} Returns the accumulated value. + */ + function arrayReduceRight(array, iteratee, accumulator, initFromArray) { + var length = array.length; + if (initFromArray && length) { + accumulator = array[--length]; + } + while (length--) { + accumulator = iteratee(accumulator, array[length], length, array); + } + return accumulator; + } + + /** + * A specialized version of `_.some` for arrays without support for callback + * shorthands or `this` binding. + * + * @private + * @param {Array} array The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if any element passes the predicate check, + * else `false`. + */ + function arraySome(array, predicate) { + var index = -1, + length = array.length; + + while (++index < length) { + if (predicate(array[index], index, array)) { + return true; + } + } + return false; + } + + /** + * Used by `_.defaults` to customize its `_.assign` use. + * + * @private + * @param {*} objectValue The destination object property value. + * @param {*} sourceValue The source object property value. + * @returns {*} Returns the value to assign to the destination object. + */ + function assignDefaults(objectValue, sourceValue) { + return typeof objectValue == 'undefined' ? sourceValue : objectValue; + } + + /** + * Used by `_.template` to customize its `_.assign` use. + * + * **Note:** This method is like `assignDefaults` except that it ignores + * inherited property values when checking if a property is `undefined`. + * + * @private + * @param {*} objectValue The destination object property value. + * @param {*} sourceValue The source object property value. + * @param {string} key The key associated with the object and source values. + * @param {Object} object The destination object. + * @returns {*} Returns the value to assign to the destination object. + */ + function assignOwnDefaults(objectValue, sourceValue, key, object) { + return (typeof objectValue == 'undefined' || !hasOwnProperty.call(object, key)) + ? sourceValue + : objectValue; + } + + /** + * The base implementation of `_.assign` without support for argument juggling, + * multiple sources, and `this` binding `customizer` functions. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @param {Function} [customizer] The function to customize assigning values. + * @returns {Object} Returns the destination object. + */ + function baseAssign(object, source, customizer) { + var props = keys(source); + if (!customizer) { + return baseCopy(source, object, props); + } + var index = -1, + length = props.length; + + while (++index < length) { + var key = props[index], + value = object[key], + result = customizer(value, source[key], key, object, source); + + if ((result === result ? result !== value : value === value) || + (typeof value == 'undefined' && !(key in object))) { + object[key] = result; + } + } + return object; + } + + /** + * The base implementation of `_.at` without support for strings and individual + * key arguments. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {number[]|string[]} [props] The property names or indexes of elements to pick. + * @returns {Array} Returns the new array of picked elements. + */ + function baseAt(collection, props) { + var index = -1, + length = collection.length, + isArr = isLength(length), + propsLength = props.length, + result = Array(propsLength); + + while(++index < propsLength) { + var key = props[index]; + if (isArr) { + key = parseFloat(key); + result[index] = isIndex(key, length) ? collection[key] : undefined; + } else { + result[index] = collection[key]; + } + } + return result; + } + + /** + * Copies the properties of `source` to `object`. + * + * @private + * @param {Object} source The object to copy properties from. + * @param {Object} [object={}] The object to copy properties to. + * @param {Array} props The property names to copy. + * @returns {Object} Returns `object`. + */ + function baseCopy(source, object, props) { + if (!props) { + props = object; + object = {}; + } + var index = -1, + length = props.length; + + while (++index < length) { + var key = props[index]; + object[key] = source[key]; + } + return object; + } + + /** + * The base implementation of `_.bindAll` without support for individual + * method name arguments. + * + * @private + * @param {Object} object The object to bind and assign the bound methods to. + * @param {string[]} methodNames The object method names to bind. + * @returns {Object} Returns `object`. + */ + function baseBindAll(object, methodNames) { + var index = -1, + length = methodNames.length; + + while (++index < length) { + var key = methodNames[index]; + object[key] = createWrapper(object[key], BIND_FLAG, object); + } + return object; + } + + /** + * The base implementation of `_.callback` which supports specifying the + * number of arguments to provide to `func`. + * + * @private + * @param {*} [func=_.identity] The value to convert to a callback. + * @param {*} [thisArg] The `this` binding of `func`. + * @param {number} [argCount] The number of arguments to provide to `func`. + * @returns {Function} Returns the callback. + */ + function baseCallback(func, thisArg, argCount) { + var type = typeof func; + if (type == 'function') { + return (typeof thisArg != 'undefined' && isBindable(func)) + ? bindCallback(func, thisArg, argCount) + : func; + } + if (func == null) { + return identity; + } + if (type == 'object') { + return baseMatches(func); + } + return typeof thisArg == 'undefined' + ? baseProperty(func + '') + : baseMatchesProperty(func + '', thisArg); + } + + /** + * The base implementation of `_.clone` without support for argument juggling + * and `this` binding `customizer` functions. + * + * @private + * @param {*} value The value to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @param {Function} [customizer] The function to customize cloning values. + * @param {string} [key] The key of `value`. + * @param {Object} [object] The object `value` belongs to. + * @param {Array} [stackA=[]] Tracks traversed source objects. + * @param {Array} [stackB=[]] Associates clones with source counterparts. + * @returns {*} Returns the cloned value. + */ + function baseClone(value, isDeep, customizer, key, object, stackA, stackB) { + var result; + if (customizer) { + result = object ? customizer(value, key, object) : customizer(value); + } + if (typeof result != 'undefined') { + return result; + } + if (!isObject(value)) { + return value; + } + var isArr = isArray(value); + if (isArr) { + result = initCloneArray(value); + if (!isDeep) { + return arrayCopy(value, result); + } + } else { + var tag = objToString.call(value), + isFunc = tag == funcTag; + + if (tag == objectTag || tag == argsTag || (isFunc && !object)) { + result = initCloneObject(isFunc ? {} : value); + if (!isDeep) { + return baseCopy(value, result, keys(value)); + } + } else { + return cloneableTags[tag] + ? initCloneByTag(value, tag, isDeep) + : (object ? value : {}); + } + } + // Check for circular references and return corresponding clone. + stackA || (stackA = []); + stackB || (stackB = []); + + var length = stackA.length; + while (length--) { + if (stackA[length] == value) { + return stackB[length]; + } + } + // Add the source value to the stack of traversed objects and associate it with its clone. + stackA.push(value); + stackB.push(result); + + // Recursively populate clone (susceptible to call stack limits). + (isArr ? arrayEach : baseForOwn)(value, function(subValue, key) { + result[key] = baseClone(subValue, isDeep, customizer, key, value, stackA, stackB); + }); + return result; + } + + /** + * The base implementation of `_.create` without support for assigning + * properties to the created object. + * + * @private + * @param {Object} prototype The object to inherit from. + * @returns {Object} Returns the new object. + */ + var baseCreate = (function() { + function Object() {} + return function(prototype) { + if (isObject(prototype)) { + Object.prototype = prototype; + var result = new Object; + Object.prototype = null; + } + return result || context.Object(); + }; + }()); + + /** + * The base implementation of `_.delay` and `_.defer` which accepts an index + * of where to slice the arguments to provide to `func`. + * + * @private + * @param {Function} func The function to delay. + * @param {number} wait The number of milliseconds to delay invocation. + * @param {Object} args The `arguments` object to slice and provide to `func`. + * @returns {number} Returns the timer id. + */ + function baseDelay(func, wait, args, fromIndex) { + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + return setTimeout(function() { func.apply(undefined, baseSlice(args, fromIndex)); }, wait); + } + + /** + * The base implementation of `_.difference` which accepts a single array + * of values to exclude. + * + * @private + * @param {Array} array The array to inspect. + * @param {Array} values The values to exclude. + * @returns {Array} Returns the new array of filtered values. + */ + function baseDifference(array, values) { + var length = array ? array.length : 0, + result = []; + + if (!length) { + return result; + } + var index = -1, + indexOf = getIndexOf(), + isCommon = indexOf == baseIndexOf, + cache = isCommon && values.length >= 200 && createCache(values), + valuesLength = values.length; + + if (cache) { + indexOf = cacheIndexOf; + isCommon = false; + values = cache; + } + outer: + while (++index < length) { + var value = array[index]; + + if (isCommon && value === value) { + var valuesIndex = valuesLength; + while (valuesIndex--) { + if (values[valuesIndex] === value) { + continue outer; + } + } + result.push(value); + } + else if (indexOf(values, value) < 0) { + result.push(value); + } + } + return result; + } + + /** + * The base implementation of `_.forEach` without support for callback + * shorthands and `this` binding. + * + * @private + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array|Object|string} Returns `collection`. + */ + function baseEach(collection, iteratee) { + var length = collection ? collection.length : 0; + if (!isLength(length)) { + return baseForOwn(collection, iteratee); + } + var index = -1, + iterable = toObject(collection); + + while (++index < length) { + if (iteratee(iterable[index], index, iterable) === false) { + break; + } + } + return collection; + } + + /** + * The base implementation of `_.forEachRight` without support for callback + * shorthands and `this` binding. + * + * @private + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array|Object|string} Returns `collection`. + */ + function baseEachRight(collection, iteratee) { + var length = collection ? collection.length : 0; + if (!isLength(length)) { + return baseForOwnRight(collection, iteratee); + } + var iterable = toObject(collection); + while (length--) { + if (iteratee(iterable[length], length, iterable) === false) { + break; + } + } + return collection; + } + + /** + * The base implementation of `_.every` without support for callback + * shorthands or `this` binding. + * + * @private + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if all elements pass the predicate check, + * else `false` + */ + function baseEvery(collection, predicate) { + var result = true; + baseEach(collection, function(value, index, collection) { + result = !!predicate(value, index, collection); + return result; + }); + return result; + } + + /** + * The base implementation of `_.fill` without an iteratee call guard. + * + * @private + * @param {Array} array The array to fill. + * @param {*} value The value to fill `array` with. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns `array`. + */ + function baseFill(array, value, start, end) { + var length = array.length; + + start = start == null ? 0 : (+start || 0); + if (start < 0) { + start = -start > length ? 0 : (length + start); + } + end = (typeof end == 'undefined' || end > length) ? length : (+end || 0); + if (end < 0) { + end += length; + } + length = start > end ? 0 : end >>> 0; + start >>>= 0; + + while (start < length) { + array[start++] = value; + } + return array; + } + + /** + * The base implementation of `_.filter` without support for callback + * shorthands or `this` binding. + * + * @private + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + */ + function baseFilter(collection, predicate) { + var result = []; + baseEach(collection, function(value, index, collection) { + if (predicate(value, index, collection)) { + result.push(value); + } + }); + return result; + } + + /** + * The base implementation of `_.find`, `_.findLast`, `_.findKey`, and `_.findLastKey`, + * without support for callback shorthands and `this` binding, which iterates + * over `collection` using the provided `eachFunc`. + * + * @private + * @param {Array|Object|string} collection The collection to search. + * @param {Function} predicate The function invoked per iteration. + * @param {Function} eachFunc The function to iterate over `collection`. + * @param {boolean} [retKey] Specify returning the key of the found element + * instead of the element itself. + * @returns {*} Returns the found element or its key, else `undefined`. + */ + function baseFind(collection, predicate, eachFunc, retKey) { + var result; + eachFunc(collection, function(value, key, collection) { + if (predicate(value, key, collection)) { + result = retKey ? key : value; + return false; + } + }); + return result; + } + + /** + * The base implementation of `_.flatten` with added support for restricting + * flattening and specifying the start index. + * + * @private + * @param {Array} array The array to flatten. + * @param {boolean} [isDeep] Specify a deep flatten. + * @param {boolean} [isStrict] Restrict flattening to arrays and `arguments` objects. + * @param {number} [fromIndex=0] The index to start from. + * @returns {Array} Returns the new flattened array. + */ + function baseFlatten(array, isDeep, isStrict, fromIndex) { + var index = (fromIndex || 0) - 1, + length = array.length, + resIndex = -1, + result = []; + + while (++index < length) { + var value = array[index]; + + if (isObjectLike(value) && isLength(value.length) && (isArray(value) || isArguments(value))) { + if (isDeep) { + // Recursively flatten arrays (susceptible to call stack limits). + value = baseFlatten(value, isDeep, isStrict); + } + var valIndex = -1, + valLength = value.length; + + result.length += valLength; + while (++valIndex < valLength) { + result[++resIndex] = value[valIndex]; + } + } else if (!isStrict) { + result[++resIndex] = value; + } + } + return result; + } + + /** + * The base implementation of `baseForIn` and `baseForOwn` which iterates + * over `object` properties returned by `keysFunc` invoking `iteratee` for + * each property. Iterator functions may exit iteration early by explicitly + * returning `false`. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {Function} keysFunc The function to get the keys of `object`. + * @returns {Object} Returns `object`. + */ + function baseFor(object, iteratee, keysFunc) { + var index = -1, + iterable = toObject(object), + props = keysFunc(object), + length = props.length; + + while (++index < length) { + var key = props[index]; + if (iteratee(iterable[key], key, iterable) === false) { + break; + } + } + return object; + } + + /** + * This function is like `baseFor` except that it iterates over properties + * in the opposite order. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {Function} keysFunc The function to get the keys of `object`. + * @returns {Object} Returns `object`. + */ + function baseForRight(object, iteratee, keysFunc) { + var iterable = toObject(object), + props = keysFunc(object), + length = props.length; + + while (length--) { + var key = props[length]; + if (iteratee(iterable[key], key, iterable) === false) { + break; + } + } + return object; + } + + /** + * The base implementation of `_.forIn` without support for callback + * shorthands and `this` binding. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Object} Returns `object`. + */ + function baseForIn(object, iteratee) { + return baseFor(object, iteratee, keysIn); + } + + /** + * The base implementation of `_.forOwn` without support for callback + * shorthands and `this` binding. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Object} Returns `object`. + */ + function baseForOwn(object, iteratee) { + return baseFor(object, iteratee, keys); + } + + /** + * The base implementation of `_.forOwnRight` without support for callback + * shorthands and `this` binding. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Object} Returns `object`. + */ + function baseForOwnRight(object, iteratee) { + return baseForRight(object, iteratee, keys); + } + + /** + * The base implementation of `_.functions` which creates an array of + * `object` function property names filtered from those provided. + * + * @private + * @param {Object} object The object to inspect. + * @param {Array} props The property names to filter. + * @returns {Array} Returns the new array of filtered property names. + */ + function baseFunctions(object, props) { + var index = -1, + length = props.length, + resIndex = -1, + result = []; + + while (++index < length) { + var key = props[index]; + if (isFunction(object[key])) { + result[++resIndex] = key; + } + } + return result; + } + + /** + * The base implementation of `_.invoke` which requires additional arguments + * to be provided as an array of arguments rather than individually. + * + * @private + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|string} methodName The name of the method to invoke or + * the function invoked per iteration. + * @param {Array} [args] The arguments to invoke the method with. + * @returns {Array} Returns the array of results. + */ + function baseInvoke(collection, methodName, args) { + var index = -1, + isFunc = typeof methodName == 'function', + length = collection ? collection.length : 0, + result = isLength(length) ? Array(length) : []; + + baseEach(collection, function(value) { + var func = isFunc ? methodName : (value != null && value[methodName]); + result[++index] = func ? func.apply(value, args) : undefined; + }); + return result; + } + + /** + * The base implementation of `_.isEqual` without support for `this` binding + * `customizer` functions. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @param {Function} [customizer] The function to customize comparing values. + * @param {boolean} [isWhere] Specify performing partial comparisons. + * @param {Array} [stackA] Tracks traversed `value` objects. + * @param {Array} [stackB] Tracks traversed `other` objects. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + */ + function baseIsEqual(value, other, customizer, isWhere, stackA, stackB) { + // Exit early for identical values. + if (value === other) { + // Treat `+0` vs. `-0` as not equal. + return value !== 0 || (1 / value == 1 / other); + } + var valType = typeof value, + othType = typeof other; + + // Exit early for unlike primitive values. + if ((valType != 'function' && valType != 'object' && othType != 'function' && othType != 'object') || + value == null || other == null) { + // Return `false` unless both values are `NaN`. + return value !== value && other !== other; + } + return baseIsEqualDeep(value, other, baseIsEqual, customizer, isWhere, stackA, stackB); + } + + /** + * A specialized version of `baseIsEqual` for arrays and objects which performs + * deep comparisons and tracks traversed objects enabling objects with circular + * references to be compared. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Function} [customizer] The function to customize comparing objects. + * @param {boolean} [isWhere] Specify performing partial comparisons. + * @param {Array} [stackA=[]] Tracks traversed `value` objects. + * @param {Array} [stackB=[]] Tracks traversed `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + function baseIsEqualDeep(object, other, equalFunc, customizer, isWhere, stackA, stackB) { + var objIsArr = isArray(object), + othIsArr = isArray(other), + objTag = arrayTag, + othTag = arrayTag; + + if (!objIsArr) { + objTag = objToString.call(object); + if (objTag == argsTag) { + objTag = objectTag; + } else if (objTag != objectTag) { + objIsArr = isTypedArray(object); + } + } + if (!othIsArr) { + othTag = objToString.call(other); + if (othTag == argsTag) { + othTag = objectTag; + } else if (othTag != objectTag) { + othIsArr = isTypedArray(other); + } + } + var objIsObj = objTag == objectTag, + othIsObj = othTag == objectTag, + isSameTag = objTag == othTag; + + if (isSameTag && !(objIsArr || objIsObj)) { + return equalByTag(object, other, objTag); + } + var valWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), + othWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); + + if (valWrapped || othWrapped) { + return equalFunc(valWrapped ? object.value() : object, othWrapped ? other.value() : other, customizer, isWhere, stackA, stackB); + } + if (!isSameTag) { + return false; + } + // Assume cyclic values are equal. + // For more information on detecting circular references see https://es5.github.io/#JO. + stackA || (stackA = []); + stackB || (stackB = []); + + var length = stackA.length; + while (length--) { + if (stackA[length] == object) { + return stackB[length] == other; + } + } + // Add `object` and `other` to the stack of traversed objects. + stackA.push(object); + stackB.push(other); + + var result = (objIsArr ? equalArrays : equalObjects)(object, other, equalFunc, customizer, isWhere, stackA, stackB); + + stackA.pop(); + stackB.pop(); + + return result; + } + + /** + * The base implementation of `_.isMatch` without support for callback + * shorthands or `this` binding. + * + * @private + * @param {Object} object The object to inspect. + * @param {Array} props The source property names to match. + * @param {Array} values The source values to match. + * @param {Array} strictCompareFlags Strict comparison flags for source values. + * @param {Function} [customizer] The function to customize comparing objects. + * @returns {boolean} Returns `true` if `object` is a match, else `false`. + */ + function baseIsMatch(object, props, values, strictCompareFlags, customizer) { + var length = props.length; + if (object == null) { + return !length; + } + var index = -1, + noCustomizer = !customizer; + + while (++index < length) { + if ((noCustomizer && strictCompareFlags[index]) + ? values[index] !== object[props[index]] + : !hasOwnProperty.call(object, props[index]) + ) { + return false; + } + } + index = -1; + while (++index < length) { + var key = props[index]; + if (noCustomizer && strictCompareFlags[index]) { + var result = hasOwnProperty.call(object, key); + } else { + var objValue = object[key], + srcValue = values[index]; + + result = customizer ? customizer(objValue, srcValue, key) : undefined; + if (typeof result == 'undefined') { + result = baseIsEqual(srcValue, objValue, customizer, true); + } + } + if (!result) { + return false; + } + } + return true; + } + + /** + * The base implementation of `_.map` without support for callback shorthands + * or `this` binding. + * + * @private + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + */ + function baseMap(collection, iteratee) { + var result = []; + baseEach(collection, function(value, key, collection) { + result.push(iteratee(value, key, collection)); + }); + return result; + } + + /** + * The base implementation of `_.matches` which does not clone `source`. + * + * @private + * @param {Object} source The object of property values to match. + * @returns {Function} Returns the new function. + */ + function baseMatches(source) { + var props = keys(source), + length = props.length; + + if (length == 1) { + var key = props[0], + value = source[key]; + + if (isStrictComparable(value)) { + return function(object) { + return object != null && value === object[key] && hasOwnProperty.call(object, key); + }; + } + } + var values = Array(length), + strictCompareFlags = Array(length); + + while (length--) { + value = source[props[length]]; + values[length] = value; + strictCompareFlags[length] = isStrictComparable(value); + } + return function(object) { + return baseIsMatch(object, props, values, strictCompareFlags); + }; + } + + /** + * The base implementation of `_.matchesProperty` which does not coerce `key` + * to a string. + * + * @private + * @param {string} key The key of the property to get. + * @param {*} value The value to compare. + * @returns {Function} Returns the new function. + */ + function baseMatchesProperty(key, value) { + if (isStrictComparable(value)) { + return function(object) { + return object != null && object[key] === value; + }; + } + return function(object) { + return object != null && baseIsEqual(value, object[key], null, true); + }; + } + + /** + * The base implementation of `_.merge` without support for argument juggling, + * multiple sources, and `this` binding `customizer` functions. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @param {Function} [customizer] The function to customize merging properties. + * @param {Array} [stackA=[]] Tracks traversed source objects. + * @param {Array} [stackB=[]] Associates values with source counterparts. + * @returns {Object} Returns the destination object. + */ + function baseMerge(object, source, customizer, stackA, stackB) { + var isSrcArr = isLength(source.length) && (isArray(source) || isTypedArray(source)); + + (isSrcArr ? arrayEach : baseForOwn)(source, function(srcValue, key, source) { + if (isObjectLike(srcValue)) { + stackA || (stackA = []); + stackB || (stackB = []); + return baseMergeDeep(object, source, key, baseMerge, customizer, stackA, stackB); + } + var value = object[key], + result = customizer ? customizer(value, srcValue, key, object, source) : undefined, + isCommon = typeof result == 'undefined'; + + if (isCommon) { + result = srcValue; + } + if ((isSrcArr || typeof result != 'undefined') && + (isCommon || (result === result ? result !== value : value === value))) { + object[key] = result; + } + }); + return object; + } + + /** + * A specialized version of `baseMerge` for arrays and objects which performs + * deep merges and tracks traversed objects enabling objects with circular + * references to be merged. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @param {string} key The key of the value to merge. + * @param {Function} mergeFunc The function to merge values. + * @param {Function} [customizer] The function to customize merging properties. + * @param {Array} [stackA=[]] Tracks traversed source objects. + * @param {Array} [stackB=[]] Associates values with source counterparts. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + function baseMergeDeep(object, source, key, mergeFunc, customizer, stackA, stackB) { + var length = stackA.length, + srcValue = source[key]; + + while (length--) { + if (stackA[length] == srcValue) { + object[key] = stackB[length]; + return; + } + } + var value = object[key], + result = customizer ? customizer(value, srcValue, key, object, source) : undefined, + isCommon = typeof result == 'undefined'; + + if (isCommon) { + result = srcValue; + if (isLength(srcValue.length) && (isArray(srcValue) || isTypedArray(srcValue))) { + result = isArray(value) + ? value + : (value ? arrayCopy(value) : []); + } + else if (isPlainObject(srcValue) || isArguments(srcValue)) { + result = isArguments(value) + ? toPlainObject(value) + : (isPlainObject(value) ? value : {}); + } + else { + isCommon = false; + } + } + // Add the source value to the stack of traversed objects and associate + // it with its merged value. + stackA.push(srcValue); + stackB.push(result); + + if (isCommon) { + // Recursively merge objects and arrays (susceptible to call stack limits). + object[key] = mergeFunc(result, srcValue, customizer, stackA, stackB); + } else if (result === result ? result !== value : value === value) { + object[key] = result; + } + } + + /** + * The base implementation of `_.property` which does not coerce `key` to a string. + * + * @private + * @param {string} key The key of the property to get. + * @returns {Function} Returns the new function. + */ + function baseProperty(key) { + return function(object) { + return object == null ? undefined : object[key]; + }; + } + + /** + * The base implementation of `_.pullAt` without support for individual + * index arguments. + * + * @private + * @param {Array} array The array to modify. + * @param {number[]} indexes The indexes of elements to remove. + * @returns {Array} Returns the new array of removed elements. + */ + function basePullAt(array, indexes) { + var length = indexes.length, + result = baseAt(array, indexes); + + indexes.sort(baseCompareAscending); + while (length--) { + var index = parseFloat(indexes[length]); + if (index != previous && isIndex(index)) { + var previous = index; + splice.call(array, index, 1); + } + } + return result; + } + + /** + * The base implementation of `_.random` without support for argument juggling + * and returning floating-point numbers. + * + * @private + * @param {number} min The minimum possible value. + * @param {number} max The maximum possible value. + * @returns {number} Returns the random number. + */ + function baseRandom(min, max) { + return min + floor(nativeRandom() * (max - min + 1)); + } + + /** + * The base implementation of `_.reduce` and `_.reduceRight` without support + * for callback shorthands or `this` binding, which iterates over `collection` + * using the provided `eachFunc`. + * + * @private + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {*} accumulator The initial value. + * @param {boolean} initFromCollection Specify using the first or last element + * of `collection` as the initial value. + * @param {Function} eachFunc The function to iterate over `collection`. + * @returns {*} Returns the accumulated value. + */ + function baseReduce(collection, iteratee, accumulator, initFromCollection, eachFunc) { + eachFunc(collection, function(value, index, collection) { + accumulator = initFromCollection + ? (initFromCollection = false, value) + : iteratee(accumulator, value, index, collection); + }); + return accumulator; + } + + /** + * The base implementation of `setData` without support for hot loop detection. + * + * @private + * @param {Function} func The function to associate metadata with. + * @param {*} data The metadata. + * @returns {Function} Returns `func`. + */ + var baseSetData = !metaMap ? identity : function(func, data) { + metaMap.set(func, data); + return func; + }; + + /** + * The base implementation of `_.slice` without an iteratee call guard. + * + * @private + * @param {Array} array The array to slice. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the slice of `array`. + */ + function baseSlice(array, start, end) { + var index = -1, + length = array.length; + + start = start == null ? 0 : (+start || 0); + if (start < 0) { + start = -start > length ? 0 : (length + start); + } + end = (typeof end == 'undefined' || end > length) ? length : (+end || 0); + if (end < 0) { + end += length; + } + length = start > end ? 0 : (end - start) >>> 0; + start >>>= 0; + + var result = Array(length); + while (++index < length) { + result[index] = array[index + start]; + } + return result; + } + + /** + * The base implementation of `_.some` without support for callback shorthands + * or `this` binding. + * + * @private + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if any element passes the predicate check, + * else `false`. + */ + function baseSome(collection, predicate) { + var result; + + baseEach(collection, function(value, index, collection) { + result = predicate(value, index, collection); + return !result; + }); + return !!result; + } + + /** + * The base implementation of `_.uniq` without support for callback shorthands + * and `this` binding. + * + * @private + * @param {Array} array The array to inspect. + * @param {Function} [iteratee] The function invoked per iteration. + * @returns {Array} Returns the new duplicate-value-free array. + */ + function baseUniq(array, iteratee) { + var index = -1, + indexOf = getIndexOf(), + length = array.length, + isCommon = indexOf == baseIndexOf, + isLarge = isCommon && length >= 200, + seen = isLarge && createCache(), + result = []; + + if (seen) { + indexOf = cacheIndexOf; + isCommon = false; + } else { + isLarge = false; + seen = iteratee ? [] : result; + } + outer: + while (++index < length) { + var value = array[index], + computed = iteratee ? iteratee(value, index, array) : value; + + if (isCommon && value === value) { + var seenIndex = seen.length; + while (seenIndex--) { + if (seen[seenIndex] === computed) { + continue outer; + } + } + if (iteratee) { + seen.push(computed); + } + result.push(value); + } + else if (indexOf(seen, computed) < 0) { + if (iteratee || isLarge) { + seen.push(computed); + } + result.push(value); + } + } + return result; + } + + /** + * The base implementation of `_.values` and `_.valuesIn` which creates an + * array of `object` property values corresponding to the property names + * returned by `keysFunc`. + * + * @private + * @param {Object} object The object to query. + * @param {Array} props The property names to get values for. + * @returns {Object} Returns the array of property values. + */ + function baseValues(object, props) { + var index = -1, + length = props.length, + result = Array(length); + + while (++index < length) { + result[index] = object[props[index]]; + } + return result; + } + + /** + * The base implementation of `wrapperValue` which returns the result of + * performing a sequence of actions on the unwrapped `value`, where each + * successive action is supplied the return value of the previous. + * + * @private + * @param {*} value The unwrapped value. + * @param {Array} actions Actions to peform to resolve the unwrapped value. + * @returns {*} Returns the resolved unwrapped value. + */ + function baseWrapperValue(value, actions) { + var result = value; + if (result instanceof LazyWrapper) { + result = result.value(); + } + var index = -1, + length = actions.length; + + while (++index < length) { + var args = [result], + action = actions[index]; + + push.apply(args, action.args); + result = action.func.apply(action.thisArg, args); + } + return result; + } + + /** + * Performs a binary search of `array` to determine the index at which `value` + * should be inserted into `array` in order to maintain its sort order. + * + * @private + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @param {boolean} [retHighest] Specify returning the highest, instead + * of the lowest, index at which a value should be inserted into `array`. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + */ + function binaryIndex(array, value, retHighest) { + var low = 0, + high = array ? array.length : low; + + if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) { + while (low < high) { + var mid = (low + high) >>> 1, + computed = array[mid]; + + if (retHighest ? (computed <= value) : (computed < value)) { + low = mid + 1; + } else { + high = mid; + } + } + return high; + } + return binaryIndexBy(array, value, identity, retHighest); + } + + /** + * This function is like `binaryIndex` except that it invokes `iteratee` for + * `value` and each element of `array` to compute their sort ranking. The + * iteratee is invoked with one argument; (value). + * + * @private + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @param {Function} iteratee The function invoked per iteration. + * @param {boolean} [retHighest] Specify returning the highest, instead + * of the lowest, index at which a value should be inserted into `array`. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + */ + function binaryIndexBy(array, value, iteratee, retHighest) { + value = iteratee(value); + + var low = 0, + high = array ? array.length : 0, + valIsNaN = value !== value, + valIsUndef = typeof value == 'undefined'; + + while (low < high) { + var mid = floor((low + high) / 2), + computed = iteratee(array[mid]), + isReflexive = computed === computed; + + if (valIsNaN) { + var setLow = isReflexive || retHighest; + } else if (valIsUndef) { + setLow = isReflexive && (retHighest || typeof computed != 'undefined'); + } else { + setLow = retHighest ? (computed <= value) : (computed < value); + } + if (setLow) { + low = mid + 1; + } else { + high = mid; + } + } + return nativeMin(high, MAX_ARRAY_INDEX); + } + + /** + * A specialized version of `baseCallback` which only supports `this` binding + * and specifying the number of arguments to provide to `func`. + * + * @private + * @param {Function} func The function to bind. + * @param {*} thisArg The `this` binding of `func`. + * @param {number} [argCount] The number of arguments to provide to `func`. + * @returns {Function} Returns the callback. + */ + function bindCallback(func, thisArg, argCount) { + if (typeof func != 'function') { + return identity; + } + if (typeof thisArg == 'undefined') { + return func; + } + switch (argCount) { + case 1: return function(value) { + return func.call(thisArg, value); + }; + case 3: return function(value, index, collection) { + return func.call(thisArg, value, index, collection); + }; + case 4: return function(accumulator, value, index, collection) { + return func.call(thisArg, accumulator, value, index, collection); + }; + case 5: return function(value, other, key, object, source) { + return func.call(thisArg, value, other, key, object, source); + }; + } + return function() { + return func.apply(thisArg, arguments); + }; + } + + /** + * Creates a clone of the given array buffer. + * + * @private + * @param {ArrayBuffer} buffer The array buffer to clone. + * @returns {ArrayBuffer} Returns the cloned array buffer. + */ + function bufferClone(buffer) { + return bufferSlice.call(buffer, 0); + } + if (!bufferSlice) { + // PhantomJS has `ArrayBuffer` and `Uint8Array` but not `Float64Array`. + bufferClone = !(ArrayBuffer && Uint8Array) ? constant(null) : function(buffer) { + var byteLength = buffer.byteLength, + floatLength = Float64Array ? floor(byteLength / FLOAT64_BYTES_PER_ELEMENT) : 0, + offset = floatLength * FLOAT64_BYTES_PER_ELEMENT, + result = new ArrayBuffer(byteLength); + + if (floatLength) { + var view = new Float64Array(result, 0, floatLength); + view.set(new Float64Array(buffer, 0, floatLength)); + } + if (byteLength != offset) { + view = new Uint8Array(result, offset); + view.set(new Uint8Array(buffer, offset)); + } + return result; + }; + } + + /** + * Creates an array that is the composition of partially applied arguments, + * placeholders, and provided arguments into a single array of arguments. + * + * @private + * @param {Array|Object} args The provided arguments. + * @param {Array} partials The arguments to prepend to those provided. + * @param {Array} holders The `partials` placeholder indexes. + * @returns {Array} Returns the new array of composed arguments. + */ + function composeArgs(args, partials, holders) { + var holdersLength = holders.length, + argsIndex = -1, + argsLength = nativeMax(args.length - holdersLength, 0), + leftIndex = -1, + leftLength = partials.length, + result = Array(argsLength + leftLength); + + while (++leftIndex < leftLength) { + result[leftIndex] = partials[leftIndex]; + } + while (++argsIndex < holdersLength) { + result[holders[argsIndex]] = args[argsIndex]; + } + while (argsLength--) { + result[leftIndex++] = args[argsIndex++]; + } + return result; + } + + /** + * This function is like `composeArgs` except that the arguments composition + * is tailored for `_.partialRight`. + * + * @private + * @param {Array|Object} args The provided arguments. + * @param {Array} partials The arguments to append to those provided. + * @param {Array} holders The `partials` placeholder indexes. + * @returns {Array} Returns the new array of composed arguments. + */ + function composeArgsRight(args, partials, holders) { + var holdersIndex = -1, + holdersLength = holders.length, + argsIndex = -1, + argsLength = nativeMax(args.length - holdersLength, 0), + rightIndex = -1, + rightLength = partials.length, + result = Array(argsLength + rightLength); + + while (++argsIndex < argsLength) { + result[argsIndex] = args[argsIndex]; + } + var pad = argsIndex; + while (++rightIndex < rightLength) { + result[pad + rightIndex] = partials[rightIndex]; + } + while (++holdersIndex < holdersLength) { + result[pad + holders[holdersIndex]] = args[argsIndex++]; + } + return result; + } + + /** + * Creates a function that aggregates a collection, creating an accumulator + * object composed from the results of running each element in the collection + * through an iteratee. + * + * @private + * @param {Function} setter The function to set keys and values of the accumulator object. + * @param {Function} [initializer] The function to initialize the accumulator object. + * @returns {Function} Returns the new aggregator function. + */ + function createAggregator(setter, initializer) { + return function(collection, iteratee, thisArg) { + var result = initializer ? initializer() : {}; + iteratee = getCallback(iteratee, thisArg, 3); + + if (isArray(collection)) { + var index = -1, + length = collection.length; + + while (++index < length) { + var value = collection[index]; + setter(result, value, iteratee(value, index, collection), collection); + } + } else { + baseEach(collection, function(value, key, collection) { + setter(result, value, iteratee(value, key, collection), collection); + }); + } + return result; + }; + } + + /** + * Creates a function that assigns properties of source object(s) to a given + * destination object. + * + * @private + * @param {Function} assigner The function to assign values. + * @returns {Function} Returns the new assigner function. + */ + function createAssigner(assigner) { + return function() { + var length = arguments.length, + object = arguments[0]; + + if (length < 2 || object == null) { + return object; + } + if (length > 3 && isIterateeCall(arguments[1], arguments[2], arguments[3])) { + length = 2; + } + // Juggle arguments. + if (length > 3 && typeof arguments[length - 2] == 'function') { + var customizer = bindCallback(arguments[--length - 1], arguments[length--], 5); + } else if (length > 2 && typeof arguments[length - 1] == 'function') { + customizer = arguments[--length]; + } + var index = 0; + while (++index < length) { + var source = arguments[index]; + if (source) { + assigner(object, source, customizer); + } + } + return object; + }; + } + + /** + * Creates a function that wraps `func` and invokes it with the `this` + * binding of `thisArg`. + * + * @private + * @param {Function} func The function to bind. + * @param {*} [thisArg] The `this` binding of `func`. + * @returns {Function} Returns the new bound function. + */ + function createBindWrapper(func, thisArg) { + var Ctor = createCtorWrapper(func); + + function wrapper() { + return (this instanceof wrapper ? Ctor : func).apply(thisArg, arguments); + } + return wrapper; + } + + /** + * Creates a `Set` cache object to optimize linear searches of large arrays. + * + * @private + * @param {Array} [values] The values to cache. + * @returns {null|Object} Returns the new cache object if `Set` is supported, else `null`. + */ + var createCache = !(nativeCreate && Set) ? constant(null) : function(values) { + return new SetCache(values); + }; + + /** + * Creates a function that produces compound words out of the words in a + * given string. + * + * @private + * @param {Function} callback The function to combine each word. + * @returns {Function} Returns the new compounder function. + */ + function createCompounder(callback) { + return function(string) { + var index = -1, + array = words(deburr(string)), + length = array.length, + result = ''; + + while (++index < length) { + result = callback(result, array[index], index); + } + return result; + }; + } + + /** + * Creates a function that produces an instance of `Ctor` regardless of + * whether it was invoked as part of a `new` expression or by `call` or `apply`. + * + * @private + * @param {Function} Ctor The constructor to wrap. + * @returns {Function} Returns the new wrapped function. + */ + function createCtorWrapper(Ctor) { + return function() { + var thisBinding = baseCreate(Ctor.prototype), + result = Ctor.apply(thisBinding, arguments); + + // Mimic the constructor's `return` behavior. + // See https://es5.github.io/#x13.2.2 for more details. + return isObject(result) ? result : thisBinding; + }; + } + + /** + * Creates a function that gets the extremum value of a collection. + * + * @private + * @param {Function} arrayFunc The function to get the extremum value from an array. + * @param {boolean} [isMin] Specify returning the minimum, instead of the maximum, + * extremum value. + * @returns {Function} Returns the new extremum function. + */ + function createExtremum(arrayFunc, isMin) { + return function(collection, iteratee, thisArg) { + if (thisArg && isIterateeCall(collection, iteratee, thisArg)) { + iteratee = null; + } + var func = getCallback(), + noIteratee = iteratee == null; + + if (!(func === baseCallback && noIteratee)) { + noIteratee = false; + iteratee = func(iteratee, thisArg, 3); + } + if (noIteratee) { + var isArr = isArray(collection); + if (!isArr && isString(collection)) { + iteratee = charAtCallback; + } else { + return arrayFunc(isArr ? collection : toIterable(collection)); + } + } + return extremumBy(collection, iteratee, isMin); + }; + } + + /** + * Creates a function that wraps `func` and invokes it with optional `this` + * binding of, partial application, and currying. + * + * @private + * @param {Function|string} func The function or method name to reference. + * @param {number} bitmask The bitmask of flags. See `createWrapper` for more details. + * @param {*} [thisArg] The `this` binding of `func`. + * @param {Array} [partials] The arguments to prepend to those provided to the new function. + * @param {Array} [holders] The `partials` placeholder indexes. + * @param {Array} [partialsRight] The arguments to append to those provided to the new function. + * @param {Array} [holdersRight] The `partialsRight` placeholder indexes. + * @param {Array} [argPos] The argument positions of the new function. + * @param {number} [ary] The arity cap of `func`. + * @param {number} [arity] The arity of `func`. + * @returns {Function} Returns the new wrapped function. + */ + function createHybridWrapper(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) { + var isAry = bitmask & ARY_FLAG, + isBind = bitmask & BIND_FLAG, + isBindKey = bitmask & BIND_KEY_FLAG, + isCurry = bitmask & CURRY_FLAG, + isCurryBound = bitmask & CURRY_BOUND_FLAG, + isCurryRight = bitmask & CURRY_RIGHT_FLAG; + + var Ctor = !isBindKey && createCtorWrapper(func), + key = func; + + function wrapper() { + // Avoid `arguments` object use disqualifying optimizations by + // converting it to an array before providing it to other functions. + var length = arguments.length, + index = length, + args = Array(length); + + while (index--) { + args[index] = arguments[index]; + } + if (partials) { + args = composeArgs(args, partials, holders); + } + if (partialsRight) { + args = composeArgsRight(args, partialsRight, holdersRight); + } + if (isCurry || isCurryRight) { + var placeholder = wrapper.placeholder, + argsHolders = replaceHolders(args, placeholder); + + length -= argsHolders.length; + if (length < arity) { + var newArgPos = argPos ? arrayCopy(argPos) : null, + newArity = nativeMax(arity - length, 0), + newsHolders = isCurry ? argsHolders : null, + newHoldersRight = isCurry ? null : argsHolders, + newPartials = isCurry ? args : null, + newPartialsRight = isCurry ? null : args; + + bitmask |= (isCurry ? PARTIAL_FLAG : PARTIAL_RIGHT_FLAG); + bitmask &= ~(isCurry ? PARTIAL_RIGHT_FLAG : PARTIAL_FLAG); + + if (!isCurryBound) { + bitmask &= ~(BIND_FLAG | BIND_KEY_FLAG); + } + var result = createHybridWrapper(func, bitmask, thisArg, newPartials, newsHolders, newPartialsRight, newHoldersRight, newArgPos, ary, newArity); + result.placeholder = placeholder; + return result; + } + } + var thisBinding = isBind ? thisArg : this; + if (isBindKey) { + func = thisBinding[key]; + } + if (argPos) { + args = reorder(args, argPos); + } + if (isAry && ary < args.length) { + args.length = ary; + } + return (this instanceof wrapper ? (Ctor || createCtorWrapper(func)) : func).apply(thisBinding, args); + } + return wrapper; + } + + /** + * Creates the pad required for `string` based on the given padding length. + * The `chars` string may be truncated if the number of padding characters + * exceeds the padding length. + * + * @private + * @param {string} string The string to create padding for. + * @param {number} [length=0] The padding length. + * @param {string} [chars=' '] The string used as padding. + * @returns {string} Returns the pad for `string`. + */ + function createPad(string, length, chars) { + var strLength = string.length; + length = +length; + + if (strLength >= length || !nativeIsFinite(length)) { + return ''; + } + var padLength = length - strLength; + chars = chars == null ? ' ' : (chars + ''); + return repeat(chars, ceil(padLength / chars.length)).slice(0, padLength); + } + + /** + * Creates a function that wraps `func` and invokes it with the optional `this` + * binding of `thisArg` and the `partials` prepended to those provided to + * the wrapper. + * + * @private + * @param {Function} func The function to partially apply arguments to. + * @param {number} bitmask The bitmask of flags. See `createWrapper` for more details. + * @param {*} thisArg The `this` binding of `func`. + * @param {Array} partials The arguments to prepend to those provided to the new function. + * @returns {Function} Returns the new bound function. + */ + function createPartialWrapper(func, bitmask, thisArg, partials) { + var isBind = bitmask & BIND_FLAG, + Ctor = createCtorWrapper(func); + + function wrapper() { + // Avoid `arguments` object use disqualifying optimizations by + // converting it to an array before providing it `func`. + var argsIndex = -1, + argsLength = arguments.length, + leftIndex = -1, + leftLength = partials.length, + args = Array(argsLength + leftLength); + + while (++leftIndex < leftLength) { + args[leftIndex] = partials[leftIndex]; + } + while (argsLength--) { + args[leftIndex++] = arguments[++argsIndex]; + } + return (this instanceof wrapper ? Ctor : func).apply(isBind ? thisArg : this, args); + } + return wrapper; + } + + /** + * Creates a function that either curries or invokes `func` with optional + * `this` binding and partially applied arguments. + * + * @private + * @param {Function|string} func The function or method name to reference. + * @param {number} bitmask The bitmask of flags. + * The bitmask may be composed of the following flags: + * 1 - `_.bind` + * 2 - `_.bindKey` + * 4 - `_.curry` or `_.curryRight` of a bound function + * 8 - `_.curry` + * 16 - `_.curryRight` + * 32 - `_.partial` + * 64 - `_.partialRight` + * 128 - `_.rearg` + * 256 - `_.ary` + * @param {*} [thisArg] The `this` binding of `func`. + * @param {Array} [partials] The arguments to be partially applied. + * @param {Array} [holders] The `partials` placeholder indexes. + * @param {Array} [argPos] The argument positions of the new function. + * @param {number} [ary] The arity cap of `func`. + * @param {number} [arity] The arity of `func`. + * @returns {Function} Returns the new wrapped function. + */ + function createWrapper(func, bitmask, thisArg, partials, holders, argPos, ary, arity) { + var isBindKey = bitmask & BIND_KEY_FLAG; + if (!isBindKey && typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + var length = partials ? partials.length : 0; + if (!length) { + bitmask &= ~(PARTIAL_FLAG | PARTIAL_RIGHT_FLAG); + partials = holders = null; + } + length -= (holders ? holders.length : 0); + if (bitmask & PARTIAL_RIGHT_FLAG) { + var partialsRight = partials, + holdersRight = holders; + + partials = holders = null; + } + var data = !isBindKey && getData(func), + newData = [func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity]; + + if (data && data !== true) { + mergeData(newData, data); + bitmask = newData[1]; + arity = newData[9]; + } + newData[9] = arity == null + ? (isBindKey ? 0 : func.length) + : (nativeMax(arity - length, 0) || 0); + + if (bitmask == BIND_FLAG) { + var result = createBindWrapper(newData[0], newData[2]); + } else if ((bitmask == PARTIAL_FLAG || bitmask == (BIND_FLAG | PARTIAL_FLAG)) && !newData[4].length) { + result = createPartialWrapper.apply(undefined, newData); + } else { + result = createHybridWrapper.apply(undefined, newData); + } + var setter = data ? baseSetData : setData; + return setter(result, newData); + } + + /** + * A specialized version of `baseIsEqualDeep` for arrays with support for + * partial deep comparisons. + * + * @private + * @param {Array} array The array to compare. + * @param {Array} other The other array to compare. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Function} [customizer] The function to customize comparing arrays. + * @param {boolean} [isWhere] Specify performing partial comparisons. + * @param {Array} [stackA] Tracks traversed `value` objects. + * @param {Array} [stackB] Tracks traversed `other` objects. + * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. + */ + function equalArrays(array, other, equalFunc, customizer, isWhere, stackA, stackB) { + var index = -1, + arrLength = array.length, + othLength = other.length, + result = true; + + if (arrLength != othLength && !(isWhere && othLength > arrLength)) { + return false; + } + // Deep compare the contents, ignoring non-numeric properties. + while (result && ++index < arrLength) { + var arrValue = array[index], + othValue = other[index]; + + result = undefined; + if (customizer) { + result = isWhere + ? customizer(othValue, arrValue, index) + : customizer(arrValue, othValue, index); + } + if (typeof result == 'undefined') { + // Recursively compare arrays (susceptible to call stack limits). + if (isWhere) { + var othIndex = othLength; + while (othIndex--) { + othValue = other[othIndex]; + result = (arrValue && arrValue === othValue) || equalFunc(arrValue, othValue, customizer, isWhere, stackA, stackB); + if (result) { + break; + } + } + } else { + result = (arrValue && arrValue === othValue) || equalFunc(arrValue, othValue, customizer, isWhere, stackA, stackB); + } + } + } + return !!result; + } + + /** + * A specialized version of `baseIsEqualDeep` for comparing objects of + * the same `toStringTag`. + * + * **Note:** This function only supports comparing values with tags of + * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. + * + * @private + * @param {Object} value The object to compare. + * @param {Object} other The other object to compare. + * @param {string} tag The `toStringTag` of the objects to compare. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + function equalByTag(object, other, tag) { + switch (tag) { + case boolTag: + case dateTag: + // Coerce dates and booleans to numbers, dates to milliseconds and booleans + // to `1` or `0` treating invalid dates coerced to `NaN` as not equal. + return +object == +other; + + case errorTag: + return object.name == other.name && object.message == other.message; + + case numberTag: + // Treat `NaN` vs. `NaN` as equal. + return (object != +object) + ? other != +other + // But, treat `-0` vs. `+0` as not equal. + : (object == 0 ? ((1 / object) == (1 / other)) : object == +other); + + case regexpTag: + case stringTag: + // Coerce regexes to strings and treat strings primitives and string + // objects as equal. See https://es5.github.io/#x15.10.6.4 for more details. + return object == (other + ''); + } + return false; + } + + /** + * A specialized version of `baseIsEqualDeep` for objects with support for + * partial deep comparisons. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Function} [customizer] The function to customize comparing values. + * @param {boolean} [isWhere] Specify performing partial comparisons. + * @param {Array} [stackA] Tracks traversed `value` objects. + * @param {Array} [stackB] Tracks traversed `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + function equalObjects(object, other, equalFunc, customizer, isWhere, stackA, stackB) { + var objProps = keys(object), + objLength = objProps.length, + othProps = keys(other), + othLength = othProps.length; + + if (objLength != othLength && !isWhere) { + return false; + } + var hasCtor, + index = -1; + + while (++index < objLength) { + var key = objProps[index], + result = hasOwnProperty.call(other, key); + + if (result) { + var objValue = object[key], + othValue = other[key]; + + result = undefined; + if (customizer) { + result = isWhere + ? customizer(othValue, objValue, key) + : customizer(objValue, othValue, key); + } + if (typeof result == 'undefined') { + // Recursively compare objects (susceptible to call stack limits). + result = (objValue && objValue === othValue) || equalFunc(objValue, othValue, customizer, isWhere, stackA, stackB); + } + } + if (!result) { + return false; + } + hasCtor || (hasCtor = key == 'constructor'); + } + if (!hasCtor) { + var objCtor = object.constructor, + othCtor = other.constructor; + + // Non `Object` object instances with different constructors are not equal. + if (objCtor != othCtor && ('constructor' in object && 'constructor' in other) && + !(typeof objCtor == 'function' && objCtor instanceof objCtor && typeof othCtor == 'function' && othCtor instanceof othCtor)) { + return false; + } + } + return true; + } + + /** + * Gets the extremum value of `collection` invoking `iteratee` for each value + * in `collection` to generate the criterion by which the value is ranked. + * The `iteratee` is invoked with three arguments; (value, index, collection). + * + * @private + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {boolean} [isMin] Specify returning the minimum, instead of the + * maximum, extremum value. + * @returns {*} Returns the extremum value. + */ + function extremumBy(collection, iteratee, isMin) { + var exValue = isMin ? POSITIVE_INFINITY : NEGATIVE_INFINITY, + computed = exValue, + result = computed; + + baseEach(collection, function(value, index, collection) { + var current = iteratee(value, index, collection); + if ((isMin ? current < computed : current > computed) || (current === exValue && current === result)) { + computed = current; + result = value; + } + }); + return result; + } + + /** + * Gets the appropriate "callback" function. If the `_.callback` method is + * customized this function returns the custom method, otherwise it returns + * the `baseCallback` function. If arguments are provided the chosen function + * is invoked with them and its result is returned. + * + * @private + * @returns {Function} Returns the chosen function or its result. + */ + function getCallback(func, thisArg, argCount) { + var result = lodash.callback || callback; + result = result === callback ? baseCallback : result; + return argCount ? result(func, thisArg, argCount) : result; + } + + /** + * Gets metadata for `func`. + * + * @private + * @param {Function} func The function to query. + * @returns {*} Returns the metadata for `func`. + */ + var getData = !metaMap ? noop : function(func) { + return metaMap.get(func); + }; + + /** + * Gets the appropriate "indexOf" function. If the `_.indexOf` method is + * customized this function returns the custom method, otherwise it returns + * the `baseIndexOf` function. If arguments are provided the chosen function + * is invoked with them and its result is returned. + * + * @private + * @returns {Function|number} Returns the chosen function or its result. + */ + function getIndexOf(collection, target, fromIndex) { + var result = lodash.indexOf || indexOf; + result = result === indexOf ? baseIndexOf : result; + return collection ? result(collection, target, fromIndex) : result; + } + + /** + * Gets the view, applying any `transforms` to the `start` and `end` positions. + * + * @private + * @param {number} start The start of the view. + * @param {number} end The end of the view. + * @param {Array} [transforms] The transformations to apply to the view. + * @returns {Object} Returns an object containing the `start` and `end` + * positions of the view. + */ + function getView(start, end, transforms) { + var index = -1, + length = transforms ? transforms.length : 0; + + while (++index < length) { + var data = transforms[index], + size = data.size; + + switch (data.type) { + case 'drop': start += size; break; + case 'dropRight': end -= size; break; + case 'take': end = nativeMin(end, start + size); break; + case 'takeRight': start = nativeMax(start, end - size); break; + } + } + return { 'start': start, 'end': end }; + } + + /** + * Initializes an array clone. + * + * @private + * @param {Array} array The array to clone. + * @returns {Array} Returns the initialized clone. + */ + function initCloneArray(array) { + var length = array.length, + result = new array.constructor(length); + + // Add array properties assigned by `RegExp#exec`. + if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) { + result.index = array.index; + result.input = array.input; + } + return result; + } + + /** + * Initializes an object clone. + * + * @private + * @param {Object} object The object to clone. + * @returns {Object} Returns the initialized clone. + */ + function initCloneObject(object) { + var Ctor = object.constructor; + if (!(typeof Ctor == 'function' && Ctor instanceof Ctor)) { + Ctor = Object; + } + return new Ctor; + } + + /** + * Initializes an object clone based on its `toStringTag`. + * + * **Note:** This function only supports cloning values with tags of + * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. + * + * + * @private + * @param {Object} object The object to clone. + * @param {string} tag The `toStringTag` of the object to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the initialized clone. + */ + function initCloneByTag(object, tag, isDeep) { + var Ctor = object.constructor; + switch (tag) { + case arrayBufferTag: + return bufferClone(object); + + case boolTag: + case dateTag: + return new Ctor(+object); + + case float32Tag: case float64Tag: + case int8Tag: case int16Tag: case int32Tag: + case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag: + var buffer = object.buffer; + return new Ctor(isDeep ? bufferClone(buffer) : buffer, object.byteOffset, object.length); + + case numberTag: + case stringTag: + return new Ctor(object); + + case regexpTag: + var result = new Ctor(object.source, reFlags.exec(object)); + result.lastIndex = object.lastIndex; + } + return result; + } + + /** + * Checks if `func` is eligible for `this` binding. + * + * @private + * @param {Function} func The function to check. + * @returns {boolean} Returns `true` if `func` is eligible, else `false`. + */ + function isBindable(func) { + var support = lodash.support, + result = !(support.funcNames ? func.name : support.funcDecomp); + + if (!result) { + var source = fnToString.call(func); + if (!support.funcNames) { + result = !reFuncName.test(source); + } + if (!result) { + // Check if `func` references the `this` keyword and store the result. + result = reThis.test(source) || isNative(func); + baseSetData(func, result); + } + } + return result; + } + + /** + * Checks if `value` is a valid array-like index. + * + * @private + * @param {*} value The value to check. + * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. + * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. + */ + function isIndex(value, length) { + value = +value; + length = length == null ? MAX_SAFE_INTEGER : length; + return value > -1 && value % 1 == 0 && value < length; + } + + /** + * Checks if the provided arguments are from an iteratee call. + * + * @private + * @param {*} value The potential iteratee value argument. + * @param {*} index The potential iteratee index or key argument. + * @param {*} object The potential iteratee object argument. + * @returns {boolean} Returns `true` if the arguments are from an iteratee call, else `false`. + */ + function isIterateeCall(value, index, object) { + if (!isObject(object)) { + return false; + } + var type = typeof index; + if (type == 'number') { + var length = object.length, + prereq = isLength(length) && isIndex(index, length); + } else { + prereq = type == 'string' && index in object; + } + return prereq && object[index] === value; + } + + /** + * Checks if `value` is a valid array-like length. + * + * **Note:** This function is based on ES `ToLength`. See the + * [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength) + * for more details. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. + */ + function isLength(value) { + return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; + } + + /** + * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` if suitable for strict + * equality comparisons, else `false`. + */ + function isStrictComparable(value) { + return value === value && (value === 0 ? ((1 / value) > 0) : !isObject(value)); + } + + /** + * Merges the function metadata of `source` into `data`. + * + * Merging metadata reduces the number of wrappers required to invoke a function. + * This is possible because methods like `_.bind`, `_.curry`, and `_.partial` + * may be applied regardless of execution order. Methods like `_.ary` and `_.rearg` + * augment function arguments, making the order in which they are executed important, + * preventing the merging of metadata. However, we make an exception for a safe + * common case where curried functions have `_.ary` and or `_.rearg` applied. + * + * @private + * @param {Array} data The destination metadata. + * @param {Array} source The source metadata. + * @returns {Array} Returns `data`. + */ + function mergeData(data, source) { + var bitmask = data[1], + srcBitmask = source[1], + newBitmask = bitmask | srcBitmask; + + var arityFlags = ARY_FLAG | REARG_FLAG, + bindFlags = BIND_FLAG | BIND_KEY_FLAG, + comboFlags = arityFlags | bindFlags | CURRY_BOUND_FLAG | CURRY_RIGHT_FLAG; + + var isAry = bitmask & ARY_FLAG && !(srcBitmask & ARY_FLAG), + isRearg = bitmask & REARG_FLAG && !(srcBitmask & REARG_FLAG), + argPos = (isRearg ? data : source)[7], + ary = (isAry ? data : source)[8]; + + var isCommon = !(bitmask >= REARG_FLAG && srcBitmask > bindFlags) && + !(bitmask > bindFlags && srcBitmask >= REARG_FLAG); + + var isCombo = (newBitmask >= arityFlags && newBitmask <= comboFlags) && + (bitmask < REARG_FLAG || ((isRearg || isAry) && argPos.length <= ary)); + + // Exit early if metadata can't be merged. + if (!(isCommon || isCombo)) { + return data; + } + // Use source `thisArg` if available. + if (srcBitmask & BIND_FLAG) { + data[2] = source[2]; + // Set when currying a bound function. + newBitmask |= (bitmask & BIND_FLAG) ? 0 : CURRY_BOUND_FLAG; + } + // Compose partial arguments. + var value = source[3]; + if (value) { + var partials = data[3]; + data[3] = partials ? composeArgs(partials, value, source[4]) : arrayCopy(value); + data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : arrayCopy(source[4]); + } + // Compose partial right arguments. + value = source[5]; + if (value) { + partials = data[5]; + data[5] = partials ? composeArgsRight(partials, value, source[6]) : arrayCopy(value); + data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : arrayCopy(source[6]); + } + // Use source `argPos` if available. + value = source[7]; + if (value) { + data[7] = arrayCopy(value); + } + // Use source `ary` if it's smaller. + if (srcBitmask & ARY_FLAG) { + data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]); + } + // Use source `arity` if one is not provided. + if (data[9] == null) { + data[9] = source[9]; + } + // Use source `func` and merge bitmasks. + data[0] = source[0]; + data[1] = newBitmask; + + return data; + } + + /** + * A specialized version of `_.pick` that picks `object` properties specified + * by the `props` array. + * + * @private + * @param {Object} object The source object. + * @param {string[]} props The property names to pick. + * @returns {Object} Returns the new object. + */ + function pickByArray(object, props) { + object = toObject(object); + + var index = -1, + length = props.length, + result = {}; + + while (++index < length) { + var key = props[index]; + if (key in object) { + result[key] = object[key]; + } + } + return result; + } + + /** + * A specialized version of `_.pick` that picks `object` properties `predicate` + * returns truthy for. + * + * @private + * @param {Object} object The source object. + * @param {Function} predicate The function invoked per iteration. + * @returns {Object} Returns the new object. + */ + function pickByCallback(object, predicate) { + var result = {}; + baseForIn(object, function(value, key, object) { + if (predicate(value, key, object)) { + result[key] = value; + } + }); + return result; + } + + /** + * Reorder `array` according to the specified indexes where the element at + * the first index is assigned as the first element, the element at + * the second index is assigned as the second element, and so on. + * + * @private + * @param {Array} array The array to reorder. + * @param {Array} indexes The arranged array indexes. + * @returns {Array} Returns `array`. + */ + function reorder(array, indexes) { + var arrLength = array.length, + length = nativeMin(indexes.length, arrLength), + oldArray = arrayCopy(array); + + while (length--) { + var index = indexes[length]; + array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined; + } + return array; + } + + /** + * Sets metadata for `func`. + * + * **Note:** If this function becomes hot, i.e. is invoked a lot in a short + * period of time, it will trip its breaker and transition to an identity function + * to avoid garbage collection pauses in V8. See [V8 issue 2070](https://code.google.com/p/v8/issues/detail?id=2070) + * for more details. + * + * @private + * @param {Function} func The function to associate metadata with. + * @param {*} data The metadata. + * @returns {Function} Returns `func`. + */ + var setData = (function() { + var count = 0, + lastCalled = 0; + + return function(key, value) { + var stamp = now(), + remaining = HOT_SPAN - (stamp - lastCalled); + + lastCalled = stamp; + if (remaining > 0) { + if (++count >= HOT_COUNT) { + return key; + } + } else { + count = 0; + } + return baseSetData(key, value); + }; + }()); + + /** + * A fallback implementation of `_.isPlainObject` which checks if `value` + * is an object created by the `Object` constructor or has a `[[Prototype]]` + * of `null`. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. + */ + function shimIsPlainObject(value) { + var Ctor, + support = lodash.support; + + // Exit early for non `Object` objects. + if (!(isObjectLike(value) && objToString.call(value) == objectTag) || + (!hasOwnProperty.call(value, 'constructor') && + (Ctor = value.constructor, typeof Ctor == 'function' && !(Ctor instanceof Ctor)))) { + return false; + } + // IE < 9 iterates inherited properties before own properties. If the first + // iterated property is an object's own property then there are no inherited + // enumerable properties. + var result; + // In most environments an object's own properties are iterated before + // its inherited properties. If the last iterated property is an object's + // own property then there are no inherited enumerable properties. + baseForIn(value, function(subValue, key) { + result = key; + }); + return typeof result == 'undefined' || hasOwnProperty.call(value, result); + } + + /** + * A fallback implementation of `Object.keys` which creates an array of the + * own enumerable property names of `object`. + * + * @private + * @param {Object} object The object to inspect. + * @returns {Array} Returns the array of property names. + */ + function shimKeys(object) { + var props = keysIn(object), + propsLength = props.length, + length = propsLength && object.length, + support = lodash.support; + + var allowIndexes = length && isLength(length) && + (isArray(object) || (support.nonEnumArgs && isArguments(object))); + + var index = -1, + result = []; + + while (++index < propsLength) { + var key = props[index]; + if ((allowIndexes && isIndex(key, length)) || hasOwnProperty.call(object, key)) { + result.push(key); + } + } + return result; + } + + /** + * Converts `value` to an array-like object if it is not one. + * + * @private + * @param {*} value The value to process. + * @returns {Array|Object} Returns the array-like object. + */ + function toIterable(value) { + if (value == null) { + return []; + } + if (!isLength(value.length)) { + return values(value); + } + return isObject(value) ? value : Object(value); + } + + /** + * Converts `value` to an object if it is not one. + * + * @private + * @param {*} value The value to process. + * @returns {Object} Returns the object. + */ + function toObject(value) { + return isObject(value) ? value : Object(value); + } + + /** + * Creates a clone of `wrapper`. + * + * @private + * @param {Object} wrapper The wrapper to clone. + * @returns {Object} Returns the cloned wrapper. + */ + function wrapperClone(wrapper) { + return wrapper instanceof LazyWrapper + ? wrapper.clone() + : new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__, arrayCopy(wrapper.__actions__)); + } + + /*------------------------------------------------------------------------*/ + + /** + * Creates an array of elements split into groups the length of `size`. + * If `collection` can't be split evenly, the final chunk will be the remaining + * elements. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to process. + * @param {number} [size=1] The length of each chunk. + * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. + * @returns {Array} Returns the new array containing chunks. + * @example + * + * _.chunk(['a', 'b', 'c', 'd'], 2); + * // => [['a', 'b'], ['c', 'd']] + * + * _.chunk(['a', 'b', 'c', 'd'], 3); + * // => [['a', 'b', 'c'], ['d']] + */ + function chunk(array, size, guard) { + if (guard ? isIterateeCall(array, size, guard) : size == null) { + size = 1; + } else { + size = nativeMax(+size || 1, 1); + } + var index = 0, + length = array ? array.length : 0, + resIndex = -1, + result = Array(ceil(length / size)); + + while (index < length) { + result[++resIndex] = baseSlice(array, index, (index += size)); + } + return result; + } + + /** + * Creates an array with all falsey values removed. The values `false`, `null`, + * `0`, `""`, `undefined`, and `NaN` are falsey. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to compact. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * _.compact([0, 1, false, 2, '', 3]); + * // => [1, 2, 3] + */ + function compact(array) { + var index = -1, + length = array ? array.length : 0, + resIndex = -1, + result = []; + + while (++index < length) { + var value = array[index]; + if (value) { + result[++resIndex] = value; + } + } + return result; + } + + /** + * Creates an array excluding all values of the provided arrays using + * `SameValueZero` for equality comparisons. + * + * **Note:** `SameValueZero` comparisons are like strict equality comparisons, + * e.g. `===`, except that `NaN` matches `NaN`. See the + * [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero) + * for more details. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to inspect. + * @param {...Array} [values] The arrays of values to exclude. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * _.difference([1, 2, 3], [5, 2, 10]); + * // => [1, 3] + */ + function difference() { + var index = -1, + length = arguments.length; + + while (++index < length) { + var value = arguments[index]; + if (isArray(value) || isArguments(value)) { + break; + } + } + return baseDifference(value, baseFlatten(arguments, false, true, ++index)); + } + + /** + * Creates a slice of `array` with `n` elements dropped from the beginning. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to drop. + * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.drop([1, 2, 3]); + * // => [2, 3] + * + * _.drop([1, 2, 3], 2); + * // => [3] + * + * _.drop([1, 2, 3], 5); + * // => [] + * + * _.drop([1, 2, 3], 0); + * // => [1, 2, 3] + */ + function drop(array, n, guard) { + var length = array ? array.length : 0; + if (!length) { + return []; + } + if (guard ? isIterateeCall(array, n, guard) : n == null) { + n = 1; + } + return baseSlice(array, n < 0 ? 0 : n); + } + + /** + * Creates a slice of `array` with `n` elements dropped from the end. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to drop. + * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.dropRight([1, 2, 3]); + * // => [1, 2] + * + * _.dropRight([1, 2, 3], 2); + * // => [1] + * + * _.dropRight([1, 2, 3], 5); + * // => [] + * + * _.dropRight([1, 2, 3], 0); + * // => [1, 2, 3] + */ + function dropRight(array, n, guard) { + var length = array ? array.length : 0; + if (!length) { + return []; + } + if (guard ? isIterateeCall(array, n, guard) : n == null) { + n = 1; + } + n = length - (+n || 0); + return baseSlice(array, 0, n < 0 ? 0 : n); + } + + /** + * Creates a slice of `array` excluding elements dropped from the end. + * Elements are dropped until `predicate` returns falsey. The predicate is + * bound to `thisArg` and invoked with three arguments; (value, index, array). + * + * If a property name is provided for `predicate` the created "_.property" + * style callback returns the property value of the given element. + * + * If value is also provided for `thisArg` the created "_.matchesProperty" + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `predicate` the created "_.matches" style + * callback returns `true` for elements that match the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to query. + * @param {Function|Object|string} [predicate=_.identity] The function invoked + * per element. + * @param {*} [thisArg] The `this` binding of `predicate`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.dropRightWhile([1, 2, 3], function(n) { return n > 1; }); + * // => [1] + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': true }, + * { 'user': 'fred', 'age': 40, 'active': false }, + * { 'user': 'pebbles', 'age': 1, 'active': false } + * ]; + * + * // using the "_.matches" callback shorthand + * _.pluck(_.dropRightWhile(users, { 'age': 1, 'active': false }), 'user'); + * // => ['barney', 'fred'] + * + * // using the "_.matchesProperty" callback shorthand + * _.pluck(_.dropRightWhile(users, 'active', false), 'user'); + * // => ['barney'] + * + * // using the "_.property" callback shorthand + * _.pluck(_.dropRightWhile(users, 'active'), 'user'); + * // => ['barney', 'fred', 'pebbles'] + */ + function dropRightWhile(array, predicate, thisArg) { + var length = array ? array.length : 0; + if (!length) { + return []; + } + predicate = getCallback(predicate, thisArg, 3); + while (length-- && predicate(array[length], length, array)) {} + return baseSlice(array, 0, length + 1); + } + + /** + * Creates a slice of `array` excluding elements dropped from the beginning. + * Elements are dropped until `predicate` returns falsey. The predicate is + * bound to `thisArg` and invoked with three arguments; (value, index, array). + * + * If a property name is provided for `predicate` the created "_.property" + * style callback returns the property value of the given element. + * + * If value is also provided for `thisArg` the created "_.matchesProperty" + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `predicate` the created "_.matches" style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to query. + * @param {Function|Object|string} [predicate=_.identity] The function invoked + * per element. + * @param {*} [thisArg] The `this` binding of `predicate`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.dropWhile([1, 2, 3], function(n) { return n < 3; }); + * // => [3] + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': false }, + * { 'user': 'fred', 'age': 40, 'active': false }, + * { 'user': 'pebbles', 'age': 1, 'active': true } + * ]; + * + * // using the "_.matches" callback shorthand + * _.pluck(_.dropWhile(users, { 'age': 36, 'active': false }), 'user'); + * // => ['fred', 'pebbles'] + * + * // using the "_.matchesProperty" callback shorthand + * _.pluck(_.dropWhile(users, 'active', false), 'user'); + * // => ['pebbles'] + * + * // using the "_.property" callback shorthand + * _.pluck(_.dropWhile(users, 'active'), 'user'); + * // => ['barney', 'fred', 'pebbles'] + */ + function dropWhile(array, predicate, thisArg) { + var length = array ? array.length : 0; + if (!length) { + return []; + } + var index = -1; + predicate = getCallback(predicate, thisArg, 3); + while (++index < length && predicate(array[index], index, array)) {} + return baseSlice(array, index); + } + + /** + * Fills elements of `array` with `value` from `start` up to, but not + * including, `end`. + * + * **Note:** This method mutates `array`. + * + * @private + * @param {Array} array The array to fill. + * @param {*} value The value to fill `array` with. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns `array`. + */ + function fill(array, value, start, end) { + var length = array ? array.length : 0; + if (!length) { + return []; + } + if (start && typeof start != 'number' && isIterateeCall(array, value, start)) { + start = 0; + end = length; + } + return baseFill(array, value, start, end); + } + + /** + * This method is like `_.find` except that it returns the index of the first + * element `predicate` returns truthy for, instead of the element itself. + * + * If a property name is provided for `predicate` the created "_.property" + * style callback returns the property value of the given element. + * + * If value is also provided for `thisArg` the created "_.matchesProperty" + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `predicate` the created "_.matches" style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to search. + * @param {Function|Object|string} [predicate=_.identity] The function invoked + * per iteration. If a property name or object is provided it is used to + * create a "_.property" or "_.matches" style callback respectively. + * @param {*} [thisArg] The `this` binding of `predicate`. + * @returns {number} Returns the index of the found element, else `-1`. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': false }, + * { 'user': 'fred', 'age': 40, 'active': true }, + * { 'user': 'pebbles', 'age': 1, 'active': false } + * ]; + * + * _.findIndex(users, function(chr) { return chr.age < 40; }); + * // => 0 + * + * // using the "_.matches" callback shorthand + * _.findIndex(users, { 'age': 40, 'active': true }); + * // => 1 + * + * // using the "_.matchesProperty" callback shorthand + * _.findIndex(users, 'age', 1); + * // => 2 + * + * // using the "_.property" callback shorthand + * _.findIndex(users, 'active'); + * // => 1 + */ + function findIndex(array, predicate, thisArg) { + var index = -1, + length = array ? array.length : 0; + + predicate = getCallback(predicate, thisArg, 3); + while (++index < length) { + if (predicate(array[index], index, array)) { + return index; + } + } + return -1; + } + + /** + * This method is like `_.findIndex` except that it iterates over elements + * of `collection` from right to left. + * + * If a property name is provided for `predicate` the created "_.property" + * style callback returns the property value of the given element. + * + * If value is also provided for `thisArg` the created "_.matchesProperty" + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `predicate` the created "_.matches" style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to search. + * @param {Function|Object|string} [predicate=_.identity] The function invoked + * per iteration. If a property name or object is provided it is used to + * create a "_.property" or "_.matches" style callback respectively. + * @param {*} [thisArg] The `this` binding of `predicate`. + * @returns {number} Returns the index of the found element, else `-1`. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': true }, + * { 'user': 'fred', 'age': 40, 'active': false }, + * { 'user': 'pebbles', 'age': 1, 'active': false } + * ]; + * + * _.findLastIndex(users, function(chr) { return chr.age < 40; }); + * // => 2 + * + * // using the "_.matches" callback shorthand + * _.findLastIndex(users, { 'age': 36, 'active': true }); + * // => 0 + * + * // using the "_.matchesProperty" callback shorthand + * _.findLastIndex(users, 'age', 40); + * // => 1 + * + * // using the "_.property" callback shorthand + * _.findLastIndex(users, 'active'); + * // => 0 + */ + function findLastIndex(array, predicate, thisArg) { + var length = array ? array.length : 0; + predicate = getCallback(predicate, thisArg, 3); + while (length--) { + if (predicate(array[length], length, array)) { + return length; + } + } + return -1; + } + + /** + * Gets the first element of `array`. + * + * @static + * @memberOf _ + * @alias head + * @category Array + * @param {Array} array The array to query. + * @returns {*} Returns the first element of `array`. + * @example + * + * _.first([1, 2, 3]); + * // => 1 + * + * _.first([]); + * // => undefined + */ + function first(array) { + return array ? array[0] : undefined; + } + + /** + * Flattens a nested array. If `isDeep` is `true` the array is recursively + * flattened, otherwise it is only flattened a single level. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to flatten. + * @param {boolean} [isDeep] Specify a deep flatten. + * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. + * @returns {Array} Returns the new flattened array. + * @example + * + * _.flatten([1, [2], [3, [[4]]]]); + * // => [1, 2, 3, [[4]]]; + * + * // using `isDeep` + * _.flatten([1, [2], [3, [[4]]]], true); + * // => [1, 2, 3, 4]; + */ + function flatten(array, isDeep, guard) { + var length = array ? array.length : 0; + if (guard && isIterateeCall(array, isDeep, guard)) { + isDeep = false; + } + return length ? baseFlatten(array, isDeep) : []; + } + + /** + * Recursively flattens a nested array. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to recursively flatten. + * @returns {Array} Returns the new flattened array. + * @example + * + * _.flattenDeep([1, [2], [3, [[4]]]]); + * // => [1, 2, 3, 4]; + */ + function flattenDeep(array) { + var length = array ? array.length : 0; + return length ? baseFlatten(array, true) : []; + } + + /** + * Gets the index at which the first occurrence of `value` is found in `array` + * using `SameValueZero` for equality comparisons. If `fromIndex` is negative, + * it is used as the offset from the end of `array`. If `array` is sorted + * providing `true` for `fromIndex` performs a faster binary search. + * + * **Note:** `SameValueZero` comparisons are like strict equality comparisons, + * e.g. `===`, except that `NaN` matches `NaN`. See the + * [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero) + * for more details. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to search. + * @param {*} value The value to search for. + * @param {boolean|number} [fromIndex=0] The index to search from or `true` + * to perform a binary search on a sorted array. + * @returns {number} Returns the index of the matched value, else `-1`. + * @example + * + * _.indexOf([1, 2, 3, 1, 2, 3], 2); + * // => 1 + * + * // using `fromIndex` + * _.indexOf([1, 2, 3, 1, 2, 3], 2, 3); + * // => 4 + * + * // performing a binary search + * _.indexOf([4, 4, 5, 5, 6, 6], 5, true); + * // => 2 + */ + function indexOf(array, value, fromIndex) { + var length = array ? array.length : 0; + if (!length) { + return -1; + } + if (typeof fromIndex == 'number') { + fromIndex = fromIndex < 0 ? nativeMax(length + fromIndex, 0) : (fromIndex || 0); + } else if (fromIndex) { + var index = binaryIndex(array, value), + other = array[index]; + + return (value === value ? value === other : other !== other) ? index : -1; + } + return baseIndexOf(array, value, fromIndex); + } + + /** + * Gets all but the last element of `array`. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to query. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.initial([1, 2, 3]); + * // => [1, 2] + */ + function initial(array) { + return dropRight(array, 1); + } + + /** + * Creates an array of unique values in all provided arrays using `SameValueZero` + * for equality comparisons. + * + * **Note:** `SameValueZero` comparisons are like strict equality comparisons, + * e.g. `===`, except that `NaN` matches `NaN`. See the + * [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero) + * for more details. + * + * @static + * @memberOf _ + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @returns {Array} Returns the new array of shared values. + * @example + * + * _.intersection([1, 2, 3], [5, 2, 1, 4], [2, 1]); + * // => [1, 2] + */ + function intersection() { + var args = [], + argsIndex = -1, + argsLength = arguments.length, + caches = [], + indexOf = getIndexOf(), + isCommon = indexOf == baseIndexOf; + + while (++argsIndex < argsLength) { + var value = arguments[argsIndex]; + if (isArray(value) || isArguments(value)) { + args.push(value); + caches.push(isCommon && value.length >= 120 && createCache(argsIndex && value)); + } + } + argsLength = args.length; + var array = args[0], + index = -1, + length = array ? array.length : 0, + result = [], + seen = caches[0]; + + outer: + while (++index < length) { + value = array[index]; + if ((seen ? cacheIndexOf(seen, value) : indexOf(result, value)) < 0) { + argsIndex = argsLength; + while (--argsIndex) { + var cache = caches[argsIndex]; + if ((cache ? cacheIndexOf(cache, value) : indexOf(args[argsIndex], value)) < 0) { + continue outer; + } + } + if (seen) { + seen.push(value); + } + result.push(value); + } + } + return result; + } + + /** + * Gets the last element of `array`. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to query. + * @returns {*} Returns the last element of `array`. + * @example + * + * _.last([1, 2, 3]); + * // => 3 + */ + function last(array) { + var length = array ? array.length : 0; + return length ? array[length - 1] : undefined; + } + + /** + * This method is like `_.indexOf` except that it iterates over elements of + * `array` from right to left. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to search. + * @param {*} value The value to search for. + * @param {boolean|number} [fromIndex=array.length-1] The index to search from + * or `true` to perform a binary search on a sorted array. + * @returns {number} Returns the index of the matched value, else `-1`. + * @example + * + * _.lastIndexOf([1, 2, 3, 1, 2, 3], 2); + * // => 4 + * + * // using `fromIndex` + * _.lastIndexOf([1, 2, 3, 1, 2, 3], 2, 3); + * // => 1 + * + * // performing a binary search + * _.lastIndexOf([4, 4, 5, 5, 6, 6], 5, true); + * // => 3 + */ + function lastIndexOf(array, value, fromIndex) { + var length = array ? array.length : 0; + if (!length) { + return -1; + } + var index = length; + if (typeof fromIndex == 'number') { + index = (fromIndex < 0 ? nativeMax(length + fromIndex, 0) : nativeMin(fromIndex || 0, length - 1)) + 1; + } else if (fromIndex) { + index = binaryIndex(array, value, true) - 1; + var other = array[index]; + return (value === value ? value === other : other !== other) ? index : -1; + } + if (value !== value) { + return indexOfNaN(array, index, true); + } + while (index--) { + if (array[index] === value) { + return index; + } + } + return -1; + } + + /** + * Removes all provided values from `array` using `SameValueZero` for equality + * comparisons. + * + * **Notes:** + * - Unlike `_.without`, this method mutates `array`. + * - `SameValueZero` comparisons are like strict equality comparisons, e.g. `===`, + * except that `NaN` matches `NaN`. See the [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero) + * for more details. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to modify. + * @param {...*} [values] The values to remove. + * @returns {Array} Returns `array`. + * @example + * + * var array = [1, 2, 3, 1, 2, 3]; + * _.pull(array, 2, 3); + * console.log(array); + * // => [1, 1] + */ + function pull() { + var array = arguments[0]; + if (!(array && array.length)) { + return array; + } + var index = 0, + indexOf = getIndexOf(), + length = arguments.length; + + while (++index < length) { + var fromIndex = 0, + value = arguments[index]; + + while ((fromIndex = indexOf(array, value, fromIndex)) > -1) { + splice.call(array, fromIndex, 1); + } + } + return array; + } + + /** + * Removes elements from `array` corresponding to the given indexes and returns + * an array of the removed elements. Indexes may be specified as an array of + * indexes or as individual arguments. + * + * **Note:** Unlike `_.at`, this method mutates `array`. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to modify. + * @param {...(number|number[])} [indexes] The indexes of elements to remove, + * specified as individual indexes or arrays of indexes. + * @returns {Array} Returns the new array of removed elements. + * @example + * + * var array = [5, 10, 15, 20]; + * var evens = _.pullAt(array, [1, 3]); + * + * console.log(array); + * // => [5, 15] + * + * console.log(evens); + * // => [10, 20] + */ + function pullAt(array) { + return basePullAt(array || [], baseFlatten(arguments, false, false, 1)); + } + + /** + * Removes all elements from `array` that `predicate` returns truthy for + * and returns an array of the removed elements. The predicate is bound to + * `thisArg` and invoked with three arguments; (value, index, array). + * + * If a property name is provided for `predicate` the created "_.property" + * style callback returns the property value of the given element. + * + * If value is also provided for `thisArg` the created "_.matchesProperty" + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `predicate` the created "_.matches" style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * **Note:** Unlike `_.filter`, this method mutates `array`. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to modify. + * @param {Function|Object|string} [predicate=_.identity] The function invoked + * per iteration. If a property name or object is provided it is used to + * create a "_.property" or "_.matches" style callback respectively. + * @param {*} [thisArg] The `this` binding of `predicate`. + * @returns {Array} Returns the new array of removed elements. + * @example + * + * var array = [1, 2, 3, 4]; + * var evens = _.remove(array, function(n) { return n % 2 == 0; }); + * + * console.log(array); + * // => [1, 3] + * + * console.log(evens); + * // => [2, 4] + */ + function remove(array, predicate, thisArg) { + var index = -1, + length = array ? array.length : 0, + result = []; + + predicate = getCallback(predicate, thisArg, 3); + while (++index < length) { + var value = array[index]; + if (predicate(value, index, array)) { + result.push(value); + splice.call(array, index--, 1); + length--; + } + } + return result; + } + + /** + * Gets all but the first element of `array`. + * + * @static + * @memberOf _ + * @alias tail + * @category Array + * @param {Array} array The array to query. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.rest([1, 2, 3]); + * // => [2, 3] + */ + function rest(array) { + return drop(array, 1); + } + + /** + * Creates a slice of `array` from `start` up to, but not including, `end`. + * + * **Note:** This function is used instead of `Array#slice` to support node + * lists in IE < 9 and to ensure dense arrays are returned. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to slice. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the slice of `array`. + */ + function slice(array, start, end) { + var length = array ? array.length : 0; + if (!length) { + return []; + } + if (end && typeof end != 'number' && isIterateeCall(array, start, end)) { + start = 0; + end = length; + } + return baseSlice(array, start, end); + } + + /** + * Uses a binary search to determine the lowest index at which `value` should + * be inserted into `array` in order to maintain its sort order. If an iteratee + * function is provided it is invoked for `value` and each element of `array` + * to compute their sort ranking. The iteratee is bound to `thisArg` and + * invoked with one argument; (value). + * + * If a property name is provided for `predicate` the created "_.property" + * style callback returns the property value of the given element. + * + * If value is also provided for `thisArg` the created "_.matchesProperty" + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `predicate` the created "_.matches" style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @param {Function|Object|string} [iteratee=_.identity] The function invoked + * per iteration. If a property name or object is provided it is used to + * create a "_.property" or "_.matches" style callback respectively. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + * @example + * + * _.sortedIndex([30, 50], 40); + * // => 1 + * + * _.sortedIndex([4, 4, 5, 5, 6, 6], 5); + * // => 2 + * + * var dict = { 'data': { 'thirty': 30, 'forty': 40, 'fifty': 50 } }; + * + * // using an iteratee function + * _.sortedIndex(['thirty', 'fifty'], 'forty', function(word) { + * return this.data[word]; + * }, dict); + * // => 1 + * + * // using the "_.property" callback shorthand + * _.sortedIndex([{ 'x': 30 }, { 'x': 50 }], { 'x': 40 }, 'x'); + * // => 1 + */ + function sortedIndex(array, value, iteratee, thisArg) { + var func = getCallback(iteratee); + return (func === baseCallback && iteratee == null) + ? binaryIndex(array, value) + : binaryIndexBy(array, value, func(iteratee, thisArg, 1)); + } + + /** + * This method is like `_.sortedIndex` except that it returns the highest + * index at which `value` should be inserted into `array` in order to + * maintain its sort order. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @param {Function|Object|string} [iteratee=_.identity] The function invoked + * per iteration. If a property name or object is provided it is used to + * create a "_.property" or "_.matches" style callback respectively. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + * @example + * + * _.sortedLastIndex([4, 4, 5, 5, 6, 6], 5); + * // => 4 + */ + function sortedLastIndex(array, value, iteratee, thisArg) { + var func = getCallback(iteratee); + return (func === baseCallback && iteratee == null) + ? binaryIndex(array, value, true) + : binaryIndexBy(array, value, func(iteratee, thisArg, 1), true); + } + + /** + * Creates a slice of `array` with `n` elements taken from the beginning. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to take. + * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.take([1, 2, 3]); + * // => [1] + * + * _.take([1, 2, 3], 2); + * // => [1, 2] + * + * _.take([1, 2, 3], 5); + * // => [1, 2, 3] + * + * _.take([1, 2, 3], 0); + * // => [] + */ + function take(array, n, guard) { + var length = array ? array.length : 0; + if (!length) { + return []; + } + if (guard ? isIterateeCall(array, n, guard) : n == null) { + n = 1; + } + return baseSlice(array, 0, n < 0 ? 0 : n); + } + + /** + * Creates a slice of `array` with `n` elements taken from the end. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to take. + * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.takeRight([1, 2, 3]); + * // => [3] + * + * _.takeRight([1, 2, 3], 2); + * // => [2, 3] + * + * _.takeRight([1, 2, 3], 5); + * // => [1, 2, 3] + * + * _.takeRight([1, 2, 3], 0); + * // => [] + */ + function takeRight(array, n, guard) { + var length = array ? array.length : 0; + if (!length) { + return []; + } + if (guard ? isIterateeCall(array, n, guard) : n == null) { + n = 1; + } + n = length - (+n || 0); + return baseSlice(array, n < 0 ? 0 : n); + } + + /** + * Creates a slice of `array` with elements taken from the end. Elements are + * taken until `predicate` returns falsey. The predicate is bound to `thisArg` + * and invoked with three arguments; (value, index, array). + * + * If a property name is provided for `predicate` the created "_.property" + * style callback returns the property value of the given element. + * + * If value is also provided for `thisArg` the created "_.matchesProperty" + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `predicate` the created "_.matches" style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to query. + * @param {Function|Object|string} [predicate=_.identity] The function invoked + * per element. + * @param {*} [thisArg] The `this` binding of `predicate`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.takeRightWhile([1, 2, 3], function(n) { return n > 1; }); + * // => [2, 3] + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': true }, + * { 'user': 'fred', 'age': 40, 'active': false }, + * { 'user': 'pebbles', 'age': 1, 'active': false } + * ]; + * + * // using the "_.matches" callback shorthand + * _.pluck(_.takeRightWhile(users, { 'age': 1, 'active': true }), 'user'); + * // => ['pebbles'] + * + * // using the "_.matchesProperty" callback shorthand + * _.pluck(_.takeRightWhile(users, 'active', false), 'user'); + * // => ['fred', 'pebbles'] + * + * // using the "_.property" callback shorthand + * _.pluck(_.takeRightWhile(users, 'active'), 'user'); + * // => [] + */ + function takeRightWhile(array, predicate, thisArg) { + var length = array ? array.length : 0; + if (!length) { + return []; + } + predicate = getCallback(predicate, thisArg, 3); + while (length-- && predicate(array[length], length, array)) {} + return baseSlice(array, length + 1); + } + + /** + * Creates a slice of `array` with elements taken from the beginning. Elements + * are taken until `predicate` returns falsey. The predicate is bound to + * `thisArg` and invoked with three arguments; (value, index, array). + * + * If a property name is provided for `predicate` the created "_.property" + * style callback returns the property value of the given element. + * + * If value is also provided for `thisArg` the created "_.matchesProperty" + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `predicate` the created "_.matches" style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to query. + * @param {Function|Object|string} [predicate=_.identity] The function invoked + * per element. + * @param {*} [thisArg] The `this` binding of `predicate`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.takeWhile([1, 2, 3], function(n) { return n < 3; }); + * // => [1, 2] + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': false }, + * { 'user': 'fred', 'age': 40, 'active': false }, + * { 'user': 'pebbles', 'age': 1, 'active': true } + * ]; + * + * // using the "_.matches" callback shorthand + * _.pluck(_.takeWhile(users, { 'age': 36, 'active': true }), 'user'); + * // => ['barney'] + * + * // using the "_.matchesProperty" callback shorthand + * _.pluck(_.takeWhile(users, 'active', false), 'user'); + * // => ['barney', 'fred'] + * + * // using the "_.property" callback shorthand + * _.pluck(_.takeWhile(users, 'active'), 'user'); + * // => [] + */ + function takeWhile(array, predicate, thisArg) { + var length = array ? array.length : 0; + if (!length) { + return []; + } + var index = -1; + predicate = getCallback(predicate, thisArg, 3); + while (++index < length && predicate(array[index], index, array)) {} + return baseSlice(array, 0, index); + } + + /** + * Creates an array of unique values, in order, of the provided arrays using + * `SameValueZero` for equality comparisons. + * + * **Note:** `SameValueZero` comparisons are like strict equality comparisons, + * e.g. `===`, except that `NaN` matches `NaN`. See the + * [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero) + * for more details. + * + * @static + * @memberOf _ + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @returns {Array} Returns the new array of combined values. + * @example + * + * _.union([1, 2, 3], [5, 2, 1, 4], [2, 1]); + * // => [1, 2, 3, 5, 4] + */ + function union() { + return baseUniq(baseFlatten(arguments, false, true)); + } + + /** + * Creates a duplicate-value-free version of an array using `SameValueZero` + * for equality comparisons. Providing `true` for `isSorted` performs a faster + * search algorithm for sorted arrays. If an iteratee function is provided it + * is invoked for each value in the array to generate the criterion by which + * uniqueness is computed. The `iteratee` is bound to `thisArg` and invoked + * with three arguments; (value, index, array). + * + * If a property name is provided for `predicate` the created "_.property" + * style callback returns the property value of the given element. + * + * If value is also provided for `thisArg` the created "_.matchesProperty" + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `predicate` the created "_.matches" style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * **Note:** `SameValueZero` comparisons are like strict equality comparisons, + * e.g. `===`, except that `NaN` matches `NaN`. See the + * [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero) + * for more details. + * + * @static + * @memberOf _ + * @alias unique + * @category Array + * @param {Array} array The array to inspect. + * @param {boolean} [isSorted] Specify the array is sorted. + * @param {Function|Object|string} [iteratee] The function invoked per iteration. + * If a property name or object is provided it is used to create a "_.property" + * or "_.matches" style callback respectively. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {Array} Returns the new duplicate-value-free array. + * @example + * + * _.uniq([1, 2, 1]); + * // => [1, 2] + * + * // using `isSorted` + * _.uniq([1, 1, 2], true); + * // => [1, 2] + * + * // using an iteratee function + * _.uniq([1, 2.5, 1.5, 2], function(n) { return this.floor(n); }, Math); + * // => [1, 2.5] + * + * // using the "_.property" callback shorthand + * _.uniq([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 1 }, { 'x': 2 }] + */ + function uniq(array, isSorted, iteratee, thisArg) { + var length = array ? array.length : 0; + if (!length) { + return []; + } + // Juggle arguments. + if (typeof isSorted != 'boolean' && isSorted != null) { + thisArg = iteratee; + iteratee = isIterateeCall(array, isSorted, thisArg) ? null : isSorted; + isSorted = false; + } + var func = getCallback(); + if (!(func === baseCallback && iteratee == null)) { + iteratee = func(iteratee, thisArg, 3); + } + return (isSorted && getIndexOf() == baseIndexOf) + ? sortedUniq(array, iteratee) + : baseUniq(array, iteratee); + } + + /** + * This method is like `_.zip` except that it accepts an array of grouped + * elements and creates an array regrouping the elements to their pre-`_.zip` + * configuration. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array of grouped elements to process. + * @returns {Array} Returns the new array of regrouped elements. + * @example + * + * var zipped = _.zip(['fred', 'barney'], [30, 40], [true, false]); + * // => [['fred', 30, true], ['barney', 40, false]] + * + * _.unzip(zipped); + * // => [['fred', 'barney'], [30, 40], [true, false]] + */ + function unzip(array) { + var index = -1, + length = (array && array.length && arrayMax(arrayMap(array, getLength))) >>> 0, + result = Array(length); + + while (++index < length) { + result[index] = arrayMap(array, baseProperty(index)); + } + return result; + } + + /** + * Creates an array excluding all provided values using `SameValueZero` for + * equality comparisons. + * + * **Note:** `SameValueZero` comparisons are like strict equality comparisons, + * e.g. `===`, except that `NaN` matches `NaN`. See the + * [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero) + * for more details. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to filter. + * @param {...*} [values] The values to exclude. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * _.without([1, 2, 1, 0, 3, 1, 4], 0, 1); + * // => [2, 3, 4] + */ + function without(array) { + return baseDifference(array, baseSlice(arguments, 1)); + } + + /** + * Creates an array that is the symmetric difference of the provided arrays. + * See [Wikipedia](https://en.wikipedia.org/wiki/Symmetric_difference) for + * more details. + * + * @static + * @memberOf _ + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @returns {Array} Returns the new array of values. + * @example + * + * _.xor([1, 2, 3], [5, 2, 1, 4]); + * // => [3, 5, 4] + * + * _.xor([1, 2, 5], [2, 3, 5], [3, 4, 5]); + * // => [1, 4, 5] + */ + function xor() { + var index = -1, + length = arguments.length; + + while (++index < length) { + var array = arguments[index]; + if (isArray(array) || isArguments(array)) { + var result = result + ? baseDifference(result, array).concat(baseDifference(array, result)) + : array; + } + } + return result ? baseUniq(result) : []; + } + + /** + * Creates an array of grouped elements, the first of which contains the first + * elements of the given arrays, the second of which contains the second elements + * of the given arrays, and so on. + * + * @static + * @memberOf _ + * @category Array + * @param {...Array} [arrays] The arrays to process. + * @returns {Array} Returns the new array of grouped elements. + * @example + * + * _.zip(['fred', 'barney'], [30, 40], [true, false]); + * // => [['fred', 30, true], ['barney', 40, false]] + */ + function zip() { + var length = arguments.length, + array = Array(length); + + while (length--) { + array[length] = arguments[length]; + } + return unzip(array); + } + + /** + * Creates an object composed from arrays of property names and values. Provide + * either a single two dimensional array, e.g. `[[key1, value1], [key2, value2]]` + * or two arrays, one of property names and one of corresponding values. + * + * @static + * @memberOf _ + * @alias object + * @category Array + * @param {Array} props The property names. + * @param {Array} [values=[]] The property values. + * @returns {Object} Returns the new object. + * @example + * + * _.zipObject(['fred', 'barney'], [30, 40]); + * // => { 'fred': 30, 'barney': 40 } + */ + function zipObject(props, values) { + var index = -1, + length = props ? props.length : 0, + result = {}; + + if (length && !values && !isArray(props[0])) { + values = []; + } + while (++index < length) { + var key = props[index]; + if (values) { + result[key] = values[index]; + } else if (key) { + result[key[0]] = key[1]; + } + } + return result; + } + + /*------------------------------------------------------------------------*/ + + /** + * Creates a `lodash` object that wraps `value` with explicit method + * chaining enabled. + * + * @static + * @memberOf _ + * @category Chain + * @param {*} value The value to wrap. + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 40 }, + * { 'user': 'pebbles', 'age': 1 } + * ]; + * + * var youngest = _.chain(users) + * .sortBy('age') + * .map(function(chr) { return chr.user + ' is ' + chr.age; }) + * .first() + * .value(); + * // => 'pebbles is 1' + */ + function chain(value) { + var result = lodash(value); + result.__chain__ = true; + return result; + } + + /** + * This method invokes `interceptor` and returns `value`. The interceptor is + * bound to `thisArg` and invoked with one argument; (value). The purpose of + * this method is to "tap into" a method chain in order to perform operations + * on intermediate results within the chain. + * + * @static + * @memberOf _ + * @category Chain + * @param {*} value The value to provide to `interceptor`. + * @param {Function} interceptor The function to invoke. + * @param {*} [thisArg] The `this` binding of `interceptor`. + * @returns {*} Returns `value`. + * @example + * + * _([1, 2, 3]) + * .tap(function(array) { array.pop(); }) + * .reverse() + * .value(); + * // => [2, 1] + */ + function tap(value, interceptor, thisArg) { + interceptor.call(thisArg, value); + return value; + } + + /** + * This method is like `_.tap` except that it returns the result of `interceptor`. + * + * @static + * @memberOf _ + * @category Chain + * @param {*} value The value to provide to `interceptor`. + * @param {Function} interceptor The function to invoke. + * @param {*} [thisArg] The `this` binding of `interceptor`. + * @returns {*} Returns the result of `interceptor`. + * @example + * + * _([1, 2, 3]) + * .last() + * .thru(function(value) { return [value]; }) + * .value(); + * // => [3] + */ + function thru(value, interceptor, thisArg) { + return interceptor.call(thisArg, value); + } + + /** + * Enables explicit method chaining on the wrapper object. + * + * @name chain + * @memberOf _ + * @category Chain + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 40 } + * ]; + * + * // without explicit chaining + * _(users).first(); + * // => { 'user': 'barney', 'age': 36 } + * + * // with explicit chaining + * _(users).chain() + * .first() + * .pick('user') + * .value(); + * // => { 'user': 'barney' } + */ + function wrapperChain() { + return chain(this); + } + + /** + * Executes the chained sequence and returns the wrapped result. + * + * @name commit + * @memberOf _ + * @category Chain + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var array = [1, 2]; + * var wrapper = _(array).push(3); + * + * console.log(array); + * // => [1, 2] + * + * wrapper = wrapper.commit(); + * console.log(array); + * // => [1, 2, 3] + * + * wrapper.last(); + * // => 3 + * + * console.log(array); + * // => [1, 2, 3] + */ + function wrapperCommit() { + return new LodashWrapper(this.value(), this.__chain__); + } + + /** + * Creates a clone of the chained sequence planting `value` as the wrapped value. + * + * @name plant + * @memberOf _ + * @category Chain + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var array = [1, 2]; + * var wrapper = _(array).map(_.partial(Math.pow, _, 2)); + * + * var other = [3, 4]; + * var otherWrapper = wrapper.plant(other); + * + * otherWrapper.value(); + * // => [9, 16] + * + * wrapper.value(); + * // => [1, 4] + */ + function wrapperPlant(value) { + var result, + parent = this; + + while (parent instanceof LodashWrapper) { + var clone = wrapperClone(parent); + if (result) { + previous.__wrapped__ = clone; + } else { + result = clone; + } + var previous = clone; + parent = parent.__wrapped__; + } + previous.__wrapped__ = value; + return result; + } + + /** + * Reverses the wrapped array so the first element becomes the last, the + * second element becomes the second to last, and so on. + * + * **Note:** This method mutates the wrapped array. + * + * @name reverse + * @memberOf _ + * @category Chain + * @returns {Object} Returns the new reversed `lodash` wrapper instance. + * @example + * + * var array = [1, 2, 3]; + * + * _(array).reverse().value() + * // => [3, 2, 1] + * + * console.log(array); + * // => [3, 2, 1] + */ + function wrapperReverse() { + var value = this.__wrapped__; + if (value instanceof LazyWrapper) { + if (this.__actions__.length) { + value = new LazyWrapper(this); + } + return new LodashWrapper(value.reverse(), this.__chain__); + } + return this.thru(function(value) { + return value.reverse(); + }); + } + + /** + * Produces the result of coercing the unwrapped value to a string. + * + * @name toString + * @memberOf _ + * @category Chain + * @returns {string} Returns the coerced string value. + * @example + * + * _([1, 2, 3]).toString(); + * // => '1,2,3' + */ + function wrapperToString() { + return (this.value() + ''); + } + + /** + * Executes the chained sequence to extract the unwrapped value. + * + * @name value + * @memberOf _ + * @alias run, toJSON, valueOf + * @category Chain + * @returns {*} Returns the resolved unwrapped value. + * @example + * + * _([1, 2, 3]).value(); + * // => [1, 2, 3] + */ + function wrapperValue() { + return baseWrapperValue(this.__wrapped__, this.__actions__); + } + + /*------------------------------------------------------------------------*/ + + /** + * Creates an array of elements corresponding to the given keys, or indexes, + * of `collection`. Keys may be specified as individual arguments or as arrays + * of keys. + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {...(number|number[]|string|string[])} [props] The property names + * or indexes of elements to pick, specified individually or in arrays. + * @returns {Array} Returns the new array of picked elements. + * @example + * + * _.at(['a', 'b', 'c', 'd', 'e'], [0, 2, 4]); + * // => ['a', 'c', 'e'] + * + * _.at(['fred', 'barney', 'pebbles'], 0, 2); + * // => ['fred', 'pebbles'] + */ + function at(collection) { + var length = collection ? collection.length : 0; + if (isLength(length)) { + collection = toIterable(collection); + } + return baseAt(collection, baseFlatten(arguments, false, false, 1)); + } + + /** + * Checks if `value` is in `collection` using `SameValueZero` for equality + * comparisons. If `fromIndex` is negative, it is used as the offset from + * the end of `collection`. + * + * **Note:** `SameValueZero` comparisons are like strict equality comparisons, + * e.g. `===`, except that `NaN` matches `NaN`. See the + * [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero) + * for more details. + * + * @static + * @memberOf _ + * @alias contains, include + * @category Collection + * @param {Array|Object|string} collection The collection to search. + * @param {*} target The value to search for. + * @param {number} [fromIndex=0] The index to search from. + * @returns {boolean} Returns `true` if a matching element is found, else `false`. + * @example + * + * _.includes([1, 2, 3], 1); + * // => true + * + * _.includes([1, 2, 3], 1, 2); + * // => false + * + * _.includes({ 'user': 'fred', 'age': 40 }, 'fred'); + * // => true + * + * _.includes('pebbles', 'eb'); + * // => true + */ + function includes(collection, target, fromIndex) { + var length = collection ? collection.length : 0; + if (!isLength(length)) { + collection = values(collection); + length = collection.length; + } + if (!length) { + return false; + } + if (typeof fromIndex == 'number') { + fromIndex = fromIndex < 0 ? nativeMax(length + fromIndex, 0) : (fromIndex || 0); + } else { + fromIndex = 0; + } + return (typeof collection == 'string' || !isArray(collection) && isString(collection)) + ? (fromIndex < length && collection.indexOf(target, fromIndex) > -1) + : (getIndexOf(collection, target, fromIndex) > -1); + } + + /** + * Creates an object composed of keys generated from the results of running + * each element of `collection` through `iteratee`. The corresponding value + * of each key is the number of times the key was returned by `iteratee`. + * The `iteratee` is bound to `thisArg` and invoked with three arguments; + * (value, index|key, collection). + * + * If a property name is provided for `predicate` the created "_.property" + * style callback returns the property value of the given element. + * + * If value is also provided for `thisArg` the created "_.matchesProperty" + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `predicate` the created "_.matches" style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [iteratee=_.identity] The function invoked + * per iteration. If a property name or object is provided it is used to + * create a "_.property" or "_.matches" style callback respectively. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {Object} Returns the composed aggregate object. + * @example + * + * _.countBy([4.3, 6.1, 6.4], function(n) { return Math.floor(n); }); + * // => { '4': 1, '6': 2 } + * + * _.countBy([4.3, 6.1, 6.4], function(n) { return this.floor(n); }, Math); + * // => { '4': 1, '6': 2 } + * + * _.countBy(['one', 'two', 'three'], 'length'); + * // => { '3': 2, '5': 1 } + */ + var countBy = createAggregator(function(result, value, key) { + hasOwnProperty.call(result, key) ? ++result[key] : (result[key] = 1); + }); + + /** + * Checks if `predicate` returns truthy for **all** elements of `collection`. + * The predicate is bound to `thisArg` and invoked with three arguments; + * (value, index|key, collection). + * + * If a property name is provided for `predicate` the created "_.property" + * style callback returns the property value of the given element. + * + * If value is also provided for `thisArg` the created "_.matchesProperty" + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `predicate` the created "_.matches" style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @alias all + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [predicate=_.identity] The function invoked + * per iteration. If a property name or object is provided it is used to + * create a "_.property" or "_.matches" style callback respectively. + * @param {*} [thisArg] The `this` binding of `predicate`. + * @returns {boolean} Returns `true` if all elements pass the predicate check, + * else `false`. + * @example + * + * _.every([true, 1, null, 'yes']); + * // => false + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': false }, + * { 'user': 'fred', 'age': 40, 'active': false } + * ]; + * + * // using the "_.matches" callback shorthand + * _.every(users, { 'age': 36, 'active': false }); + * // => false + * + * // using the "_.matchesProperty" callback shorthand + * _.every(users, 'active', false); + * // => true + * + * // using the "_.property" callback shorthand + * _.every(users, 'active'); + * // => false + */ + function every(collection, predicate, thisArg) { + var func = isArray(collection) ? arrayEvery : baseEvery; + if (typeof predicate != 'function' || typeof thisArg != 'undefined') { + predicate = getCallback(predicate, thisArg, 3); + } + return func(collection, predicate); + } + + /** + * Iterates over elements of `collection`, returning an array of all elements + * `predicate` returns truthy for. The predicate is bound to `thisArg` and + * invoked with three arguments; (value, index|key, collection). + * + * If a property name is provided for `predicate` the created "_.property" + * style callback returns the property value of the given element. + * + * If value is also provided for `thisArg` the created "_.matchesProperty" + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `predicate` the created "_.matches" style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @alias select + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [predicate=_.identity] The function invoked + * per iteration. If a property name or object is provided it is used to + * create a "_.property" or "_.matches" style callback respectively. + * @param {*} [thisArg] The `this` binding of `predicate`. + * @returns {Array} Returns the new filtered array. + * @example + * + * var evens = _.filter([1, 2, 3, 4], function(n) { return n % 2 == 0; }); + * // => [2, 4] + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': true }, + * { 'user': 'fred', 'age': 40, 'active': false } + * ]; + * + * // using the "_.matches" callback shorthand + * _.pluck(_.filter(users, { 'age': 36, 'active': true }), 'user'); + * // => ['barney'] + * + * // using the "_.matchesProperty" callback shorthand + * _.pluck(_.filter(users, 'active', false), 'user'); + * // => ['fred'] + * + * // using the "_.property" callback shorthand + * _.pluck(_.filter(users, 'active'), 'user'); + * // => ['barney'] + */ + function filter(collection, predicate, thisArg) { + var func = isArray(collection) ? arrayFilter : baseFilter; + predicate = getCallback(predicate, thisArg, 3); + return func(collection, predicate); + } + + /** + * Iterates over elements of `collection`, returning the first element + * `predicate` returns truthy for. The predicate is bound to `thisArg` and + * invoked with three arguments; (value, index|key, collection). + * + * If a property name is provided for `predicate` the created "_.property" + * style callback returns the property value of the given element. + * + * If value is also provided for `thisArg` the created "_.matchesProperty" + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `predicate` the created "_.matches" style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @alias detect + * @category Collection + * @param {Array|Object|string} collection The collection to search. + * @param {Function|Object|string} [predicate=_.identity] The function invoked + * per iteration. If a property name or object is provided it is used to + * create a "_.property" or "_.matches" style callback respectively. + * @param {*} [thisArg] The `this` binding of `predicate`. + * @returns {*} Returns the matched element, else `undefined`. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': true }, + * { 'user': 'fred', 'age': 40, 'active': false }, + * { 'user': 'pebbles', 'age': 1, 'active': true } + * ]; + * + * _.result(_.find(users, function(chr) { return chr.age < 40; }), 'user'); + * // => 'barney' + * + * // using the "_.matches" callback shorthand + * _.result(_.find(users, { 'age': 1, 'active': true }), 'user'); + * // => 'pebbles' + * + * // using the "_.matchesProperty" callback shorthand + * _.result(_.find(users, 'active', false), 'user'); + * // => 'fred' + * + * // using the "_.property" callback shorthand + * _.result(_.find(users, 'active'), 'user'); + * // => 'barney' + */ + function find(collection, predicate, thisArg) { + if (isArray(collection)) { + var index = findIndex(collection, predicate, thisArg); + return index > -1 ? collection[index] : undefined; + } + predicate = getCallback(predicate, thisArg, 3); + return baseFind(collection, predicate, baseEach); + } + + /** + * This method is like `_.find` except that it iterates over elements of + * `collection` from right to left. + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to search. + * @param {Function|Object|string} [predicate=_.identity] The function invoked + * per iteration. If a property name or object is provided it is used to + * create a "_.property" or "_.matches" style callback respectively. + * @param {*} [thisArg] The `this` binding of `predicate`. + * @returns {*} Returns the matched element, else `undefined`. + * @example + * + * _.findLast([1, 2, 3, 4], function(n) { return n % 2 == 1; }); + * // => 3 + */ + function findLast(collection, predicate, thisArg) { + predicate = getCallback(predicate, thisArg, 3); + return baseFind(collection, predicate, baseEachRight); + } + + /** + * Performs a deep comparison between each element in `collection` and the + * source object, returning the first element that has equivalent property + * values. + * + * **Note:** This method supports comparing arrays, booleans, `Date` objects, + * numbers, `Object` objects, regexes, and strings. Objects are compared by + * their own, not inherited, enumerable properties. For comparing a single + * own or inherited property value see `_.matchesProperty`. + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to search. + * @param {Object} source The object of property values to match. + * @returns {*} Returns the matched element, else `undefined`. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': true }, + * { 'user': 'fred', 'age': 40, 'active': false } + * ]; + * + * _.result(_.findWhere(users, { 'age': 36, 'active': true }), 'user'); + * // => 'barney' + * + * _.result(_.findWhere(users, { 'age': 40, 'active': false }), 'user'); + * // => 'fred' + */ + function findWhere(collection, source) { + return find(collection, baseMatches(source)); + } + + /** + * Iterates over elements of `collection` invoking `iteratee` for each element. + * The `iteratee` is bound to `thisArg` and invoked with three arguments; + * (value, index|key, collection). Iterator functions may exit iteration early + * by explicitly returning `false`. + * + * **Note:** As with other "Collections" methods, objects with a `length` property + * are iterated like arrays. To avoid this behavior `_.forIn` or `_.forOwn` + * may be used for object iteration. + * + * @static + * @memberOf _ + * @alias each + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {Array|Object|string} Returns `collection`. + * @example + * + * _([1, 2, 3]).forEach(function(n) { console.log(n); }).value(); + * // => logs each value from left to right and returns the array + * + * _.forEach({ 'one': 1, 'two': 2, 'three': 3 }, function(n, key) { console.log(n, key); }); + * // => logs each value-key pair and returns the object (iteration order is not guaranteed) + */ + function forEach(collection, iteratee, thisArg) { + return (typeof iteratee == 'function' && typeof thisArg == 'undefined' && isArray(collection)) + ? arrayEach(collection, iteratee) + : baseEach(collection, bindCallback(iteratee, thisArg, 3)); + } + + /** + * This method is like `_.forEach` except that it iterates over elements of + * `collection` from right to left. + * + * @static + * @memberOf _ + * @alias eachRight + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {Array|Object|string} Returns `collection`. + * @example + * + * _([1, 2, 3]).forEachRight(function(n) { console.log(n); }).join(','); + * // => logs each value from right to left and returns the array + */ + function forEachRight(collection, iteratee, thisArg) { + return (typeof iteratee == 'function' && typeof thisArg == 'undefined' && isArray(collection)) + ? arrayEachRight(collection, iteratee) + : baseEachRight(collection, bindCallback(iteratee, thisArg, 3)); + } + + /** + * Creates an object composed of keys generated from the results of running + * each element of `collection` through `iteratee`. The corresponding value + * of each key is an array of the elements responsible for generating the key. + * The `iteratee` is bound to `thisArg` and invoked with three arguments; + * (value, index|key, collection). + * + * If a property name is provided for `predicate` the created "_.property" + * style callback returns the property value of the given element. + * + * If value is also provided for `thisArg` the created "_.matchesProperty" + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `predicate` the created "_.matches" style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [iteratee=_.identity] The function invoked + * per iteration. If a property name or object is provided it is used to + * create a "_.property" or "_.matches" style callback respectively. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {Object} Returns the composed aggregate object. + * @example + * + * _.groupBy([4.2, 6.1, 6.4], function(n) { return Math.floor(n); }); + * // => { '4': [4.2], '6': [6.1, 6.4] } + * + * _.groupBy([4.2, 6.1, 6.4], function(n) { return this.floor(n); }, Math); + * // => { '4': [4.2], '6': [6.1, 6.4] } + * + * // using the "_.property" callback shorthand + * _.groupBy(['one', 'two', 'three'], 'length'); + * // => { '3': ['one', 'two'], '5': ['three'] } + */ + var groupBy = createAggregator(function(result, value, key) { + if (hasOwnProperty.call(result, key)) { + result[key].push(value); + } else { + result[key] = [value]; + } + }); + + /** + * Creates an object composed of keys generated from the results of running + * each element of `collection` through `iteratee`. The corresponding value + * of each key is the last element responsible for generating the key. The + * iteratee function is bound to `thisArg` and invoked with three arguments; + * (value, index|key, collection). + * + * If a property name is provided for `predicate` the created "_.property" + * style callback returns the property value of the given element. + * + * If value is also provided for `thisArg` the created "_.matchesProperty" + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `predicate` the created "_.matches" style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [iteratee=_.identity] The function invoked + * per iteration. If a property name or object is provided it is used to + * create a "_.property" or "_.matches" style callback respectively. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {Object} Returns the composed aggregate object. + * @example + * + * var keyData = [ + * { 'dir': 'left', 'code': 97 }, + * { 'dir': 'right', 'code': 100 } + * ]; + * + * _.indexBy(keyData, 'dir'); + * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } } + * + * _.indexBy(keyData, function(object) { return String.fromCharCode(object.code); }); + * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } + * + * _.indexBy(keyData, function(object) { return this.fromCharCode(object.code); }, String); + * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } + */ + var indexBy = createAggregator(function(result, value, key) { + result[key] = value; + }); + + /** + * Invokes the method named by `methodName` on each element in `collection`, + * returning an array of the results of each invoked method. Any additional + * arguments are provided to each invoked method. If `methodName` is a function + * it is invoked for, and `this` bound to, each element in `collection`. + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|string} methodName The name of the method to invoke or + * the function invoked per iteration. + * @param {...*} [args] The arguments to invoke the method with. + * @returns {Array} Returns the array of results. + * @example + * + * _.invoke([[5, 1, 7], [3, 2, 1]], 'sort'); + * // => [[1, 5, 7], [1, 2, 3]] + * + * _.invoke([123, 456], String.prototype.split, ''); + * // => [['1', '2', '3'], ['4', '5', '6']] + */ + function invoke(collection, methodName) { + return baseInvoke(collection, methodName, baseSlice(arguments, 2)); + } + + /** + * Creates an array of values by running each element in `collection` through + * `iteratee`. The `iteratee` is bound to `thisArg` and invoked with three + * arguments; (value, index|key, collection). + * + * If a property name is provided for `predicate` the created "_.property" + * style callback returns the property value of the given element. + * + * If value is also provided for `thisArg` the created "_.matchesProperty" + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `predicate` the created "_.matches" style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * Many lodash methods are guarded to work as interatees for methods like + * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`. + * + * The guarded methods are: + * `ary`, `callback`, `chunk`, `clone`, `create`, `curry`, `curryRight`, `drop`, + * `dropRight`, `fill`, `flatten`, `invert`, `max`, `min`, `parseInt`, `slice`, + * `sortBy`, `take`, `takeRight`, `template`, `trim`, `trimLeft`, `trimRight`, + * `trunc`, `random`, `range`, `sample`, `uniq`, and `words` + * + * @static + * @memberOf _ + * @alias collect + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [iteratee=_.identity] The function invoked + * per iteration. If a property name or object is provided it is used to + * create a "_.property" or "_.matches" style callback respectively. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {Array} Returns the new mapped array. + * @example + * + * _.map([1, 2, 3], function(n) { return n * 3; }); + * // => [3, 6, 9] + * + * _.map({ 'one': 1, 'two': 2, 'three': 3 }, function(n) { return n * 3; }); + * // => [3, 6, 9] (iteration order is not guaranteed) + * + * var users = [ + * { 'user': 'barney' }, + * { 'user': 'fred' } + * ]; + * + * // using the "_.property" callback shorthand + * _.map(users, 'user'); + * // => ['barney', 'fred'] + */ + function map(collection, iteratee, thisArg) { + var func = isArray(collection) ? arrayMap : baseMap; + iteratee = getCallback(iteratee, thisArg, 3); + return func(collection, iteratee); + } + + /** + * Gets the maximum value of `collection`. If `collection` is empty or falsey + * `-Infinity` is returned. If an iteratee function is provided it is invoked + * for each value in `collection` to generate the criterion by which the value + * is ranked. The `iteratee` is bound to `thisArg` and invoked with three + * arguments; (value, index, collection). + * + * If a property name is provided for `predicate` the created "_.property" + * style callback returns the property value of the given element. + * + * If value is also provided for `thisArg` the created "_.matchesProperty" + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `predicate` the created "_.matches" style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [iteratee] The function invoked per iteration. + * If a property name or object is provided it is used to create a "_.property" + * or "_.matches" style callback respectively. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {*} Returns the maximum value. + * @example + * + * _.max([4, 2, 8, 6]); + * // => 8 + * + * _.max([]); + * // => -Infinity + * + * var users = [ + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 40 } + * ]; + * + * _.max(users, function(chr) { return chr.age; }); + * // => { 'user': 'fred', 'age': 40 }; + * + * // using the "_.property" callback shorthand + * _.max(users, 'age'); + * // => { 'user': 'fred', 'age': 40 }; + */ + var max = createExtremum(arrayMax); + + /** + * Gets the minimum value of `collection`. If `collection` is empty or falsey + * `Infinity` is returned. If an iteratee function is provided it is invoked + * for each value in `collection` to generate the criterion by which the value + * is ranked. The `iteratee` is bound to `thisArg` and invoked with three + * arguments; (value, index, collection). + * + * If a property name is provided for `predicate` the created "_.property" + * style callback returns the property value of the given element. + * + * If value is also provided for `thisArg` the created "_.matchesProperty" + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `predicate` the created "_.matches" style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [iteratee] The function invoked per iteration. + * If a property name or object is provided it is used to create a "_.property" + * or "_.matches" style callback respectively. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {*} Returns the minimum value. + * @example + * + * _.min([4, 2, 8, 6]); + * // => 2 + * + * _.min([]); + * // => Infinity + * + * var users = [ + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 40 } + * ]; + * + * _.min(users, function(chr) { return chr.age; }); + * // => { 'user': 'barney', 'age': 36 }; + * + * // using the "_.property" callback shorthand + * _.min(users, 'age'); + * // => { 'user': 'barney', 'age': 36 }; + */ + var min = createExtremum(arrayMin, true); + + /** + * Creates an array of elements split into two groups, the first of which + * contains elements `predicate` returns truthy for, while the second of which + * contains elements `predicate` returns falsey for. The predicate is bound + * to `thisArg` and invoked with three arguments; (value, index|key, collection). + * + * If a property name is provided for `predicate` the created "_.property" + * style callback returns the property value of the given element. + * + * If value is also provided for `thisArg` the created "_.matchesProperty" + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `predicate` the created "_.matches" style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [predicate=_.identity] The function invoked + * per iteration. If a property name or object is provided it is used to + * create a "_.property" or "_.matches" style callback respectively. + * @param {*} [thisArg] The `this` binding of `predicate`. + * @returns {Array} Returns the array of grouped elements. + * @example + * + * _.partition([1, 2, 3], function(n) { return n % 2; }); + * // => [[1, 3], [2]] + * + * _.partition([1.2, 2.3, 3.4], function(n) { return this.floor(n) % 2; }, Math); + * // => [[1, 3], [2]] + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': false }, + * { 'user': 'fred', 'age': 40, 'active': true }, + * { 'user': 'pebbles', 'age': 1, 'active': false } + * ]; + * + * var mapper = function(array) { return _.pluck(array, 'user'); }; + * + * // using the "_.matches" callback shorthand + * _.map(_.partition(users, { 'age': 1, 'active': false }), mapper); + * // => [['pebbles'], ['barney', 'fred']] + * + * // using the "_.matchesProperty" callback shorthand + * _.map(_.partition(users, 'active', false), mapper); + * // => [['barney', 'pebbles'], ['fred']] + * + * // using the "_.property" callback shorthand + * _.map(_.partition(users, 'active'), mapper); + * // => [['fred'], ['barney', 'pebbles']] + */ + var partition = createAggregator(function(result, value, key) { + result[key ? 0 : 1].push(value); + }, function() { return [[], []]; }); + + /** + * Gets the value of `key` from all elements in `collection`. + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {string} key The key of the property to pluck. + * @returns {Array} Returns the property values. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 40 } + * ]; + * + * _.pluck(users, 'user'); + * // => ['barney', 'fred'] + * + * var userIndex = _.indexBy(users, 'user'); + * _.pluck(userIndex, 'age'); + * // => [36, 40] (iteration order is not guaranteed) + */ + function pluck(collection, key) { + return map(collection, baseProperty(key)); + } + + /** + * Reduces `collection` to a value which is the accumulated result of running + * each element in `collection` through `iteratee`, where each successive + * invocation is supplied the return value of the previous. If `accumulator` + * is not provided the first element of `collection` is used as the initial + * value. The `iteratee` is bound to `thisArg`and invoked with four arguments; + * (accumulator, value, index|key, collection). + * + * Many lodash methods are guarded to work as interatees for methods like + * `_.reduce`, `_.reduceRight`, and `_.transform`. + * + * The guarded methods are: + * `assign`, `defaults`, `merge`, and `sortAllBy` + * + * @static + * @memberOf _ + * @alias foldl, inject + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {*} Returns the accumulated value. + * @example + * + * var sum = _.reduce([1, 2, 3], function(sum, n) { return sum + n; }); + * // => 6 + * + * var mapped = _.reduce({ 'a': 1, 'b': 2, 'c': 3 }, function(result, n, key) { + * result[key] = n * 3; + * return result; + * }, {}); + * // => { 'a': 3, 'b': 6, 'c': 9 } (iteration order is not guaranteed) + */ + function reduce(collection, iteratee, accumulator, thisArg) { + var func = isArray(collection) ? arrayReduce : baseReduce; + return func(collection, getCallback(iteratee, thisArg, 4), accumulator, arguments.length < 3, baseEach); + } + + /** + * This method is like `_.reduce` except that it iterates over elements of + * `collection` from right to left. + * + * @static + * @memberOf _ + * @alias foldr + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {*} Returns the accumulated value. + * @example + * + * var array = [[0, 1], [2, 3], [4, 5]]; + * _.reduceRight(array, function(flattened, other) { return flattened.concat(other); }, []); + * // => [4, 5, 2, 3, 0, 1] + */ + function reduceRight(collection, iteratee, accumulator, thisArg) { + var func = isArray(collection) ? arrayReduceRight : baseReduce; + return func(collection, getCallback(iteratee, thisArg, 4), accumulator, arguments.length < 3, baseEachRight); + } + + /** + * The opposite of `_.filter`; this method returns the elements of `collection` + * that `predicate` does **not** return truthy for. + * + * If a property name is provided for `predicate` the created "_.property" + * style callback returns the property value of the given element. + * + * If value is also provided for `thisArg` the created "_.matchesProperty" + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `predicate` the created "_.matches" style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [predicate=_.identity] The function invoked + * per iteration. If a property name or object is provided it is used to + * create a "_.property" or "_.matches" style callback respectively. + * @param {*} [thisArg] The `this` binding of `predicate`. + * @returns {Array} Returns the new filtered array. + * @example + * + * var odds = _.reject([1, 2, 3, 4], function(n) { return n % 2 == 0; }); + * // => [1, 3] + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': false }, + * { 'user': 'fred', 'age': 40, 'active': true } + * ]; + * + * // using the "_.matches" callback shorthand + * _.pluck(_.reject(users, { 'age': 40, 'active': true }), 'user'); + * // => ['barney'] + * + * // using the "_.matchesProperty" callback shorthand + * _.pluck(_.reject(users, 'active', false), 'user'); + * // => ['fred'] + * + * // using the "_.property" callback shorthand + * _.pluck(_.reject(users, 'active'), 'user'); + * // => ['barney'] + */ + function reject(collection, predicate, thisArg) { + var func = isArray(collection) ? arrayFilter : baseFilter; + predicate = getCallback(predicate, thisArg, 3); + return func(collection, function(value, index, collection) { + return !predicate(value, index, collection); + }); + } + + /** + * Gets a random element or `n` random elements from a collection. + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to sample. + * @param {number} [n] The number of elements to sample. + * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. + * @returns {*} Returns the random sample(s). + * @example + * + * _.sample([1, 2, 3, 4]); + * // => 2 + * + * _.sample([1, 2, 3, 4], 2); + * // => [3, 1] + */ + function sample(collection, n, guard) { + if (guard ? isIterateeCall(collection, n, guard) : n == null) { + collection = toIterable(collection); + var length = collection.length; + return length > 0 ? collection[baseRandom(0, length - 1)] : undefined; + } + var result = shuffle(collection); + result.length = nativeMin(n < 0 ? 0 : (+n || 0), result.length); + return result; + } + + /** + * Creates an array of shuffled values, using a version of the Fisher-Yates + * shuffle. See [Wikipedia](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle) + * for more details. + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to shuffle. + * @returns {Array} Returns the new shuffled array. + * @example + * + * _.shuffle([1, 2, 3, 4]); + * // => [4, 1, 3, 2] + */ + function shuffle(collection) { + collection = toIterable(collection); + + var index = -1, + length = collection.length, + result = Array(length); + + while (++index < length) { + var rand = baseRandom(0, index); + if (index != rand) { + result[index] = result[rand]; + } + result[rand] = collection[index]; + } + return result; + } + + /** + * Gets the size of `collection` by returning `collection.length` for + * array-like values or the number of own enumerable properties for objects. + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to inspect. + * @returns {number} Returns the size of `collection`. + * @example + * + * _.size([1, 2]); + * // => 2 + * + * _.size({ 'one': 1, 'two': 2, 'three': 3 }); + * // => 3 + * + * _.size('pebbles'); + * // => 7 + */ + function size(collection) { + var length = collection ? collection.length : 0; + return isLength(length) ? length : keys(collection).length; + } + + /** + * Checks if `predicate` returns truthy for **any** element of `collection`. + * The function returns as soon as it finds a passing value and does not iterate + * over the entire collection. The predicate is bound to `thisArg` and invoked + * with three arguments; (value, index|key, collection). + * + * If a property name is provided for `predicate` the created "_.property" + * style callback returns the property value of the given element. + * + * If value is also provided for `thisArg` the created "_.matchesProperty" + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `predicate` the created "_.matches" style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @alias any + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [predicate=_.identity] The function invoked + * per iteration. If a property name or object is provided it is used to + * create a "_.property" or "_.matches" style callback respectively. + * @param {*} [thisArg] The `this` binding of `predicate`. + * @returns {boolean} Returns `true` if any element passes the predicate check, + * else `false`. + * @example + * + * _.some([null, 0, 'yes', false], Boolean); + * // => true + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': false }, + * { 'user': 'fred', 'age': 40, 'active': true } + * ]; + * + * // using the "_.matches" callback shorthand + * _.some(users, { 'age': 1, 'active': true }); + * // => false + * + * // using the "_.matchesProperty" callback shorthand + * _.some(users, 'active', false); + * // => true + * + * // using the "_.property" callback shorthand + * _.some(users, 'active'); + * // => true + */ + function some(collection, predicate, thisArg) { + var func = isArray(collection) ? arraySome : baseSome; + if (typeof predicate != 'function' || typeof thisArg != 'undefined') { + predicate = getCallback(predicate, thisArg, 3); + } + return func(collection, predicate); + } + + /** + * Creates an array of elements, sorted in ascending order by the results of + * running each element in a collection through `iteratee`. This method performs + * a stable sort, that is, it preserves the original sort order of equal elements. + * The `iteratee` is bound to `thisArg` and invoked with three arguments; + * (value, index|key, collection). + * + * If a property name is provided for `predicate` the created "_.property" + * style callback returns the property value of the given element. + * + * If value is also provided for `thisArg` the created "_.matchesProperty" + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `predicate` the created "_.matches" style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Array|Function|Object|string} [iteratee=_.identity] The function + * invoked per iteration. If a property name or an object is provided it is + * used to create a "_.property" or "_.matches" style callback respectively. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {Array} Returns the new sorted array. + * @example + * + * _.sortBy([1, 2, 3], function(n) { return Math.sin(n); }); + * // => [3, 1, 2] + * + * _.sortBy([1, 2, 3], function(n) { return this.sin(n); }, Math); + * // => [3, 1, 2] + * + * var users = [ + * { 'user': 'fred' }, + * { 'user': 'pebbles' }, + * { 'user': 'barney' } + * ]; + * + * // using the "_.property" callback shorthand + * _.pluck(_.sortBy(users, 'user'), 'user'); + * // => ['barney', 'fred', 'pebbles'] + */ + function sortBy(collection, iteratee, thisArg) { + var index = -1, + length = collection ? collection.length : 0, + result = isLength(length) ? Array(length) : []; + + if (thisArg && isIterateeCall(collection, iteratee, thisArg)) { + iteratee = null; + } + iteratee = getCallback(iteratee, thisArg, 3); + baseEach(collection, function(value, key, collection) { + result[++index] = { 'criteria': iteratee(value, key, collection), 'index': index, 'value': value }; + }); + return baseSortBy(result, compareAscending); + } + + /** + * This method is like `_.sortBy` except that it sorts by property names + * instead of an iteratee function. + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {...(string|string[])} props The property names to sort by, + * specified as individual property names or arrays of property names. + * @returns {Array} Returns the new sorted array. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 40 }, + * { 'user': 'barney', 'age': 26 }, + * { 'user': 'fred', 'age': 30 } + * ]; + * + * _.map(_.sortByAll(users, ['user', 'age']), _.values); + * // => [['barney', 26], ['barney', 36], ['fred', 30], ['fred', 40]] + */ + function sortByAll(collection) { + var args = arguments; + if (args.length > 3 && isIterateeCall(args[1], args[2], args[3])) { + args = [collection, args[1]]; + } + var index = -1, + length = collection ? collection.length : 0, + props = baseFlatten(args, false, false, 1), + result = isLength(length) ? Array(length) : []; + + baseEach(collection, function(value) { + var length = props.length, + criteria = Array(length); + + while (length--) { + criteria[length] = value == null ? undefined : value[props[length]]; + } + result[++index] = { 'criteria': criteria, 'index': index, 'value': value }; + }); + return baseSortBy(result, compareMultipleAscending); + } + + /** + * Performs a deep comparison between each element in `collection` and the + * source object, returning an array of all elements that have equivalent + * property values. + * + * **Note:** This method supports comparing arrays, booleans, `Date` objects, + * numbers, `Object` objects, regexes, and strings. Objects are compared by + * their own, not inherited, enumerable properties. For comparing a single + * own or inherited property value see `_.matchesProperty`. + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to search. + * @param {Object} source The object of property values to match. + * @returns {Array} Returns the new filtered array. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': false, 'pets': ['hoppy'] }, + * { 'user': 'fred', 'age': 40, 'active': true, 'pets': ['baby puss', 'dino'] } + * ]; + * + * _.pluck(_.where(users, { 'age': 36, 'active': false }), 'user'); + * // => ['barney'] + * + * _.pluck(_.where(users, { 'pets': ['dino'] }), 'user'); + * // => ['fred'] + */ + function where(collection, source) { + return filter(collection, baseMatches(source)); + } + + /*------------------------------------------------------------------------*/ + + /** + * Gets the number of milliseconds that have elapsed since the Unix epoch + * (1 January 1970 00:00:00 UTC). + * + * @static + * @memberOf _ + * @category Date + * @example + * + * _.defer(function(stamp) { console.log(_.now() - stamp); }, _.now()); + * // => logs the number of milliseconds it took for the deferred function to be invoked + */ + var now = nativeNow || function() { + return new Date().getTime(); + }; + + /*------------------------------------------------------------------------*/ + + /** + * The opposite of `_.before`; this method creates a function that invokes + * `func` once it is called `n` or more times. + * + * @static + * @memberOf _ + * @category Function + * @param {number} n The number of calls before `func` is invoked. + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * var saves = ['profile', 'settings']; + * + * var done = _.after(saves.length, function() { + * console.log('done saving!'); + * }); + * + * _.forEach(saves, function(type) { + * asyncSave({ 'type': type, 'complete': done }); + * }); + * // => logs 'done saving!' after the two async saves have completed + */ + function after(n, func) { + if (typeof func != 'function') { + if (typeof n == 'function') { + var temp = n; + n = func; + func = temp; + } else { + throw new TypeError(FUNC_ERROR_TEXT); + } + } + n = nativeIsFinite(n = +n) ? n : 0; + return function() { + if (--n < 1) { + return func.apply(this, arguments); + } + }; + } + + /** + * Creates a function that accepts up to `n` arguments ignoring any + * additional arguments. + * + * @static + * @memberOf _ + * @category Function + * @param {Function} func The function to cap arguments for. + * @param {number} [n=func.length] The arity cap. + * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. + * @returns {Function} Returns the new function. + * @example + * + * _.map(['6', '8', '10'], _.ary(parseInt, 1)); + * // => [6, 8, 10] + */ + function ary(func, n, guard) { + if (guard && isIterateeCall(func, n, guard)) { + n = null; + } + n = (func && n == null) ? func.length : nativeMax(+n || 0, 0); + return createWrapper(func, ARY_FLAG, null, null, null, null, n); + } + + /** + * Creates a function that invokes `func`, with the `this` binding and arguments + * of the created function, while it is called less than `n` times. Subsequent + * calls to the created function return the result of the last `func` invocation. + * + * @static + * @memberOf _ + * @category Function + * @param {number} n The number of calls at which `func` is no longer invoked. + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * jQuery('#add').on('click', _.before(5, addContactToList)); + * // => allows adding up to 4 contacts to the list + */ + function before(n, func) { + var result; + if (typeof func != 'function') { + if (typeof n == 'function') { + var temp = n; + n = func; + func = temp; + } else { + throw new TypeError(FUNC_ERROR_TEXT); + } + } + return function() { + if (--n > 0) { + result = func.apply(this, arguments); + } else { + func = null; + } + return result; + }; + } + + /** + * Creates a function that invokes `func` with the `this` binding of `thisArg` + * and prepends any additional `_.bind` arguments to those provided to the + * bound function. + * + * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds, + * may be used as a placeholder for partially applied arguments. + * + * **Note:** Unlike native `Function#bind` this method does not set the `length` + * property of bound functions. + * + * @static + * @memberOf _ + * @category Function + * @param {Function} func The function to bind. + * @param {*} thisArg The `this` binding of `func`. + * @param {...*} [args] The arguments to be partially applied. + * @returns {Function} Returns the new bound function. + * @example + * + * var greet = function(greeting, punctuation) { + * return greeting + ' ' + this.user + punctuation; + * }; + * + * var object = { 'user': 'fred' }; + * + * var bound = _.bind(greet, object, 'hi'); + * bound('!'); + * // => 'hi fred!' + * + * // using placeholders + * var bound = _.bind(greet, object, _, '!'); + * bound('hi'); + * // => 'hi fred!' + */ + function bind(func, thisArg) { + var bitmask = BIND_FLAG; + if (arguments.length > 2) { + var partials = baseSlice(arguments, 2), + holders = replaceHolders(partials, bind.placeholder); + + bitmask |= PARTIAL_FLAG; + } + return createWrapper(func, bitmask, thisArg, partials, holders); + } + + /** + * Binds methods of an object to the object itself, overwriting the existing + * method. Method names may be specified as individual arguments or as arrays + * of method names. If no method names are provided all enumerable function + * properties, own and inherited, of `object` are bound. + * + * **Note:** This method does not set the `length` property of bound functions. + * + * @static + * @memberOf _ + * @category Function + * @param {Object} object The object to bind and assign the bound methods to. + * @param {...(string|string[])} [methodNames] The object method names to bind, + * specified as individual method names or arrays of method names. + * @returns {Object} Returns `object`. + * @example + * + * var view = { + * 'label': 'docs', + * 'onClick': function() { console.log('clicked ' + this.label); } + * }; + * + * _.bindAll(view); + * jQuery('#docs').on('click', view.onClick); + * // => logs 'clicked docs' when the element is clicked + */ + function bindAll(object) { + return baseBindAll(object, + arguments.length > 1 + ? baseFlatten(arguments, false, false, 1) + : functions(object) + ); + } + + /** + * Creates a function that invokes the method at `object[key]` and prepends + * any additional `_.bindKey` arguments to those provided to the bound function. + * + * This method differs from `_.bind` by allowing bound functions to reference + * methods that may be redefined or don't yet exist. + * See [Peter Michaux's article](http://michaux.ca/articles/lazy-function-definition-pattern) + * for more details. + * + * The `_.bindKey.placeholder` value, which defaults to `_` in monolithic + * builds, may be used as a placeholder for partially applied arguments. + * + * @static + * @memberOf _ + * @category Function + * @param {Object} object The object the method belongs to. + * @param {string} key The key of the method. + * @param {...*} [args] The arguments to be partially applied. + * @returns {Function} Returns the new bound function. + * @example + * + * var object = { + * 'user': 'fred', + * 'greet': function(greeting, punctuation) { + * return greeting + ' ' + this.user + punctuation; + * } + * }; + * + * var bound = _.bindKey(object, 'greet', 'hi'); + * bound('!'); + * // => 'hi fred!' + * + * object.greet = function(greeting, punctuation) { + * return greeting + 'ya ' + this.user + punctuation; + * }; + * + * bound('!'); + * // => 'hiya fred!' + * + * // using placeholders + * var bound = _.bindKey(object, 'greet', _, '!'); + * bound('hi'); + * // => 'hiya fred!' + */ + function bindKey(object, key) { + var bitmask = BIND_FLAG | BIND_KEY_FLAG; + if (arguments.length > 2) { + var partials = baseSlice(arguments, 2), + holders = replaceHolders(partials, bindKey.placeholder); + + bitmask |= PARTIAL_FLAG; + } + return createWrapper(key, bitmask, object, partials, holders); + } + + /** + * Creates a function that accepts one or more arguments of `func` that when + * called either invokes `func` returning its result, if all `func` arguments + * have been provided, or returns a function that accepts one or more of the + * remaining `func` arguments, and so on. The arity of `func` may be specified + * if `func.length` is not sufficient. + * + * The `_.curry.placeholder` value, which defaults to `_` in monolithic builds, + * may be used as a placeholder for provided arguments. + * + * **Note:** This method does not set the `length` property of curried functions. + * + * @static + * @memberOf _ + * @category Function + * @param {Function} func The function to curry. + * @param {number} [arity=func.length] The arity of `func`. + * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. + * @returns {Function} Returns the new curried function. + * @example + * + * var abc = function(a, b, c) { + * return [a, b, c]; + * }; + * + * var curried = _.curry(abc); + * + * curried(1)(2)(3); + * // => [1, 2, 3] + * + * curried(1, 2)(3); + * // => [1, 2, 3] + * + * curried(1, 2, 3); + * // => [1, 2, 3] + * + * // using placeholders + * curried(1)(_, 3)(2); + * // => [1, 2, 3] + */ + function curry(func, arity, guard) { + if (guard && isIterateeCall(func, arity, guard)) { + arity = null; + } + var result = createWrapper(func, CURRY_FLAG, null, null, null, null, null, arity); + result.placeholder = curry.placeholder; + return result; + } + + /** + * This method is like `_.curry` except that arguments are applied to `func` + * in the manner of `_.partialRight` instead of `_.partial`. + * + * The `_.curryRight.placeholder` value, which defaults to `_` in monolithic + * builds, may be used as a placeholder for provided arguments. + * + * **Note:** This method does not set the `length` property of curried functions. + * + * @static + * @memberOf _ + * @category Function + * @param {Function} func The function to curry. + * @param {number} [arity=func.length] The arity of `func`. + * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. + * @returns {Function} Returns the new curried function. + * @example + * + * var abc = function(a, b, c) { + * return [a, b, c]; + * }; + * + * var curried = _.curryRight(abc); + * + * curried(3)(2)(1); + * // => [1, 2, 3] + * + * curried(2, 3)(1); + * // => [1, 2, 3] + * + * curried(1, 2, 3); + * // => [1, 2, 3] + * + * // using placeholders + * curried(3)(1, _)(2); + * // => [1, 2, 3] + */ + function curryRight(func, arity, guard) { + if (guard && isIterateeCall(func, arity, guard)) { + arity = null; + } + var result = createWrapper(func, CURRY_RIGHT_FLAG, null, null, null, null, null, arity); + result.placeholder = curryRight.placeholder; + return result; + } + + /** + * Creates a function that delays invoking `func` until after `wait` milliseconds + * have elapsed since the last time it was invoked. The created function comes + * with a `cancel` method to cancel delayed invocations. Provide an options + * object to indicate that `func` should be invoked on the leading and/or + * trailing edge of the `wait` timeout. Subsequent calls to the debounced + * function return the result of the last `func` invocation. + * + * **Note:** If `leading` and `trailing` options are `true`, `func` is invoked + * on the trailing edge of the timeout only if the the debounced function is + * invoked more than once during the `wait` timeout. + * + * See [David Corbacho's article](http://drupalmotion.com/article/debounce-and-throttle-visual-explanation) + * for details over the differences between `_.debounce` and `_.throttle`. + * + * @static + * @memberOf _ + * @category Function + * @param {Function} func The function to debounce. + * @param {number} wait The number of milliseconds to delay. + * @param {Object} [options] The options object. + * @param {boolean} [options.leading=false] Specify invoking on the leading + * edge of the timeout. + * @param {number} [options.maxWait] The maximum time `func` is allowed to be + * delayed before it is invoked. + * @param {boolean} [options.trailing=true] Specify invoking on the trailing + * edge of the timeout. + * @returns {Function} Returns the new debounced function. + * @example + * + * // avoid costly calculations while the window size is in flux + * jQuery(window).on('resize', _.debounce(calculateLayout, 150)); + * + * // invoke `sendMail` when the click event is fired, debouncing subsequent calls + * jQuery('#postbox').on('click', _.debounce(sendMail, 300, { + * 'leading': true, + * 'trailing': false + * })); + * + * // ensure `batchLog` is invoked once after 1 second of debounced calls + * var source = new EventSource('/stream'); + * jQuery(source).on('message', _.debounce(batchLog, 250, { + * 'maxWait': 1000 + * })); + * + * // cancel a debounced call + * var todoChanges = _.debounce(batchLog, 1000); + * Object.observe(models.todo, todoChanges); + * + * Object.observe(models, function(changes) { + * if (_.find(changes, { 'user': 'todo', 'type': 'delete'})) { + * todoChanges.cancel(); + * } + * }, ['delete']); + * + * // ...at some point `models.todo` is changed + * models.todo.completed = true; + * + * // ...before 1 second has passed `models.todo` is deleted + * // which cancels the debounced `todoChanges` call + * delete models.todo; + */ + function debounce(func, wait, options) { + var args, + maxTimeoutId, + result, + stamp, + thisArg, + timeoutId, + trailingCall, + lastCalled = 0, + maxWait = false, + trailing = true; + + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + wait = wait < 0 ? 0 : wait; + if (options === true) { + var leading = true; + trailing = false; + } else if (isObject(options)) { + leading = options.leading; + maxWait = 'maxWait' in options && nativeMax(+options.maxWait || 0, wait); + trailing = 'trailing' in options ? options.trailing : trailing; + } + + function cancel() { + if (timeoutId) { + clearTimeout(timeoutId); + } + if (maxTimeoutId) { + clearTimeout(maxTimeoutId); + } + maxTimeoutId = timeoutId = trailingCall = undefined; + } + + function delayed() { + var remaining = wait - (now() - stamp); + if (remaining <= 0 || remaining > wait) { + if (maxTimeoutId) { + clearTimeout(maxTimeoutId); + } + var isCalled = trailingCall; + maxTimeoutId = timeoutId = trailingCall = undefined; + if (isCalled) { + lastCalled = now(); + result = func.apply(thisArg, args); + if (!timeoutId && !maxTimeoutId) { + args = thisArg = null; + } + } + } else { + timeoutId = setTimeout(delayed, remaining); + } + } + + function maxDelayed() { + if (timeoutId) { + clearTimeout(timeoutId); + } + maxTimeoutId = timeoutId = trailingCall = undefined; + if (trailing || (maxWait !== wait)) { + lastCalled = now(); + result = func.apply(thisArg, args); + if (!timeoutId && !maxTimeoutId) { + args = thisArg = null; + } + } + } + + function debounced() { + args = arguments; + stamp = now(); + thisArg = this; + trailingCall = trailing && (timeoutId || !leading); + + if (maxWait === false) { + var leadingCall = leading && !timeoutId; + } else { + if (!maxTimeoutId && !leading) { + lastCalled = stamp; + } + var remaining = maxWait - (stamp - lastCalled), + isCalled = remaining <= 0 || remaining > maxWait; + + if (isCalled) { + if (maxTimeoutId) { + maxTimeoutId = clearTimeout(maxTimeoutId); + } + lastCalled = stamp; + result = func.apply(thisArg, args); + } + else if (!maxTimeoutId) { + maxTimeoutId = setTimeout(maxDelayed, remaining); + } + } + if (isCalled && timeoutId) { + timeoutId = clearTimeout(timeoutId); + } + else if (!timeoutId && wait !== maxWait) { + timeoutId = setTimeout(delayed, wait); + } + if (leadingCall) { + isCalled = true; + result = func.apply(thisArg, args); + } + if (isCalled && !timeoutId && !maxTimeoutId) { + args = thisArg = null; + } + return result; + } + debounced.cancel = cancel; + return debounced; + } + + /** + * Defers invoking the `func` until the current call stack has cleared. Any + * additional arguments are provided to `func` when it is invoked. + * + * @static + * @memberOf _ + * @category Function + * @param {Function} func The function to defer. + * @param {...*} [args] The arguments to invoke the function with. + * @returns {number} Returns the timer id. + * @example + * + * _.defer(function(text) { console.log(text); }, 'deferred'); + * // logs 'deferred' after one or more milliseconds + */ + function defer(func) { + return baseDelay(func, 1, arguments, 1); + } + + /** + * Invokes `func` after `wait` milliseconds. Any additional arguments are + * provided to `func` when it is invoked. + * + * @static + * @memberOf _ + * @category Function + * @param {Function} func The function to delay. + * @param {number} wait The number of milliseconds to delay invocation. + * @param {...*} [args] The arguments to invoke the function with. + * @returns {number} Returns the timer id. + * @example + * + * _.delay(function(text) { console.log(text); }, 1000, 'later'); + * // => logs 'later' after one second + */ + function delay(func, wait) { + return baseDelay(func, wait, arguments, 2); + } + + /** + * Creates a function that returns the result of invoking the provided + * functions with the `this` binding of the created function, where each + * successive invocation is supplied the return value of the previous. + * + * @static + * @memberOf _ + * @category Function + * @param {...Function} [funcs] Functions to invoke. + * @returns {Function} Returns the new function. + * @example + * + * function add(x, y) { + * return x + y; + * } + * + * function square(n) { + * return n * n; + * } + * + * var addSquare = _.flow(add, square); + * addSquare(1, 2); + * // => 9 + */ + function flow() { + var funcs = arguments, + length = funcs.length; + + if (!length) { + return function() { return arguments[0]; }; + } + if (!arrayEvery(funcs, isFunction)) { + throw new TypeError(FUNC_ERROR_TEXT); + } + return function() { + var index = 0, + result = funcs[index].apply(this, arguments); + + while (++index < length) { + result = funcs[index].call(this, result); + } + return result; + }; + } + + /** + * This method is like `_.flow` except that it creates a function that + * invokes the provided functions from right to left. + * + * @static + * @memberOf _ + * @alias backflow, compose + * @category Function + * @param {...Function} [funcs] Functions to invoke. + * @returns {Function} Returns the new function. + * @example + * + * function add(x, y) { + * return x + y; + * } + * + * function square(n) { + * return n * n; + * } + * + * var addSquare = _.flowRight(square, add); + * addSquare(1, 2); + * // => 9 + */ + function flowRight() { + var funcs = arguments, + fromIndex = funcs.length - 1; + + if (fromIndex < 0) { + return function() { return arguments[0]; }; + } + if (!arrayEvery(funcs, isFunction)) { + throw new TypeError(FUNC_ERROR_TEXT); + } + return function() { + var index = fromIndex, + result = funcs[index].apply(this, arguments); + + while (index--) { + result = funcs[index].call(this, result); + } + return result; + }; + } + + /** + * Creates a function that memoizes the result of `func`. If `resolver` is + * provided it determines the cache key for storing the result based on the + * arguments provided to the memoized function. By default, the first argument + * provided to the memoized function is coerced to a string and used as the + * cache key. The `func` is invoked with the `this` binding of the memoized + * function. + * + * **Note:** The cache is exposed as the `cache` property on the memoized + * function. Its creation may be customized by replacing the `_.memoize.Cache` + * constructor with one whose instances implement the ES `Map` method interface + * of `get`, `has`, and `set`. See the + * [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-properties-of-the-map-prototype-object) + * for more details. + * + * @static + * @memberOf _ + * @category Function + * @param {Function} func The function to have its output memoized. + * @param {Function} [resolver] The function to resolve the cache key. + * @returns {Function} Returns the new memoizing function. + * @example + * + * var upperCase = _.memoize(function(string) { + * return string.toUpperCase(); + * }); + * + * upperCase('fred'); + * // => 'FRED' + * + * // modifying the result cache + * upperCase.cache.set('fred', 'BARNEY'); + * upperCase('fred'); + * // => 'BARNEY' + * + * // replacing `_.memoize.Cache` + * var object = { 'user': 'fred' }; + * var other = { 'user': 'barney' }; + * var identity = _.memoize(_.identity); + * + * identity(object); + * // => { 'user': 'fred' } + * identity(other); + * // => { 'user': 'fred' } + * + * _.memoize.Cache = WeakMap; + * var identity = _.memoize(_.identity); + * + * identity(object); + * // => { 'user': 'fred' } + * identity(other); + * // => { 'user': 'barney' } + */ + function memoize(func, resolver) { + if (typeof func != 'function' || (resolver && typeof resolver != 'function')) { + throw new TypeError(FUNC_ERROR_TEXT); + } + var memoized = function() { + var cache = memoized.cache, + key = resolver ? resolver.apply(this, arguments) : arguments[0]; + + if (cache.has(key)) { + return cache.get(key); + } + var result = func.apply(this, arguments); + cache.set(key, result); + return result; + }; + memoized.cache = new memoize.Cache; + return memoized; + } + + /** + * Creates a function that negates the result of the predicate `func`. The + * `func` predicate is invoked with the `this` binding and arguments of the + * created function. + * + * @static + * @memberOf _ + * @category Function + * @param {Function} predicate The predicate to negate. + * @returns {Function} Returns the new function. + * @example + * + * function isEven(n) { + * return n % 2 == 0; + * } + * + * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven)); + * // => [1, 3, 5] + */ + function negate(predicate) { + if (typeof predicate != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + return function() { + return !predicate.apply(this, arguments); + }; + } + + /** + * Creates a function that is restricted to invoking `func` once. Repeat calls + * to the function return the value of the first call. The `func` is invoked + * with the `this` binding of the created function. + * + * @static + * @memberOf _ + * @category Function + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * var initialize = _.once(createApplication); + * initialize(); + * initialize(); + * // `initialize` invokes `createApplication` once + */ + function once(func) { + return before(func, 2); + } + + /** + * Creates a function that invokes `func` with `partial` arguments prepended + * to those provided to the new function. This method is like `_.bind` except + * it does **not** alter the `this` binding. + * + * The `_.partial.placeholder` value, which defaults to `_` in monolithic + * builds, may be used as a placeholder for partially applied arguments. + * + * **Note:** This method does not set the `length` property of partially + * applied functions. + * + * @static + * @memberOf _ + * @category Function + * @param {Function} func The function to partially apply arguments to. + * @param {...*} [args] The arguments to be partially applied. + * @returns {Function} Returns the new partially applied function. + * @example + * + * var greet = function(greeting, name) { + * return greeting + ' ' + name; + * }; + * + * var sayHelloTo = _.partial(greet, 'hello'); + * sayHelloTo('fred'); + * // => 'hello fred' + * + * // using placeholders + * var greetFred = _.partial(greet, _, 'fred'); + * greetFred('hi'); + * // => 'hi fred' + */ + function partial(func) { + var partials = baseSlice(arguments, 1), + holders = replaceHolders(partials, partial.placeholder); + + return createWrapper(func, PARTIAL_FLAG, null, partials, holders); + } + + /** + * This method is like `_.partial` except that partially applied arguments + * are appended to those provided to the new function. + * + * The `_.partialRight.placeholder` value, which defaults to `_` in monolithic + * builds, may be used as a placeholder for partially applied arguments. + * + * **Note:** This method does not set the `length` property of partially + * applied functions. + * + * @static + * @memberOf _ + * @category Function + * @param {Function} func The function to partially apply arguments to. + * @param {...*} [args] The arguments to be partially applied. + * @returns {Function} Returns the new partially applied function. + * @example + * + * var greet = function(greeting, name) { + * return greeting + ' ' + name; + * }; + * + * var greetFred = _.partialRight(greet, 'fred'); + * greetFred('hi'); + * // => 'hi fred' + * + * // using placeholders + * var sayHelloTo = _.partialRight(greet, 'hello', _); + * sayHelloTo('fred'); + * // => 'hello fred' + */ + function partialRight(func) { + var partials = baseSlice(arguments, 1), + holders = replaceHolders(partials, partialRight.placeholder); + + return createWrapper(func, PARTIAL_RIGHT_FLAG, null, partials, holders); + } + + /** + * Creates a function that invokes `func` with arguments arranged according + * to the specified indexes where the argument value at the first index is + * provided as the first argument, the argument value at the second index is + * provided as the second argument, and so on. + * + * @static + * @memberOf _ + * @category Function + * @param {Function} func The function to rearrange arguments for. + * @param {...(number|number[])} indexes The arranged argument indexes, + * specified as individual indexes or arrays of indexes. + * @returns {Function} Returns the new function. + * @example + * + * var rearged = _.rearg(function(a, b, c) { + * return [a, b, c]; + * }, 2, 0, 1); + * + * rearged('b', 'c', 'a') + * // => ['a', 'b', 'c'] + * + * var map = _.rearg(_.map, [1, 0]); + * map(function(n) { return n * 3; }, [1, 2, 3]); + * // => [3, 6, 9] + */ + function rearg(func) { + var indexes = baseFlatten(arguments, false, false, 1); + return createWrapper(func, REARG_FLAG, null, null, null, indexes); + } + + /** + * Creates a function that invokes `func` with the `this` binding of the + * created function and the array of arguments provided to the created + * function much like [Function#apply](http://es5.github.io/#x15.3.4.3). + * + * @static + * @memberOf _ + * @category Function + * @param {Function} func The function to spread arguments over. + * @returns {*} Returns the new function. + * @example + * + * var spread = _.spread(function(who, what) { + * return who + ' says ' + what; + * }); + * + * spread(['Fred', 'hello']); + * // => 'Fred says hello' + * + * // with a Promise + * var numbers = Promise.all([ + * Promise.resolve(40), + * Promise.resolve(36) + * ]); + * + * var add = function(x, y) { + * return x + y; + * }; + * + * numbers.then(_.spread(add)); + * // => a Promise of 76 + */ + function spread(func) { + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + return function(array) { + return func.apply(this, array); + }; + } + + /** + * Creates a function that only invokes `func` at most once per every `wait` + * milliseconds. The created function comes with a `cancel` method to cancel + * delayed invocations. Provide an options object to indicate that `func` + * should be invoked on the leading and/or trailing edge of the `wait` timeout. + * Subsequent calls to the throttled function return the result of the last + * `func` call. + * + * **Note:** If `leading` and `trailing` options are `true`, `func` is invoked + * on the trailing edge of the timeout only if the the throttled function is + * invoked more than once during the `wait` timeout. + * + * See [David Corbacho's article](http://drupalmotion.com/article/debounce-and-throttle-visual-explanation) + * for details over the differences between `_.throttle` and `_.debounce`. + * + * @static + * @memberOf _ + * @category Function + * @param {Function} func The function to throttle. + * @param {number} wait The number of milliseconds to throttle invocations to. + * @param {Object} [options] The options object. + * @param {boolean} [options.leading=true] Specify invoking on the leading + * edge of the timeout. + * @param {boolean} [options.trailing=true] Specify invoking on the trailing + * edge of the timeout. + * @returns {Function} Returns the new throttled function. + * @example + * + * // avoid excessively updating the position while scrolling + * jQuery(window).on('scroll', _.throttle(updatePosition, 100)); + * + * // invoke `renewToken` when the click event is fired, but not more than once every 5 minutes + * var throttled = _.throttle(renewToken, 300000, { 'trailing': false }) + * jQuery('.interactive').on('click', throttled); + * + * // cancel a trailing throttled call + * jQuery(window).on('popstate', throttled.cancel); + */ + function throttle(func, wait, options) { + var leading = true, + trailing = true; + + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + if (options === false) { + leading = false; + } else if (isObject(options)) { + leading = 'leading' in options ? !!options.leading : leading; + trailing = 'trailing' in options ? !!options.trailing : trailing; + } + debounceOptions.leading = leading; + debounceOptions.maxWait = +wait; + debounceOptions.trailing = trailing; + return debounce(func, wait, debounceOptions); + } + + /** + * Creates a function that provides `value` to the wrapper function as its + * first argument. Any additional arguments provided to the function are + * appended to those provided to the wrapper function. The wrapper is invoked + * with the `this` binding of the created function. + * + * @static + * @memberOf _ + * @category Function + * @param {*} value The value to wrap. + * @param {Function} wrapper The wrapper function. + * @returns {Function} Returns the new function. + * @example + * + * var p = _.wrap(_.escape, function(func, text) { + * return '

' + func(text) + '

'; + * }); + * + * p('fred, barney, & pebbles'); + * // => '

fred, barney, & pebbles

' + */ + function wrap(value, wrapper) { + wrapper = wrapper == null ? identity : wrapper; + return createWrapper(wrapper, PARTIAL_FLAG, null, [value], []); + } + + /*------------------------------------------------------------------------*/ + + /** + * Creates a clone of `value`. If `isDeep` is `true` nested objects are cloned, + * otherwise they are assigned by reference. If `customizer` is provided it is + * invoked to produce the cloned values. If `customizer` returns `undefined` + * cloning is handled by the method instead. The `customizer` is bound to + * `thisArg` and invoked with two argument; (value [, index|key, object]). + * + * **Note:** This method is loosely based on the structured clone algorithm. + * The enumerable properties of `arguments` objects and objects created by + * constructors other than `Object` are cloned to plain `Object` objects. An + * empty object is returned for uncloneable values such as functions, DOM nodes, + * Maps, Sets, and WeakMaps. See the [HTML5 specification](http://www.w3.org/TR/html5/infrastructure.html#internal-structured-cloning-algorithm) + * for more details. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @param {Function} [customizer] The function to customize cloning values. + * @param {*} [thisArg] The `this` binding of `customizer`. + * @returns {*} Returns the cloned value. + * @example + * + * var users = [ + * { 'user': 'barney' }, + * { 'user': 'fred' } + * ]; + * + * var shallow = _.clone(users); + * shallow[0] === users[0]; + * // => true + * + * var deep = _.clone(users, true); + * deep[0] === users[0]; + * // => false + * + * // using a customizer callback + * var body = _.clone(document.body, function(value) { + * return _.isElement(value) ? value.cloneNode(false) : undefined; + * }); + * + * body === document.body + * // => false + * body.nodeName + * // => BODY + * body.childNodes.length; + * // => 0 + */ + function clone(value, isDeep, customizer, thisArg) { + // Juggle arguments. + if (typeof isDeep != 'boolean' && isDeep != null) { + thisArg = customizer; + customizer = isIterateeCall(value, isDeep, thisArg) ? null : isDeep; + isDeep = false; + } + customizer = typeof customizer == 'function' && bindCallback(customizer, thisArg, 1); + return baseClone(value, isDeep, customizer); + } + + /** + * Creates a deep clone of `value`. If `customizer` is provided it is invoked + * to produce the cloned values. If `customizer` returns `undefined` cloning + * is handled by the method instead. The `customizer` is bound to `thisArg` + * and invoked with two argument; (value [, index|key, object]). + * + * **Note:** This method is loosely based on the structured clone algorithm. + * The enumerable properties of `arguments` objects and objects created by + * constructors other than `Object` are cloned to plain `Object` objects. An + * empty object is returned for uncloneable values such as functions, DOM nodes, + * Maps, Sets, and WeakMaps. See the [HTML5 specification](http://www.w3.org/TR/html5/infrastructure.html#internal-structured-cloning-algorithm) + * for more details. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to deep clone. + * @param {Function} [customizer] The function to customize cloning values. + * @param {*} [thisArg] The `this` binding of `customizer`. + * @returns {*} Returns the deep cloned value. + * @example + * + * var users = [ + * { 'user': 'barney' }, + * { 'user': 'fred' } + * ]; + * + * var deep = _.cloneDeep(users); + * deep[0] === users[0]; + * // => false + * + * // using a customizer callback + * var el = _.cloneDeep(document.body, function(value) { + * return _.isElement(value) ? value.cloneNode(true) : undefined; + * }); + * + * body === document.body + * // => false + * body.nodeName + * // => BODY + * body.childNodes.length; + * // => 20 + */ + function cloneDeep(value, customizer, thisArg) { + customizer = typeof customizer == 'function' && bindCallback(customizer, thisArg, 1); + return baseClone(value, true, customizer); + } + + /** + * Checks if `value` is classified as an `arguments` object. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. + * @example + * + * (function() { return _.isArguments(arguments); })(); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ + function isArguments(value) { + var length = isObjectLike(value) ? value.length : undefined; + return (isLength(length) && objToString.call(value) == argsTag) || false; + } + + /** + * Checks if `value` is classified as an `Array` object. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. + * @example + * + * _.isArray([1, 2, 3]); + * // => true + * + * (function() { return _.isArray(arguments); })(); + * // => false + */ + var isArray = nativeIsArray || function(value) { + return (isObjectLike(value) && isLength(value.length) && objToString.call(value) == arrayTag) || false; + }; + + /** + * Checks if `value` is classified as a boolean primitive or object. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. + * @example + * + * _.isBoolean(false); + * // => true + * + * _.isBoolean(null); + * // => false + */ + function isBoolean(value) { + return (value === true || value === false || isObjectLike(value) && objToString.call(value) == boolTag) || false; + } + + /** + * Checks if `value` is classified as a `Date` object. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. + * @example + * + * _.isDate(new Date); + * // => true + * + * _.isDate('Mon April 23 2012'); + * // => false + */ + function isDate(value) { + return (isObjectLike(value) && objToString.call(value) == dateTag) || false; + } + + /** + * Checks if `value` is a DOM element. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a DOM element, else `false`. + * @example + * + * _.isElement(document.body); + * // => true + * + * _.isElement(''); + * // => false + */ + function isElement(value) { + return (value && value.nodeType === 1 && isObjectLike(value) && + objToString.call(value).indexOf('Element') > -1) || false; + } + // Fallback for environments without DOM support. + if (!support.dom) { + isElement = function(value) { + return (value && value.nodeType === 1 && isObjectLike(value) && !isPlainObject(value)) || false; + }; + } + + /** + * Checks if a value is empty. A value is considered empty unless it is an + * `arguments` object, array, string, or jQuery-like collection with a length + * greater than `0` or an object with own enumerable properties. + * + * @static + * @memberOf _ + * @category Lang + * @param {Array|Object|string} value The value to inspect. + * @returns {boolean} Returns `true` if `value` is empty, else `false`. + * @example + * + * _.isEmpty(null); + * // => true + * + * _.isEmpty(true); + * // => true + * + * _.isEmpty(1); + * // => true + * + * _.isEmpty([1, 2, 3]); + * // => false + * + * _.isEmpty({ 'a': 1 }); + * // => false + */ + function isEmpty(value) { + if (value == null) { + return true; + } + var length = value.length; + if (isLength(length) && (isArray(value) || isString(value) || isArguments(value) || + (isObjectLike(value) && isFunction(value.splice)))) { + return !length; + } + return !keys(value).length; + } + + /** + * Performs a deep comparison between two values to determine if they are + * equivalent. If `customizer` is provided it is invoked to compare values. + * If `customizer` returns `undefined` comparisons are handled by the method + * instead. The `customizer` is bound to `thisArg` and invoked with three + * arguments; (value, other [, index|key]). + * + * **Note:** This method supports comparing arrays, booleans, `Date` objects, + * numbers, `Object` objects, regexes, and strings. Objects are compared by + * their own, not inherited, enumerable properties. Functions and DOM nodes + * are **not** supported. Provide a customizer function to extend support + * for comparing other values. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @param {Function} [customizer] The function to customize comparing values. + * @param {*} [thisArg] The `this` binding of `customizer`. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'user': 'fred' }; + * var other = { 'user': 'fred' }; + * + * object == other; + * // => false + * + * _.isEqual(object, other); + * // => true + * + * // using a customizer callback + * var array = ['hello', 'goodbye']; + * var other = ['hi', 'goodbye']; + * + * _.isEqual(array, other, function(value, other) { + * return _.every([value, other], RegExp.prototype.test, /^h(?:i|ello)$/) || undefined; + * }); + * // => true + */ + function isEqual(value, other, customizer, thisArg) { + customizer = typeof customizer == 'function' && bindCallback(customizer, thisArg, 3); + if (!customizer && isStrictComparable(value) && isStrictComparable(other)) { + return value === other; + } + var result = customizer ? customizer(value, other) : undefined; + return typeof result == 'undefined' ? baseIsEqual(value, other, customizer) : !!result; + } + + /** + * Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`, + * `SyntaxError`, `TypeError`, or `URIError` object. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an error object, else `false`. + * @example + * + * _.isError(new Error); + * // => true + * + * _.isError(Error); + * // => false + */ + function isError(value) { + return (isObjectLike(value) && typeof value.message == 'string' && objToString.call(value) == errorTag) || false; + } + + /** + * Checks if `value` is a finite primitive number. + * + * **Note:** This method is based on ES `Number.isFinite`. See the + * [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.isfinite) + * for more details. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a finite number, else `false`. + * @example + * + * _.isFinite(10); + * // => true + * + * _.isFinite('10'); + * // => false + * + * _.isFinite(true); + * // => false + * + * _.isFinite(Object(10)); + * // => false + * + * _.isFinite(Infinity); + * // => false + */ + var isFinite = nativeNumIsFinite || function(value) { + return typeof value == 'number' && nativeIsFinite(value); + }; + + /** + * Checks if `value` is classified as a `Function` object. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. + * @example + * + * _.isFunction(_); + * // => true + * + * _.isFunction(/abc/); + * // => false + */ + function isFunction(value) { + // Avoid a Chakra JIT bug in compatibility modes of IE 11. + // See https://github.com/jashkenas/underscore/issues/1621 for more details. + return typeof value == 'function' || false; + } + // Fallback for environments that return incorrect `typeof` operator results. + if (isFunction(/x/) || (Uint8Array && !isFunction(Uint8Array))) { + isFunction = function(value) { + // The use of `Object#toString` avoids issues with the `typeof` operator + // in older versions of Chrome and Safari which return 'function' for regexes + // and Safari 8 equivalents which return 'object' for typed array constructors. + return objToString.call(value) == funcTag; + }; + } + + /** + * Checks if `value` is the language type of `Object`. + * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * **Note:** See the [ES5 spec](https://es5.github.io/#x8) for more details. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(1); + * // => false + */ + function isObject(value) { + // Avoid a V8 JIT bug in Chrome 19-20. + // See https://code.google.com/p/v8/issues/detail?id=2291 for more details. + var type = typeof value; + return type == 'function' || (value && type == 'object') || false; + } + + /** + * Performs a deep comparison between `object` and `source` to determine if + * `object` contains equivalent property values. If `customizer` is provided + * it is invoked to compare values. If `customizer` returns `undefined` + * comparisons are handled by the method instead. The `customizer` is bound + * to `thisArg` and invoked with three arguments; (value, other, index|key). + * + * **Note:** This method supports comparing properties of arrays, booleans, + * `Date` objects, numbers, `Object` objects, regexes, and strings. Functions + * and DOM nodes are **not** supported. Provide a customizer function to extend + * support for comparing other values. + * + * @static + * @memberOf _ + * @category Lang + * @param {Object} object The object to inspect. + * @param {Object} source The object of property values to match. + * @param {Function} [customizer] The function to customize comparing values. + * @param {*} [thisArg] The `this` binding of `customizer`. + * @returns {boolean} Returns `true` if `object` is a match, else `false`. + * @example + * + * var object = { 'user': 'fred', 'age': 40 }; + * + * _.isMatch(object, { 'age': 40 }); + * // => true + * + * _.isMatch(object, { 'age': 36 }); + * // => false + * + * // using a customizer callback + * var object = { 'greeting': 'hello' }; + * var source = { 'greeting': 'hi' }; + * + * _.isMatch(object, source, function(value, other) { + * return _.every([value, other], RegExp.prototype.test, /^h(?:i|ello)$/) || undefined; + * }); + * // => true + */ + function isMatch(object, source, customizer, thisArg) { + var props = keys(source), + length = props.length; + + customizer = typeof customizer == 'function' && bindCallback(customizer, thisArg, 3); + if (!customizer && length == 1) { + var key = props[0], + value = source[key]; + + if (isStrictComparable(value)) { + return object != null && value === object[key] && hasOwnProperty.call(object, key); + } + } + var values = Array(length), + strictCompareFlags = Array(length); + + while (length--) { + value = values[length] = source[props[length]]; + strictCompareFlags[length] = isStrictComparable(value); + } + return baseIsMatch(object, props, values, strictCompareFlags, customizer); + } + + /** + * Checks if `value` is `NaN`. + * + * **Note:** This method is not the same as native `isNaN` which returns `true` + * for `undefined` and other non-numeric values. See the [ES5 spec](https://es5.github.io/#x15.1.2.4) + * for more details. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. + * @example + * + * _.isNaN(NaN); + * // => true + * + * _.isNaN(new Number(NaN)); + * // => true + * + * isNaN(undefined); + * // => true + * + * _.isNaN(undefined); + * // => false + */ + function isNaN(value) { + // An `NaN` primitive is the only value that is not equal to itself. + // Perform the `toStringTag` check first to avoid errors with some host objects in IE. + return isNumber(value) && value != +value; + } + + /** + * Checks if `value` is a native function. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a native function, else `false`. + * @example + * + * _.isNative(Array.prototype.push); + * // => true + * + * _.isNative(_); + * // => false + */ + function isNative(value) { + if (value == null) { + return false; + } + if (objToString.call(value) == funcTag) { + return reNative.test(fnToString.call(value)); + } + return (isObjectLike(value) && reHostCtor.test(value)) || false; + } + + /** + * Checks if `value` is `null`. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `null`, else `false`. + * @example + * + * _.isNull(null); + * // => true + * + * _.isNull(void 0); + * // => false + */ + function isNull(value) { + return value === null; + } + + /** + * Checks if `value` is classified as a `Number` primitive or object. + * + * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are classified + * as numbers, use the `_.isFinite` method. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. + * @example + * + * _.isNumber(8.4); + * // => true + * + * _.isNumber(NaN); + * // => true + * + * _.isNumber('8.4'); + * // => false + */ + function isNumber(value) { + return typeof value == 'number' || (isObjectLike(value) && objToString.call(value) == numberTag) || false; + } + + /** + * Checks if `value` is a plain object, that is, an object created by the + * `Object` constructor or one with a `[[Prototype]]` of `null`. + * + * **Note:** This method assumes objects created by the `Object` constructor + * have no inherited enumerable properties. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. + * @example + * + * function Foo() { + * this.a = 1; + * } + * + * _.isPlainObject(new Foo); + * // => false + * + * _.isPlainObject([1, 2, 3]); + * // => false + * + * _.isPlainObject({ 'x': 0, 'y': 0 }); + * // => true + * + * _.isPlainObject(Object.create(null)); + * // => true + */ + var isPlainObject = !getPrototypeOf ? shimIsPlainObject : function(value) { + if (!(value && objToString.call(value) == objectTag)) { + return false; + } + var valueOf = value.valueOf, + objProto = isNative(valueOf) && (objProto = getPrototypeOf(valueOf)) && getPrototypeOf(objProto); + + return objProto + ? (value == objProto || getPrototypeOf(value) == objProto) + : shimIsPlainObject(value); + }; + + /** + * Checks if `value` is classified as a `RegExp` object. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. + * @example + * + * _.isRegExp(/abc/); + * // => true + * + * _.isRegExp('/abc/'); + * // => false + */ + function isRegExp(value) { + return (isObjectLike(value) && objToString.call(value) == regexpTag) || false; + } + + /** + * Checks if `value` is classified as a `String` primitive or object. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. + * @example + * + * _.isString('abc'); + * // => true + * + * _.isString(1); + * // => false + */ + function isString(value) { + return typeof value == 'string' || (isObjectLike(value) && objToString.call(value) == stringTag) || false; + } + + /** + * Checks if `value` is classified as a typed array. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. + * @example + * + * _.isTypedArray(new Uint8Array); + * // => true + * + * _.isTypedArray([]); + * // => false + */ + function isTypedArray(value) { + return (isObjectLike(value) && isLength(value.length) && typedArrayTags[objToString.call(value)]) || false; + } + + /** + * Checks if `value` is `undefined`. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`. + * @example + * + * _.isUndefined(void 0); + * // => true + * + * _.isUndefined(null); + * // => false + */ + function isUndefined(value) { + return typeof value == 'undefined'; + } + + /** + * Converts `value` to an array. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to convert. + * @returns {Array} Returns the converted array. + * @example + * + * (function() { return _.toArray(arguments).slice(1); })(1, 2, 3); + * // => [2, 3] + */ + function toArray(value) { + var length = value ? value.length : 0; + if (!isLength(length)) { + return values(value); + } + if (!length) { + return []; + } + return arrayCopy(value); + } + + /** + * Converts `value` to a plain object flattening inherited enumerable + * properties of `value` to own properties of the plain object. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to convert. + * @returns {Object} Returns the converted plain object. + * @example + * + * function Foo() { + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.assign({ 'a': 1 }, new Foo); + * // => { 'a': 1, 'b': 2 } + * + * _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); + * // => { 'a': 1, 'b': 2, 'c': 3 } + */ + function toPlainObject(value) { + return baseCopy(value, keysIn(value)); + } + + /*------------------------------------------------------------------------*/ + + /** + * Assigns own enumerable properties of source object(s) to the destination + * object. Subsequent sources overwrite property assignments of previous sources. + * If `customizer` is provided it is invoked to produce the assigned values. + * The `customizer` is bound to `thisArg` and invoked with five arguments; + * (objectValue, sourceValue, key, object, source). + * + * @static + * @memberOf _ + * @alias extend + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @param {Function} [customizer] The function to customize assigning values. + * @param {*} [thisArg] The `this` binding of `customizer`. + * @returns {Object} Returns `object`. + * @example + * + * _.assign({ 'user': 'barney' }, { 'age': 40 }, { 'user': 'fred' }); + * // => { 'user': 'fred', 'age': 40 } + * + * // using a customizer callback + * var defaults = _.partialRight(_.assign, function(value, other) { + * return typeof value == 'undefined' ? other : value; + * }); + * + * defaults({ 'user': 'barney' }, { 'age': 36 }, { 'user': 'fred' }); + * // => { 'user': 'barney', 'age': 36 } + */ + var assign = createAssigner(baseAssign); + + /** + * Creates an object that inherits from the given `prototype` object. If a + * `properties` object is provided its own enumerable properties are assigned + * to the created object. + * + * @static + * @memberOf _ + * @category Object + * @param {Object} prototype The object to inherit from. + * @param {Object} [properties] The properties to assign to the object. + * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. + * @returns {Object} Returns the new object. + * @example + * + * function Shape() { + * this.x = 0; + * this.y = 0; + * } + * + * function Circle() { + * Shape.call(this); + * } + * + * Circle.prototype = _.create(Shape.prototype, { 'constructor': Circle }); + * + * var circle = new Circle; + * circle instanceof Circle; + * // => true + * + * circle instanceof Shape; + * // => true + */ + function create(prototype, properties, guard) { + var result = baseCreate(prototype); + if (guard && isIterateeCall(prototype, properties, guard)) { + properties = null; + } + return properties ? baseCopy(properties, result, keys(properties)) : result; + } + + /** + * Assigns own enumerable properties of source object(s) to the destination + * object for all destination properties that resolve to `undefined`. Once a + * property is set, additional defaults of the same property are ignored. + * + * @static + * @memberOf _ + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @example + * + * _.defaults({ 'user': 'barney' }, { 'age': 36 }, { 'user': 'fred' }); + * // => { 'user': 'barney', 'age': 36 } + */ + function defaults(object) { + if (object == null) { + return object; + } + var args = arrayCopy(arguments); + args.push(assignDefaults); + return assign.apply(undefined, args); + } + + /** + * This method is like `_.findIndex` except that it returns the key of the + * first element `predicate` returns truthy for, instead of the element itself. + * + * If a property name is provided for `predicate` the created "_.property" + * style callback returns the property value of the given element. + * + * If value is also provided for `thisArg` the created "_.matchesProperty" + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `predicate` the created "_.matches" style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @category Object + * @param {Object} object The object to search. + * @param {Function|Object|string} [predicate=_.identity] The function invoked + * per iteration. If a property name or object is provided it is used to + * create a "_.property" or "_.matches" style callback respectively. + * @param {*} [thisArg] The `this` binding of `predicate`. + * @returns {string|undefined} Returns the key of the matched element, else `undefined`. + * @example + * + * var users = { + * 'barney': { 'age': 36, 'active': true }, + * 'fred': { 'age': 40, 'active': false }, + * 'pebbles': { 'age': 1, 'active': true } + * }; + * + * _.findKey(users, function(chr) { return chr.age < 40; }); + * // => 'barney' (iteration order is not guaranteed) + * + * // using the "_.matches" callback shorthand + * _.findKey(users, { 'age': 1, 'active': true }); + * // => 'pebbles' + * + * // using the "_.matchesProperty" callback shorthand + * _.findKey(users, 'active', false); + * // => 'fred' + * + * // using the "_.property" callback shorthand + * _.findKey(users, 'active'); + * // => 'barney' + */ + function findKey(object, predicate, thisArg) { + predicate = getCallback(predicate, thisArg, 3); + return baseFind(object, predicate, baseForOwn, true); + } + + /** + * This method is like `_.findKey` except that it iterates over elements of + * a collection in the opposite order. + * + * If a property name is provided for `predicate` the created "_.property" + * style callback returns the property value of the given element. + * + * If value is also provided for `thisArg` the created "_.matchesProperty" + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `predicate` the created "_.matches" style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @category Object + * @param {Object} object The object to search. + * @param {Function|Object|string} [predicate=_.identity] The function invoked + * per iteration. If a property name or object is provided it is used to + * create a "_.property" or "_.matches" style callback respectively. + * @param {*} [thisArg] The `this` binding of `predicate`. + * @returns {string|undefined} Returns the key of the matched element, else `undefined`. + * @example + * + * var users = { + * 'barney': { 'age': 36, 'active': true }, + * 'fred': { 'age': 40, 'active': false }, + * 'pebbles': { 'age': 1, 'active': true } + * }; + * + * _.findLastKey(users, function(chr) { return chr.age < 40; }); + * // => returns `pebbles` assuming `_.findKey` returns `barney` + * + * // using the "_.matches" callback shorthand + * _.findLastKey(users, { 'age': 36, 'active': true }); + * // => 'barney' + * + * // using the "_.matchesProperty" callback shorthand + * _.findLastKey(users, 'active', false); + * // => 'fred' + * + * // using the "_.property" callback shorthand + * _.findLastKey(users, 'active'); + * // => 'pebbles' + */ + function findLastKey(object, predicate, thisArg) { + predicate = getCallback(predicate, thisArg, 3); + return baseFind(object, predicate, baseForOwnRight, true); + } + + /** + * Iterates over own and inherited enumerable properties of an object invoking + * `iteratee` for each property. The `iteratee` is bound to `thisArg` and invoked + * with three arguments; (value, key, object). Iterator functions may exit + * iteration early by explicitly returning `false`. + * + * @static + * @memberOf _ + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {Object} Returns `object`. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.forIn(new Foo, function(value, key) { + * console.log(key); + * }); + * // => logs 'a', 'b', and 'c' (iteration order is not guaranteed) + */ + function forIn(object, iteratee, thisArg) { + if (typeof iteratee != 'function' || typeof thisArg != 'undefined') { + iteratee = bindCallback(iteratee, thisArg, 3); + } + return baseFor(object, iteratee, keysIn); + } + + /** + * This method is like `_.forIn` except that it iterates over properties of + * `object` in the opposite order. + * + * @static + * @memberOf _ + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {Object} Returns `object`. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.forInRight(new Foo, function(value, key) { + * console.log(key); + * }); + * // => logs 'c', 'b', and 'a' assuming `_.forIn ` logs 'a', 'b', and 'c' + */ + function forInRight(object, iteratee, thisArg) { + iteratee = bindCallback(iteratee, thisArg, 3); + return baseForRight(object, iteratee, keysIn); + } + + /** + * Iterates over own enumerable properties of an object invoking `iteratee` + * for each property. The `iteratee` is bound to `thisArg` and invoked with + * three arguments; (value, key, object). Iterator functions may exit iteration + * early by explicitly returning `false`. + * + * @static + * @memberOf _ + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {Object} Returns `object`. + * @example + * + * _.forOwn({ '0': 'zero', '1': 'one', 'length': 2 }, function(n, key) { + * console.log(key); + * }); + * // => logs '0', '1', and 'length' (iteration order is not guaranteed) + */ + function forOwn(object, iteratee, thisArg) { + if (typeof iteratee != 'function' || typeof thisArg != 'undefined') { + iteratee = bindCallback(iteratee, thisArg, 3); + } + return baseForOwn(object, iteratee); + } + + /** + * This method is like `_.forOwn` except that it iterates over properties of + * `object` in the opposite order. + * + * @static + * @memberOf _ + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {Object} Returns `object`. + * @example + * + * _.forOwnRight({ '0': 'zero', '1': 'one', 'length': 2 }, function(n, key) { + * console.log(key); + * }); + * // => logs 'length', '1', and '0' assuming `_.forOwn` logs '0', '1', and 'length' + */ + function forOwnRight(object, iteratee, thisArg) { + iteratee = bindCallback(iteratee, thisArg, 3); + return baseForRight(object, iteratee, keys); + } + + /** + * Creates an array of function property names from all enumerable properties, + * own and inherited, of `object`. + * + * @static + * @memberOf _ + * @alias methods + * @category Object + * @param {Object} object The object to inspect. + * @returns {Array} Returns the new array of property names. + * @example + * + * _.functions(_); + * // => ['all', 'any', 'bind', ...] + */ + function functions(object) { + return baseFunctions(object, keysIn(object)); + } + + /** + * Checks if `key` exists as a direct property of `object` instead of an + * inherited property. + * + * @static + * @memberOf _ + * @category Object + * @param {Object} object The object to inspect. + * @param {string} key The key to check. + * @returns {boolean} Returns `true` if `key` is a direct property, else `false`. + * @example + * + * _.has({ 'a': 1, 'b': 2, 'c': 3 }, 'b'); + * // => true + */ + function has(object, key) { + return object ? hasOwnProperty.call(object, key) : false; + } + + /** + * Creates an object composed of the inverted keys and values of `object`. + * If `object` contains duplicate values, subsequent values overwrite property + * assignments of previous values unless `multiValue` is `true`. + * + * @static + * @memberOf _ + * @category Object + * @param {Object} object The object to invert. + * @param {boolean} [multiValue] Allow multiple values per key. + * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. + * @returns {Object} Returns the new inverted object. + * @example + * + * _.invert({ 'first': 'fred', 'second': 'barney' }); + * // => { 'fred': 'first', 'barney': 'second' } + * + * // without `multiValue` + * _.invert({ 'first': 'fred', 'second': 'barney', 'third': 'fred' }); + * // => { 'fred': 'third', 'barney': 'second' } + * + * // with `multiValue` + * _.invert({ 'first': 'fred', 'second': 'barney', 'third': 'fred' }, true); + * // => { 'fred': ['first', 'third'], 'barney': ['second'] } + */ + function invert(object, multiValue, guard) { + if (guard && isIterateeCall(object, multiValue, guard)) { + multiValue = null; + } + var index = -1, + props = keys(object), + length = props.length, + result = {}; + + while (++index < length) { + var key = props[index], + value = object[key]; + + if (multiValue) { + if (hasOwnProperty.call(result, value)) { + result[value].push(key); + } else { + result[value] = [key]; + } + } + else { + result[value] = key; + } + } + return result; + } + + /** + * Creates an array of the own enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. See the + * [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.keys) + * for more details. + * + * @static + * @memberOf _ + * @category Object + * @param {Object} object The object to inspect. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keys(new Foo); + * // => ['a', 'b'] (iteration order is not guaranteed) + * + * _.keys('hi'); + * // => ['0', '1'] + */ + var keys = !nativeKeys ? shimKeys : function(object) { + if (object) { + var Ctor = object.constructor, + length = object.length; + } + if ((typeof Ctor == 'function' && Ctor.prototype === object) || + (typeof object != 'function' && (length && isLength(length)))) { + return shimKeys(object); + } + return isObject(object) ? nativeKeys(object) : []; + }; + + /** + * Creates an array of the own and inherited enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. + * + * @static + * @memberOf _ + * @category Object + * @param {Object} object The object to inspect. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keysIn(new Foo); + * // => ['a', 'b', 'c'] (iteration order is not guaranteed) + */ + function keysIn(object) { + if (object == null) { + return []; + } + if (!isObject(object)) { + object = Object(object); + } + var length = object.length; + length = (length && isLength(length) && + (isArray(object) || (support.nonEnumArgs && isArguments(object))) && length) || 0; + + var Ctor = object.constructor, + index = -1, + isProto = typeof Ctor == 'function' && Ctor.prototype === object, + result = Array(length), + skipIndexes = length > 0; + + while (++index < length) { + result[index] = (index + ''); + } + for (var key in object) { + if (!(skipIndexes && isIndex(key, length)) && + !(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { + result.push(key); + } + } + return result; + } + + /** + * Creates an object with the same keys as `object` and values generated by + * running each own enumerable property of `object` through `iteratee`. The + * iteratee function is bound to `thisArg` and invoked with three arguments; + * (value, key, object). + * + * If a property name is provided for `iteratee` the created "_.property" + * style callback returns the property value of the given element. + * + * If value is also provided for `thisArg` the created "_.matchesProperty" + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `iteratee` the created "_.matches" style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function|Object|string} [iteratee=_.identity] The function invoked + * per iteration. If a property name or object is provided it is used to + * create a "_.property" or "_.matches" style callback respectively. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {Object} Returns the new mapped object. + * @example + * + * _.mapValues({ 'a': 1, 'b': 2, 'c': 3} , function(n) { return n * 3; }); + * // => { 'a': 3, 'b': 6, 'c': 9 } + * + * var users = { + * 'fred': { 'user': 'fred', 'age': 40 }, + * 'pebbles': { 'user': 'pebbles', 'age': 1 } + * }; + * + * // using the "_.property" callback shorthand + * _.mapValues(users, 'age'); + * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) + */ + function mapValues(object, iteratee, thisArg) { + var result = {}; + iteratee = getCallback(iteratee, thisArg, 3); + + baseForOwn(object, function(value, key, object) { + result[key] = iteratee(value, key, object); + }); + return result; + } + + /** + * Recursively merges own enumerable properties of the source object(s), that + * don't resolve to `undefined` into the destination object. Subsequent sources + * overwrite property assignments of previous sources. If `customizer` is + * provided it is invoked to produce the merged values of the destination and + * source properties. If `customizer` returns `undefined` merging is handled + * by the method instead. The `customizer` is bound to `thisArg` and invoked + * with five arguments; (objectValue, sourceValue, key, object, source). + * + * @static + * @memberOf _ + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @param {Function} [customizer] The function to customize merging properties. + * @param {*} [thisArg] The `this` binding of `customizer`. + * @returns {Object} Returns `object`. + * @example + * + * var users = { + * 'data': [{ 'user': 'barney' }, { 'user': 'fred' }] + * }; + * + * var ages = { + * 'data': [{ 'age': 36 }, { 'age': 40 }] + * }; + * + * _.merge(users, ages); + * // => { 'data': [{ 'user': 'barney', 'age': 36 }, { 'user': 'fred', 'age': 40 }] } + * + * // using a customizer callback + * var object = { + * 'fruits': ['apple'], + * 'vegetables': ['beet'] + * }; + * + * var other = { + * 'fruits': ['banana'], + * 'vegetables': ['carrot'] + * }; + * + * _.merge(object, other, function(a, b) { + * return _.isArray(a) ? a.concat(b) : undefined; + * }); + * // => { 'fruits': ['apple', 'banana'], 'vegetables': ['beet', 'carrot'] } + */ + var merge = createAssigner(baseMerge); + + /** + * The opposite of `_.pick`; this method creates an object composed of the + * own and inherited enumerable properties of `object` that are not omitted. + * Property names may be specified as individual arguments or as arrays of + * property names. If `predicate` is provided it is invoked for each property + * of `object` omitting the properties `predicate` returns truthy for. The + * predicate is bound to `thisArg` and invoked with three arguments; + * (value, key, object). + * + * @static + * @memberOf _ + * @category Object + * @param {Object} object The source object. + * @param {Function|...(string|string[])} [predicate] The function invoked per + * iteration or property names to omit, specified as individual property + * names or arrays of property names. + * @param {*} [thisArg] The `this` binding of `predicate`. + * @returns {Object} Returns the new object. + * @example + * + * var object = { 'user': 'fred', 'age': 40 }; + * + * _.omit(object, 'age'); + * // => { 'user': 'fred' } + * + * _.omit(object, _.isNumber); + * // => { 'user': 'fred' } + */ + function omit(object, predicate, thisArg) { + if (object == null) { + return {}; + } + if (typeof predicate != 'function') { + var props = arrayMap(baseFlatten(arguments, false, false, 1), String); + return pickByArray(object, baseDifference(keysIn(object), props)); + } + predicate = bindCallback(predicate, thisArg, 3); + return pickByCallback(object, function(value, key, object) { + return !predicate(value, key, object); + }); + } + + /** + * Creates a two dimensional array of the key-value pairs for `object`, + * e.g. `[[key1, value1], [key2, value2]]`. + * + * @static + * @memberOf _ + * @category Object + * @param {Object} object The object to inspect. + * @returns {Array} Returns the new array of key-value pairs. + * @example + * + * _.pairs({ 'barney': 36, 'fred': 40 }); + * // => [['barney', 36], ['fred', 40]] (iteration order is not guaranteed) + */ + function pairs(object) { + var index = -1, + props = keys(object), + length = props.length, + result = Array(length); + + while (++index < length) { + var key = props[index]; + result[index] = [key, object[key]]; + } + return result; + } + + /** + * Creates an object composed of the picked `object` properties. Property + * names may be specified as individual arguments or as arrays of property + * names. If `predicate` is provided it is invoked for each property of `object` + * picking the properties `predicate` returns truthy for. The predicate is + * bound to `thisArg` and invoked with three arguments; (value, key, object). + * + * @static + * @memberOf _ + * @category Object + * @param {Object} object The source object. + * @param {Function|...(string|string[])} [predicate] The function invoked per + * iteration or property names to pick, specified as individual property + * names or arrays of property names. + * @param {*} [thisArg] The `this` binding of `predicate`. + * @returns {Object} Returns the new object. + * @example + * + * var object = { 'user': 'fred', 'age': 40 }; + * + * _.pick(object, 'user'); + * // => { 'user': 'fred' } + * + * _.pick(object, _.isString); + * // => { 'user': 'fred' } + */ + function pick(object, predicate, thisArg) { + if (object == null) { + return {}; + } + return typeof predicate == 'function' + ? pickByCallback(object, bindCallback(predicate, thisArg, 3)) + : pickByArray(object, baseFlatten(arguments, false, false, 1)); + } + + /** + * Resolves the value of property `key` on `object`. If the value of `key` is + * a function it is invoked with the `this` binding of `object` and its result + * is returned, else the property value is returned. If the property value is + * `undefined` the `defaultValue` is used in its place. + * + * @static + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @param {string} key The key of the property to resolve. + * @param {*} [defaultValue] The value returned if the property value + * resolves to `undefined`. + * @returns {*} Returns the resolved value. + * @example + * + * var object = { 'user': 'fred', 'age': _.constant(40) }; + * + * _.result(object, 'user'); + * // => 'fred' + * + * _.result(object, 'age'); + * // => 40 + * + * _.result(object, 'status', 'busy'); + * // => 'busy' + * + * _.result(object, 'status', _.constant('busy')); + * // => 'busy' + */ + function result(object, key, defaultValue) { + var value = object == null ? undefined : object[key]; + if (typeof value == 'undefined') { + value = defaultValue; + } + return isFunction(value) ? value.call(object) : value; + } + + /** + * An alternative to `_.reduce`; this method transforms `object` to a new + * `accumulator` object which is the result of running each of its own enumerable + * properties through `iteratee`, with each invocation potentially mutating + * the `accumulator` object. The `iteratee` is bound to `thisArg` and invoked + * with four arguments; (accumulator, value, key, object). Iterator functions + * may exit iteration early by explicitly returning `false`. + * + * @static + * @memberOf _ + * @category Object + * @param {Array|Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {*} [accumulator] The custom accumulator value. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {*} Returns the accumulated value. + * @example + * + * var squares = _.transform([1, 2, 3, 4, 5, 6], function(result, n) { + * n *= n; + * if (n % 2) { + * return result.push(n) < 3; + * } + * }); + * // => [1, 9, 25] + * + * var mapped = _.transform({ 'a': 1, 'b': 2, 'c': 3 }, function(result, n, key) { + * result[key] = n * 3; + * }); + * // => { 'a': 3, 'b': 6, 'c': 9 } + */ + function transform(object, iteratee, accumulator, thisArg) { + var isArr = isArray(object) || isTypedArray(object); + iteratee = getCallback(iteratee, thisArg, 4); + + if (accumulator == null) { + if (isArr || isObject(object)) { + var Ctor = object.constructor; + if (isArr) { + accumulator = isArray(object) ? new Ctor : []; + } else { + accumulator = baseCreate(isFunction(Ctor) && Ctor.prototype); + } + } else { + accumulator = {}; + } + } + (isArr ? arrayEach : baseForOwn)(object, function(value, index, object) { + return iteratee(accumulator, value, index, object); + }); + return accumulator; + } + + /** + * Creates an array of the own enumerable property values of `object`. + * + * **Note:** Non-object values are coerced to objects. + * + * @static + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property values. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.values(new Foo); + * // => [1, 2] (iteration order is not guaranteed) + * + * _.values('hi'); + * // => ['h', 'i'] + */ + function values(object) { + return baseValues(object, keys(object)); + } + + /** + * Creates an array of the own and inherited enumerable property values + * of `object`. + * + * **Note:** Non-object values are coerced to objects. + * + * @static + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property values. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.valuesIn(new Foo); + * // => [1, 2, 3] (iteration order is not guaranteed) + */ + function valuesIn(object) { + return baseValues(object, keysIn(object)); + } + + /*------------------------------------------------------------------------*/ + + /** + * Produces a random number between `min` and `max` (inclusive). If only one + * argument is provided a number between `0` and the given number is returned. + * If `floating` is `true`, or either `min` or `max` are floats, a floating-point + * number is returned instead of an integer. + * + * @static + * @memberOf _ + * @category Number + * @param {number} [min=0] The minimum possible value. + * @param {number} [max=1] The maximum possible value. + * @param {boolean} [floating] Specify returning a floating-point number. + * @returns {number} Returns the random number. + * @example + * + * _.random(0, 5); + * // => an integer between 0 and 5 + * + * _.random(5); + * // => also an integer between 0 and 5 + * + * _.random(5, true); + * // => a floating-point number between 0 and 5 + * + * _.random(1.2, 5.2); + * // => a floating-point number between 1.2 and 5.2 + */ + function random(min, max, floating) { + if (floating && isIterateeCall(min, max, floating)) { + max = floating = null; + } + var noMin = min == null, + noMax = max == null; + + if (floating == null) { + if (noMax && typeof min == 'boolean') { + floating = min; + min = 1; + } + else if (typeof max == 'boolean') { + floating = max; + noMax = true; + } + } + if (noMin && noMax) { + max = 1; + noMax = false; + } + min = +min || 0; + if (noMax) { + max = min; + min = 0; + } else { + max = +max || 0; + } + if (floating || min % 1 || max % 1) { + var rand = nativeRandom(); + return nativeMin(min + (rand * (max - min + parseFloat('1e-' + ((rand + '').length - 1)))), max); + } + return baseRandom(min, max); + } + + /*------------------------------------------------------------------------*/ + + /** + * Converts `string` to camel case. + * See [Wikipedia](https://en.wikipedia.org/wiki/CamelCase) for more details. + * + * @static + * @memberOf _ + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the camel cased string. + * @example + * + * _.camelCase('Foo Bar'); + * // => 'fooBar' + * + * _.camelCase('--foo-bar'); + * // => 'fooBar' + * + * _.camelCase('__foo_bar__'); + * // => 'fooBar' + */ + var camelCase = createCompounder(function(result, word, index) { + word = word.toLowerCase(); + return result + (index ? (word.charAt(0).toUpperCase() + word.slice(1)) : word); + }); + + /** + * Capitalizes the first character of `string`. + * + * @static + * @memberOf _ + * @category String + * @param {string} [string=''] The string to capitalize. + * @returns {string} Returns the capitalized string. + * @example + * + * _.capitalize('fred'); + * // => 'Fred' + */ + function capitalize(string) { + string = baseToString(string); + return string && (string.charAt(0).toUpperCase() + string.slice(1)); + } + + /** + * Deburrs `string` by converting latin-1 supplementary letters to basic latin letters. + * See [Wikipedia](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table) + * for more details. + * + * @static + * @memberOf _ + * @category String + * @param {string} [string=''] The string to deburr. + * @returns {string} Returns the deburred string. + * @example + * + * _.deburr('déjà vu'); + * // => 'deja vu' + */ + function deburr(string) { + string = baseToString(string); + return string && string.replace(reLatin1, deburrLetter); + } + + /** + * Checks if `string` ends with the given target string. + * + * @static + * @memberOf _ + * @category String + * @param {string} [string=''] The string to search. + * @param {string} [target] The string to search for. + * @param {number} [position=string.length] The position to search from. + * @returns {boolean} Returns `true` if `string` ends with `target`, else `false`. + * @example + * + * _.endsWith('abc', 'c'); + * // => true + * + * _.endsWith('abc', 'b'); + * // => false + * + * _.endsWith('abc', 'b', 2); + * // => true + */ + function endsWith(string, target, position) { + string = baseToString(string); + target = (target + ''); + + var length = string.length; + position = (typeof position == 'undefined' ? length : nativeMin(position < 0 ? 0 : (+position || 0), length)) - target.length; + return position >= 0 && string.indexOf(target, position) == position; + } + + /** + * Converts the characters "&", "<", ">", '"', "'", and '`', in `string` to + * their corresponding HTML entities. + * + * **Note:** No other characters are escaped. To escape additional characters + * use a third-party library like [_he_](https://mths.be/he). + * + * Though the ">" character is escaped for symmetry, characters like + * ">" and "/" don't require escaping in HTML and have no special meaning + * unless they're part of a tag or unquoted attribute value. + * See [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands) + * (under "semi-related fun fact") for more details. + * + * Backticks are escaped because in Internet Explorer < 9, they can break out + * of attribute values or HTML comments. See [#102](https://html5sec.org/#102), + * [#108](https://html5sec.org/#108), and [#133](https://html5sec.org/#133) of + * the [HTML5 Security Cheatsheet](https://html5sec.org/) for more details. + * + * When working with HTML you should always quote attribute values to reduce + * XSS vectors. See [Ryan Grove's article](http://wonko.com/post/html-escaping) + * for more details. + * + * @static + * @memberOf _ + * @category String + * @param {string} [string=''] The string to escape. + * @returns {string} Returns the escaped string. + * @example + * + * _.escape('fred, barney, & pebbles'); + * // => 'fred, barney, & pebbles' + */ + function escape(string) { + // Reset `lastIndex` because in IE < 9 `String#replace` does not. + string = baseToString(string); + return (string && reHasUnescapedHtml.test(string)) + ? string.replace(reUnescapedHtml, escapeHtmlChar) + : string; + } + + /** + * Escapes the `RegExp` special characters "\", "^", "$", ".", "|", "?", "*", + * "+", "(", ")", "[", "]", "{" and "}" in `string`. + * + * @static + * @memberOf _ + * @category String + * @param {string} [string=''] The string to escape. + * @returns {string} Returns the escaped string. + * @example + * + * _.escapeRegExp('[lodash](https://lodash.com/)'); + * // => '\[lodash\]\(https://lodash\.com/\)' + */ + function escapeRegExp(string) { + string = baseToString(string); + return (string && reHasRegExpChars.test(string)) + ? string.replace(reRegExpChars, '\\$&') + : string; + } + + /** + * Converts `string` to kebab case (a.k.a. spinal case). + * See [Wikipedia](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles) for + * more details. + * + * @static + * @memberOf _ + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the kebab cased string. + * @example + * + * _.kebabCase('Foo Bar'); + * // => 'foo-bar' + * + * _.kebabCase('fooBar'); + * // => 'foo-bar' + * + * _.kebabCase('__foo_bar__'); + * // => 'foo-bar' + */ + var kebabCase = createCompounder(function(result, word, index) { + return result + (index ? '-' : '') + word.toLowerCase(); + }); + + /** + * Pads `string` on the left and right sides if it is shorter then the given + * padding length. The `chars` string may be truncated if the number of padding + * characters can't be evenly divided by the padding length. + * + * @static + * @memberOf _ + * @category String + * @param {string} [string=''] The string to pad. + * @param {number} [length=0] The padding length. + * @param {string} [chars=' '] The string used as padding. + * @returns {string} Returns the padded string. + * @example + * + * _.pad('abc', 8); + * // => ' abc ' + * + * _.pad('abc', 8, '_-'); + * // => '_-abc_-_' + * + * _.pad('abc', 3); + * // => 'abc' + */ + function pad(string, length, chars) { + string = baseToString(string); + length = +length; + + var strLength = string.length; + if (strLength >= length || !nativeIsFinite(length)) { + return string; + } + var mid = (length - strLength) / 2, + leftLength = floor(mid), + rightLength = ceil(mid); + + chars = createPad('', rightLength, chars); + return chars.slice(0, leftLength) + string + chars; + } + + /** + * Pads `string` on the left side if it is shorter then the given padding + * length. The `chars` string may be truncated if the number of padding + * characters exceeds the padding length. + * + * @static + * @memberOf _ + * @category String + * @param {string} [string=''] The string to pad. + * @param {number} [length=0] The padding length. + * @param {string} [chars=' '] The string used as padding. + * @returns {string} Returns the padded string. + * @example + * + * _.padLeft('abc', 6); + * // => ' abc' + * + * _.padLeft('abc', 6, '_-'); + * // => '_-_abc' + * + * _.padLeft('abc', 3); + * // => 'abc' + */ + function padLeft(string, length, chars) { + string = baseToString(string); + return string && (createPad(string, length, chars) + string); + } + + /** + * Pads `string` on the right side if it is shorter then the given padding + * length. The `chars` string may be truncated if the number of padding + * characters exceeds the padding length. + * + * @static + * @memberOf _ + * @category String + * @param {string} [string=''] The string to pad. + * @param {number} [length=0] The padding length. + * @param {string} [chars=' '] The string used as padding. + * @returns {string} Returns the padded string. + * @example + * + * _.padRight('abc', 6); + * // => 'abc ' + * + * _.padRight('abc', 6, '_-'); + * // => 'abc_-_' + * + * _.padRight('abc', 3); + * // => 'abc' + */ + function padRight(string, length, chars) { + string = baseToString(string); + return string && (string + createPad(string, length, chars)); + } + + /** + * Converts `string` to an integer of the specified radix. If `radix` is + * `undefined` or `0`, a `radix` of `10` is used unless `value` is a hexadecimal, + * in which case a `radix` of `16` is used. + * + * **Note:** This method aligns with the ES5 implementation of `parseInt`. + * See the [ES5 spec](https://es5.github.io/#E) for more details. + * + * @static + * @memberOf _ + * @category String + * @param {string} string The string to convert. + * @param {number} [radix] The radix to interpret `value` by. + * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. + * @returns {number} Returns the converted integer. + * @example + * + * _.parseInt('08'); + * // => 8 + * + * _.map(['6', '08', '10'], _.parseInt); + * // => [6, 8, 10] + */ + function parseInt(string, radix, guard) { + if (guard && isIterateeCall(string, radix, guard)) { + radix = 0; + } + return nativeParseInt(string, radix); + } + // Fallback for environments with pre-ES5 implementations. + if (nativeParseInt(whitespace + '08') != 8) { + parseInt = function(string, radix, guard) { + // Firefox < 21 and Opera < 15 follow ES3 for `parseInt`. + // Chrome fails to trim leading whitespace characters. + // See https://code.google.com/p/v8/issues/detail?id=3109 for more details. + if (guard ? isIterateeCall(string, radix, guard) : radix == null) { + radix = 0; + } else if (radix) { + radix = +radix; + } + string = trim(string); + return nativeParseInt(string, radix || (reHexPrefix.test(string) ? 16 : 10)); + }; + } + + /** + * Repeats the given string `n` times. + * + * @static + * @memberOf _ + * @category String + * @param {string} [string=''] The string to repeat. + * @param {number} [n=0] The number of times to repeat the string. + * @returns {string} Returns the repeated string. + * @example + * + * _.repeat('*', 3); + * // => '***' + * + * _.repeat('abc', 2); + * // => 'abcabc' + * + * _.repeat('abc', 0); + * // => '' + */ + function repeat(string, n) { + var result = ''; + string = baseToString(string); + n = +n; + if (n < 1 || !string || !nativeIsFinite(n)) { + return result; + } + // Leverage the exponentiation by squaring algorithm for a faster repeat. + // See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details. + do { + if (n % 2) { + result += string; + } + n = floor(n / 2); + string += string; + } while (n); + + return result; + } + + /** + * Converts `string` to snake case. + * See [Wikipedia](https://en.wikipedia.org/wiki/Snake_case) for more details. + * + * @static + * @memberOf _ + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the snake cased string. + * @example + * + * _.snakeCase('Foo Bar'); + * // => 'foo_bar' + * + * _.snakeCase('fooBar'); + * // => 'foo_bar' + * + * _.snakeCase('--foo-bar'); + * // => 'foo_bar' + */ + var snakeCase = createCompounder(function(result, word, index) { + return result + (index ? '_' : '') + word.toLowerCase(); + }); + + /** + * Converts `string` to start case. + * See [Wikipedia](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage) + * for more details. + * + * @static + * @memberOf _ + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the start cased string. + * @example + * + * _.startCase('--foo-bar'); + * // => 'Foo Bar' + * + * _.startCase('fooBar'); + * // => 'Foo Bar' + * + * _.startCase('__foo_bar__'); + * // => 'Foo Bar' + */ + var startCase = createCompounder(function(result, word, index) { + return result + (index ? ' ' : '') + (word.charAt(0).toUpperCase() + word.slice(1)); + }); + + /** + * Checks if `string` starts with the given target string. + * + * @static + * @memberOf _ + * @category String + * @param {string} [string=''] The string to search. + * @param {string} [target] The string to search for. + * @param {number} [position=0] The position to search from. + * @returns {boolean} Returns `true` if `string` starts with `target`, else `false`. + * @example + * + * _.startsWith('abc', 'a'); + * // => true + * + * _.startsWith('abc', 'b'); + * // => false + * + * _.startsWith('abc', 'b', 1); + * // => true + */ + function startsWith(string, target, position) { + string = baseToString(string); + position = position == null ? 0 : nativeMin(position < 0 ? 0 : (+position || 0), string.length); + return string.lastIndexOf(target, position) == position; + } + + /** + * Creates a compiled template function that can interpolate data properties + * in "interpolate" delimiters, HTML-escape interpolated data properties in + * "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data + * properties may be accessed as free variables in the template. If a setting + * object is provided it takes precedence over `_.templateSettings` values. + * + * **Note:** In the development build `_.template` utilizes sourceURLs for easier debugging. + * See the [HTML5 Rocks article on sourcemaps](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl) + * for more details. + * + * For more information on precompiling templates see + * [lodash's custom builds documentation](https://lodash.com/custom-builds). + * + * For more information on Chrome extension sandboxes see + * [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval). + * + * @static + * @memberOf _ + * @category String + * @param {string} [string=''] The template string. + * @param {Object} [options] The options object. + * @param {RegExp} [options.escape] The HTML "escape" delimiter. + * @param {RegExp} [options.evaluate] The "evaluate" delimiter. + * @param {Object} [options.imports] An object to import into the template as free variables. + * @param {RegExp} [options.interpolate] The "interpolate" delimiter. + * @param {string} [options.sourceURL] The sourceURL of the template's compiled source. + * @param {string} [options.variable] The data object variable name. + * @param- {Object} [otherOptions] Enables the legacy `options` param signature. + * @returns {Function} Returns the compiled template function. + * @example + * + * // using the "interpolate" delimiter to create a compiled template + * var compiled = _.template('hello <%= user %>!'); + * compiled({ 'user': 'fred' }); + * // => 'hello fred!' + * + * // using the HTML "escape" delimiter to escape data property values + * var compiled = _.template('<%- value %>'); + * compiled({ 'value': '