1 2; /* Start:"a:4:{s:4:"full";s:66:"/local/templates/redesign/kladr/jquery.fias.min.js?163816774812779";s:6:"source";s:50:"/local/templates/redesign/kladr/jquery.fias.min.js";s:3:"min";s:0:"";s:3:"map";s:0:"";}"*/ 3!function(t,e){function n(t){var e={},n={type:"contentType",name:"query",withParents:"withParent"};t.parentType&&t.parentId&&(e[t.parentType+"Id"]=t.parentId);for(var a in t)r(t,a)&&t[a]&&(e[r(n,a)?n[a]:a]=t[a]);return e}function r(t,e){return t.hasOwnProperty(e)}function a(t){var n=e.console;n&&n.error&&n.error(t)}t.fias={},function(){var e="https:";t.fias.url=e+"//kladr-api.ru/api.php",t.fias.timeout=3e3}();var i=[],o=function(){for(;i.length>5;){var t=i.shift();t.abort()}};t.fias.type={region:"region",district:"district",city:"city",street:"street",building:"building"},t.fias.typeCode={city:1,settlement:2,village:4},t.fias.validate=function(e){var n=t.fias.type;switch(e.type){case n.region:case n.district:case n.city:if(e.parentType&&!e.parentId)return a("parentId undefined"),!1;break;case n.street:if(e.parentType!=n.city&&e.parentType!=n.street)return a('parentType must equal "city" or "street"'),!1;if(!e.parentId)return a("parentId undefined"),!1;break;case n.building:if(!e.zip){if(!~t.inArray(e.parentType,[n.street,n.city]))return a('parentType must equal "street" or "city"'),!1;if(!e.parentId)return a("parentId undefined"),!1}break;default:if(!e.oneString)return a("type incorrect"),!1}return e.oneString&&e.parentType&&!e.parentId?(a("parentId undefined"),!1):e.typeCode&&e.type!=n.city?(a('type must equal "city"'),!1):!(e.limit<1)||(a("limit must greater than 0"),!1)},t.fias.api=function(e,r){if(!r)return void a("Callback undefined");if(!t.fias.validate(e))return void r([]);var l=setTimeout(function(){r([]),l=null},t.fias.timeout);!e.token&&t.fias.token&&(e.token=t.fias.token),o();var u=t.ajax({url:t.fias.url+"?callback=?",type:"get",data:n(e),dataType:"jsonp"});i.push(u),u.done(function(t){l&&(r(t.result||[]),clearTimeout(l))})},t.fias.check=function(e,n){return n?(e.withParents=!1,e.limit=1,void t.fias.api(e,function(t){n(t&&t.length?t[0]:!1)})):void a("Callback undefined")}}(jQuery,window),function(t,e,n,r){function a(r,a){function i(t,e){return t.isGet?c.get(t.str[0]):(c.set(t),void e())}var c=function(){var e="kladr-data",n=r.data(e);return n||(n=t.extend({},u,s),r.data(e,n)),{set:function(t){if(t.obj)for(var a in t.obj)l(t.obj,a)&&l(u,a)&&(n[a]=t.obj[a]);else t.str&&!t.isGet&&l(u,t.str[0])&&(n[t.str[0]]=t.str[1]);r.data(e,n)},get:function(t){if(l(u,t)||l(s,t))return n[t]},_set:function(t,a){n[t]=a,r.data(e,n)},_get:function(t){if(l(n,t))return n[t]}}}();return i(a,function(){function a(a){var i=t(n.getElementById("kladr_autocomplete"));i.length||(i=t('<div id="kladr_autocomplete"></div>').appendTo(n.body));var l=B("guid");l?(V=i.find(".autocomplete"+l),A=i.find(".spinner"+l),t(e).off(z),r.off(z),V.off(z)):(l=o(),P("guid",l),r.attr("autocomplete","off"),V=t('<ul class="autocomplete'+l+' autocomplete" style="display: none;"></ul>').appendTo(i),A=t('<div class="spinner'+l+' spinner" style="display: none;"></div>').appendTo(i),k(),d(),b()),a()}function i(e,n){var r,a,i,o;V.empty();for(var l=0;l<e.length;l++){r=e[l],a=B("valueFormat")(r,n),i=B("labelFormat")(r,n);var u=a.replace(/(["])/g,"\\$1"),s=t("<div>"+i+"</div>").text().replace(/(["])/g,"\\$1");o=t('<a data-val="'+u+'">'+i+"</a>"),o.data("kladr-object",r),t('<li title="'+s+'"></li>').append(o).appendTo(V)}}function s(){var e,n,r;V.empty(),e="",n=u.noResultText,null!=n&&""!=n&&(r=t('<a data-val="'+e+'">'+n+"</a>"),r.data("kladr-object",{}),t("<li></li>").append(r).appendTo(V))}function d(){var t=r.offset(),e=r.outerWidth(),n=r.outerHeight();if(t&&(d.top!=t.top||d.left!=t.left||d.width!=e||d.height!=n)){d.top=t.top,d.left=t.left,d.width=e,d.height=n,V.css({top:t.top-1+n+"px",left:t.left});var a=V.outerWidth()-V.width();V.width(e-a);var i=A.width(),o=A.height();A.css({top:t.top+(n-o)/2-1,left:t.left+e-i-2})}}function p(e){if(!(e.which>8&&e.which<46)){if(r.data(F,!1),!w("open_before"))return void v();_(null);var n=r.val();if(!t.trim(n))return x(!1),void v();var a=j(n);if(!w("send_before",a))return void v();T(),w("send"),B("source")(a,function(e){return w("receive",e),r.is(":focus")?t.trim(r.val())&&e.length?(G=!0,i(e,a),d(),I(),V.slideDown(50),void w("open")):(I(),_(null),s(),d(),V.slideDown(50),w("open"),void(G=!1)):(I(),void v())})}}function v(){w("close_before")&&(V.empty().hide(),w("close"))}function y(t){var e=V.find("li.active");switch(t.which){case f.up:e.length?(e.removeClass("active"),e.prev().length&&(e=e.prev())):e=V.find("li").last(),function(){var t=V.scrollTop(),n=V.offset(),r=e.outerHeight(),a=e.offset();a.top-n.top<0&&V.scrollTop(t-r)}(),e.addClass("active"),g();break;case f.down:e.length?(e.removeClass("active"),e.next().length&&(e=e.next())):e=V.find("li").first(),e.length&&!function(){var t=V.scrollTop(),n=V.height(),r=V.offset(),a=e.outerHeight(),i=e.offset();i.top-r.top+a>n&&V.scrollTop(t+a)}(),e.addClass("active"),g();break;case f.enter:v()}}function h(e){var n=t(e);n.is("a")&&(n=n.parents("li")),n.addClass("active"),g(),v()}function g(){if(w("select_before")){var t=V.find(".active a");t.length&&(r.val(t.attr("data-val")).data(F,!0),x(!1),_(t.data("kladr-object")),w("select",B("current")))}}function m(){function e(t,e){x(e),_(t)}if(B("verify")&&w("check_before")){var n=t.trim(r.val());if(!n)return void e(null,!1);if(B("current"))return void x(!1);var a=j(n);if(a.withParents=!1,a.limit=10,!w("send_before",a))return e(null,!1),void w("check",null);T(),w("send"),B("source")(a,function(n){function i(t,n){I(),e(t,n)}if(w("receive"),!t.trim(r.val()))return void i(null,!1);for(var o=a.name.toLowerCase(),l=null,u=null,s=0;s<n.length;s++)if(l=n[s].name.toLowerCase(),o==l){u=n[s];break}u&&r.val(B("valueFormat")(u,a)),i(u,!u),w("check",u)})}}function k(){function e(){r.attr(i,!0)}function n(t,e,n){t?r.val(B("valueFormat")(t,e)):x(!0),_(t,n),r.removeAttr(i)}var a={setValue:function(e,n){return"object"===t.type(e)?a.setValueByObject(e,n):"number"===t.type(e)?a.setValueById(e,n):"string"===t.type(e)?a.setValueByName(e,n):e?a:a.clear(n)},setValueByName:function(r,i){if(r=t.trim(r+"")){var o=j("");if(o.name=S(r),o.withParents=!1,o.limit=10,!w("send_before",o))return n(null,o,i),a;e(),w("send"),B("source")(o,function(t){w("receive");for(var e=o.name.toLowerCase(),r=null,a=null,l=0;l<t.length;l++)if(r=t[l].name.toLowerCase(),e==r){a=t[l];break}n(a,o,i)})}return a},setValueById:function(r,i){var o=j("");
3return o.parentType=o.type,o.parentId=r,o.limit=1,e(),t.fias.api(o,function(t){t.length?n(t[0],o,i):n(null,o,i)}),a},setValueByObject:function(t,e){return n(t,j(""),e),a},clear:function(t){return n(null,null,t),a}},i="data-kladr-autofill-lock";P("controller",a)}function b(){function e(){var e=r.val();if(e){var n,a=j(e),i=a.type,o=a.parentType,l=t.fias.type,u=!0,s=B("controller").setValueByName;return i==l.street&&o!=l.city&&(u=!1),i!=l.building||~t.inArray(o,[l.street,l.city])||(u=!1),n=r.attr("data-kladr-autofill-lock"),n&&B("current")&&u&&s(e),!!B("current")}return!1}var n=0;!function a(){++n>5||e()||setTimeout(a,100)}()}function w(e,n,a){if(!e)return!0;var i=e.replace(/_([a-z])/gi,function(t,e){return e.toUpperCase()});return r.trigger("kladr_"+e,n),"function"!==t.type(B(i))||B(i).call(r.get(0),n,a)!==!1}function T(){B("spinner")&&B("showSpinner")(A)}function I(){B("spinner")&&B("hideSpinner")(A)}function j(t){var e,n={},r=["token","type","typeCode","parentType","parentId","oneString","withParents","limit","strict"];for(e=0;e<r.length;e++)n[r[e]]=B(r[e]);n.name=S(t);var a,i=B("parentInput");return i&&(a=C(i,n.type),a&&(n.parentType=a.type,n.parentId=a.id)),n.oneString&&(n.withParents=!0),n}function C(e,n){var r,a=t.fias.getInputs(e),i=t.fias.type,o={},u=null;a.each(function(){var e,n=t(this);(e=n.attr("data-kladr-id"))&&(o[n.attr("data-kladr-type")]=e)});for(r in i){if(r==n)return u;l(i,r)&&o[r]&&(u={type:r,id:o[r]})}return u}function S(t){for(var e="abcdefghijklmnopqrstuvwxyz",n=t.toLowerCase(),r=0;r<n.length;
3r++)if(~e.indexOf(n[r]))return x(!0),t;return x(!1),t}function _(t,e){var n=B("current");(n&&n.id)!==(t&&t.id)&&(P("current",t),t&&t.id?r.attr("data-kladr-id",t.id):r.removeAttr("data-kladr-id"),B("oneString")&&t&&t.contentType&&r.attr("data-kladr-type",t.contentType),w("change",t,e))}function x(t){t?r.addClass("kladr-error"):r.removeClass("kladr-error")}function B(t){return c._get(t)}function P(t,e){c._set(t,e)}var V=null,A=null,G=!1,z=".kladr",F="kladrInputChange";a(function(){var n=!1,a=!0,i="";r.attr("data-kladr-type",B("type")||"").attr("data-kladr-one-string",B("oneString")||null).on("keyup"+z,p).on("keydown"+z,y).on("blur"+z,function(){!n&&r.data(F)&&i!=r.val()&&r.change()}).on("blur"+z+" change"+z,function(t){if(!n)return"change"==t.type&&(i=r.val()),a&&(a=!1,m()),!G&&u.checkEmptyRespone&&r.val(""),v(),!1}).on("focus"+z,function(){a=!0}),V.on("touchstart"+z+" mousedown"+z,"li, a",function(t){t.preventDefault(),n=!0,h(this),n=!1}),t(e).on("resize"+z,d)})})}function i(e,n){var a={obj:!1,str:!1,isGet:!1};return"object"===t.type(e)?(a.obj=e,a):("string"===t.type(e)&&(a.str=[e,n],a.isGet=n===r),a)}function o(){return o.guid?++o.guid:o.guid=1}function l(t,e){return t.hasOwnProperty(e)}var u={token:null,key:null,type:null,typeCode:null,parentType:null,parentId:null,limit:10,oneString:!1,withParents:!1,noResultText:null,checkEmptyRespone:!1,strict:null,parentInput:null,verify:!1,spinner:!0,open:null,close:null,send:null,receive:null,select:null,check:null,change:null,openBefore:null,closeBefore:null,sendBefore:null,selectBefore:null,checkBefore:null,source:function(e,n){t.fias.api(e,n)},labelFormat:function(e,n){var r,a=function(t){var e=["-","[","]","/","{","}","(",")","*","+","?",".","\\","^","$","|"],r=RegExp("["+e.join("\\")+"]","g"),a=n.name.toLowerCase().replace(r,"\\$&"),i=new RegExp(a,"gi");return t.replace(i,"<strong>$&</strong>")};if(n.oneString)return e.parents?(r=[].concat(e.parents),r.push(e),a(t.fias.buildAddress(r))):a((e.typeShort?e.typeShort+". ":"")+e.name);var i="";if(e.typeShort&&(i+=e.typeShort+". "),i+=e.name,i=a(i),e.parents)for(var o=e.parents.length-1;o>-1;o--){var l=e.parents[o];l.name&&(i&&(i+="<small>, </small>"),i+="<small>"+l.name+" "+l.typeShort+".</small>")}return i},valueFormat:function(e,n){var r;return n.oneString?e.parents?(r=[].concat(e.parents),r.push(e),t.fias.buildAddress(r)):(e.typeShort?e.typeShort+". ":"")+e.name:e.name},showSpinner:function(t){var e=-.2,n=setInterval(function(){return t.is(":visible")?(t.css("background-position","0% "+e+"%"),e+=5.555556,void(e>95&&(e=-.2))):(clearInterval(n),void(n=null))},30);t.show()},hideSpinner:function(t){t.hide()}},s={current:null,controller:null},f={up:38,down:40,enter:13};t.fias=t.extend(t.fias,{setDefault:function(t,e){var n=i(t,e);if(n.obj)for(var r in n.obj)l(u,r)&&(u[r]=n.obj[r]);else n.str&&!n.isGet&&l(u,n.str[0])&&(u[n.str[0]]=n.str[1])},getDefault:function(t){if(l(u,t))return u[t]},getInputs:function(e){var r=t(e||n.body),a="[data-kladr-type]";return r.filter(a).add(r.find(a))},setValues:function(e,n,r){var a,i,o="kladr_change.setvalues",u=t.fias.type,s={},f={};if(~t.inArray(t.type(e),["object","array"])){t.each(e,function(t,e){if(e){var n=e.contentType||e.type||t;l(u,n)&&(s[n]=e)}});for(i in u)l(u,i)&&s[i]&&(f[i]=s[i]);a=t.fias.getInputs(n),function c(){var t,e,n;for(e in f)if(l(f,e)){n=f[e],delete f[e];break}if(e)return t=a.filter('[data-kladr-type="'+e+'"]'),t.length?void t.on(o,function(){t.off(o),c()}).fias("controller").setValue(n,r):void c()}()}},getAddress:function(e,n){var r,a=t.fias.getInputs(e),i=t.fias.type,o={},u={};a.each(function(){var e,n,r,a=t(this);if(a.attr("data-kladr-id"))if(e=a.fias("current"),a.attr("data-kladr-one-string")&&e.parents)for(n=[].concat(e.parents),n.push(e),r=0;r<n.length;r++)o[n[r].contentType]=n[r];else o[a.attr("data-kladr-type")]=e;else o[a.attr("data-kladr-type")]=a.val()});for(r in i)l(i,r)&&o[r]&&(u[r]=o[r]);return(n||t.fias.buildAddress)(u)},buildAddress:function(e){var n=[],r="",a="";return t.each(e,function(e,i){var o,l="",u="";if("object"===t.type(i)){for(o=0;o<n.length;o++)if(n[o]==i.id)return;n.push(i.id),l=i.name,u=i.typeShort+". ",a=i.zip||a}else l=i;r&&(r+=", "),r+=u+l}),r=(a?a+", ":"")+r}}),t.fn.fias=function(e,n){var r=i(e,n),o=null;return this.each(function(){var e=a(t(this),r);if(r.isGet)return o=e,!1}),r.isGet?o:this}}(jQuery,window,document),function(t){t.fn.fiasZip=function(e,n){return this.keydown(function(e){var n=e.charCode||e.keyCode||0,r=8==n||9==n||13==n||46==n||110==n||190==n||n>=35&&n<=40||n>=96&&n<=105;return t(this).val().length>=6?r:r||n>=48&&n<=57}),this.keyup(function(){function r(t){t?a.addClass("kladr-error"):a.removeClass("kladr-error")}var a=t(this),i=a.val();return i?void t.fias.api({type:t.fias.type.building,zip:i,withParents:!0,limit:1},function(a){var i=a.length&&a[0];a=[],i?(r(!1),i.parents&&(a=a.concat(i.parents)),a.push(i),t.fias.setValues(a,e),n&&n(i)):r(!0)}):void r(!1)}),this}}(jQuery); 4/* End */ 5; 6; /* Start:"a:4:{s:4:"full";s:30:"/frontend/rs.js?17289912601235";s:6:"source";s:15:"/frontend/rs.js";s:3:"min";s:0:"";s:3:"map";s:0:"";}"*/ 7var _stop50 = false;
8var _stop70 = false; 9var _stop90 = false; 10$(document).scroll(function() { 11 var _currY = $(this).scrollTop(); 12 if (!_currY) { 13 $('.to-top-button').css('opacity', 0); 14 /*for (var i = 0; i < 20; i++) { 15 setTimeout(function() {$('.header-mobile_fixed').show();}, 50 * i); 16 }*/ 17 } else { 18 $('.to-top-button').css("cssText", "opacity: 1 !important;"); 19 } 20 var _postHeight = $(this).height(); 21 var _scrollHeight = $(document).height(); 22 var _scrollPercent = Math.round((_currY * 100 / _scrollHeight)); 23 _scrollPercent = (_scrollPercent > 100) ? 100 : _scrollPercent; 24 if (_scrollPercent == 50 && !_stop50) { 25 yaCounter46852305.reachGoal('scroll_to_50'); 26 //_tmr.push({ type: 'reachGoal', id: 3210830, goal: 'vk_prosmotr_50'}); 27 _stop50 = true; 28 console.log('scroll_to_50'); 29 } 30 if (_scrollPercent == 70 && !_stop70) { 31 yaCounter46852305.reachGoal('scroll_to_70'); 32 _stop70 = true; 33 console.log('scroll_to_70'); 34 } 35 if (_scrollPercent == 80 && !_stop90) { 36 yaCounter46852305.reachGoal('scroll_to_90'); 37 _stop90 = true; 38 console.log('scroll_to_90'); 39 } 40}); 41 42$(document).on('click', '.to-top-button', function() { 43 $('html, body').animate({ 44 scrollTop: 0 45 }, { 46 duration: 1300, 47 easing: "linear" 48 }); 49}); 50 51/* End */ 52; 53; /* Start:"a:4:{s:4:"full";s:101:"/local/templates/.default/components/bitrix/sale.basket.basket.line/redesign/script.js?16381677485335";s:6:"source";s:86:"/local/templates/.default/components/bitrix/sale.basket.basket.line/redesign/script.js";s:3:"min";s:0:"";s:3:"map";s:0:"";}"*/ 54'use strict'; 55 56function BitrixSmallCart(){} 57 58BitrixSmallCart.prototype = { 59 60 activate: function () 61 { 62 this.cartElement = BX(this.cartId); 63 this.fixedPosition = this.arParams.POSITION_FIXED == 'Y'; 64 if (this.fixedPosition) 65 { 66 this.cartClosed = true; 67 this.maxHeight = false; 68 this.itemRemoved = false; 69 this.verticalPosition = this.arParams.POSITION_VERTICAL; 70 this.horizontalPosition = this.arParams.POSITION_HORIZONTAL; 71 this.topPanelElement = BX("bx-panel"); 72 73 this.fixAfterRender(); // TODO onready 74 this.fixAfterRenderClosure = this.closure('fixAfterRender'); 75 76 var fixCartClosure = this.closure('fixCart'); 77 this.fixCartClosure = fixCartClosure; 78 79 if (this.topPanelElement && this.verticalPosition == 'top') 80 BX.addCustomEvent(window, 'onTopPanelCollapse', fixCartClosure); 81 82 var resizeTimer = null; 83 BX.bind(window, 'resize', function() { 84 clearTimeout(resizeTimer); 85 resizeTimer = setTimeout(fixCartClosure, 200); 86 }); 87 } 88 this.setCartBodyClosure = this.closure('setCartBody'); 89 BX.addCustomEvent(window, 'OnBasketChange', this.closure('refreshCart', {})); 90 }, 91 92 fixAfterRender: function () 93 { 94 this.statusElement = BX(this.cartId + 'status'); 95 if (this.statusElement) 96 { 97 if (this.cartClosed) 98 this.statusElement.innerHTML = this.openMessage; 99 else 100 this.statusElement.innerHTML = this.closeMessage; 101 } 102 this.productsElement = BX(this.cartId + 'products'); 103 this.fixCart(); 104 }, 105 106 closure: function (fname, data) 107 { 108 var obj = this; 109 return data 110 ? function(){obj[fname](data)} 111 : function(arg1){obj[fname](arg1)}; 112 }, 113 114 toggleOpenCloseCart: function () 115 { 116 if (this.cartClosed) 117 { 118 BX.removeClass(this.cartElement, 'bx-closed'); 119 BX.addClass(this.cartElement, 'bx-opener'); 120 this.statusElement.innerHTML = this.closeMessage; 121 this.cartClosed = false; 122 this.fixCart(); 123 } 124 else // Opened 125 { 126 BX.addClass(this.cartElement, 'bx-closed'); 127 BX.removeClass(this.cartElement, 'bx-opener'); 128 BX.removeClass(this.cartElement, 'bx-max-height'); 129 this.statusElement.innerHTML = this.openMessage; 130 this.cartClosed = true; 131 var itemList = this.cartElement.querySelector("[data-role='basket-item-list']"); 132 if (itemList) 133 itemList.style.top = "auto"; 134 } 135 setTimeout(this.fixCartClosure, 100); 136 }, 137 138 setVerticalCenter: function(windowHeight) 139 { 140 var top = windowHeight/2 - (this.cartElement.offsetHeight/2); 141 if (top < 5) 142 top = 5; 143 this.cartElement.style.top = top + 'px'; 144 }, 145 146 fixCart: function() 147 { 148 // set horizontal center 149 if (this.horizontalPosition == 'hcenter') 150 { 151 var windowWidth = 'innerWidth' in window 152 ? window.innerWidth 153 : document.documentElement.offsetWidth; 154 var left = windowWidth/2 - (this.cartElement.offsetWidth/2); 155 if (left < 5) 156 left = 5; 157 this.cartElement.style.left = left + 'px'; 158 } 159
160 var windowHeight = 'innerHeight' in window 161 ? window.innerHeight 162 : document.documentElement.offsetHeight; 163 164 // set vertical position 165 switch (this.verticalPosition) { 166 case 'top': 167 if (this.topPanelElement) 168 this.cartElement.style.top = this.topPanelElement.offsetHeight + 5 + 'px'; 169 break; 170 case 'vcenter': 171 this.setVerticalCenter(windowHeight); 172 break; 173 } 174 175 // toggle max height 176 if (this.productsElement) 177 { 178 var itemList = this.cartElement.querySelector("[data-role='basket-item-list']"); 179 if (this.cartClosed) 180 { 181 if (this.maxHeight) 182 { 183 BX.removeClass(this.cartElement, 'bx-max-height'); 184 if (itemList) 185 itemList.style.top = "auto"; 186 this.maxHeight = false; 187 } 188 } 189 else // Opened 190 { 191 if (this.maxHeight) 192 { 193 if (this.productsElement.scrollHeight == this.productsElement.clientHeight) 194 { 195 BX.removeClass(this.cartElement, 'bx-max-height'); 196 if (itemList) 197 itemList.style.top = "auto"; 198 this.maxHeight = false; 199 } 200 } 201 else 202 { 203 if (this.verticalPosition == 'top' || this.verticalPosition == 'vcenter') 204 { 205 if (this.cartElement.offsetTop + this.cartElement.offsetHeight >= windowHeight) 206 { 207 BX.addClass(this.cartElement, 'bx-max-height'); 208 if (itemList) 209 itemList.style.top = 82+"px"; 210 this.maxHeight = true; 211 } 212 } 213 else 214 { 215 if (this.cartElement.offsetHeight >= windowHeight) 216 { 217 BX.addClass(this.cartElement, 'bx-max-height'); 218 if (itemList) 219 itemList.style.top = 82+"px"; 220 this.maxHeight = true; 221 } 222 } 223 } 224 } 225 226 if (this.verticalPosition == 'vcenter') 227 this.setVerticalCenter(windowHeight); 228 } 229 }, 230 231 refreshCart: function (data) 232 { 233 if (this.itemRemoved) 234 { 235 this.itemRemoved = false; 236 return; 237 } 238 data.sessid = BX.bitrix_sessid(); 239 data.siteId = this.siteId; 240 data.templateName = this.templateName; 241 data.arParams = this.arParams; 242 BX.ajax({ 243 url: this.ajaxPath, 244 method: 'POST', 245 dataType: 'html', 246 data: data, 247 onsuccess: this.setCartBodyClosure 248 }); 249 }, 250 251 setCartBody: function (result) 252 { 253 if (this.cartElement) 254 this.cartElement.innerHTML = result.replace(/#CURRENT_URL#/g, this.currentUrl); 255 if (this.fixedPosition) 256 setTimeout(this.fixAfterRenderClosure, 100); 257 }, 258 259 removeItemFromCart: function (id) 260 { 261 this.refreshCart ({sbblRemoveItemFromCart: id}); 262 this.itemRemoved = true; 263 BX.onCustomEvent('OnBasketChange'); 264 } 265}; 266 267/* End */ 268; 269; /* Start:"a:4:{s:4:"full";s:99:"/local/templates/.default/components/bitrix/sale.basket.basket.line/mobile/script.js?15976823465335";s:6:"source";s:84:"/local/templates/.default/components/bitrix/sale.basket.basket.line/mobile/script.js";s:3:"min";s:0:"";s:3:"map";s:0:"";}"*/ 270'use strict'; 271 272function BitrixSmallCart(){} 273 274BitrixSmallCart.prototype = { 275 276 activate: function () 277 { 278 this.cartElement = BX(this.cartId); 279 this.fixedPosition = this.arParams.POSITION_FIXED == 'Y'; 280 if (this.fixedPosition) 281 { 282 this.cartClosed = true; 283 this.maxHeight = false; 284 this.itemRemoved = false; 285 this.verticalPosition = this.arParams.POSITION_VERTICAL; 286 this.horizontalPosition = this.arParams.POSITION_HORIZONTAL; 287 this.topPanelElement = BX("bx-panel"); 288 289 this.fixAfterRender(); // TODO onready 290 this.fixAfterRenderClosure = this.closure('fixAfterRender'); 291 292 var fixCartClosure = this.closure('fixCart'); 293 this.fixCartClosure = fixCartClosure; 294 295 if (this.topPanelElement && this.verticalPosition == 'top') 296 BX.addCustomEvent(window, 'onTopPanelCollapse', fixCartClosure); 297 298 var resizeTimer = null; 299 BX.bind(window, 'resize', function() { 300 clearTimeout(resizeTimer); 301 resizeTimer = setTimeout(fixCartClosure, 200); 302 }); 303 } 304 this.setCartBodyClosure = this.closure('setCartBody'); 305 BX.addCustomEvent(window, 'OnBasketChange', this.closure('refreshCart', {})); 306 }, 307 308 fixAfterRender: function () 309 { 310 this.statusElement = BX(this.cartId + 'status'); 311 if (this.statusElement) 312 { 313 if (this.cartClosed) 314 this.statusElement.innerHTML = this.openMessage; 315 else 316 this.statusElement.innerHTML = this.closeMessage; 317 } 318 this.productsElement = BX(this.cartId + 'products'); 319 this.fixCart(); 320 }, 321 322 closure: function (fname, data) 323 { 324 var obj = this; 325 return data 326 ? function(){obj[fname](data)} 327 : function(arg1){obj[fname](arg1)}; 328 }, 329 330 toggleOpenCloseCart: function () 331 { 332 if (this.cartClosed) 333 { 334 BX.removeClass(this.cartElement, 'bx-closed'); 335 BX.addClass(this.cartElement, 'bx-opener'); 336 this.statusElement.innerHTML = this.closeMessage; 337 this.cartClosed = false;
338 this.fixCart(); 339 } 340 else // Opened 341 { 342 BX.addClass(this.cartElement, 'bx-closed'); 343 BX.removeClass(this.cartElement, 'bx-opener'); 344 BX.removeClass(this.cartElement, 'bx-max-height'); 345 this.statusElement.innerHTML = this.openMessage; 346 this.cartClosed = true; 347 var itemList = this.cartElement.querySelector("[data-role='basket-item-list']"); 348 if (itemList) 349 itemList.style.top = "auto"; 350 } 351 setTimeout(this.fixCartClosure, 100); 352 }, 353 354 setVerticalCenter: function(windowHeight) 355 { 356 var top = windowHeight/2 - (this.cartElement.offsetHeight/2); 357 if (top < 5) 358 top = 5; 359 this.cartElement.style.top = top + 'px'; 360 }, 361 362 fixCart: function() 363 { 364 // set horizontal center 365 if (this.horizontalPosition == 'hcenter') 366 { 367 var windowWidth = 'innerWidth' in window 368 ? window.innerWidth 369 : document.documentElement.offsetWidth; 370 var left = windowWidth/2 - (this.cartElement.offsetWidth/2); 371 if (left < 5) 372 left = 5; 373 this.cartElement.style.left = left + 'px'; 374 } 375 376 var windowHeight = 'innerHeight' in window 377 ? window.innerHeight 378 : document.documentElement.offsetHeight; 379 380 // set vertical position 381 switch (this.verticalPosition) { 382 case 'top': 383 if (this.topPanelElement) 384 this.cartElement.style.top = this.topPanelElement.offsetHeight + 5 + 'px'; 385 break; 386 case 'vcenter': 387 this.setVerticalCenter(windowHeight); 388 break; 389 } 390 391 // toggle max height 392 if (this.productsElement) 393 { 394 var itemList = this.cartElement.querySelector("[data-role='basket-item-list']"); 395 if (this.cartClosed) 396 { 397 if (this.maxHeight) 398 { 399 BX.removeClass(this.cartElement, 'bx-max-height'); 400 if (itemList) 401 itemList.style.top = "auto"; 402 this.maxHeight = false; 403 } 404 } 405 else // Opened 406 { 407 if (this.maxHeight) 408 { 409 if (this.productsElement.scrollHeight == this.productsElement.clientHeight) 410 { 411 BX.removeClass(this.cartElement, 'bx-max-height'); 412 if (itemList) 413 itemList.style.top = "auto"; 414 this.maxHeight = false; 415 } 416 } 417 else 418 { 419 if (this.verticalPosition == 'top' || this.verticalPosition == 'vcenter') 420 { 421 if (this.cartElement.offsetTop + this.cartElement.offsetHeight >= windowHeight) 422 { 423 BX.addClass(this.cartElement, 'bx-max-height'); 424 if (itemList) 425 itemList.style.top = 82+"px"; 426 this.maxHeight = true; 427 } 428 } 429 else 430 { 431 if (this.cartElement.offsetHeight >= windowHeight) 432 { 433 BX.addClass(this.cartElement, 'bx-max-height'); 434 if (itemList) 435 itemList.style.top = 82+"px"; 436 this.maxHeight = true; 437 } 438 } 439 } 440 } 441 442 if (this.verticalPosition == 'vcenter') 443 this.setVerticalCenter(windowHeight); 444 } 445 }, 446 447 refreshCart: function (data) 448 { 449 if (this.itemRemoved) 450 { 451 this.itemRemoved = false; 452 return; 453 } 454 data.sessid = BX.bitrix_sessid(); 455 data.siteId = this.siteId; 456 data.templateName = this.templateName; 457 data.arParams = this.arParams; 458 BX.ajax({ 459 url: this.ajaxPath, 460 method: 'POST', 461 dataType: 'html', 462 data: data, 463 onsuccess: this.setCartBodyClosure 464 }); 465 }, 466 467 setCartBody: function (result) 468 { 469 if (this.cartElement) 470 this.cartElement.innerHTML = result.replace(/#CURRENT_URL#/g, this.currentUrl); 471 if (this.fixedPosition) 472 setTimeout(this.fixAfterRenderClosure, 100); 473 }, 474 475 removeItemFromCart: function (id) 476 { 477 this.refreshCart ({sbblRemoveItemFromCart: id}); 478 this.itemRemoved = true; 479 BX.onCustomEvent('OnBasketChange'); 480 } 481}; 482 483/* End */ 484; 485; /* Start:"a:4:{s:4:"full";s:84:"/local/templates/.default/components/itech/garant/.default/script.js?178963287613606";s:6:"source";s:68:"/local/templates/.default/components/itech/garant/.default/script.js";s:3:"min";s:0:"";s:3:"map";s:0:"";}"*/ 486YearForm = function (params) { 487 488 489 var asteq = new BX.Asteq.Helper(); 490 var simpleVueValidator = asteq.simpleVueValidator(); 491 var mask = asteq.mask(); 492 var axios = asteq.axios(); 493 var promise = asteq.promise(); 494 495 BX.Vue.use(simpleVueValidator); 496 BX.Vue.use(mask); 497 498 BX.Vue.component('yearForm', { 499 data: function () { 500 return { 501 step: 1, 502 email: null, 503 code: null, 504 agree: false, 505 user: { 506 lname: null, 507 name: null, 508 phone: null, 509 sex: null, 510 family: null, 511 children: null, 512 money: null, 513 work: null, 514 date: null, 515 region: null, 516 }, 517 apparat: { 518 id: null, 519 serialNumber: null, 520 year: null, 521 place: null, 522 date: null, 523 }, 524 datasourse: [], 525 buyEarlier: [], 526 file: null, 527 timer: null 528 } 529 }, 530 mixins: [simpleVueValidator.mixin], 531 validators: { 532 'email': function (value) { 533 return simpleVueValidator.Validator.value(value).required('Ðоле обÑзаÑелÑно Ð´Ð»Ñ Ð·Ð°Ð¿Ð¾Ð»Ð½ÐµÐ½Ð¸Ñ').email('ÐведиÑе коÑÑекÑнÑй email'); 534 }, 535 'agree': function (value) { 536 return simpleVueValidator.Validator.value(value).custom(function () { 537 if (!value) { 538 return 'Ðоле обÑзаÑелÑно Ð´Ð»Ñ Ð·Ð°Ð¿Ð¾Ð»Ð½ÐµÐ½Ð¸Ñ' 539 } 540 }); 541 }, 542 }, 543 props: [ 544 'action', 545 'result', 546 'detectedRegion' 547 ], 548 methods: { 549 goToStep2: function () { 550 this.$validate().then(function (success) { 551 if (success) { 552 this.step = 2; 553 this.agree = null; 554 } 555 }.bind(this)); 556 }, 557 sendRequest: function () { 558 this.$validate().then(function (success) { 559 if (success) { 560 BX.ajax.post( 561 this.action, 562 this.prepareData(), 563 function (data) { 564 var data = JSON.parse(data); 565 566 if (data.file) { 567 dataLayer.push({'event': 'Sertificat_garantii', 'eventAction': 'send'}); 568 ym(37064555, 'reachGoal', 'guarantee'); 569 this.file = data.file; 570 return 1; 571 } 572 573 var container = window.popups.formResult.container[0]; 574 if (container != undefined) { 575 576 var body = container.querySelector('[data-entity="body"]'); 577 if (body != undefined) { 578 body.innerHTML = '<p>' + data.msg + '</p>'; 579 } 580 581 window.popups.formResult.open(); 582 } 583 584 return 1; 585 }.bind(this) 586 ); 587 } 588 }.bind(this)); 589 }, 590 prepareData: function () { 591 const data = {}; 592 data['email'] = this.email;
593 data['code'] = this.code; 594 data['user'] = JSON.stringify(this.user); 595 data['apparat'] = JSON.stringify(this.apparat); 596 data['id'] = this.apparat.id; 597 data['datasourse'] = JSON.stringify(this.datasourse); 598 data['buyEarlier'] = JSON.stringify(this.buyEarlier); 599 data['action'] = 'add'; 600 601 return data; 602 } 603 }, 604 watch: { 605 step: function (value) { 606 const validators = {}; 607 608 if (value === 1) { 609 validators['email'] = function (value) { 610 return simpleVueValidator.Validator.value(value).required('Ðоле обÑзаÑелÑно Ð´Ð»Ñ Ð·Ð°Ð¿Ð¾Ð»Ð½ÐµÐ½Ð¸Ñ').email('ÐведиÑе коÑÑекÑнÑй адÑÐµÑ ÑлекÑÑонной поÑÑÑ'); 611 }; 612 validators['agree'] = function (value) { 613 return simpleVueValidator.Validator.value(value).custom(function () { 614 if (!value) { 615 return 'Ðоле обÑзаÑелÑно Ð´Ð»Ñ Ð·Ð°Ð¿Ð¾Ð»Ð½ÐµÐ½Ð¸Ñ' 616 } 617 }); 618 } 619 } 620 621 if (value === 2) { 622 this.agree = null; 623 validators['agree'] = function (value) { 624 return simpleVueValidator.Validator.value(value).custom(function () { 625 if (!value) { 626 return 'Ðоле обÑзаÑелÑно Ð´Ð»Ñ Ð·Ð°Ð¿Ð¾Ð»Ð½ÐµÐ½Ð¸Ñ' 627 } 628 }); 629 } 630 validators['user.lname'] = function (value) { 631 return simpleVueValidator.Validator.value(value).required('Ðоле обÑзаÑелÑно Ð´Ð»Ñ Ð·Ð°Ð¿Ð¾Ð»Ð½ÐµÐ½Ð¸Ñ').custom(function () { 632 if (!simpleVueValidator.Validator.isEmpty(value)) { 633 if (!(/.*[A-ZÐ-ЯÐ].*/.test(value) && /.*[a-zа-ÑÑ].*/.test(value))) { 634 return 'Ðоле должно ÑодеÑжаÑÑ Ð±ÑÐºÐ²Ñ Ð²ÐµÑÑ Ð½ÐµÐ³Ð¾ и нижнего ÑегиÑÑÑа' 635 } 636 } 637 }); 638 }; 639 validators['user.name'] = function (value) { 640 return simpleVueValidator.Validator.value(value).required('Ðоле обÑзаÑелÑно Ð´Ð»Ñ Ð·Ð°Ð¿Ð¾Ð»Ð½ÐµÐ½Ð¸Ñ').custom(function () { 641 if (!simpleVueValidator.Validator.isEmpty(value)) { 642 if (!(/.*[A-ZÐ-ЯÐ].*/.test(value) && /.*[a-zа-ÑÑ].*/.test(value))) { 643 return 'Ðоле должно ÑодеÑжаÑÑ Ð±ÑÐºÐ²Ñ Ð²ÐµÑÑ Ð½ÐµÐ³Ð¾ и нижнего ÑегиÑÑÑа' 644 } 645 } 646 }); 647 }; 648 validators['user.date'] = function (value) { 649 return simpleVueValidator.Validator.value(value).required('ÐÐµÐ¾Ð±Ñ Ð¾Ð´Ð¸Ð¼Ð¾ вÑбÑаÑÑ ÑадиобаÑÑон'); 650 }; 651 validators['user.sex'] = function (value) { 652 return simpleVueValidator.Validator.value(value).required('ÐÐµÐ¾Ð±Ñ Ð¾Ð´Ð¸Ð¼Ð¾ вÑбÑаÑÑ Ð¿Ð¾Ð»'); 653 }; 654 validators['user.phone'] = function (value) { 655 return simpleVueValidator.Validator.value(value).required('Ðоле обÑзаÑелÑно Ð´Ð»Ñ Ð·Ð°Ð¿Ð¾Ð»Ð½ÐµÐ½Ð¸Ñ'); 656 }; 657 validators['user.family'] = function (value) { 658 return simpleVueValidator.Validator.value(value).required('ÐÐµÐ¾Ð±Ñ Ð¾Ð´Ð¸Ð¼Ð¾ вÑбÑаÑÑ Ð¿Ð¾Ð»Ðµ из ÑпиÑка'); 659 }; 660 validators['user.children'] = function (value) { 661 return simpleVueValidator.Validator.value(value).required('ÐÐµÐ¾Ð±Ñ Ð¾Ð´Ð¸Ð¼Ð¾ вÑбÑаÑÑ Ð¿Ð¾Ð»Ðµ из ÑпиÑка'); 662 }; 663 validators['user.money'] = function (value) { 664 return simpleVueValidator.Validator.value(value).required('ÐÐµÐ¾Ð±Ñ Ð¾Ð´Ð¸Ð¼Ð¾ вÑбÑаÑÑ Ð¿Ð¾Ð»Ðµ из ÑпиÑка'); 665 }; 666 validators['user.work'] = function (value) { 667 return simpleVueValidator.Validator.value(value).required('ÐÐµÐ¾Ð±Ñ Ð¾Ð´Ð¸Ð¼Ð¾ вÑбÑаÑÑ Ð¿Ð¾Ð»Ðµ из ÑпиÑка'); 668 }; 669 validators['user.region'] = function (value) { 670 if (value == undefined) { 671 value = ''; 672 } 673 return simpleVueValidator.Validator.value(value).required('Ðоле обÑзаÑелÑно Ð´Ð»Ñ Ð·Ð°Ð¿Ð¾Ð»Ð½ÐµÐ½Ð¸Ñ'); 674 }; 675 validators['datasourse'] = function (value) { 676 return simpleVueValidator.Validator.value(value).required('ÐÐµÐ¾Ð±Ñ Ð¾Ð´Ð¸Ð¼Ð¾ вÑбÑаÑÑ Ð¿Ð¾Ð»Ðµ из ÑпиÑка').custom(function () { 677 if (!simpleVueValidator.Validator.isEmpty(value)) { 678 if (value.length == 0) { 679 return 'ÐÐµÐ¾Ð±Ñ Ð¾Ð´Ð¸Ð¼Ð¾ вÑбÑаÑÑ Ð¿Ð¾Ð»Ðµ из ÑпиÑка' 680 } 681 } 682 }); 683 }; 684 /*validators['buyEarlier'] = function (value) { 685 return simpleVueValidator.Validator.value(value).required('ÐÐµÐ¾Ð±Ñ Ð¾Ð´Ð¸Ð¼Ð¾ вÑбÑаÑÑ Ñек-бокÑ').custom(function () { 686 if (!simpleVueValidator.Validator.isEmpty(value)) { 687 if (value.length == 0) { 688 return 'ÐÐµÐ¾Ð±Ñ Ð¾Ð´Ð¸Ð¼Ð¾ вÑбÑаÑÑ Ñек-бокÑ' 689 } 690 } 691 }); 692 };*/ 693 validators['apparat.id'] = function (value) { 694 return simpleVueValidator.Validator.value(value).required('ÐÐµÐ¾Ð±Ñ Ð¾Ð´Ð¸Ð¼Ð¾ вÑбÑаÑÑ Ð¿Ð¾Ð»Ðµ из ÑпиÑка'); 695 }; 696 validators['apparat.serialNumber'] = function (value) { 697 return simpleVueValidator.Validator.value(value).required('Ðоле обÑзаÑелÑно Ð´Ð»Ñ Ð·Ð°Ð¿Ð¾Ð»Ð½ÐµÐ½Ð¸Ñ').digit('ÐоддеÑÐ¶Ð¸Ð²Ð°ÐµÑ Ð²Ð²Ð¾Ð´ ÑолÑко ÑиÑÑ'); 698 }; 699 700 validators['apparat.year'] = function (value) { 701 return simpleVueValidator.Validator.value(value).required('Ðоле обÑзаÑелÑно Ð´Ð»Ñ Ð·Ð°Ð¿Ð¾Ð»Ð½ÐµÐ½Ð¸Ñ').digit('ÐоддеÑÐ¶Ð¸Ð²Ð°ÐµÑ Ð²Ð²Ð¾Ð´ ÑолÑко ÑиÑÑ'); 702 }; 703 validators['apparat.place'] = function (value) { 704 return simpleVueValidator.Validator.value(value).required('Ðоле обÑзаÑелÑно Ð´Ð»Ñ Ð·Ð°Ð¿Ð¾Ð»Ð½ÐµÐ½Ð¸Ñ'); 705 }; 706 validators['apparat.date'] = function (value) { 707 return simpleVueValidator.Validator.value(value) 708 .required('Ðоле обÑзаÑелÑно Ð´Ð»Ñ Ð·Ð°Ð¿Ð¾Ð»Ð½ÐµÐ½Ð¸Ñ') 709 .custom(function () { 710 if (!value) return; 711 712 const selectedDate = new Date(value); 713 const oneMonthAgo = new Date(); 714 715 // ÐÑнимаем 1 меÑÑÑ Ð¾Ñ ÑекÑÑей даÑÑ 716 oneMonthAgo.setMonth(oneMonthAgo.getMonth() - 1); 717 718 // СбÑаÑÑваем вÑÐµÐ¼Ñ Ð² 00:00:00 Ð´Ð»Ñ ÑоÑного ÑÑÐ°Ð²Ð½ÐµÐ½Ð¸Ñ ÑолÑко Ð´Ð°Ñ 719 selectedDate.setHours(0, 0, 0, 0); 720 oneMonthAgo.setHours(0, 0, 0, 0); 721 722 if (selectedDate < oneMonthAgo) { 723 return 'ÐаÑа покÑпки не Ð¼Ð¾Ð¶ÐµÑ Ð±ÑÑÑ ÑÑаÑÑе 1 меÑÑÑа'; 724 } 725 }); 726 }; 727 728 } 729 this.$setValidators(validators); 730 }, 731 }, 732 mounted: function () { 733 window.customInputMaskInit(); 734 this.user.region = this.detectedRedion; 735 736 $.fias.url = "https://kladr-api.com/api.php";
737 const kladr = $(this.$refs.kladr); 738 kladr.fias({ 739 select: function (obj) { 740 this.user.region = obj.name + ' ' + obj.type; 741 }.bind(this) 742 }); 743 744 kladr.fias('type', $.fias.type.region); 745 }, 746 template: '#tpl-year' 747 }); 748 749 750 return BX.Vue.create({ 751 el: '#year-form', 752 render: function (createElement) { 753 return createElement( 754 'yearForm', { 755 props: params, 756 } 757 ) 758 }, 759 }); 760 761}; 762 763/* End */ 764; 765; /* Start:"a:4:{s:4:"full";s:61:"/local/js/asteq/helper/dist/Helper.bundle.js?1597682347265687";s:6:"source";s:44:"/local/js/asteq/helper/dist/Helper.bundle.js";s:3:"min";s:0:"";s:3:"map";s:0:"";}"*/ 766this.BX = this.BX || {}; 767(function (exports,main_core,Axios) { 768 'use strict'; 769 770 Axios = Axios && Axios.hasOwnProperty('default') ? Axios['default'] : Axios; 771 772 var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; 773 function commonjsRequire() { 774 throw new Error('Dynamic requires are not currently supported by rollup-plugin-commonjs'); 775 } 776 function unwrapExports(x) { 777 return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; 778 } 779 function createCommonjsModule(fn, module) { 780 return module = { 781 exports: {} 782 }, fn(module, module.exports), module.exports; 783 } 784 785 var bluebird = createCommonjsModule(function (module, exports) { 786 /* @preserve 787 * The MIT License (MIT) 788 * 789 * Copyright (c) 2013-2018 Petka Antonov 790 * 791 * Permission is hereby granted, free of charge, to any person obtaining a copy 792 * of this software and associated documentation files (the "Software"), to deal 793 * in the Software without restriction, including without limitation the rights 794 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 795 * copies of the Software, and to permit persons to whom the Software is 796 * furnished to do so, subject to the following conditions: 797 * 798 * The above copyright notice and this permission notice shall be included in 799 * all copies or substantial portions of the Software. 800 * 801 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 802 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 803 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 804 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 805 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 806 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 807 * THE SOFTWARE. 808 * 809 */ 810 811 /** 812 * bluebird build version 3.7.2 813 * Features enabled: core, race, call_get, generators, map, nodeify, promisify, props, reduce, settle, some, using, timers, filter, any, each 814 */ 815 !function (e) { 816 if ("object" == (babelHelpers.typeof(exports)) && "undefined" != 'object') module.exports = e();else { 817 var f; 818 "undefined" != typeof window ? f = window : "undefined" != typeof commonjsGlobal ? f = commonjsGlobal : "undefined" != typeof self && (f = self), f.Promise = e(); 819 } 820 }(function () { 821 return function e(t, n, r) { 822 function s(o, u) { 823 if (!n[o]) { 824 if (!t[o]) { 825 var a = typeof _dereq_ == "function" && _dereq_; 826 if (!u && a) return a(o, !0); 827 if (i) return i(o, !0); 828 var f = new Error("Cannot find module '" + o + "'"); 829 throw f.code = "MODULE_NOT_FOUND", f; 830 } 831 832 var l = n[o] = { 833 exports: {} 834 }; 835 t[o][0].call(l.exports, function (e) { 836 var n = t[o][1][e]; 837 return s(n ? n : e); 838 }, l, l.exports, e, t, n, r); 839 } 840 841 return n[o].exports; 842 } 843 844 var i = typeof _dereq_ == "function" && _dereq_; 845 846 for (var o = 0; o < r.length; o++) { 847 s(r[o]); 848 } 849 850 return s; 851 }({
852 1: [function (_dereq_, module, exports) { 853 854 module.exports = function (Promise) { 855 var SomePromiseArray = Promise._SomePromiseArray; 856 857 function any(promises) { 858 var ret = new SomePromiseArray(promises); 859 var promise = ret.promise(); 860 ret.setHowMany(1); 861 ret.setUnwrap(); 862 ret.init(); 863 return promise; 864 } 865 866 Promise.any = function (promises) { 867 return any(promises); 868 }; 869 870 Promise.prototype.any = function () { 871 return any(this); 872 }; 873 }; 874 }, {}], 875 2: [function (_dereq_, module, exports) { 876 877 var firstLineError; 878 879 try { 880 throw new Error(); 881 } catch (e) { 882 firstLineError = e; 883 } 884 885 var schedule = _dereq_("./schedule"); 886 887 var Queue = _dereq_("./queue"); 888 889 function Async() { 890 this._customScheduler = false; 891 this._isTickUsed = false; 892 this._lateQueue = new Queue(16); 893 this._normalQueue = new Queue(16); 894 this._haveDrainedQueues = false; 895 var self = this; 896 897 this.drainQueues = function () { 898 self._drainQueues(); 899 }; 900 901 this._schedule = schedule; 902 } 903 904 Async.prototype.setScheduler = function (fn) { 905 var prev = this._schedule; 906 this._schedule = fn; 907 this._customScheduler = true; 908 return prev; 909 }; 910 911 Async.prototype.hasCustomScheduler = function () { 912 return this._customScheduler; 913 }; 914 915 Async.prototype.haveItemsQueued = function () { 916 return this._isTickUsed || this._haveDrainedQueues; 917 }; 918 919 Async.prototype.fatalError = function (e, isNode) { 920 if (isNode) { 921 process.stderr.write("Fatal " + (e instanceof Error ? e.stack : e) + "\n"); 922 process.exit(2); 923 } else { 924 this.throwLater(e); 925 } 926 }; 927 928 Async.prototype.throwLater = function (fn, arg) { 929 if (arguments.length === 1) { 930 arg = fn; 931 932 fn = function fn() { 933 throw arg; 934 }; 935 } 936 937 if (typeof setTimeout !== "undefined") { 938 setTimeout(function () { 939 fn(arg); 940 }, 0); 941 } else try { 942 this._schedule(function () { 943 fn(arg); 944 }); 945 } catch (e) { 946 throw new Error("No async scheduler available\n\n See http://goo.gl/MqrFmX\n"); 947 } 948 }; 949 950 function AsyncInvokeLater(fn, receiver, arg) { 951 this._lateQueue.push(fn, receiver, arg); 952 953 this._queueTick(); 954 } 955 956 function AsyncInvoke(fn, receiver, arg) { 957 this._normalQueue.push(fn, receiver, arg); 958 959 this._queueTick(); 960 } 961 962 function AsyncSettlePromises(promise) { 963 this._normalQueue._pushOne(promise); 964 965 this._queueTick(); 966 } 967 968 Async.prototype.invokeLater = AsyncInvokeLater; 969 Async.prototype.invoke = AsyncInvoke; 970 Async.prototype.settlePromises = AsyncSettlePromises; 971 972 function _drainQueue(queue) { 973 while (queue.length() > 0) { 974 _drainQueueStep(queue); 975 } 976 } 977 978 function _drainQueueStep(queue) { 979 var fn = queue.shift(); 980 981 if (typeof fn !== "function") { 982 fn._settlePromises(); 983 } else { 984 var receiver = queue.shift(); 985 var arg = queue.shift(); 986 fn.call(receiver, arg); 987 } 988 } 989 990 Async.prototype._drainQueues = function () { 991 _drainQueue(this._normalQueue); 992 993 this._reset(); 994 995 this._haveDrainedQueues = true; 996 997 _drainQueue(this._lateQueue); 998 }; 999 1000 Async.prototype._queueTick = function () { 1001 if (!this._isTickUsed) { 1002 this._isTickUsed = true; 1003 1004 this._schedule(this.drainQueues); 1005 } 1006 }; 1007 1008 Async.prototype._reset = function () { 1009 this._isTickUsed = false; 1010 }; 1011 1012 module.exports = Async; 1013 module.exports.firstLineError = firstLineError; 1014 }, { 1015 "./queue": 26, 1016 "./schedule": 29 1017 }],
1018 3: [function (_dereq_, module, exports) { 1019 1020 module.exports = function (Promise, INTERNAL, tryConvertToPromise, debug) { 1021 var calledBind = false; 1022 1023 var rejectThis = function rejectThis(_, e) { 1024 this._reject(e); 1025 }; 1026 1027 var targetRejected = function targetRejected(e, context) { 1028 context.promiseRejectionQueued = true; 1029 1030 context.bindingPromise._then(rejectThis, rejectThis, null, this, e); 1031 }; 1032 1033 var bindingResolved = function bindingResolved(thisArg, context) { 1034 if ((this._bitField & 50397184) === 0) { 1035 this._resolveCallback(context.target); 1036 } 1037 }; 1038 1039 var bindingRejected = function bindingRejected(e, context) { 1040 if (!context.promiseRejectionQueued) this._reject(e); 1041 }; 1042 1043 Promise.prototype.bind = function (thisArg) { 1044 if (!calledBind) { 1045 calledBind = true; 1046 Promise.prototype._propagateFrom = debug.propagateFromFunction(); 1047 Promise.prototype._boundValue = debug.boundValueFunction(); 1048 } 1049 1050 var maybePromise = tryConvertToPromise(thisArg); 1051 var ret = new Promise(INTERNAL); 1052 1053 ret._propagateFrom(this, 1); 1054 1055 var target = this._target(); 1056 1057 ret._setBoundTo(maybePromise); 1058 1059 if (maybePromise instanceof Promise) { 1060 var context = { 1061 promiseRejectionQueued: false, 1062 promise: ret, 1063 target: target, 1064 bindingPromise: maybePromise 1065 }; 1066 1067 target._then(INTERNAL, targetRejected, undefined, ret, context); 1068 1069 maybePromise._then(bindingResolved, bindingRejected, undefined, ret, context); 1070 1071 ret._setOnCancel(maybePromise); 1072 } else { 1073 ret._resolveCallback(target); 1074 } 1075 1076 return ret; 1077 }; 1078 1079 Promise.prototype._setBoundTo = function (obj) { 1080 if (obj !== undefined) { 1081 this._bitField = this._bitField | 2097152; 1082 this._boundTo = obj; 1083 } else { 1084 this._bitField = this._bitField & ~2097152; 1085 } 1086 }; 1087 1088 Promise.prototype._isBound = function () { 1089 return (this._bitField & 2097152) === 2097152; 1090 }; 1091 1092 Promise.bind = function (thisArg, value) { 1093 return Promise.resolve(value).bind(thisArg); 1094 }; 1095 }; 1096 }, {}], 1097 4: [function (_dereq_, module, exports) { 1098 1099 var old; 1100 if (typeof Promise !== "undefined") old = Promise; 1101 1102 function noConflict() { 1103 try { 1104 if (Promise === bluebird) Promise = old; 1105 } catch (e) {} 1106 1107 return bluebird; 1108 } 1109 1110 var bluebird = _dereq_("./promise")(); 1111 1112 bluebird.noConflict = noConflict; 1113 module.exports = bluebird; 1114 }, { 1115 "./promise": 22 1116 }], 1117 5: [function (_dereq_, module, exports) { 1118 1119 var cr = Object.create; 1120 1121 if (cr) { 1122 var callerCache = cr(null); 1123 var getterCache = cr(null); 1124 callerCache[" size"] = getterCache[" size"] = 0; 1125 } 1126 1127 module.exports = function (Promise) { 1128 var util = _dereq_("./util"); 1129 1130 var canEvaluate = util.canEvaluate; 1131 var isIdentifier = util.isIdentifier; 1132 var getGetter; 1133 1134 function ensureMethod(obj, methodName) { 1135 var fn; 1136 if (obj != null) fn = obj[methodName]; 1137 1138 if (typeof fn !== "function") { 1139 var message = "Object " + util.classString(obj) + " has no method '" + util.toString(methodName) + "'"; 1140 throw new Promise.TypeError(message); 1141 } 1142 1143 return fn; 1144 } 1145 1146 function caller(obj) { 1147 var methodName = this.pop(); 1148 var fn = ensureMethod(obj, methodName); 1149 return fn.apply(obj, this); 1150 } 1151 1152 Promise.prototype.call = function (methodName) { 1153 var args = [].slice.call(arguments, 1); 1154 1155 args.push(methodName); 1156 return this._then(caller, undefined, undefined, args, undefined); 1157 }; 1158 1159 function namedGetter(obj) { 1160 return obj[this]; 1161 } 1162 1163 function indexedGetter(obj) { 1164 var index = +this; 1165 if (index < 0) index = Math.max(0, index + obj.length); 1166 return obj[index]; 1167 } 1168 1169 Promise.prototype.get = function (propertyName) { 1170 var isIndex = typeof propertyName === "number"; 1171 var getter; 1172 1173 if (!isIndex) { 1174 if (canEvaluate) { 1175 var maybeGetter = getGetter(propertyName); 1176 getter = maybeGetter !== null ? maybeGetter : namedGetter; 1177 } else { 1178 getter = namedGetter; 1179 } 1180 } else { 1181 getter = indexedGetter; 1182 } 1183 1184 return this._then(getter, undefined, undefined, propertyName, undefined); 1185 }; 1186 }; 1187 }, { 1188 "./util": 36 1189 }
1189], 1190 6: [function (_dereq_, module, exports) { 1191 1192 module.exports = function (Promise, PromiseArray, apiRejection, debug) { 1193 var util = _dereq_("./util"); 1194 1195 var tryCatch = util.tryCatch; 1196 var errorObj = util.errorObj; 1197 var async = Promise._async; 1198 1199 Promise.prototype["break"] = Promise.prototype.cancel = function () { 1200 if (!debug.cancellation()) return this._warn("cancellation is disabled"); 1201 var promise = this; 1202 var child = promise; 1203 1204 while (promise._isCancellable()) { 1205 if (!promise._cancelBy(child)) { 1206 if (child._isFollowing()) { 1207 child._followee().cancel(); 1208 } else { 1209 child._cancelBranched(); 1210 } 1211 1212 break; 1213 } 1214 1215 var parent = promise._cancellationParent; 1216 1217 if (parent == null || !parent._isCancellable()) { 1218 if (promise._isFollowing()) { 1219 promise._followee().cancel(); 1220 } else { 1221 promise._cancelBranched(); 1222 } 1223 1224 break; 1225 } else { 1226 if (promise._isFollowing()) promise._followee().cancel(); 1227 1228 promise._setWillBeCancelled(); 1229 1230 child = promise; 1231 promise = parent; 1232 } 1233 } 1234 }; 1235 1236 Promise.prototype._branchHasCancelled = function () { 1237 this._branchesRemainingToCancel--; 1238 }; 1239 1240 Promise.prototype._enoughBranchesHaveCancelled = function () { 1241 return this._branchesRemainingToCancel === undefined || this._branchesRemainingToCancel <= 0; 1242 }; 1243 1244 Promise.prototype._cancelBy = function (canceller) { 1245 if (canceller === this) { 1246 this._branchesRemainingToCancel = 0; 1247 1248 this._invokeOnCancel(); 1249 1250 return true; 1251 } else { 1252 this._branchHasCancelled(); 1253 1254 if (this._enoughBranchesHaveCancelled()) { 1255 this._invokeOnCancel(); 1256 1257 return true; 1258 } 1259 } 1260 1261 return false; 1262 }; 1263 1264 Promise.prototype._cancelBranched = function () { 1265 if (this._enoughBranchesHaveCancelled()) { 1266 this._cancel(); 1267 } 1268 }; 1269 1270 Promise.prototype._cancel = function () { 1271 if (!this._isCancellable()) return; 1272 1273 this._setCancelled(); 1274 1275 async.invoke(this._cancelPromises, this, undefined); 1276 }; 1277 1278 Promise.prototype._cancelPromises = function () { 1279 if (this._length() > 0) this._settlePromises(); 1280 }; 1281 1282 Promise.prototype._unsetOnCancel = function () { 1283 this._onCancelField = undefined; 1284 }; 1285 1286 Promise.prototype._isCancellable = function () { 1287 return this.isPending() && !this._isCancelled(); 1288 }; 1289 1290 Promise.prototype.isCancellable = function () { 1291 return this.isPending() && !this.isCancelled(); 1292 }; 1293 1294 Promise.prototype._doInvokeOnCancel = function (onCancelCallback, internalOnly) { 1295 if (util.isArray(onCancelCallback)) { 1296 for (var i = 0; i < onCancelCallback.length; ++i) { 1297 this._doInvokeOnCancel(onCancelCallback[i], internalOnly); 1298 } 1299 } else if (onCancelCallback !== undefined) { 1300 if (typeof onCancelCallback === "function") { 1301 if (!internalOnly) { 1302 var e = tryCatch(onCancelCallback).call(this._boundValue()); 1303 1304 if (e === errorObj) { 1305 this._attachExtraTrace(e.e); 1306 1307 async.throwLater(e.e); 1308 } 1309 } 1310 } else { 1311 onCancelCallback._resultCancelled(this); 1312 } 1313 } 1314 }; 1315 1316 Promise.prototype._invokeOnCancel = function () { 1317 var onCancelCallback = this._onCancel(); 1318 1319 this._unsetOnCancel(); 1320 1321 async.invoke(this._doInvokeOnCancel, this, onCancelCallback); 1322 }; 1323 1324 Promise.prototype._invokeInternalOnCancel = function () { 1325 if (this._isCancellable()) { 1326 this._doInvokeOnCancel(this._onCancel(), true); 1327 1328 this._unsetOnCancel(); 1329 } 1330 }; 1331 1332 Promise.prototype._resultCancelled = function () { 1333 this.cancel(); 1334 }; 1335 }; 1336 }, { 1337 "./util": 36 1338 }
1338], 1339 7: [function (_dereq_, module, exports) { 1340 1341 module.exports = function (NEXT_FILTER) { 1342 var util = _dereq_("./util"); 1343 1344 var getKeys = _dereq_("./es5").keys; 1345 1346 var tryCatch = util.tryCatch; 1347 var errorObj = util.errorObj; 1348 1349 function catchFilter(instances, cb, promise) { 1350 return function (e) { 1351 var boundTo = promise._boundValue(); 1352 1353 predicateLoop: for (var i = 0; i < instances.length; ++i) { 1354 var item = instances[i]; 1355 1356 if (item === Error || item != null && item.prototype instanceof Error) { 1357 if (e instanceof item) { 1358 return tryCatch(cb).call(boundTo, e); 1359 } 1360 } else if (typeof item === "function") { 1361 var matchesPredicate = tryCatch(item).call(boundTo, e); 1362 1363 if (matchesPredicate === errorObj) { 1364 return matchesPredicate; 1365 } else if (matchesPredicate) { 1366 return tryCatch(cb).call(boundTo, e); 1367 } 1368 } else if (util.isObject(e)) { 1369 var keys = getKeys(item); 1370 1371 for (var j = 0; j < keys.length; ++j) { 1372 var key = keys[j]; 1373 1374 if (item[key] != e[key]) { 1375 continue predicateLoop; 1376 } 1377 } 1378 1379 return tryCatch(cb).call(boundTo, e); 1380 } 1381 } 1382 1383 return NEXT_FILTER; 1384 }; 1385 } 1386 1387 return catchFilter; 1388 }; 1389 }, { 1390 "./es5": 13, 1391 "./util": 36 1392 }], 1393 8: [function (_dereq_, module, exports) { 1394 1395 module.exports = function (Promise) { 1396 var longStackTraces = false; 1397 var contextStack = []; 1398 1399 Promise.prototype._promiseCreated = function () {}; 1400 1401 Promise.prototype._pushContext = function () {}; 1402 1403 Promise.prototype._popContext = function () { 1404 return null; 1405 }; 1406 1407 Promise._peekContext = Promise.prototype._peekContext = function () {}; 1408 1409 function Context() { 1410 this._trace = new Context.CapturedTrace(peekContext()); 1411 } 1412 1413 Context.prototype._pushContext = function () { 1414 if (this._trace !== undefined) { 1415 this._trace._promiseCreated = null; 1416 contextStack.push(this._trace); 1417 } 1418 }; 1419 1420 Context.prototype._popContext = function () { 1421 if (this._trace !== undefined) { 1422 var trace = contextStack.pop(); 1423 var ret = trace._promiseCreated; 1424 trace._promiseCreated = null; 1425 return ret; 1426 } 1427 1428 return null; 1429 }; 1430 1431 function createContext() { 1432 if (longStackTraces) return new Context(); 1433 } 1434 1435 function peekContext() { 1436 var lastIndex = contextStack.length - 1; 1437 1438 if (lastIndex >= 0) { 1439 return contextStack[lastIndex]; 1440 } 1441 1442 return undefined; 1443 } 1444 1445 Context.CapturedTrace = null; 1446 Context.create = createContext; 1447 1448 Context.deactivateLongStackTraces = function () {}; 1449 1450 Context.activateLongStackTraces = function () { 1451 var Promise_pushContext = Promise.prototype._pushContext; 1452 var Promise_popContext = Promise.prototype._popContext; 1453 var Promise_PeekContext = Promise._peekContext; 1454 var Promise_peekContext = Promise.prototype._peekContext; 1455 var Promise_promiseCreated = Promise.prototype._promiseCreated; 1456 1457 Context.deactivateLongStackTraces = function () { 1458 Promise.prototype._pushContext = Promise_pushContext; 1459 Promise.prototype._popContext = Promise_popContext; 1460 Promise._peekContext = Promise_PeekContext; 1461 Promise.prototype._peekContext = Promise_peekContext; 1462 Promise.prototype._promiseCreated = Promise_promiseCreated; 1463 longStackTraces = false; 1464 }; 1465 1466 longStackTraces = true; 1467 Promise.prototype._pushContext = Context.prototype._pushContext; 1468 Promise.prototype._popContext = Context.prototype._popContext; 1469 Promise._peekContext = Promise.prototype._peekContext = peekContext; 1470 1471 Promise.prototype._promiseCreated = function () { 1472 var ctx = this._peekContext(); 1473 1474 if (ctx && ctx._promiseCreated == null) ctx._promiseCreated = this; 1475 }; 1476 }; 1477 1478 return Context; 1479 }; 1480 }, {}],
1481 9: [function (_dereq_, module, exports) { 1482 1483 module.exports = function (Promise, Context, enableAsyncHooks, disableAsyncHooks) { 1484 var async = Promise._async; 1485 1486 var Warning = _dereq_("./errors").Warning; 1487 1488 var util = _dereq_("./util"); 1489 1490 var es5 = _dereq_("./es5"); 1491 1492 var canAttachTrace = util.canAttachTrace; 1493 var unhandledRejectionHandled; 1494 var possiblyUnhandledRejection; 1495 var bluebirdFramePattern = /[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/; 1496 var nodeFramePattern = /\((?:timers\.js):\d+:\d+\)/; 1497 var parseLinePattern = /[\/<\(](.+?):(\d+):(\d+)\)?\s*$/; 1498 var stackFramePattern = null; 1499 var formatStack = null; 1500 var indentStackFrames = false; 1501 var printWarning; 1502 var debugging = !!(util.env("BLUEBIRD_DEBUG") != 0 && (true || util.env("BLUEBIRD_DEBUG") || util.env("NODE_ENV") === "development")); 1503 var warnings = !!(util.env("BLUEBIRD_WARNINGS") != 0 && (debugging || util.env("BLUEBIRD_WARNINGS"))); 1504 var longStackTraces = !!(util.env("BLUEBIRD_LONG_STACK_TRACES") != 0 && (debugging || util.env("BLUEBIRD_LONG_STACK_TRACES"))); 1505 var wForgottenReturn = util.env("BLUEBIRD_W_FORGOTTEN_RETURN") != 0 && (warnings || !!util.env("BLUEBIRD_W_FORGOTTEN_RETURN")); 1506 var deferUnhandledRejectionCheck; 1507 1508 (function () { 1509 var promises = []; 1510 1511 function unhandledRejectionCheck() { 1512 for (var i = 0; i < promises.length; ++i) { 1513 promises[i]._notifyUnhandledRejection(); 1514 } 1515 1516 unhandledRejectionClear(); 1517 } 1518 1519 function unhandledRejectionClear() { 1520 promises.length = 0; 1521 } 1522 1523 deferUnhandledRejectionCheck = function deferUnhandledRejectionCheck(promise) { 1524 promises.push(promise); 1525 setTimeout(unhandledRejectionCheck, 1); 1526 }; 1527 1528 es5.defineProperty(Promise, "_unhandledRejectionCheck", { 1529 value: unhandledRejectionCheck 1530 }); 1531 es5.defineProperty(Promise, "_unhandledRejectionClear", { 1532 value: unhandledRejectionClear 1533 }); 1534 })(); 1535 1536 Promise.prototype.suppressUnhandledRejections = function () { 1537 var target = this._target(); 1538 1539 target._bitField = target._bitField & ~1048576 | 524288; 1540 }; 1541 1542 Promise.prototype._ensurePossibleRejectionHandled = function () { 1543 if ((this._bitField & 524288) !== 0) return; 1544 1545 this._setRejectionIsUnhandled(); 1546 1547 deferUnhandledRejectionCheck(this); 1548 }; 1549 1550 Promise.prototype._notifyUnhandledRejectionIsHandled = function () { 1551 fireRejectionEvent("rejectionHandled", unhandledRejectionHandled, undefined, this); 1552 }; 1553 1554 Promise.prototype._setReturnedNonUndefined = function () { 1555 this._bitField = this._bitField | 268435456; 1556 }; 1557 1558 Promise.prototype._returnedNonUndefined = function () { 1559 return (this._bitField & 268435456) !== 0; 1560 }; 1561 1562 Promise.prototype._notifyUnhandledRejection = function () { 1563 if (this._isRejectionUnhandled()) { 1564 var reason = this._settledValue(); 1565 1566 this._setUnhandledRejectionIsNotified(); 1567 1568 fireRejectionEvent("unhandledRejection", possiblyUnhandledRejection, reason, this); 1569 } 1570 }; 1571 1572 Promise.prototype._setUnhandledRejectionIsNotified = function () { 1573 this._bitField = this._bitField | 262144; 1574 }; 1575 1576 Promise.prototype._unsetUnhandledRejectionIsNotified = function () { 1577 this._bitField = this._bitField & ~262144; 1578 }; 1579 1580 Promise.prototype._isUnhandledRejectionNotified = function () { 1581 return (this._bitField & 262144) > 0; 1582 }; 1583 1584 Promise.prototype._setRejectionIsUnhandled = function () { 1585 this._bitField = this._bitField | 1048576; 1586 }; 1587 1588 Promise.prototype._unsetRejectionIsUnhandled = function () { 1589 this._bitField = this._bitField & ~1048576; 1590 1591 if (this._isUnhandledRejectionNotified()) { 1592 this._unsetUnhandledRejectionIsNotified(); 1593 1594 this._notifyUnhandledRejectionIsHandled(); 1595 } 1596 }; 1597 1598 Promise.prototype._isRejectionUnhandled = function () { 1599 return (this._bitField & 1048576) > 0; 1600 }; 1601 1602 Promise.prototype._warn = function (message, shouldUseOwnTrace, promise) { 1603 return warn(message, shouldUseOwnTrace, promise || this); 1604 }; 1605 1606 Promise.onPossiblyUnhandledRejection = function (fn) { 1607 var context = Promise._getContext(); 1608 1609 possiblyUnhandledRejection = util.contextBind(context, fn); 1610 }; 1611 1612 Promise.onUnhandledRejectionHandled = function (fn) { 1613 var context = Promise._getContext(); 1614 1615 unhandledRejectionHandled = util.contextBind(context, fn); 1616 }; 1617 1618 var disableLongStackTraces = function disableLongStackTraces() {}; 1619 1620 Promise.longStackTraces = function () { 1621 if (async.haveItemsQueued() && !config.longStackTraces) { 1622 throw new Error("cannot enable long stack traces after promises have been created\n\n See http://goo.gl/MqrFmX\n"); 1623 } 1624 1625 if (!config.longStackTraces && longStackTracesIsSupported()) { 1626 var Promise_captureStackTrace = Promise.prototype._captureStackTrace; 1627 var Promise_attachExtraTrace = Promise.prototype._attachExtraTrace; 1628 var Promise_dereferenceTrace = Promise.prototype._dereferenceTrace; 1629 config.longStackTraces = true; 1630 1631 disableLongStackTraces = function disableLongStackTraces() { 1632 if (async.haveItemsQueued() && !config.longStackTraces) { 1633 throw new Error("cannot enable long stack traces after promises have been created\n\n See http://goo.gl/MqrFmX\n"); 1634 } 1635 1636 Promise.prototype._captureStackTrace = Promise_captureStackTrace; 1637 Promise.prototype._attachExtraTrace = Promise_attachExtraTrace; 1638 Promise.prototype._dereferenceTrace = Promise_dereferenceTrace; 1639 Context.deactivateLongStackTraces(); 1640 config.longStackTraces = false;
1641 }; 1642 1643 Promise.prototype._captureStackTrace = longStackTracesCaptureStackTrace; 1644 Promise.prototype._attachExtraTrace = longStackTracesAttachExtraTrace; 1645 Promise.prototype._dereferenceTrace = longStackTracesDereferenceTrace; 1646 Context.activateLongStackTraces(); 1647 } 1648 }; 1649 1650 Promise.hasLongStackTraces = function () { 1651 return config.longStackTraces && longStackTracesIsSupported(); 1652 }; 1653 1654 var legacyHandlers = { 1655 unhandledrejection: { 1656 before: function before() { 1657 var ret = util.global.onunhandledrejection; 1658 util.global.onunhandledrejection = null; 1659 return ret; 1660 }, 1661 after: function after(fn) { 1662 util.global.onunhandledrejection = fn; 1663 } 1664 }, 1665 rejectionhandled: { 1666 before: function before() { 1667 var ret = util.global.onrejectionhandled; 1668 util.global.onrejectionhandled = null; 1669 return ret; 1670 }, 1671 after: function after(fn) { 1672 util.global.onrejectionhandled = fn; 1673 } 1674 } 1675 }; 1676 1677 var fireDomEvent = function () { 1678 var dispatch = function dispatch(legacy, e) { 1679 if (legacy) { 1680 var fn; 1681 1682 try { 1683 fn = legacy.before(); 1684 return !util.global.dispatchEvent(e); 1685 } finally { 1686 legacy.after(fn); 1687 } 1688 } else { 1689 return !util.global.dispatchEvent(e); 1690 } 1691 }; 1692 1693 try { 1694 if (typeof CustomEvent === "function") { 1695 var event = new CustomEvent("CustomEvent"); 1696 util.global.dispatchEvent(event); 1697 return function (name, event) { 1698 name = name.toLowerCase(); 1699 var eventData = { 1700 detail: event, 1701 cancelable: true 1702 }; 1703 var domEvent = new CustomEvent(name, eventData); 1704 es5.defineProperty(domEvent, "promise", { 1705 value: event.promise 1706 }); 1707 es5.defineProperty(domEvent, "reason", { 1708 value: event.reason 1709 }); 1710 return dispatch(legacyHandlers[name], domEvent); 1711 }; 1712 } else if (typeof Event === "function") { 1713 var event = new Event("CustomEvent"); 1714 util.global.dispatchEvent(event); 1715 return function (name, event) { 1716 name = name.toLowerCase(); 1717 var domEvent = new Event(name, { 1718 cancelable: true 1719 }); 1720 domEvent.detail = event; 1721 es5.defineProperty(domEvent, "promise", { 1722 value: event.promise 1723 }); 1724 es5.defineProperty(domEvent, "reason", { 1725 value: event.reason 1726 }); 1727 return dispatch(legacyHandlers[name], domEvent); 1728 }; 1729 } else { 1730 var event = document.createEvent("CustomEvent"); 1731 event.initCustomEvent("testingtheevent", false, true, {}); 1732 util.global.dispatchEvent(event); 1733 return function (name, event) { 1734 name = name.toLowerCase(); 1735 var domEvent = document.createEvent("CustomEvent"); 1736 domEvent.initCustomEvent(name, false, true, event); 1737 return dispatch(legacyHandlers[name], domEvent); 1738 }; 1739 } 1740 } catch (e) {} 1741 1742 return function () { 1743 return false; 1744 }; 1745 }(); 1746 1747 var fireGlobalEvent = function () { 1748 if (util.isNode) { 1749 return function () { 1750 return process.emit.apply(process, arguments); 1751 }; 1752 } else { 1753 if (!util.global) { 1754 return function () { 1755 return false;
1756 }; 1757 } 1758 1759 return function (name) { 1760 var methodName = "on" + name.toLowerCase(); 1761 var method = util.global[methodName]; 1762 if (!method) return false; 1763 method.apply(util.global, [].slice.call(arguments, 1)); 1764 return true; 1765 }; 1766 } 1767 }(); 1768 1769 function generatePromiseLifecycleEventObject(name, promise) { 1770 return { 1771 promise: promise 1772 }; 1773 } 1774 1775 var eventToObjectGenerator = { 1776 promiseCreated: generatePromiseLifecycleEventObject, 1777 promiseFulfilled: generatePromiseLifecycleEventObject, 1778 promiseRejected: generatePromiseLifecycleEventObject, 1779 promiseResolved: generatePromiseLifecycleEventObject, 1780 promiseCancelled: generatePromiseLifecycleEventObject, 1781 promiseChained: function promiseChained(name, promise, child) { 1782 return { 1783 promise: promise, 1784 child: child 1785 }; 1786 }, 1787 warning: function warning(name, _warning) { 1788 return { 1789 warning: _warning 1790 }; 1791 }, 1792 unhandledRejection: function unhandledRejection(name, reason, promise) { 1793 return { 1794 reason: reason, 1795 promise: promise 1796 }; 1797 }, 1798 rejectionHandled: generatePromiseLifecycleEventObject 1799 }; 1800 1801 var activeFireEvent = function activeFireEvent(name) { 1802 var globalEventFired = false; 1803 1804 try { 1805 globalEventFired = fireGlobalEvent.apply(null, arguments); 1806 } catch (e) { 1807 async.throwLater(e); 1808 globalEventFired = true; 1809 } 1810 1811 var domEventFired = false; 1812 1813 try { 1814 domEventFired = fireDomEvent(name, eventToObjectGenerator[name].apply(null, arguments)); 1815 } catch (e) { 1816 async.throwLater(e); 1817 domEventFired = true; 1818 } 1819 1820 return domEventFired || globalEventFired; 1821 }; 1822 1823 Promise.config = function (opts) { 1824 opts = Object(opts); 1825 1826 if ("longStackTraces" in opts) { 1827 if (opts.longStackTraces) { 1828 Promise.longStackTraces(); 1829 } else if (!opts.longStackTraces && Promise.hasLongStackTraces()) { 1830 disableLongStackTraces(); 1831 } 1832 } 1833 1834 if ("warnings" in opts) { 1835 var warningsOption = opts.warnings; 1836 config.warnings = !!warningsOption; 1837 wForgottenReturn = config.warnings; 1838 1839 if (util.isObject(warningsOption)) { 1840 if ("wForgottenReturn" in warningsOption) { 1841 wForgottenReturn = !!warningsOption.wForgottenReturn; 1842 } 1843 } 1844 } 1845 1846 if ("cancellation" in opts && opts.cancellation && !config.cancellation) { 1847 if (async.haveItemsQueued()) { 1848 throw new Error("cannot enable cancellation after promises are in use"); 1849 } 1850 1851 Promise.prototype._clearCancellationData = cancellationClearCancellationData; 1852 Promise.prototype._propagateFrom = cancellationPropagateFrom; 1853 Promise.prototype._onCancel = cancellationOnCancel; 1854 Promise.prototype._setOnCancel = cancellationSetOnCancel; 1855 Promise.prototype._attachCancellationCallback = cancellationAttachCancellationCallback; 1856 Promise.prototype._execute = cancellationExecute; 1857 _propagateFromFunction = cancellationPropagateFrom; 1858 config.cancellation = true; 1859 } 1860 1861 if ("monitoring" in opts) { 1862 if (opts.monitoring && !config.monitoring) { 1863 config.monitoring = true; 1864 Promise.prototype._fireEvent = activeFireEvent; 1865 } else if (!opts.monitoring && config.monitoring) { 1866 config.monitoring = false; 1867 Promise.prototype._fireEvent = defaultFireEvent; 1868 } 1869 } 1870 1871 if ("asyncHooks" in opts && util.nodeSupportsAsyncResource) { 1872 var prev = config.asyncHooks; 1873 var cur = !!opts.asyncHooks; 1874 1875 if (prev !== cur) { 1876 config.asyncHooks = cur; 1877 1878 if (cur) { 1879 enableAsyncHooks(); 1880 } else { 1881 disableAsyncHooks(); 1882 } 1883 } 1884 } 1885 1886 return Promise; 1887 }; 1888 1889 function defaultFireEvent() { 1890 return false;
1891 } 1892 1893 Promise.prototype._fireEvent = defaultFireEvent; 1894 1895 Promise.prototype._execute = function (executor, resolve, reject) { 1896 try { 1897 executor(resolve, reject); 1898 } catch (e) { 1899 return e; 1900 } 1901 }; 1902 1903 Promise.prototype._onCancel = function () {}; 1904 1905 Promise.prototype._setOnCancel = function (handler) { 1906 }; 1907 1908 Promise.prototype._attachCancellationCallback = function (onCancel) { 1909 }; 1910 1911 Promise.prototype._captureStackTrace = function () {}; 1912 1913 Promise.prototype._attachExtraTrace = function () {}; 1914 1915 Promise.prototype._dereferenceTrace = function () {}; 1916 1917 Promise.prototype._clearCancellationData = function () {}; 1918 1919 Promise.prototype._propagateFrom = function (parent, flags) { 1920 }; 1921 1922 function cancellationExecute(executor, resolve, reject) { 1923 var promise = this; 1924 1925 try { 1926 executor(resolve, reject, function (onCancel) { 1927 if (typeof onCancel !== "function") { 1928 throw new TypeError("onCancel must be a function, got: " + util.toString(onCancel)); 1929 } 1930 1931 promise._attachCancellationCallback(onCancel); 1932 }); 1933 } catch (e) { 1934 return e; 1935 } 1936 } 1937 1938 function cancellationAttachCancellationCallback(onCancel) { 1939 if (!this._isCancellable()) return this; 1940 1941 var previousOnCancel = this._onCancel(); 1942 1943 if (previousOnCancel !== undefined) { 1944 if (util.isArray(previousOnCancel)) { 1945 previousOnCancel.push(onCancel); 1946 } else { 1947 this._setOnCancel([previousOnCancel, onCancel]); 1948 } 1949 } else { 1950 this._setOnCancel(onCancel); 1951 } 1952 } 1953 1954 function cancellationOnCancel() { 1955 return this._onCancelField; 1956 } 1957 1958 function cancellationSetOnCancel(onCancel) { 1959 this._onCancelField = onCancel; 1960 } 1961 1962 function cancellationClearCancellationData() { 1963 this._cancellationParent = undefined; 1964 this._onCancelField = undefined; 1965 } 1966 1967 function cancellationPropagateFrom(parent, flags) { 1968 if ((flags & 1) !== 0) { 1969 this._cancellationParent = parent; 1970 var branchesRemainingToCancel = parent._branchesRemainingToCancel; 1971 1972 if (branchesRemainingToCancel === undefined) { 1973 branchesRemainingToCancel = 0; 1974 } 1975 1976 parent._branchesRemainingToCancel = branchesRemainingToCancel + 1; 1977 } 1978 1979 if ((flags & 2) !== 0 && parent._isBound()) { 1980 this._setBoundTo(parent._boundTo); 1981 } 1982 } 1983 1984 function bindingPropagateFrom(parent, flags) { 1985 if ((flags & 2) !== 0 && parent._isBound()) { 1986 this._setBoundTo(parent._boundTo); 1987 } 1988 } 1989 1990 var _propagateFromFunction = bindingPropagateFrom; 1991 1992 function _boundValueFunction() { 1993 var ret = this._boundTo; 1994 1995 if (ret !== undefined) { 1996 if (ret instanceof Promise) { 1997 if (ret.isFulfilled()) { 1998 return ret.value(); 1999 } else { 2000 return undefined; 2001 } 2002 } 2003 } 2004 2005 return ret; 2006 } 2007 2008 function longStackTracesCaptureStackTrace() { 2009 this._trace = new CapturedTrace(this._peekContext()); 2010 } 2011 2012 function longStackTracesAttachExtraTrace(error, ignoreSelf) { 2013 if (canAttachTrace(error)) { 2014 var trace = this._trace; 2015 2016 if (trace !== undefined) { 2017 if (ignoreSelf) trace = trace._parent; 2018 } 2019 2020 if (trace !== undefined) { 2021 trace.attachExtraTrace(error); 2022 } else if (!error.__stackCleaned__) { 2023 var parsed = parseStackAndMessage(error); 2024 util.notEnumerableProp(error, "stack", parsed.message + "\n" + parsed.stack.join("\n")); 2025 util.notEnumerableProp(error, "__stackCleaned__", true); 2026 } 2027 } 2028 } 2029 2030 function longStackTracesDereferenceTrace() { 2031 this._trace = undefined; 2032 } 2033 2034 function checkForgottenReturns(returnValue, promiseCreated, name, promise, parent) { 2035 if (returnValue === undefined && promiseCreated !== null && wForgottenReturn) { 2036 if (parent !== undefined && parent._returnedNonUndefined()) return; 2037 if ((promise._bitField & 65535) === 0) return; 2038 if (name) name = name + " "; 2039 var handlerLine = ""; 2040 var creatorLine = ""; 2041 2042 if (promiseCreated._trace) { 2043 var traceLines = promiseCreated._trace.stack.split("\n"); 2044 2045 var stack = cleanStack(traceLines); 2046 2047 for (var i = stack.length - 1; i >= 0; --i) { 2048 var line = stack[i]; 2049 2050 if (!nodeFramePattern.test(line)) { 2051 var lineMatches = line.match(parseLinePattern); 2052 2053 if (lineMatches) { 2054 handlerLine = "at " + lineMatches[1] + ":" + lineMatches[2] + ":" + lineMatches[3] + " "; 2055 } 2056 2057 break; 2058 } 2059 } 2060 2061 if (stack.length > 0) { 2062 var firstUserLine = stack[0]; 2063 2064 for (var i = 0; i < traceLines.length; ++i) { 2065 if (traceLines[i] === firstUserLine) { 2066 if (i > 0) { 2067 creatorLine = "\n" + traceLines[i - 1]; 2068 } 2069 2070 break; 2071 } 2072 } 2073 } 2074 } 2075 2076 var msg = "a promise was created in a " + name + "handler " + handlerLine + "but was not returned from it, " + "see http://goo.gl/rRqMUw" + creatorLine; 2077 2078 promise._warn(msg, true, promiseCreated); 2079 } 2080 } 2081 2082 function deprecated(name, replacement) { 2083 var message = name + " is deprecated and will be removed in a future version."; 2084 if (replacement) message += " Use " + replacement + " instead."; 2085 return warn(message); 2086 } 2087 2088 function warn(message, shouldUseOwnTrace, promise) { 2089 if (!config.warnings) return; 2090 var warning = new Warning(message); 2091 var ctx; 2092 2093 if (shouldUseOwnTrace) { 2094 promise._attachExtraTrace(warning); 2095 } else if (config.longStackTraces && (ctx = Promise._peekContext())) { 2096 ctx.attachExtraTrace(warning); 2097 } else { 2098 var parsed = parseStackAndMessage(warning); 2099 warning.stack = parsed.message + "\n" + parsed.stack.join("\n"); 2100 } 2101 2102 if (!activeFireEvent("warning", warning)) { 2103 formatAndLogError(warning, "", true); 2104 } 2105 } 2106 2107 function reconstructStack(message, stacks) { 2108 for (var i = 0; i < stacks.length - 1; ++i) { 2109 stacks[i].push("From previous event:"); 2110 stacks[i] = stacks[i].join("\n"); 2111 } 2112 2113 if (i < stacks.length) { 2114 stacks[i] = stacks[i].join("\n"); 2115 } 2116 2117 return message + "\n" + stacks.join("\n"); 2118 } 2119 2120 function removeDuplicateOrEmptyJumps(stacks) { 2121 for (var i = 0; i < stacks.length; ++i) { 2122 if (stacks[i].length === 0 || i + 1 < stacks.length && stacks[i][0] === stacks[i + 1][0]) { 2123 stacks.splice(i, 1); 2124 i--; 2125 } 2126 } 2127 } 2128 2129 function removeCommonRoots(stacks) { 2130 var current = stacks[0]; 2131 2132 for (var i = 1; i < stacks.length; ++i) { 2133 var prev = stacks[i]; 2134 var currentLastIndex = current.length - 1; 2135 var currentLastLine = current[currentLastIndex]; 2136 var commonRootMeetPoint = -1; 2137 2138 for (var j = prev.length - 1; j >= 0; --j) { 2139 if (prev[j] === currentLastLine) { 2140 commonRootMeetPoint = j; 2141 break; 2142 } 2143 } 2144 2145 for (var j = commonRootMeetPoint; j >= 0; --j) { 2146 var line = prev[j]; 2147 2148 if (current[currentLastIndex] === line) { 2149 current.pop(); 2150 currentLastIndex--; 2151 } else { 2152 break; 2153 } 2154 } 2155 2156 current = prev; 2157 } 2158 } 2159 2160 function cleanStack(stack) { 2161 var ret = []; 2162 2163 for (var i = 0; i < stack.length; ++i) { 2164 var line = stack[i]; 2165 var isTraceLine = " (No stack trace)" === line || stackFramePattern.test(line); 2166 var isInternalFrame = isTraceLine && shouldIgnore(line); 2167 2168 if (isTraceLine && !isInternalFrame) { 2169 if (indentStackFrames && line.charAt(0) !== " ") { 2170 line = " " + line; 2171 } 2172
2173 ret.push(line); 2174 } 2175 } 2176 2177 return ret; 2178 } 2179 2180 function stackFramesAsArray(error) { 2181 var stack = error.stack.replace(/\s+$/g, "").split("\n"); 2182 2183 for (var i = 0; i < stack.length; ++i) { 2184 var line = stack[i]; 2185 2186 if (" (No stack trace)" === line || stackFramePattern.test(line)) { 2187 break; 2188 } 2189 } 2190 2191 if (i > 0 && error.name != "SyntaxError") { 2192 stack = stack.slice(i); 2193 } 2194 2195 return stack; 2196 } 2197 2198 function parseStackAndMessage(error) { 2199 var stack = error.stack; 2200 var message = error.toString(); 2201 stack = typeof stack === "string" && stack.length > 0 ? stackFramesAsArray(error) : [" (No stack trace)"]; 2202 return { 2203 message: message, 2204 stack: error.name == "SyntaxError" ? stack : cleanStack(stack) 2205 }; 2206 } 2207 2208 function formatAndLogError(error, title, isSoft) { 2209 if (typeof console !== "undefined") { 2210 var message; 2211 2212 if (util.isObject(error)) { 2213 var stack = error.stack; 2214 message = title + formatStack(stack, error); 2215 } else { 2216 message = title + String(error); 2217 } 2218 2219 if (typeof printWarning === "function") { 2220 printWarning(message, isSoft); 2221 } else if (typeof console.log === "function" || babelHelpers.typeof(console.log) === "object") { 2222 console.log(message); 2223 } 2224 } 2225 } 2226 2227 function fireRejectionEvent(name, localHandler, reason, promise) { 2228 var localEventFired = false; 2229 2230 try { 2231 if (typeof localHandler === "function") { 2232 localEventFired = true; 2233 2234 if (name === "rejectionHandled") { 2235 localHandler(promise); 2236 } else { 2237 localHandler(reason, promise); 2238 } 2239 } 2240 } catch (e) { 2241 async.throwLater(e); 2242 } 2243 2244 if (name === "unhandledRejection") { 2245 if (!activeFireEvent(name, reason, promise) && !localEventFired) { 2246 formatAndLogError(reason, "Unhandled rejection "); 2247 } 2248 } else { 2249 activeFireEvent(name, promise); 2250 } 2251 } 2252 2253 function formatNonError(obj) { 2254 var str; 2255 2256 if (typeof obj === "function") { 2257 str = "[function " + (obj.name || "anonymous") + "]"; 2258 } else { 2259 str = obj && typeof obj.toString === "function" ? obj.toString() : util.toString(obj); 2260 var ruselessToString = /\[object [a-zA-Z0-9$_]+\]/; 2261 2262 if (ruselessToString.test(str)) { 2263 try { 2264 var newStr = JSON.stringify(obj); 2265 str = newStr; 2266 } catch (e) {} 2267 } 2268 2269 if (str.length === 0) { 2270 str = "(empty array)"; 2271 } 2272 } 2273 2274 return "(<" + snip(str) + ">, no stack trace)"; 2275 } 2276 2277 function snip(str) { 2278 var maxChars = 41; 2279 2280 if (str.length < maxChars) { 2281 return str; 2282 } 2283 2284 return str.substr(0, maxChars - 3) + "..."; 2285 } 2286 2287 function longStackTracesIsSupported() { 2288 return typeof captureStackTrace === "function"; 2289 } 2290 2291 var shouldIgnore = function shouldIgnore() { 2292 return false; 2293 }; 2294 2295 var parseLineInfoRegex = /[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/; 2296 2297 function parseLineInfo(line) { 2298 var matches = line.match(parseLineInfoRegex); 2299 2300 if (matches) { 2301 return { 2302 fileName: matches[1], 2303 line: parseInt(matches[2], 10) 2304 }; 2305 } 2306 } 2307 2308 function setBounds(firstLineError, lastLineError) { 2309 if (!longStackTracesIsSupported()) return; 2310 var firstStackLines = (firstLineError.stack || "").split("\n"); 2311 var lastStackLines = (lastLineError.stack || "").split("\n"); 2312 var firstIndex = -1; 2313 var lastIndex = -1; 2314 var firstFileName; 2315 var lastFileName; 2316 2317 for (var i = 0; i < firstStackLines.length; ++i) { 2318 var result = parseLineInfo(firstStackLines[i]); 2319 2320 if (result) { 2321 firstFileName = result.fileName; 2322 firstIndex = result.line; 2323 break; 2324 } 2325 } 2326 2327 for (var i = 0; i < lastStackLines.length; ++i) { 2328 var result = parseLineInfo(lastStackLines[i]); 2329 2330 if (result) { 2331 lastFileName = result.fileName; 2332 lastIndex = result.line; 2333 break; 2334 } 2335 } 2336 2337 if (firstIndex < 0 || lastIndex < 0 || !firstFileName || !lastFileName || firstFileName !== lastFileName || firstIndex >= lastIndex) { 2338 return; 2339 } 2340 2341 shouldIgnore = function shouldIgnore(line) { 2342 if (bluebirdFramePattern.test(line)) return true; 2343 var info = parseLineInfo(line); 2344 2345 if (info) { 2346 if (info.fileName === firstFileName && firstIndex <= info.line && info.line <= lastIndex) { 2347 return true; 2348 } 2349 } 2350 2351 return false;
2352 }; 2353 } 2354 2355 function CapturedTrace(parent) { 2356 this._parent = parent; 2357 this._promisesCreated = 0; 2358 var length = this._length = 1 + (parent === undefined ? 0 : parent._length); 2359 captureStackTrace(this, CapturedTrace); 2360 if (length > 32) this.uncycle(); 2361 } 2362 2363 util.inherits(CapturedTrace, Error); 2364 Context.CapturedTrace = CapturedTrace; 2365 2366 CapturedTrace.prototype.uncycle = function () { 2367 var length = this._length; 2368 if (length < 2) return; 2369 var nodes = []; 2370 var stackToIndex = {}; 2371 2372 for (var i = 0, node = this; node !== undefined; ++i) { 2373 nodes.push(node); 2374 node = node._parent; 2375 } 2376 2377 length = this._length = i; 2378 2379 for (var i = length - 1; i >= 0; --i) { 2380 var stack = nodes[i].stack; 2381 2382 if (stackToIndex[stack] === undefined) { 2383 stackToIndex[stack] = i; 2384 } 2385 } 2386 2387 for (var i = 0; i < length; ++i) { 2388 var currentStack = nodes[i].stack; 2389 var index = stackToIndex[currentStack]; 2390 2391 if (index !== undefined && index !== i) { 2392 if (index > 0) { 2393 nodes[index - 1]._parent = undefined; 2394 nodes[index - 1]._length = 1; 2395 } 2396 2397 nodes[i]._parent = undefined; 2398 nodes[i]._length = 1; 2399 var cycleEdgeNode = i > 0 ? nodes[i - 1] : this; 2400 2401 if (index < length - 1) { 2402 cycleEdgeNode._parent = nodes[index + 1]; 2403 2404 cycleEdgeNode._parent.uncycle(); 2405 2406 cycleEdgeNode._length = cycleEdgeNode._parent._length + 1; 2407 } else { 2408 cycleEdgeNode._parent = undefined; 2409 cycleEdgeNode._length = 1; 2410 } 2411 2412 var currentChildLength = cycleEdgeNode._length + 1; 2413 2414 for (var j = i - 2; j >= 0; --j) { 2415 nodes[j]._length = currentChildLength; 2416 currentChildLength++; 2417 } 2418 2419 return; 2420 } 2421 } 2422 }; 2423 2424 CapturedTrace.prototype.attachExtraTrace = function (error) { 2425 if (error.__stackCleaned__) return; 2426 this.uncycle(); 2427 var parsed = parseStackAndMessage(error); 2428 var message = parsed.message; 2429 var stacks = [parsed.stack]; 2430 var trace = this; 2431 2432 while (trace !== undefined) { 2433 stacks.push(cleanStack(trace.stack.split("\n"))); 2434 trace = trace._parent; 2435 } 2436 2437 removeCommonRoots(stacks); 2438 removeDuplicateOrEmptyJumps(stacks); 2439 util.notEnumerableProp(error, "stack", reconstructStack(message, stacks)); 2440 util.notEnumerableProp(error, "__stackCleaned__", true); 2441 }; 2442 2443 var captureStackTrace = function stackDetection() { 2444 var v8stackFramePattern = /^\s*at\s*/; 2445 2446 var v8stackFormatter = function v8stackFormatter(stack, error) { 2447 if (typeof stack === "string") return stack; 2448 2449 if (error.name !== undefined && error.message !== undefined) { 2450 return error.toString(); 2451 } 2452 2453 return formatNonError(error); 2454 }; 2455 2456 if (typeof Error.stackTraceLimit === "number" && typeof Error.captureStackTrace === "function") { 2457 Error.stackTraceLimit += 6; 2458 stackFramePattern = v8stackFramePattern; 2459 formatStack = v8stackFormatter; 2460 var captureStackTrace = Error.captureStackTrace; 2461 2462 shouldIgnore = function shouldIgnore(line) { 2463 return bluebirdFramePattern.test(line); 2464 }; 2465 2466 return function (receiver, ignoreUntil) { 2467 Error.stackTraceLimit += 6; 2468 captureStackTrace(receiver, ignoreUntil); 2469 Error.stackTraceLimit -= 6; 2470 }; 2471 } 2472 2473 var err = new Error(); 2474 2475 if (typeof err.stack === "string" && err.stack.split("\n")[0].indexOf("stackDetection@") >= 0) { 2476 stackFramePattern = /@/; 2477 formatStack = v8stackFormatter; 2478 indentStackFrames = true; 2479 return function captureStackTrace(o) { 2480 o.stack = new Error().stack; 2481 }; 2482 } 2483 2484 var hasStackAfterThrow; 2485 2486 try { 2487 throw new Error(); 2488 } catch (e) { 2489 hasStackAfterThrow = "stack" in e; 2490 } 2491 2492 if (!("stack" in err) && hasStackAfterThrow && typeof Error.stackTraceLimit === "number") { 2493 stackFramePattern = v8stackFramePattern; 2494 formatStack = v8stackFormatter; 2495 return function captureStackTrace(o) { 2496 Error.stackTraceLimit += 6; 2497 2498 try { 2499 throw new Error(); 2500 } catch (e) { 2501 o.stack = e.stack; 2502 } 2503 2504 Error.stackTraceLimit -= 6; 2505 }; 2506 } 2507 2508 formatStack = function formatStack(stack, error) { 2509 if (typeof stack === "string") return stack; 2510 2511 if ((babelHelpers.typeof(error) === "object" || typeof error === "function") && error.
2511name !== undefined && error.message !== undefined) { 2512 return error.toString(); 2513 } 2514 2515 return formatNonError(error); 2516 }; 2517 2518 return null; 2519 }([]); 2520 2521 if (typeof console !== "undefined" && typeof console.warn !== "undefined") { 2522 printWarning = function printWarning(message) { 2523 console.warn(message); 2524 }; 2525 2526 if (util.isNode && process.stderr.isTTY) { 2527 printWarning = function printWarning(message, isSoft) { 2528 var color = isSoft ? "\x1B[33m" : "\x1B[31m"; 2529 console.warn(color + message + "\x1B[0m\n"); 2530 }; 2531 } else if (!util.isNode && typeof new Error().stack === "string") { 2532 printWarning = function printWarning(message, isSoft) { 2533 console.warn("%c" + message, isSoft ? "color: darkorange" : "color: red"); 2534 }; 2535 } 2536 } 2537 2538 var config = { 2539 warnings: warnings, 2540 longStackTraces: false, 2541 cancellation: false, 2542 monitoring: false, 2543 asyncHooks: false 2544 }; 2545 if (longStackTraces) Promise.longStackTraces(); 2546 return { 2547 asyncHooks: function asyncHooks() { 2548 return config.asyncHooks; 2549 }, 2550 longStackTraces: function longStackTraces() { 2551 return config.longStackTraces; 2552 }, 2553 warnings: function warnings() { 2554 return config.warnings; 2555 }, 2556 cancellation: function cancellation() { 2557 return config.cancellation; 2558 }, 2559 monitoring: function monitoring() { 2560 return config.monitoring; 2561 }, 2562 propagateFromFunction: function propagateFromFunction() { 2563 return _propagateFromFunction; 2564 }, 2565 boundValueFunction: function boundValueFunction() { 2566 return _boundValueFunction; 2567 }, 2568 checkForgottenReturns: checkForgottenReturns, 2569 setBounds: setBounds, 2570 warn: warn, 2571 deprecated: deprecated, 2572 CapturedTrace: CapturedTrace, 2573 fireDomEvent: fireDomEvent, 2574 fireGlobalEvent: fireGlobalEvent 2575 }; 2576 }; 2577 }, { 2578 "./errors": 12, 2579 "./es5": 13, 2580 "./util": 36 2581 }], 2582 10: [function (_dereq_, module, exports) { 2583 2584 module.exports = function (Promise) { 2585 function returner() { 2586 return this.value; 2587 } 2588 2589 function thrower() { 2590 throw this.reason; 2591 } 2592 2593 Promise.prototype["return"] = Promise.prototype.thenReturn = function (value) { 2594 if (value instanceof Promise) value.suppressUnhandledRejections(); 2595 return this._then(returner, undefined, undefined, { 2596 value: value 2597 }, undefined); 2598 }; 2599 2600 Promise.prototype["throw"] = Promise.prototype.thenThrow = function (reason) { 2601 return this._then(thrower, undefined, undefined, { 2602 reason: reason 2603 }, undefined); 2604 }; 2605 2606 Promise.prototype.catchThrow = function (reason) { 2607 if (arguments.length <= 1) { 2608 return this._then(undefined, thrower, undefined, { 2609 reason: reason 2610 }, undefined); 2611 } else { 2612 var _reason = arguments[1]; 2613 2614 var handler = function handler() { 2615 throw _reason; 2616 }; 2617 2618 return this.caught(reason, handler); 2619 } 2620 }; 2621 2622 Promise.prototype.catchReturn = function (value) { 2623 if (arguments.length <= 1) { 2624 if (value instanceof Promise) value.suppressUnhandledRejections(); 2625 return this._then(undefined, returner, undefined, { 2626 value: value 2627 }, undefined); 2628 } else { 2629 var _value = arguments[1]; 2630 if (_value instanceof Promise) _value.suppressUnhandledRejections(); 2631 2632 var handler = function handler() { 2633 return _value; 2634 }; 2635 2636 return this.caught(value, handler); 2637 } 2638 }; 2639 }; 2640 }, {}],
2641 11: [function (_dereq_, module, exports) { 2642 2643 module.exports = function (Promise, INTERNAL) { 2644 var PromiseReduce = Promise.reduce; 2645 var PromiseAll = Promise.all; 2646 2647 function promiseAllThis() { 2648 return PromiseAll(this); 2649 } 2650 2651 function PromiseMapSeries(promises, fn) { 2652 return PromiseReduce(promises, fn, INTERNAL, INTERNAL); 2653 } 2654 2655 Promise.prototype.each = function (fn) { 2656 return PromiseReduce(this, fn, INTERNAL, 0)._then(promiseAllThis, undefined, undefined, this, undefined); 2657 }; 2658 2659 Promise.prototype.mapSeries = function (fn) { 2660 return PromiseReduce(this, fn, INTERNAL, INTERNAL); 2661 }; 2662 2663 Promise.each = function (promises, fn) { 2664 return PromiseReduce(promises, fn, INTERNAL, 0)._then(promiseAllThis, undefined, undefined, promises, undefined); 2665 }; 2666 2667 Promise.mapSeries = PromiseMapSeries; 2668 }; 2669 }, {}], 2670 12: [function (_dereq_, module, exports) { 2671 2672 var es5 = _dereq_("./es5"); 2673 2674 var Objectfreeze = es5.freeze; 2675 2676 var util = _dereq_("./util"); 2677 2678 var inherits = util.inherits; 2679 var notEnumerableProp = util.notEnumerableProp; 2680 2681 function subError(nameProperty, defaultMessage) { 2682 function SubError(message) { 2683 if (!(this instanceof SubError)) return new SubError(message); 2684 notEnumerableProp(this, "message", typeof message === "string" ? message : defaultMessage); 2685 notEnumerableProp(this, "name", nameProperty); 2686 2687 if (Error.captureStackTrace) { 2688 Error.captureStackTrace(this, this.constructor); 2689 } else { 2690 Error.call(this); 2691 } 2692 } 2693 2694 inherits(SubError, Error); 2695 return SubError; 2696 } 2697 2698 var _TypeError, _RangeError; 2699 2700 var Warning = subError("Warning", "warning"); 2701 var CancellationError = subError("CancellationError", "cancellation error"); 2702 var TimeoutError = subError("TimeoutError", "timeout error"); 2703 var AggregateError = subError("AggregateError", "aggregate error"); 2704 2705 try { 2706 _TypeError = TypeError; 2707 _RangeError = RangeError; 2708 } catch (e) { 2709 _TypeError = subError("TypeError", "type error"); 2710 _RangeError = subError("RangeError", "range error"); 2711 } 2712 2713 var methods = ("join pop push shift unshift slice filter forEach some " + "every map indexOf lastIndexOf reduce reduceRight sort reverse").split(" "); 2714 2715 for (var i = 0; i < methods.length; ++i) { 2716 if (typeof Array.prototype[methods[i]] === "function") { 2717 AggregateError.prototype[methods[i]] = Array.prototype[methods[i]]; 2718 } 2719 } 2720 2721 es5.defineProperty(AggregateError.prototype, "length", { 2722 value: 0, 2723 configurable: false, 2724 writable: true, 2725 enumerable: true 2726 }); 2727 AggregateError.prototype["isOperational"] = true; 2728 var level = 0; 2729 2730 AggregateError.prototype.toString = function () { 2731 var indent = Array(level * 4 + 1).join(" "); 2732 var ret = "\n" + indent + "AggregateError of:" + "\n"; 2733 level++; 2734 indent = Array(level * 4 + 1).join(" "); 2735 2736 for (var i = 0; i < this.length; ++i) { 2737 var str = this[i] === this ? "[Circular AggregateError]" : this[i] + ""; 2738 var lines = str.split("\n"); 2739 2740 for (var j = 0; j < lines.length; ++j) { 2741 lines[j] = indent + lines[j]; 2742 } 2743 2744 str = lines.join("\n"); 2745 ret += str + "\n"; 2746 } 2747 2748 level--; 2749 return ret; 2750 }; 2751 2752 function OperationalError(message) { 2753 if (!(this instanceof OperationalError)) return new OperationalError(message); 2754 notEnumerableProp(this, "name", "OperationalError"); 2755 notEnumerableProp(this, "message", message); 2756 this.cause = message; 2757 this["isOperational"] = true; 2758 2759 if (message instanceof Error) { 2760 notEnumerableProp(this, "message", message.message); 2761 notEnumerableProp(this, "stack", message.stack); 2762 } else if (Error.captureStackTrace) { 2763 Error.captureStackTrace(this, this.constructor); 2764 } 2765 } 2766 2767 inherits(OperationalError, Error); 2768 var errorTypes = Error["__BluebirdErrorTypes__"]; 2769 2770 if (!errorTypes) { 2771 errorTypes = Objectfreeze({ 2772 CancellationError: CancellationError, 2773 TimeoutError: TimeoutError, 2774 OperationalError: OperationalError, 2775 RejectionError: OperationalError, 2776 AggregateError: AggregateError 2777 }); 2778 es5.defineProperty(Error, "__BluebirdErrorTypes__", { 2779 value: errorTypes, 2780 writable: false, 2781 enumerable: false, 2782 configurable: false 2783 }); 2784 } 2785 2786 module.exports = { 2787 Error: Error, 2788 TypeError: _TypeError, 2789 RangeError: _RangeError, 2790 CancellationError: errorTypes.CancellationError, 2791 OperationalError: errorTypes.OperationalError, 2792 TimeoutError: errorTypes.TimeoutError, 2793 AggregateError: errorTypes.AggregateError, 2794 Warning: Warning 2795 }; 2796 }, { 2797 "./es5": 13, 2798 "./util": 36 2799 }
2799], 2800 13: [function (_dereq_, module, exports) { 2801 var isES5 = function () { 2802 2803 return this === undefined; 2804 }(); 2805 2806 if (isES5) { 2807 module.exports = { 2808 freeze: Object.freeze, 2809 defineProperty: Object.defineProperty, 2810 getDescriptor: Object.getOwnPropertyDescriptor, 2811 keys: Object.keys, 2812 names: Object.getOwnPropertyNames, 2813 getPrototypeOf: Object.getPrototypeOf, 2814 isArray: Array.isArray, 2815 isES5: isES5, 2816 propertyIsWritable: function propertyIsWritable(obj, prop) { 2817 var descriptor = Object.getOwnPropertyDescriptor(obj, prop); 2818 return !!(!descriptor || descriptor.writable || descriptor.set); 2819 } 2820 }; 2821 } else { 2822 var has = {}.hasOwnProperty; 2823 var str = {}.toString; 2824 var proto = {}.constructor.prototype; 2825 2826 var ObjectKeys = function ObjectKeys(o) { 2827 var ret = []; 2828 2829 for (var key in o) { 2830 if (has.call(o, key)) { 2831 ret.push(key); 2832 } 2833 } 2834 2835 return ret; 2836 }; 2837 2838 var ObjectGetDescriptor = function ObjectGetDescriptor(o, key) { 2839 return { 2840 value: o[key] 2841 }; 2842 }; 2843 2844 var ObjectDefineProperty = function ObjectDefineProperty(o, key, desc) { 2845 o[key] = desc.value; 2846 return o; 2847 }; 2848 2849 var ObjectFreeze = function ObjectFreeze(obj) { 2850 return obj; 2851 }; 2852 2853 var ObjectGetPrototypeOf = function ObjectGetPrototypeOf(obj) { 2854 try { 2855 return Object(obj).constructor.prototype; 2856 } catch (e) { 2857 return proto; 2858 } 2859 }; 2860 2861 var ArrayIsArray = function ArrayIsArray(obj) { 2862 try { 2863 return str.call(obj) === "[object Array]"; 2864 } catch (e) { 2865 return false; 2866 } 2867 }; 2868 2869 module.exports = { 2870 isArray: ArrayIsArray, 2871 keys: ObjectKeys, 2872 names: ObjectKeys, 2873 defineProperty: ObjectDefineProperty, 2874 getDescriptor: ObjectGetDescriptor, 2875 freeze: ObjectFreeze, 2876 getPrototypeOf: ObjectGetPrototypeOf, 2877 isES5: isES5, 2878 propertyIsWritable: function propertyIsWritable() { 2879 return true; 2880 } 2881 }; 2882 } 2883 }, {}], 2884 14: [function (_dereq_, module, exports) { 2885 2886 module.exports = function (Promise, INTERNAL) { 2887 var PromiseMap = Promise.map; 2888 2889 Promise.prototype.filter = function (fn, options) { 2890 return PromiseMap(this, fn, options, INTERNAL); 2891 }; 2892 2893 Promise.filter = function (promises, fn, options) { 2894 return PromiseMap(promises, fn, options, INTERNAL); 2895 }; 2896 }; 2897 }, {}], 2898 15: [function (_dereq_, module, exports) { 2899 2900 module.exports = function (Promise, tryConvertToPromise, NEXT_FILTER) { 2901 var util = _dereq_("./util"); 2902 2903 var CancellationError = Promise.CancellationError; 2904 var errorObj = util.errorObj; 2905 2906 var catchFilter = _dereq_("./catch_filter")(NEXT_FILTER); 2907 2908 function PassThroughHandlerContext(promise, type, handler) { 2909 this.promise = promise; 2910 this.type = type; 2911 this.handler = handler; 2912 this.called = false; 2913 this.cancelPromise = null; 2914 } 2915 2916 PassThroughHandlerContext.prototype.isFinallyHandler = function () { 2917 return this.type === 0; 2918 }; 2919 2920 function FinallyHandlerCancelReaction(finallyHandler) { 2921 this.finallyHandler = finallyHandler; 2922 } 2923 2924 FinallyHandlerCancelReaction.prototype._resultCancelled = function () { 2925 checkCancel(this.finallyHandler); 2926 }; 2927 2928 function checkCancel(ctx, reason) { 2929 if (ctx.cancelPromise != null) { 2930 if (arguments.length > 1) { 2931 ctx.cancelPromise._reject(reason); 2932 } else { 2933 ctx.cancelPromise._cancel(); 2934 } 2935 2936 ctx.cancelPromise = null; 2937 return true; 2938 } 2939 2940 return false;
2941 } 2942 2943 function succeed() { 2944 return finallyHandler.call(this, this.promise._target()._settledValue()); 2945 } 2946 2947 function fail(reason) { 2948 if (checkCancel(this, reason)) return; 2949 errorObj.e = reason; 2950 return errorObj; 2951 } 2952 2953 function finallyHandler(reasonOrValue) { 2954 var promise = this.promise; 2955 var handler = this.handler; 2956 2957 if (!this.called) { 2958 this.called = true; 2959 var ret = this.isFinallyHandler() ? handler.call(promise._boundValue()) : handler.call(promise._boundValue(), reasonOrValue); 2960 2961 if (ret === NEXT_FILTER) { 2962 return ret; 2963 } else if (ret !== undefined) { 2964 promise._setReturnedNonUndefined(); 2965 2966 var maybePromise = tryConvertToPromise(ret, promise); 2967 2968 if (maybePromise instanceof Promise) { 2969 if (this.cancelPromise != null) { 2970 if (maybePromise._isCancelled()) { 2971 var reason = new CancellationError("late cancellation observer"); 2972 2973 promise._attachExtraTrace(reason); 2974 2975 errorObj.e = reason; 2976 return errorObj; 2977 } else if (maybePromise.isPending()) { 2978 maybePromise._attachCancellationCallback(new FinallyHandlerCancelReaction(this)); 2979 } 2980 } 2981 2982 return maybePromise._then(succeed, fail, undefined, this, undefined); 2983 } 2984 } 2985 } 2986 2987 if (promise.isRejected()) { 2988 checkCancel(this); 2989 errorObj.e = reasonOrValue; 2990 return errorObj; 2991 } else { 2992 checkCancel(this); 2993 return reasonOrValue; 2994 } 2995 } 2996 2997 Promise.prototype._passThrough = function (handler, type, success, fail) { 2998 if (typeof handler !== "function") return this.then(); 2999 return this._then(success, fail, undefined, new PassThroughHandlerContext(this, type, handler), undefined); 3000 }; 3001 3002 Promise.prototype.lastly = Promise.prototype["finally"] = function (handler) { 3003 return this._passThrough(handler, 0, finallyHandler, finallyHandler); 3004 }; 3005 3006 Promise.prototype.tap = function (handler) { 3007 return this._passThrough(handler, 1, finallyHandler); 3008 }; 3009 3010 Promise.prototype.tapCatch = function (handlerOrPredicate) { 3011 var len = arguments.length; 3012 3013 if (len === 1) { 3014 return this._passThrough(handlerOrPredicate, 1, undefined, finallyHandler); 3015 } else { 3016 var catchInstances = new Array(len - 1), 3017 j = 0, 3018 i; 3019 3020 for (i = 0; i < len - 1; ++i) { 3021 var item = arguments[i]; 3022 3023 if (util.isObject(item)) { 3024 catchInstances[j++] = item; 3025 } else { 3026 return Promise.reject(new TypeError("tapCatch statement predicate: " + "expecting an object but got " + util.classString(item))); 3027 } 3028 } 3029 3030 catchInstances.length = j; 3031 var handler = arguments[i]; 3032 return this._passThrough(catchFilter(catchInstances, handler, this), 1, undefined, finallyHandler); 3033 } 3034 }; 3035 3036 return PassThroughHandlerContext; 3037 }; 3038 }, { 3039 "./catch_filter": 7, 3040 "./util": 36 3041 }], 3042 16: [function (_dereq_, module, exports) { 3043 3044 module.exports = function (Promise, apiRejection, INTERNAL, tryConvertToPromise, Proxyable, debug) { 3045 var errors = _dereq_("./errors"); 3046 3047 var TypeError = errors.TypeError; 3048 3049 var util = _dereq_("./util"); 3050 3051 var errorObj = util.errorObj; 3052 var tryCatch = util.tryCatch; 3053 var yieldHandlers = []; 3054 3055 function promiseFromYieldHandler(value, yieldHandlers, traceParent) { 3056 for (var i = 0; i < yieldHandlers.length; ++i) { 3057 traceParent._pushContext(); 3058 3059 var result = tryCatch(yieldHandlers[i])(value); 3060 3061 traceParent._popContext(); 3062 3063 if (result === errorObj) { 3064 traceParent._pushContext(); 3065 3066 var ret = Promise.reject(errorObj.e); 3067 3068 traceParent._popContext(); 3069 3070 return ret; 3071 } 3072 3073 var maybePromise = tryConvertToPromise(result, traceParent); 3074 if (maybePromise instanceof Promise) return maybePromise; 3075 } 3076 3077 return null; 3078 } 3079 3080 function PromiseSpawn(generatorFunction, receiver, yieldHandler, stack) { 3081 if (debug.cancellation()) { 3082 var internal = new Promise(INTERNAL); 3083 3084 var _finallyPromise = this._finallyPromise = new Promise(INTERNAL); 3085 3086 this._promise = internal.lastly(function () { 3087 return _finallyPromise; 3088 }); 3089 3090 internal._captureStackTrace(); 3091 3092 internal._setOnCancel(this); 3093 } else { 3094 var promise = this._promise = new Promise(INTERNAL); 3095 3096 promise._captureStackTrace(); 3097 } 3098 3099 this._stack = stack; 3100 this._generatorFunction = generatorFunction; 3101 this._receiver = receiver; 3102 this._generator = undefined; 3103 this._yieldHandlers = typeof yieldHandler === "function" ? [yieldHandler].concat(yieldHandlers) : yieldHandlers; 3104 this._yieldedPromise = null; 3105 this._cancellationPhase = false;
3106 } 3107 3108 util.inherits(PromiseSpawn, Proxyable); 3109 3110 PromiseSpawn.prototype._isResolved = function () { 3111 return this._promise === null; 3112 }; 3113 3114 PromiseSpawn.prototype._cleanup = function () { 3115 this._promise = this._generator = null; 3116 3117 if (debug.cancellation() && this._finallyPromise !== null) { 3118 this._finallyPromise._fulfill(); 3119 3120 this._finallyPromise = null; 3121 } 3122 }; 3123 3124 PromiseSpawn.prototype._promiseCancelled = function () { 3125 if (this._isResolved()) return; 3126 var implementsReturn = typeof this._generator["return"] !== "undefined"; 3127 var result; 3128 3129 if (!implementsReturn) { 3130 var reason = new Promise.CancellationError("generator .return() sentinel"); 3131 Promise.coroutine.returnSentinel = reason; 3132 3133 this._promise._attachExtraTrace(reason); 3134 3135 this._promise._pushContext(); 3136 3137 result = tryCatch(this._generator["throw"]).call(this._generator, reason); 3138 3139 this._promise._popContext(); 3140 } else { 3141 this._promise._pushContext(); 3142 3143 result = tryCatch(this._generator["return"]).call(this._generator, undefined); 3144 3145 this._promise._popContext(); 3146 } 3147 3148 this._cancellationPhase = true; 3149 this._yieldedPromise = null; 3150 3151 this._continue(result); 3152 }; 3153 3154 PromiseSpawn.prototype._promiseFulfilled = function (value) { 3155 this._yieldedPromise = null; 3156 3157 this._promise._pushContext(); 3158 3159 var result = tryCatch(this._generator.next).call(this._generator, value); 3160 3161 this._promise._popContext(); 3162 3163 this._continue(result); 3164 }; 3165
3166 PromiseSpawn.prototype._promiseRejected = function (reason) { 3167 this._yieldedPromise = null; 3168 3169 this._promise._attachExtraTrace(reason); 3170 3171 this._promise._pushContext(); 3172 3173 var result = tryCatch(this._generator["throw"]).call(this._generator, reason); 3174 3175 this._promise._popContext(); 3176 3177 this._continue(result); 3178 }; 3179 3180 PromiseSpawn.prototype._resultCancelled = function () { 3181 if (this._yieldedPromise instanceof Promise) { 3182 var promise = this._yieldedPromise; 3183 this._yieldedPromise = null; 3184 promise.cancel(); 3185 } 3186 }; 3187 3188 PromiseSpawn.prototype.promise = function () { 3189 return this._promise; 3190 }; 3191 3192 PromiseSpawn.prototype._run = function () { 3193 this._generator = this._generatorFunction.call(this._receiver); 3194 this._receiver = this._generatorFunction = undefined; 3195 3196 this._promiseFulfilled(undefined); 3197 }; 3198 3199 PromiseSpawn.prototype._continue = function (result) { 3200 var promise = this._promise; 3201 3202 if (result === errorObj) { 3203 this._cleanup(); 3204 3205 if (this._cancellationPhase) { 3206 return promise.cancel(); 3207 } else { 3208 return promise._rejectCallback(result.e, false); 3209 } 3210 } 3211 3212 var value = result.value; 3213 3214 if (result.done === true) { 3215 this._cleanup(); 3216 3217 if (this._cancellationPhase) { 3218 return promise.cancel(); 3219 } else { 3220 return promise._resolveCallback(value); 3221 } 3222 } else { 3223 var maybePromise = tryConvertToPromise(value, this._promise); 3224 3225 if (!(maybePromise instanceof Promise)) { 3226 maybePromise = promiseFromYieldHandler(maybePromise, this._yieldHandlers, this._promise); 3227 3228 if (maybePromise === null) { 3229 this._promiseRejected(new TypeError("A value %s was yielded that could not be treated as a promise\n\n See http://goo.gl/MqrFmX\n\n".replace("%s", String(value)) + "From coroutine:\n" + this._stack.split("\n").slice(1, -7).join("\n"))); 3230 3231 return; 3232 } 3233 } 3234 3235 maybePromise = maybePromise._target(); 3236 var bitField = maybePromise._bitField; 3237 3238 if ((bitField & 50397184) === 0) { 3239 this._yieldedPromise = maybePromise; 3240 3241 maybePromise._proxy(this, null); 3242 } else if ((bitField & 33554432) !== 0) { 3243 Promise._async.invoke(this._promiseFulfilled, this, maybePromise._value()); 3244 } else if ((bitField & 16777216) !== 0) { 3245 Promise._async.invoke(this._promiseRejected, this, maybePromise._reason()); 3246 } else { 3247 this._promiseCancelled(); 3248 } 3249 } 3250 }; 3251 3252 Promise.coroutine = function (generatorFunction, options) { 3253 if (typeof generatorFunction !== "function") { 3254 throw new TypeError("generatorFunction must be a function\n\n See http://goo.gl/MqrFmX\n"); 3255 } 3256 3257 var yieldHandler = Object(options).yieldHandler; 3258 var PromiseSpawn$ = PromiseSpawn; 3259 var stack = new Error().stack; 3260 return function () { 3261 var generator = generatorFunction.apply(this, arguments); 3262 var spawn = new PromiseSpawn$(undefined, undefined, yieldHandler, stack); 3263 var ret = spawn.promise(); 3264 spawn._generator = generator; 3265 3266 spawn._promiseFulfilled(undefined); 3267 3268 return ret; 3269 }; 3270 }; 3271 3272 Promise.coroutine.addYieldHandler = function (fn) { 3273 if (typeof fn !== "function") { 3274 throw new TypeError("expecting a function but got " + util.classString(fn)); 3275 } 3276 3277 yieldHandlers.push(fn); 3278 }; 3279 3280 Promise.spawn = function (generatorFunction) { 3281 debug.deprecated("Promise.spawn()", "Promise.coroutine()"); 3282 3283 if (typeof generatorFunction !== "function") { 3284 return apiRejection("generatorFunction must be a function\n\n See http://goo.gl/MqrFmX\n"); 3285 } 3286 3287 var spawn = new PromiseSpawn(generatorFunction, this); 3288 var ret = spawn.promise(); 3289
3290 spawn._run(Promise.spawn); 3291 3292 return ret; 3293 }; 3294 }; 3295 }, { 3296 "./errors": 12, 3297 "./util": 36 3298 }], 3299 17: [function (_dereq_, module, exports) { 3300 3301 module.exports = function (Promise, PromiseArray, tryConvertToPromise, INTERNAL, async) { 3302 var util = _dereq_("./util"); 3303 3304 var canEvaluate = util.canEvaluate; 3305 var tryCatch = util.tryCatch; 3306 var errorObj = util.errorObj; 3307 3308 Promise.join = function () { 3309 var last = arguments.length - 1; 3310 var fn; 3311 3312 if (last > 0 && typeof arguments[last] === "function") { 3313 fn = arguments[last]; 3314 3315 if (false) { 3316 { 3317 var ret; 3318 } 3319 } 3320 } 3321 3322 var args = [].slice.call(arguments); 3323 if (fn) args.pop(); 3324 var ret = new PromiseArray(args).promise(); 3325 return fn !== undefined ? ret.spread(fn) : ret; 3326 }; 3327 }; 3328 }, { 3329 "./util": 36 3330 }], 3331 18: [function (_dereq_, module, exports) { 3332 3333 module.exports = function (Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug) { 3334 var util = _dereq_("./util"); 3335 3336 var tryCatch = util.tryCatch; 3337 var errorObj = util.errorObj; 3338 var async = Promise._async; 3339 3340 function MappingPromiseArray(promises, fn, limit, _filter) { 3341 this.constructor$(promises); 3342 3343 this._promise._captureStackTrace(); 3344 3345 var context = Promise._getContext(); 3346 3347 this._callback = util.contextBind(context, fn); 3348 this._preservedValues = _filter === INTERNAL ? new Array(this.length()) : null; 3349 this._limit = limit; 3350 this._inFlight = 0; 3351 this._queue = []; 3352 async.invoke(this._asyncInit, this, undefined); 3353 3354 if (util.isArray(promises)) { 3355 for (var i = 0; i < promises.length; ++i) { 3356 var maybePromise = promises[i]; 3357 3358 if (maybePromise instanceof Promise) { 3359 maybePromise.suppressUnhandledRejections(); 3360 } 3361 } 3362 } 3363 } 3364 3365 util.inherits(MappingPromiseArray, PromiseArray); 3366 3367 MappingPromiseArray.prototype._asyncInit = function () { 3368 this._init$(undefined, -2); 3369 }; 3370 3371 MappingPromiseArray.prototype._init = function () {}; 3372 3373 MappingPromiseArray.prototype._promiseFulfilled = function (value, index) { 3374 var values = this._values; 3375 var length = this.length(); 3376 var preservedValues = this._preservedValues; 3377 var limit = this._limit; 3378 3379 if (index < 0) { 3380 index = index * -1 - 1; 3381 values[index] = value; 3382 3383 if (limit >= 1) { 3384 this._inFlight--; 3385 3386 this._drainQueue(); 3387 3388 if (this._isResolved()) return true; 3389 } 3390 } else { 3391 if (limit >= 1 && this._inFlight >= limit) { 3392 values[index] = value; 3393 3394 this._queue.push(index); 3395 3396 return false; 3397 } 3398 3399 if (preservedValues !== null) preservedValues[index] = value; 3400 var promise = this._promise; 3401 var callback = this._callback; 3402 3403 var receiver = promise._boundValue(); 3404 3405 promise._pushContext(); 3406 3407 var ret = tryCatch(callback).call(receiver, value, index, length); 3408 3409 var promiseCreated = promise._popContext(); 3410 3411 debug.checkForgottenReturns(ret, promiseCreated, preservedValues !== null ? "Promise.filter" : "Promise.map", promise); 3412 3413 if (ret === errorObj) { 3414 this._reject(ret.e); 3415 3416 return true; 3417 } 3418 3419 var maybePromise = tryConvertToPromise(ret, this._promise); 3420 3421 if (maybePromise instanceof Promise) { 3422 maybePromise = maybePromise._target(); 3423 var bitField = maybePromise._bitField; 3424 3425 if ((bitField & 50397184) === 0) { 3426 if (limit >= 1) this._inFlight++; 3427 values[index] = maybePromise; 3428 3429 maybePromise._proxy(this, (index + 1) * -1); 3430 3431 return false;
3432 } else if ((bitField & 33554432) !== 0) { 3433 ret = maybePromise._value(); 3434 } else if ((bitField & 16777216) !== 0) { 3435 this._reject(maybePromise._reason()); 3436 3437 return true; 3438 } else { 3439 this._cancel(); 3440 3441 return true; 3442 } 3443 } 3444 3445 values[index] = ret; 3446 } 3447 3448 var totalResolved = ++this._totalResolved; 3449 3450 if (totalResolved >= length) { 3451 if (preservedValues !== null) { 3452 this._filter(values, preservedValues); 3453 } else { 3454 this._resolve(values); 3455 } 3456 3457 return true; 3458 } 3459 3460 return false; 3461 }; 3462 3463 MappingPromiseArray.prototype._drainQueue = function () { 3464 var queue = this._queue; 3465 var limit = this._limit; 3466 var values = this._values; 3467 3468 while (queue.length > 0 && this._inFlight < limit) { 3469 if (this._isResolved()) return; 3470 var index = queue.pop(); 3471 3472 this._promiseFulfilled(values[index], index); 3473 } 3474 }; 3475 3476 MappingPromiseArray.prototype._filter = function (booleans, values) { 3477 var len = values.length; 3478 var ret = new Array(len); 3479 var j = 0; 3480 3481 for (var i = 0; i < len; ++i) { 3482 if (booleans[i]) ret[j++] = values[i]; 3483 } 3484 3485 ret.length = j; 3486 3487 this._resolve(ret); 3488 }; 3489 3490 MappingPromiseArray.prototype.preservedValues = function () { 3491 return this._preservedValues; 3492 }; 3493 3494 function map(promises, fn, options, _filter) { 3495 if (typeof fn !== "function") { 3496 return apiRejection("expecting a function but got " + util.classString(fn)); 3497 } 3498 3499 var limit = 0; 3500 3501 if (options !== undefined) { 3502 if (babelHelpers.typeof(options) === "object" && options !== null) { 3503 if (typeof options.concurrency !== "number") { 3504 return Promise.reject(new TypeError("'concurrency' must be a number but it is " + util.classString(options.concurrency))); 3505 } 3506 3507 limit = options.concurrency; 3508 } else { 3509 return Promise.reject(new TypeError("options argument must be an object but it is " + util.classString(options))); 3510 } 3511 } 3512 3513 limit = typeof limit === "number" && isFinite(limit) && limit >= 1 ? limit : 0; 3514 return new MappingPromiseArray(promises, fn, limit, _filter).promise(); 3515 } 3516 3517 Promise.prototype.map = function (fn, options) { 3518 return map(this, fn, options, null); 3519 }; 3520 3521 Promise.map = function (promises, fn, options, _filter) { 3522 return map(promises, fn, options, _filter); 3523 }; 3524 }; 3525 }, { 3526 "./util": 36 3527 }], 3528 19: [function (_dereq_, module, exports) { 3529 3530 module.exports = function (Promise, INTERNAL, tryConvertToPromise, apiRejection, debug) { 3531 var util = _dereq_("./util"); 3532 3533 var tryCatch = util.tryCatch; 3534 3535 Promise.method = function (fn) { 3536 if (typeof fn !== "function") { 3537 throw new Promise.TypeError("expecting a function but got " + util.classString(fn)); 3538 } 3539 3540 return function () { 3541 var ret = new Promise(INTERNAL); 3542 3543 ret._captureStackTrace(); 3544 3545 ret._pushContext(); 3546 3547 var value = tryCatch(fn).apply(this, arguments); 3548 3549 var promiseCreated = ret._popContext(); 3550 3551 debug.checkForgottenReturns(value, promiseCreated, "Promise.method", ret); 3552 3553 ret._resolveFromSyncValue(value); 3554 3555 return ret; 3556 }; 3557 }; 3558 3559 Promise.attempt = Promise["try"] = function (fn) { 3560 if (typeof fn !== "function") { 3561 return apiRejection("expecting a function but got " + util.classString(fn)); 3562 } 3563 3564 var ret = new Promise(INTERNAL); 3565 3566 ret._captureStackTrace(); 3567 3568 ret._pushContext(); 3569 3570 var value; 3571 3572 if (arguments.length > 1) { 3573 debug.deprecated("calling Promise.try with more than 1 argument"); 3574 var arg = arguments[1]; 3575 var ctx = arguments[2]; 3576 value = util.isArray(arg) ? tryCatch(fn).apply(ctx, arg) : tryCatch(fn).call(ctx, arg); 3577 } else { 3578 value = tryCatch(fn)(); 3579 } 3580 3581 var promiseCreated = ret._popContext(); 3582 3583 debug.checkForgottenReturns(value, promiseCreated, "Promise.try", ret); 3584 3585 ret._resolveFromSyncValue(value); 3586 3587 return ret; 3588 }; 3589 3590 Promise.prototype._resolveFromSyncValue = function (value) { 3591 if (value === util.errorObj) { 3592 this._rejectCallback(value.e, false); 3593 } else { 3594 this._resolveCallback(value, true); 3595 } 3596 }; 3597 }; 3598 }, { 3599 "./util": 36 3600 }
3600], 3601 20: [function (_dereq_, module, exports) { 3602 3603 var util = _dereq_("./util"); 3604 3605 var maybeWrapAsError = util.maybeWrapAsError; 3606 3607 var errors = _dereq_("./errors"); 3608 3609 var OperationalError = errors.OperationalError; 3610 3611 var es5 = _dereq_("./es5"); 3612 3613 function isUntypedError(obj) { 3614 return obj instanceof Error && es5.getPrototypeOf(obj) === Error.prototype; 3615 } 3616 3617 var rErrorKey = /^(?:name|message|stack|cause)$/; 3618 3619 function wrapAsOperationalError(obj) { 3620 var ret; 3621 3622 if (isUntypedError(obj)) { 3623 ret = new OperationalError(obj); 3624 ret.name = obj.name; 3625 ret.message = obj.message; 3626 ret.stack = obj.stack; 3627 var keys = es5.keys(obj); 3628 3629 for (var i = 0; i < keys.length; ++i) { 3630 var key = keys[i]; 3631 3632 if (!rErrorKey.test(key)) { 3633 ret[key] = obj[key]; 3634 } 3635 } 3636 3637 return ret; 3638 } 3639 3640 util.markAsOriginatingFromRejection(obj); 3641 return obj; 3642 } 3643 3644 function nodebackForPromise(promise, multiArgs) { 3645 return function (err, value) { 3646 if (promise === null) return; 3647 3648 if (err) { 3649 var wrapped = wrapAsOperationalError(maybeWrapAsError(err)); 3650 3651 promise._attachExtraTrace(wrapped); 3652 3653 promise._reject(wrapped); 3654 } else if (!multiArgs) { 3655 promise._fulfill(value); 3656 } else { 3657 var args = [].slice.call(arguments, 1); 3658 3659 promise._fulfill(args); 3660 } 3661 3662 promise = null; 3663 }; 3664 } 3665 3666 module.exports = nodebackForPromise; 3667 }, { 3668 "./errors": 12, 3669 "./es5": 13, 3670 "./util": 36 3671 }], 3672 21: [function (_dereq_, module, exports) { 3673 3674 module.exports = function (Promise) { 3675 var util = _dereq_("./util"); 3676 3677 var async = Promise._async; 3678 var tryCatch = util.tryCatch; 3679 var errorObj = util.errorObj; 3680 3681 function spreadAdapter(val, nodeback) { 3682 var promise = this; 3683 if (!util.isArray(val)) return successAdapter.call(promise, val, nodeback); 3684 var ret = tryCatch(nodeback).apply(promise._boundValue(), [null].concat(val)); 3685 3686 if (ret === errorObj) { 3687 async.throwLater(ret.e); 3688 } 3689 } 3690 3691 function successAdapter(val, nodeback) { 3692 var promise = this; 3693 3694 var receiver = promise._boundValue(); 3695 3696 var ret = val === undefined ? tryCatch(nodeback).call(receiver, null) : tryCatch(nodeback).call(receiver, null, val); 3697 3698 if (ret === errorObj) { 3699 async.throwLater(ret.e); 3700 } 3701 } 3702 3703 function errorAdapter(reason, nodeback) { 3704 var promise = this; 3705 3706 if (!reason) { 3707 var newReason = new Error(reason + ""); 3708 newReason.cause = reason; 3709 reason = newReason; 3710 } 3711 3712 var ret = tryCatch(nodeback).call(promise._boundValue(), reason); 3713 3714 if (ret === errorObj) { 3715 async.throwLater(ret.e); 3716 } 3717 } 3718 3719 Promise.prototype.asCallback = Promise.prototype.nodeify = function (nodeback, options) { 3720 if (typeof nodeback == "function") { 3721 var adapter = successAdapter; 3722 3723 if (options !== undefined && Object(options).spread) { 3724 adapter = spreadAdapter; 3725 } 3726 3727 this._then(adapter, errorAdapter, undefined, this, nodeback); 3728 } 3729 3730 return this; 3731 }; 3732 }; 3733 }, { 3734 "./util": 36 3735 }], 3736 22: [function (_dereq_, module, exports) { 3737 3738 module.exports = function () { 3739 var makeSelfResolutionError = function makeSelfResolutionError() { 3740 return new TypeError("circular promise resolution chain\n\n See http://goo.gl/MqrFmX\n"); 3741 }; 3742 3743 var reflectHandler = function reflectHandler() { 3744 return new Promise.PromiseInspection(this._target()); 3745 }; 3746 3747 var apiRejection = function apiRejection(msg) { 3748 return Promise.reject(new TypeError(msg)); 3749 }; 3750 3751 function Proxyable() {} 3752 3753 var UNDEFINED_BINDING = {}; 3754 3755 var util = _dereq_("./util"); 3756 3757 util.setReflectHandler(reflectHandler); 3758 3759 var getDomain = function getDomain() { 3760 var domain = process.domain; 3761 3762 if (domain === undefined) { 3763 return null; 3764 } 3765 3766 return domain; 3767 }; 3768 3769 var getContextDefault = function getContextDefault() { 3770 return null; 3771 }; 3772 3773 var getContextDomain = function getContextDomain() { 3774 return { 3775 domain: getDomain(), 3776 async: null 3777 }; 3778 }; 3779 3780 var AsyncResource = util.isNode && util.nodeSupportsAsyncResource ? _dereq_("async_hooks").AsyncResource : null; 3781 3782 var getContextAsyncHooks = function getContextAsyncHooks() { 3783 return { 3784 domain: getDomain(), 3785 async: new AsyncResource("Bluebird::Promise") 3786 }; 3787 }; 3788 3789 var getContext = util.isNode ? getContextDomain : getContextDefault; 3790 util.notEnumerableProp(Promise, "_getContext", getContext); 3791 3792 var enableAsyncHooks = function enableAsyncHooks() { 3793 getContext = getContextAsyncHooks; 3794 util.notEnumerableProp(Promise, "_getContext", getContextAsyncHooks); 3795 }; 3796 3797 var disableAsyncHooks = function disableAsyncHooks() { 3798 getContext = getContextDomain; 3799 util.notEnumerableProp(Promise, "_getContext", getContextDomain); 3800 }; 3801
3802 var es5 = _dereq_("./es5"); 3803 3804 var Async = _dereq_("./async"); 3805 3806 var async = new Async(); 3807 es5.defineProperty(Promise, "_async", { 3808 value: async 3809 }); 3810 3811 var errors = _dereq_("./errors"); 3812 3813 var TypeError = Promise.TypeError = errors.TypeError; 3814 Promise.RangeError = errors.RangeError; 3815 var CancellationError = Promise.CancellationError = errors.CancellationError; 3816 Promise.TimeoutError = errors.TimeoutError; 3817 Promise.OperationalError = errors.OperationalError; 3818 Promise.RejectionError = errors.OperationalError; 3819 Promise.AggregateError = errors.AggregateError; 3820 3821 var INTERNAL = function INTERNAL() {}; 3822 3823 var APPLY = {}; 3824 var NEXT_FILTER = {}; 3825 3826 var tryConvertToPromise = _dereq_("./thenables")(Promise, INTERNAL); 3827 3828 var PromiseArray = _dereq_("./promise_array")(Promise, INTERNAL, tryConvertToPromise, apiRejection, Proxyable); 3829 3830 var Context = _dereq_("./context")(Promise); 3831 /*jshint unused:false*/ 3832 3833 3834 var createContext = Context.create; 3835 3836 var debug = _dereq_("./debuggability")(Promise, Context, enableAsyncHooks, disableAsyncHooks); 3837 3838 var CapturedTrace = debug.CapturedTrace; 3839 3840 var PassThroughHandlerContext = _dereq_("./finally")(Promise, tryConvertToPromise, NEXT_FILTER); 3841 3842 var catchFilter = _dereq_("./catch_filter")(NEXT_FILTER); 3843 3844 var nodebackForPromise = _dereq_("./nodeback"); 3845 3846 var errorObj = util.errorObj; 3847 var tryCatch = util.tryCatch; 3848 3849 function check(self, executor) { 3850 if (self == null || self.constructor !== Promise) { 3851 throw new TypeError("the promise constructor cannot be invoked directly\n\n See http://goo.gl/MqrFmX\n"); 3852 } 3853 3854 if (typeof executor !== "function") { 3855 throw new TypeError("expecting a function but got " + util.classString(executor)); 3856 } 3857 } 3858 3859 function Promise(executor) { 3860 if (executor !== INTERNAL) { 3861 check(this, executor); 3862 } 3863 3864 this._bitField = 0; 3865 this._fulfillmentHandler0 = undefined; 3866 this._rejectionHandler0 = undefined; 3867 this._promise0 = undefined; 3868 this._receiver0 = undefined; 3869 3870 this._resolveFromExecutor(executor); 3871 3872 this._promiseCreated(); 3873 3874 this._fireEvent("promiseCreated", this); 3875 } 3876 3877 Promise.prototype.toString = function () { 3878 return "[object Promise]"; 3879 }; 3880 3881 Promise.prototype.caught = Promise.prototype["catch"] = function (fn) { 3882 var len = arguments.length; 3883 3884 if (len > 1) { 3885 var catchInstances = new Array(len - 1), 3886 j = 0, 3887 i; 3888 3889 for (i = 0; i < len - 1; ++i) { 3890 var item = arguments[i]; 3891 3892 if (util.isObject(item)) { 3893 catchInstances[j++] = item; 3894 } else { 3895 return apiRejection("Catch statement predicate: " + "expecting an object but got " + util.classString(item)); 3896 } 3897 } 3898 3899 catchInstances.length = j; 3900 fn = arguments[i]; 3901 3902 if (typeof fn !== "function") { 3903 throw new TypeError("The last argument to .catch() " + "must be a function, got " + util.toString(fn)); 3904 } 3905 3906 return this.then(undefined, catchFilter(catchInstances, fn, this)); 3907 } 3908 3909 return this.then(undefined, fn); 3910 }; 3911 3912 Promise.prototype.reflect = function () { 3913 return this._then(reflectHandler, reflectHandler, undefined, this, undefined); 3914 }; 3915 3916 Promise.prototype.then = function (didFulfill, didReject) { 3917 if (debug.warnings() && arguments.length > 0 && typeof didFulfill !== "function" && typeof didReject !== "function") { 3918 var msg = ".then() only accepts functions but was passed: " + util.classString(didFulfill); 3919 3920 if (arguments.length > 1) { 3921 msg += ", " + util.classString(didReject); 3922 } 3923 3924 this._warn(msg); 3925 } 3926 3927 return this._then(didFulfill, didReject, undefined, undefined, undefined); 3928 }; 3929 3930 Promise.prototype.done = function (didFulfill, didReject) { 3931 var promise = this._then(didFulfill, didReject, undefined, undefined, undefined); 3932 3933 promise._setIsFinal(); 3934 }; 3935 3936 Promise.prototype.spread = function (fn) { 3937 if (typeof fn !== "function") { 3938 return apiRejection("expecting a function but got " + util.classString(fn)); 3939 } 3940 3941 return this.all()._then(fn, undefined, undefined, APPLY, undefined); 3942 }; 3943 3944 Promise.prototype.toJSON = function () { 3945 var ret = { 3946 isFulfilled: false, 3947 isRejected: false, 3948 fulfillmentValue: undefined, 3949 rejectionReason: undefined 3950 }; 3951 3952 if (this.isFulfilled()) { 3953 ret.fulfillmentValue = this.value(); 3954 ret.isFulfilled = true; 3955 } else if (this.isRejected()) { 3956 ret.rejectionReason = this.reason(); 3957 ret.isRejected = true; 3958 } 3959 3960 return ret; 3961 }; 3962 3963 Promise.prototype.all = function () { 3964 if (arguments.length > 0) { 3965 this._warn(".all() was passed arguments but it does not take any"); 3966 } 3967 3968 return new PromiseArray(this).promise(); 3969 }; 3970 3971 Promise.prototype.error = function (fn) { 3972 return this.caught(util.originatesFromRejection, fn); 3973 }; 3974 3975 Promise.getNewLibraryCopy = module.exports; 3976 3977 Promise.is = function (val) { 3978 return val instanceof Promise; 3979 }; 3980 3981 Promise.fromNode = Promise.fromCallback = function (fn) { 3982 var ret = new Promise(INTERNAL); 3983 3984 ret._captureStackTrace(); 3985 3986 var multiArgs = arguments.length > 1 ? !!Object(arguments[1]).multiArgs : false;
3987 var result = tryCatch(fn)(nodebackForPromise(ret, multiArgs)); 3988 3989 if (result === errorObj) { 3990 ret._rejectCallback(result.e, true); 3991 } 3992 3993 if (!ret._isFateSealed()) ret._setAsyncGuaranteed(); 3994 return ret; 3995 }; 3996 3997 Promise.all = function (promises) { 3998 return new PromiseArray(promises).promise(); 3999 }; 4000 4001 Promise.cast = function (obj) { 4002 var ret = tryConvertToPromise(obj); 4003 4004 if (!(ret instanceof Promise)) { 4005 ret = new Promise(INTERNAL); 4006 4007 ret._captureStackTrace(); 4008 4009 ret._setFulfilled(); 4010 4011 ret._rejectionHandler0 = obj; 4012 } 4013 4014 return ret; 4015 }; 4016 4017 Promise.resolve = Promise.fulfilled = Promise.cast; 4018 4019 Promise.reject = Promise.rejected = function (reason) { 4020 var ret = new Promise(INTERNAL); 4021 4022 ret._captureStackTrace(); 4023 4024 ret._rejectCallback(reason, true); 4025 4026 return ret; 4027 }; 4028 4029 Promise.setScheduler = function (fn) { 4030 if (typeof fn !== "function") { 4031 throw new TypeError("expecting a function but got " + util.classString(fn)); 4032 } 4033 4034 return async.setScheduler(fn); 4035 }; 4036 4037 Promise.prototype._then = function (didFulfill, didReject, _, receiver, internalData) { 4038 var haveInternalData = internalData !== undefined; 4039 var promise = haveInternalData ? internalData : new Promise(INTERNAL); 4040 4041 var target = this._target(); 4042 4043 var bitField = target._bitField; 4044 4045 if (!haveInternalData) { 4046 promise._propagateFrom(this, 3); 4047 4048 promise._captureStackTrace(); 4049 4050 if (receiver === undefined && (this._bitField & 2097152) !== 0) { 4051 if (!((bitField & 50397184) === 0)) { 4052 receiver = this._boundValue(); 4053 } else { 4054 receiver = target === this ? undefined : this._boundTo; 4055 } 4056 } 4057 4058 this._fireEvent("promiseChained", this, promise); 4059 } 4060 4061 var context = getContext(); 4062 4063 if (!((bitField & 50397184) === 0)) { 4064 var handler, 4065 value, 4066 settler = target._settlePromiseCtx; 4067 4068 if ((bitField & 33554432) !== 0) { 4069 value = target._rejectionHandler0; 4070 handler = didFulfill; 4071 } else if ((bitField & 16777216) !== 0) { 4072 value = target._fulfillmentHandler0; 4073 handler = didReject; 4074 4075 target._unsetRejectionIsUnhandled(); 4076 } else { 4077 settler = target._settlePromiseLateCancellationObserver; 4078 value = new CancellationError("late cancellation observer"); 4079 4080 target._attachExtraTrace(value); 4081 4082 handler = didReject; 4083 } 4084 4085 async.invoke(settler, target, { 4086 handler: util.contextBind(context, handler), 4087 promise: promise, 4088 receiver: receiver, 4089 value: value 4090 }); 4091 } else { 4092 target._addCallbacks(didFulfill, didReject, promise, receiver, context); 4093 } 4094 4095 return promise; 4096 }; 4097 4098 Promise.prototype._length = function () { 4099 return this._bitField & 65535; 4100 }; 4101 4102 Promise.prototype._isFateSealed = function () { 4103 return (this._bitField & 117506048) !== 0; 4104 }; 4105 4106 Promise.prototype._isFollowing = function () { 4107 return (this._bitField & 67108864) === 67108864; 4108 }; 4109 4110 Promise.prototype._setLength = function (len) { 4111 this._bitField = this._bitField & -65536 | len & 65535; 4112 }; 4113 4114 Promise.prototype._setFulfilled = function () { 4115 this._bitField = this._bitField | 33554432; 4116 4117 this._fireEvent("promiseFulfilled", this); 4118 }; 4119 4120 Promise.prototype._setRejected = function () { 4121 this._bitField = this._bitField | 16777216; 4122
4123 this._fireEvent("promiseRejected", this); 4124 }; 4125 4126 Promise.prototype._setFollowing = function () { 4127 this._bitField = this._bitField | 67108864; 4128 4129 this._fireEvent("promiseResolved", this); 4130 }; 4131 4132 Promise.prototype._setIsFinal = function () { 4133 this._bitField = this._bitField | 4194304; 4134 }; 4135 4136 Promise.prototype._isFinal = function () { 4137 return (this._bitField & 4194304) > 0; 4138 }; 4139 4140 Promise.prototype._unsetCancelled = function () { 4141 this._bitField = this._bitField & ~65536; 4142 }; 4143 4144 Promise.prototype._setCancelled = function () { 4145 this._bitField = this._bitField | 65536; 4146 4147 this._fireEvent("promiseCancelled", this); 4148 }; 4149 4150 Promise.prototype._setWillBeCancelled = function () { 4151 this._bitField = this._bitField | 8388608; 4152 }; 4153 4154 Promise.prototype._setAsyncGuaranteed = function () { 4155 if (async.hasCustomScheduler()) return; 4156 var bitField = this._bitField; 4157 this._bitField = bitField | (bitField & 536870912) >> 2 ^ 134217728; 4158 }; 4159 4160 Promise.prototype._setNoAsyncGuarantee = function () { 4161 this._bitField = (this._bitField | 536870912) & ~134217728; 4162 }; 4163 4164 Promise.prototype._receiverAt = function (index) { 4165 var ret = index === 0 ? this._receiver0 : this[index * 4 - 4 + 3]; 4166 4167 if (ret === UNDEFINED_BINDING) { 4168 return undefined; 4169 } else if (ret === undefined && this._isBound()) { 4170 return this._boundValue(); 4171 } 4172 4173 return ret; 4174 }; 4175 4176 Promise.prototype._promiseAt = function (index) { 4177 return this[index * 4 - 4 + 2]; 4178 }; 4179 4180 Promise.prototype._fulfillmentHandlerAt = function (index) { 4181 return this[index * 4 - 4 + 0]; 4182 }; 4183 4184 Promise.prototype._rejectionHandlerAt = function (index) { 4185 return this[index * 4 - 4 + 1]; 4186 }; 4187 4188 Promise.prototype._boundValue = function () {}; 4189 4190 Promise.prototype._migrateCallback0 = function (follower) { 4191 var bitField = follower._bitField; 4192 var fulfill = follower._fulfillmentHandler0; 4193 var reject = follower._rejectionHandler0; 4194 var promise = follower._promise0; 4195 4196 var receiver = follower._receiverAt(0); 4197 4198 if (receiver === undefined) receiver = UNDEFINED_BINDING; 4199 4200 this._addCallbacks(fulfill, reject, promise, receiver, null); 4201 }; 4202 4203 Promise.prototype._migrateCallbackAt = function (follower, index) { 4204 var fulfill = follower._fulfillmentHandlerAt(index); 4205 4206 var reject = follower._rejectionHandlerAt(index); 4207 4208 var promise = follower._promiseAt(index); 4209 4210 var receiver = follower._receiverAt(index); 4211 4212 if (receiver === undefined) receiver = UNDEFINED_BINDING; 4213 4214 this._addCallbacks(fulfill, reject, promise, receiver, null); 4215 }; 4216 4217 Promise.prototype._addCallbacks = function (fulfill, reject, promise, receiver, context) { 4218 var index = this._length(); 4219 4220 if (index >= 65535 - 4) { 4221 index = 0; 4222 4223 this._setLength(0); 4224 } 4225 4226 if (index === 0) { 4227 this._promise0 = promise; 4228 this._receiver0 = receiver; 4229 4230 if (typeof fulfill === "function") { 4231 this._fulfillmentHandler0 = util.contextBind(context, fulfill); 4232 } 4233 4234 if (typeof reject === "function") { 4235 this._rejectionHandler0 = util.contextBind(context, reject); 4236 } 4237 } else { 4238 var base = index * 4 - 4; 4239 this[base + 2] = promise; 4240 this[base + 3] = receiver; 4241 4242 if (typeof fulfill === "function") { 4243 this[base + 0] = util.contextBind(context, fulfill); 4244 } 4245 4246 if (typeof reject === "function") { 4247 this[base + 1] = util.contextBind(context, reject); 4248 } 4249 } 4250 4251 this._setLength(index + 1); 4252 4253 return index; 4254 }; 4255 4256 Promise.prototype._proxy = function (proxyable, arg) { 4257 this._addCallbacks(undefined, undefined, arg, proxyable, null); 4258 }; 4259 4260 Promise.prototype._resolveCallback = function (value, shouldBind) { 4261 if ((this._bitField & 117506048) !== 0) return; 4262 if (value === this) return this._rejectCallback(makeSelfResolutionError(), false); 4263 var maybePromise = tryConvertToPromise(value, this); 4264 if (!(maybePromise instanceof Promise)) return this._fulfill(value); 4265 if (shouldBind) this._propagateFrom(maybePromise, 2); 4266 4267 var promise = maybePromise._target(); 4268 4269 if (promise === this) { 4270 this._reject(makeSelfResolutionError()); 4271 4272 return; 4273 } 4274 4275 var bitField = promise._bitField; 4276 4277 if ((bitField & 50397184) === 0) { 4278 var len = this._length(); 4279 4280 if (len > 0) promise._migrateCallback0(this); 4281 4282 for (var i = 1; i < len; ++i) { 4283 promise._migrateCallbackAt(this, i); 4284 } 4285 4286 this._setFollowing(); 4287 4288 this._setLength(0); 4289 4290 this._setFollowee(maybePromise); 4291 } else if ((bitField & 33554432) !== 0) { 4292 this._fulfill(promise._value()); 4293 } else if ((bitField & 16777216) !== 0) { 4294 this._reject(promise._reason()); 4295 } else { 4296 var reason = new CancellationError("late cancellation observer"); 4297 4298 promise._attachExtraTrace(reason); 4299 4300 this._reject(reason); 4301 } 4302 }; 4303 4304 Promise.prototype._rejectCallback = function (reason, synchronous, ignoreNonErrorWarnings) { 4305 var trace = util.ensureErrorObject(reason); 4306 var hasStack = trace === reason; 4307 4308 if (!hasStack && !ignoreNonErrorWarnings && debug.warnings()) { 4309 var message = "a promise was rejected with a non-error: " + util.classString(reason); 4310 4311 this._warn(message, true); 4312 } 4313 4314 this._attachExtraTrace(trace, synchronous ? hasStack : false); 4315 4316 this._reject(reason); 4317 }; 4318 4319 Promise.prototype._resolveFromExecutor = function (executor) { 4320 if (executor === INTERNAL) return; 4321 var promise = this; 4322 4323 this._captureStackTrace(); 4324 4325 this._pushContext(); 4326 4327 var synchronous = true; 4328 4329 var r = this._execute(executor, function (value) { 4330 promise._resolveCallback(value); 4331 }, function (reason) { 4332 promise._rejectCallback(reason, synchronous); 4333 }); 4334 4335 synchronous = false;
4336 4337 this._popContext(); 4338 4339 if (r !== undefined) { 4340 promise._rejectCallback(r, true); 4341 } 4342 }; 4343 4344 Promise.prototype._settlePromiseFromHandler = function (handler, receiver, value, promise) { 4345 var bitField = promise._bitField; 4346 if ((bitField & 65536) !== 0) return; 4347 4348 promise._pushContext(); 4349 4350 var x; 4351 4352 if (receiver === APPLY) { 4353 if (!value || typeof value.length !== "number") { 4354 x = errorObj; 4355 x.e = new TypeError("cannot .spread() a non-array: " + util.classString(value)); 4356 } else { 4357 x = tryCatch(handler).apply(this._boundValue(), value); 4358 } 4359 } else { 4360 x = tryCatch(handler).call(receiver, value); 4361 } 4362 4363 var promiseCreated = promise._popContext(); 4364 4365 bitField = promise._bitField; 4366 if ((bitField & 65536) !== 0) return; 4367 4368 if (x === NEXT_FILTER) { 4369 promise._reject(value); 4370 } else if (x === errorObj) { 4371 promise._rejectCallback(x.e, false); 4372 } else { 4373 debug.checkForgottenReturns(x, promiseCreated, "", promise, this); 4374 4375 promise._resolveCallback(x); 4376 } 4377 }; 4378 4379 Promise.prototype._target = function () { 4380 var ret = this; 4381 4382 while (ret._isFollowing()) { 4383 ret = ret._followee(); 4384 } 4385 4386 return ret; 4387 }; 4388 4389 Promise.prototype._followee = function () { 4390 return this._rejectionHandler0; 4391 }; 4392 4393 Promise.prototype._setFollowee = function (promise) { 4394 this._rejectionHandler0 = promise; 4395 }; 4396 4397 Promise.prototype._settlePromise = function (promise, handler, receiver, value) { 4398 var isPromise = promise instanceof Promise; 4399 var bitField = this._bitField; 4400 var asyncGuaranteed = (bitField & 134217728) !== 0; 4401 4402 if ((bitField & 65536) !== 0) { 4403 if (isPromise) promise._invokeInternalOnCancel(); 4404 4405 if (receiver instanceof PassThroughHandlerContext && receiver.isFinallyHandler()) { 4406 receiver.cancelPromise = promise; 4407 4408 if (tryCatch(handler).call(receiver, value) === errorObj) { 4409 promise._reject(errorObj.e); 4410 } 4411 } else if (handler === reflectHandler) { 4412 promise._fulfill(reflectHandler.call(receiver)); 4413 } else if (receiver instanceof Proxyable) { 4414 receiver._promiseCancelled(promise); 4415 } else if (isPromise || promise instanceof PromiseArray) { 4416 promise._cancel(); 4417 } else { 4418 receiver.cancel(); 4419 } 4420 } else if (typeof handler === "function") { 4421 if (!isPromise) { 4422 handler.call(receiver, value, promise); 4423 } else { 4424 if (asyncGuaranteed) promise._setAsyncGuaranteed(); 4425 4426 this._settlePromiseFromHandler(handler, receiver, value, promise); 4427 } 4428 } else if (receiver instanceof Proxyable) { 4429 if (!receiver._isResolved()) { 4430 if ((bitField & 33554432) !== 0) { 4431 receiver._promiseFulfilled(value, promise); 4432 } else {
4433 receiver._promiseRejected(value, promise); 4434 } 4435 } 4436 } else if (isPromise) { 4437 if (asyncGuaranteed) promise._setAsyncGuaranteed(); 4438 4439 if ((bitField & 33554432) !== 0) { 4440 promise._fulfill(value); 4441 } else { 4442 promise._reject(value); 4443 } 4444 } 4445 }; 4446 4447 Promise.prototype._settlePromiseLateCancellationObserver = function (ctx) { 4448 var handler = ctx.handler; 4449 var promise = ctx.promise; 4450 var receiver = ctx.receiver; 4451 var value = ctx.value; 4452 4453 if (typeof handler === "function") { 4454 if (!(promise instanceof Promise)) { 4455 handler.call(receiver, value, promise); 4456 } else { 4457 this._settlePromiseFromHandler(handler, receiver, value, promise); 4458 } 4459 } else if (promise instanceof Promise) { 4460 promise._reject(value); 4461 } 4462 }; 4463 4464 Promise.prototype._settlePromiseCtx = function (ctx) { 4465 this._settlePromise(ctx.promise, ctx.handler, ctx.receiver, ctx.value); 4466 }; 4467 4468 Promise.prototype._settlePromise0 = function (handler, value, bitField) { 4469 var promise = this._promise0; 4470 4471 var receiver = this._receiverAt(0); 4472 4473 this._promise0 = undefined; 4474 this._receiver0 = undefined; 4475 4476 this._settlePromise(promise, handler, receiver, value); 4477 }; 4478 4479 Promise.prototype._clearCallbackDataAtIndex = function (index) { 4480 var base = index * 4 - 4; 4481 this[base + 2] = this[base + 3] = this[base + 0] = this[base + 1] = undefined; 4482 }; 4483 4484 Promise.prototype._fulfill = function (value) { 4485 var bitField = this._bitField; 4486 if ((bitField & 117506048) >>> 16) return; 4487 4488 if (value === this) { 4489 var err = makeSelfResolutionError(); 4490 4491 this._attachExtraTrace(err); 4492 4493 return this._reject(err); 4494 } 4495 4496 this._setFulfilled(); 4497 4498 this._rejectionHandler0 = value; 4499 4500 if ((bitField & 65535) > 0) { 4501 if ((bitField & 134217728) !== 0) { 4502 this._settlePromises(); 4503 } else { 4504 async.settlePromises(this); 4505 } 4506 4507 this._dereferenceTrace(); 4508 } 4509 }; 4510 4511 Promise.prototype._reject = function (reason) { 4512 var bitField = this._bitField; 4513 if ((bitField & 117506048) >>> 16) return; 4514 4515 this._setRejected(); 4516 4517 this._fulfillmentHandler0 = reason; 4518 4519 if (this._isFinal()) { 4520 return async.fatalError(reason, util.isNode); 4521 } 4522 4523 if ((bitField & 65535) > 0) { 4524 async.settlePromises(this); 4525 } else { 4526 this._ensurePossibleRejectionHandled(); 4527 } 4528 }; 4529 4530 Promise.prototype._fulfillPromises = function (len, value) { 4531 for (var i = 1; i < len; i++) { 4532 var handler = this._fulfillmentHandlerAt(i); 4533 4534 var promise = this._promiseAt(i); 4535 4536 var receiver = this._receiverAt(i); 4537 4538 this._clearCallbackDataAtIndex(i); 4539 4540 this._settlePromise(promise, handler, receiver, value); 4541 } 4542 }; 4543 4544 Promise.prototype._rejectPromises = function (len, reason) { 4545 for (var i = 1; i < len; i++) { 4546 var handler = this._rejectionHandlerAt(i); 4547 4548 var promise = this._promiseAt(i); 4549 4550 var receiver = this._receiverAt(i); 4551 4552 this._clearCallbackDataAtIndex(i); 4553 4554 this._settlePromise(promise, handler, receiver, reason); 4555 } 4556 }; 4557 4558 Promise.prototype._settlePromises = function () { 4559 var bitField = this._bitField; 4560 var len = bitField & 65535; 4561 4562 if (len > 0) { 4563 if ((bitField & 16842752) !== 0) { 4564 var reason = this._fulfillmentHandler0; 4565 4566 this._settlePromise0(this._rejectionHandler0, reason, bitField); 4567 4568 this._rejectPromises(len, reason); 4569 } else { 4570 var value = this._rejectionHandler0; 4571 4572 this._settlePromise0(this._fulfillmentHandler0, value, bitField); 4573 4574 this._fulfillPromises(len, value); 4575 } 4576 4577 this._setLength(0); 4578 } 4579 4580 this._clearCancellationData(); 4581 }; 4582 4583 Promise.prototype._settledValue = function () { 4584 var bitField = this._bitField; 4585 4586 if ((bitField & 33554432) !== 0) { 4587 return this._rejectionHandler0; 4588 } else if ((bitField & 16777216) !== 0) { 4589 return this._fulfillmentHandler0; 4590 } 4591 }; 4592 4593 if (typeof Symbol !== "undefined" && Symbol.toStringTag) { 4594 es5.defineProperty(Promise.prototype, Symbol.toStringTag, { 4595 get: function get() { 4596 return "Object"; 4597 } 4598 }); 4599 } 4600 4601 function deferResolve(v) { 4602 this.promise._resolveCallback(v); 4603 } 4604 4605 function deferReject(v) { 4606 this.promise._rejectCallback(v, false); 4607 } 4608 4609 Promise.defer = Promise.pending = function () { 4610 debug.deprecated("Promise.defer", "new Promise"); 4611 var promise = new Promise(INTERNAL); 4612 return { 4613 promise: promise, 4614 resolve: deferResolve, 4615 reject: deferReject 4616 }; 4617 }; 4618 4619 util.notEnumerableProp(Promise, "_makeSelfResolutionError", makeSelfResolutionError); 4620 4621 _dereq_("./method")(Promise, INTERNAL, tryConvertToPromise, apiRejection, debug); 4622 4623 _dereq_("./bind")(Promise, INTERNAL, tryConvertToPromise, debug); 4624 4625 _dereq_("./cancel")(Promise, PromiseArray, apiRejection, debug); 4626 4627 _dereq_("./direct_resolve")(Promise); 4628 4629 _dereq_("./synchronous_inspection")(Promise); 4630 4631 _dereq_("./join")(Promise, PromiseArray, tryConvertToPromise, INTERNAL, async); 4632 4633 Promise.Promise = Promise; 4634 Promise.version = "3.7.2"; 4635 4636 _dereq_('./call_get.js')(Promise); 4637 4638 _dereq_('./generators.js')(Promise, apiRejection, INTERNAL, tryConvertToPromise, Proxyable, debug); 4639 4640 _dereq_('./map.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug); 4641 4642 _dereq_('./nodeify.js')(Promise); 4643 4644 _dereq_('./promisify.js')(Promise, INTERNAL); 4645 4646 _dereq_('./props.js')(Promise, PromiseArray, tryConvertToPromise, apiRejection); 4647 4648 _dereq_('./race.js')(Promise, INTERNAL, tryConvertToPromise, apiRejection); 4649 4650 _dereq_('./reduce.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug); 4651 4652 _dereq_('./settle.js')(Promise, PromiseArray, debug); 4653 4654 _dereq_('./some.js')(Promise, PromiseArray, apiRejection); 4655 4656 _dereq_('./timers.js')(Promise, INTERNAL, debug); 4657 4658 _dereq_('./using.js')(Promise, apiRejection, tryConvertToPromise, createContext, INT
4658ERNAL, debug); 4659 4660 _dereq_('./any.js')(Promise); 4661 4662 _dereq_('./each.js')(Promise, INTERNAL); 4663 4664 _dereq_('./filter.js')(Promise, INTERNAL); 4665 4666 util.toFastProperties(Promise); 4667 util.toFastProperties(Promise.prototype); 4668 4669 function fillTypes(value) { 4670 var p = new Promise(INTERNAL); 4671 p._fulfillmentHandler0 = value; 4672 p._rejectionHandler0 = value; 4673 p._promise0 = value; 4674 p._receiver0 = value; 4675 } // Complete slack tracking, opt out of field-type tracking and 4676 // stabilize map 4677 4678 4679 fillTypes({ 4680 a: 1 4681 }); 4682 fillTypes({ 4683 b: 2 4684 }); 4685 fillTypes({ 4686 c: 3 4687 }); 4688 fillTypes(1); 4689 fillTypes(function () {}); 4690 fillTypes(undefined); 4691 fillTypes(false); 4692 fillTypes(new Promise(INTERNAL)); 4693 debug.setBounds(Async.firstLineError, util.lastLineError); 4694 return Promise; 4695 }; 4696 }, { 4697 "./any.js": 1, 4698 "./async": 2, 4699 "./bind": 3, 4700 "./call_get.js": 5, 4701 "./cancel": 6, 4702 "./catch_filter": 7, 4703 "./context": 8, 4704 "./debuggability": 9, 4705 "./direct_resolve": 10, 4706 "./each.js": 11, 4707 "./errors": 12, 4708 "./es5": 13, 4709 "./filter.js": 14, 4710 "./finally": 15, 4711 "./generators.js": 16, 4712 "./join": 17, 4713 "./map.js": 18, 4714 "./method": 19, 4715 "./nodeback": 20, 4716 "./nodeify.js": 21, 4717 "./promise_array": 23, 4718 "./promisify.js": 24, 4719 "./props.js": 25, 4720 "./race.js": 27, 4721 "./reduce.js": 28, 4722 "./settle.js": 30, 4723 "./some.js": 31, 4724 "./synchronous_inspection": 32, 4725 "./thenables": 33, 4726 "./timers.js": 34, 4727 "./using.js": 35, 4728 "./util": 36, 4729 "async_hooks": undefined 4730 }], 4731 23: [function (_dereq_, module, exports) { 4732 4733 module.exports = function (Promise, INTERNAL, tryConvertToPromise, apiRejection, Proxyable) { 4734 var util = _dereq_("./util"); 4735 4736 var isArray = util.isArray; 4737 4738 function toResolutionValue(val) { 4739 switch (val) { 4740 case -2: 4741 return []; 4742 4743 case -3: 4744 return {}; 4745 4746 case -6: 4747 return new Map(); 4748 } 4749 } 4750 4751 function PromiseArray(values) { 4752 var promise = this._promise = new Promise(INTERNAL); 4753 4754 if (values instanceof Promise) { 4755 promise._propagateFrom(values, 3); 4756 4757 values.suppressUnhandledRejections(); 4758 } 4759 4760 promise._setOnCancel(this); 4761 4762 this._values = values; 4763 this._length = 0; 4764 this._totalResolved = 0; 4765 4766 this._init(undefined, -2); 4767 } 4768 4769 util.inherits(PromiseArray, Proxyable); 4770 4771 PromiseArray.prototype.length = function () { 4772 return this._length; 4773 }; 4774 4775 PromiseArray.prototype.promise = function () { 4776 return this._promise; 4777 }; 4778 4779 PromiseArray.prototype._init = function init(_, resolveValueIfEmpty) { 4780 var values = tryConvertToPromise(this._values, this._promise); 4781 4782 if (values instanceof Promise) { 4783 values = values._target(); 4784 var bitField = values._bitField; 4785 this._values = values; 4786 4787 if ((bitField & 50397184) === 0) { 4788 this._promise._setAsyncGuaranteed(); 4789 4790 return values._then(init, this._reject, undefined, this, resolveValueIfEmpty); 4791 } else if ((bitField & 33554432) !== 0) { 4792 values = values._value(); 4793 } else if ((bitField & 16777216) !== 0) { 4794 return this._reject(values._reason()); 4795 } else { 4796 return this._cancel(); 4797 } 4798 } 4799 4800 values = util.asArray(values); 4801 4802 if (values === null) { 4803 var err = apiRejection("expecting an array or an iterable object but got " + util.classString(values)).reason(); 4804 4805 this._promise._rejectCallback(err, false); 4806 4807 return; 4808 } 4809 4810 if (values.length === 0) { 4811 if (resolveValueIfEmpty === -5) { 4812 this._resolveEmptyArray(); 4813 } else { 4814 this._resolve(toResolutionValue(resolveValueIfEmpty)); 4815 } 4816 4817 return; 4818 } 4819 4820 this._iterate(values); 4821 }; 4822 4823 PromiseArray.prototype._iterate = function (values) { 4824 var len = this.getActualLength(values.length); 4825 this._length = len; 4826 this._values = this.shouldCopyValues() ? new Array(len) : this._values; 4827 var result = this._promise; 4828 var isResolved = false;
4829 var bitField = null; 4830 4831 for (var i = 0; i < len; ++i) { 4832 var maybePromise = tryConvertToPromise(values[i], result); 4833 4834 if (maybePromise instanceof Promise) { 4835 maybePromise = maybePromise._target(); 4836 bitField = maybePromise._bitField; 4837 } else { 4838 bitField = null; 4839 } 4840 4841 if (isResolved) { 4842 if (bitField !== null) { 4843 maybePromise.suppressUnhandledRejections(); 4844 } 4845 } else if (bitField !== null) { 4846 if ((bitField & 50397184) === 0) { 4847 maybePromise._proxy(this, i); 4848 4849 this._values[i] = maybePromise; 4850 } else if ((bitField & 33554432) !== 0) { 4851 isResolved = this._promiseFulfilled(maybePromise._value(), i); 4852 } else if ((bitField & 16777216) !== 0) { 4853 isResolved = this._promiseRejected(maybePromise._reason(), i); 4854 } else { 4855 isResolved = this._promiseCancelled(i); 4856 } 4857 } else { 4858 isResolved = this._promiseFulfilled(maybePromise, i); 4859 } 4860 } 4861 4862 if (!isResolved) result._setAsyncGuaranteed(); 4863 }; 4864 4865 PromiseArray.prototype._isResolved = function () { 4866 return this._values === null; 4867 }; 4868 4869 PromiseArray.prototype._resolve = function (value) { 4870 this._values = null; 4871 4872 this._promise._fulfill(value); 4873 }; 4874 4875 PromiseArray.prototype._cancel = function () { 4876 if (this._isResolved() || !this._promise._isCancellable()) return; 4877 this._values = null; 4878 4879 this._promise._cancel(); 4880 }; 4881 4882 PromiseArray.prototype._reject = function (reason) { 4883 this._values = null; 4884 4885 this._promise._rejectCallback(reason, false); 4886 }; 4887 4888 PromiseArray.prototype._promiseFulfilled = function (value, index) { 4889 this._values[index] = value; 4890 var totalResolved = ++this._totalResolved; 4891 4892 if (totalResolved >= this._length) { 4893 this._resolve(this._values); 4894 4895 return true; 4896 } 4897 4898 return false; 4899 }; 4900 4901 PromiseArray.prototype._promiseCancelled = function () { 4902 this._cancel(); 4903 4904 return true; 4905 }; 4906
4907 PromiseArray.prototype._promiseRejected = function (reason) { 4908 this._totalResolved++; 4909 4910 this._reject(reason); 4911 4912 return true; 4913 }; 4914 4915 PromiseArray.prototype._resultCancelled = function () { 4916 if (this._isResolved()) return; 4917 var values = this._values; 4918 4919 this._cancel(); 4920 4921 if (values instanceof Promise) { 4922 values.cancel(); 4923 } else { 4924 for (var i = 0; i < values.length; ++i) { 4925 if (values[i] instanceof Promise) { 4926 values[i].cancel(); 4927 } 4928 } 4929 } 4930 }; 4931 4932 PromiseArray.prototype.shouldCopyValues = function () { 4933 return true; 4934 }; 4935 4936 PromiseArray.prototype.getActualLength = function (len) { 4937 return len; 4938 }; 4939 4940 return PromiseArray; 4941 }; 4942 }, { 4943 "./util": 36 4944 }], 4945 24: [function (_dereq_, module, exports) { 4946 4947 module.exports = function (Promise, INTERNAL) { 4948 var THIS = {}; 4949 4950 var util = _dereq_("./util"); 4951 4952 var nodebackForPromise = _dereq_("./nodeback"); 4953 4954 var withAppended = util.withAppended; 4955 var maybeWrapAsError = util.maybeWrapAsError; 4956 var canEvaluate = util.canEvaluate; 4957 4958 var TypeError = _dereq_("./errors").TypeError; 4959 4960 var defaultSuffix = "Async"; 4961 var defaultPromisified = { 4962 __isPromisified__: true 4963 }; 4964 var noCopyProps = ["arity", "length", "name", "arguments", "caller", "callee", "prototype", "__isPromisified__"]; 4965 var noCopyPropsPattern = new RegExp("^(?:" + noCopyProps.join("|") + ")$"); 4966 4967 var defaultFilter = function defaultFilter(name) { 4968 return util.isIdentifier(name) && name.charAt(0) !== "_" && name !== "constructor"; 4969 }; 4970 4971 function propsFilter(key) { 4972 return !noCopyPropsPattern.test(key); 4973 } 4974 4975 function isPromisified(fn) { 4976 try { 4977 return fn.__isPromisified__ === true; 4978 } catch (e) { 4979 return false; 4980 } 4981 } 4982 4983 function hasPromisified(obj, key, suffix) { 4984 var val = util.getDataPropertyOrDefault(obj, key + suffix, defaultPromisified); 4985 return val ? isPromisified(val) : false; 4986 } 4987 4988 function checkValid(ret, suffix, suffixRegexp) { 4989 for (var i = 0; i < ret.length; i += 2) { 4990 var key = ret[i]; 4991 4992 if (suffixRegexp.test(key)) { 4993 var keyWithoutAsyncSuffix = key.replace(suffixRegexp, ""); 4994 4995 for (var j = 0; j < ret.length; j += 2) { 4996 if (ret[j] === keyWithoutAsyncSuffix) { 4997 throw new TypeError("Cannot promisify an API that has normal methods with '%s'-suffix\n\n See http://goo.gl/MqrFmX\n".replace("%s", suffix)); 4998 } 4999 } 5000 } 5001 } 5002 } 5003 5004 function promisifiableMethods(obj, suffix, suffixRegexp, filter) { 5005 var keys = util.inheritedDataKeys(obj); 5006 var ret = []; 5007 5008 for (var i = 0; i < keys.length; ++i) { 5009 var key = keys[i]; 5010 var value = obj[key]; 5011 var passesDefaultFilter = filter === defaultFilter ? true : defaultFilter(key, value, obj); 5012 5013 if (typeof value === "function" && !isPromisified(value) && !hasPromisified(obj, key, suffix) && filter(key, value, obj, passesDefaultFilter)) { 5014 ret.push(key, value); 5015 } 5016 } 5017 5018 checkValid(ret, suffix, suffixRegexp); 5019 return ret; 5020 } 5021 5022 var escapeIdentRegex = function escapeIdentRegex(str) { 5023 return str.replace(/([$])/, "\\$"); 5024 }; 5025 5026 var makeNodePromisifiedEval; 5027 5028 function makeNodePromisifiedClosure(callback, receiver, _, fn, __, multiArgs) { 5029 var defaultThis = function () { 5030 return this; 5031 }(); 5032 5033 var method = callback; 5034 5035 if (typeof method === "string") { 5036 callback = fn; 5037 } 5038 5039 function promisified() { 5040 var _receiver = receiver; 5041 if (receiver === THIS) _receiver = this; 5042 var promise = new Promise(INTERNAL); 5043 5044 promise._captureStackTrace(); 5045 5046 var cb = typeof method === "string" && this !== defaultThis ? this[method] : callback; 5047 var fn = nodebackForPromise(promise, multiArgs); 5048 5049 try { 5050 cb.apply(_receiver, withAppended(arguments, fn)); 5051 } catch (e) { 5052 promise._rejectCallback(maybeWrapAsError(e), true, true); 5053 } 5054 5055 if (!promise._isFateSealed()) promise._setAsyncGuaranteed(); 5056 return promise; 5057 } 5058 5059 util.notEnumerableProp(promisified, "__isPromisified__", true); 5060 return promisified; 5061 } 5062 5063 var makeNodePromisified = canEvaluate ? makeNodePromisifiedEval : makeNodePromisifiedClosure; 5064 5065 function promisifyAll(obj, suffix, filter, promisifier, multiArgs) { 5066 var suffixRegexp = new RegExp(escapeIdentRegex(suffix) + "$"); 5067 var methods = promisifiableMethods(obj, suffix, suffixRegexp, filter); 5068 5069 for (var i = 0, len = methods.length; i < len; i += 2) { 5070 var key = methods[i]; 5071 var fn = methods[i + 1]; 5072 var promisifiedKey = key + suffix; 5073 5074 if (promisifier === makeNodePromisified) { 5075 obj[promisifiedKey] = makeNodePromisified(key, THIS, key, fn, suffix, multiArgs); 5076 } else { 5077 var promisified = promisifier(fn, function () { 5078 return makeNodePromisified(key, THIS, key, fn, suffix, multiArgs); 5079 }); 5080 util.notEnumerableProp(promisified, "__isPromisified__", true); 5081 obj[promisifiedKey] = promisified; 5082 } 5083 } 5084 5085 util.toFastProperties(obj); 5086 return obj; 5087 } 5088 5089 function promisify(callback, receiver, multiArgs) { 5090 return makeNodePromisified(callback, receiver, undefined, callback, null, multiArgs); 5091 } 5092 5093 Promise.promisify = function (fn, options) { 5094 if (typeof fn !== "function") { 5095 throw new TypeError("expecting a function but got " + util.classString(fn)); 5096 } 5097
5098 if (isPromisified(fn)) { 5099 return fn; 5100 } 5101 5102 options = Object(options); 5103 var receiver = options.context === undefined ? THIS : options.context; 5104 var multiArgs = !!options.multiArgs; 5105 var ret = promisify(fn, receiver, multiArgs); 5106 util.copyDescriptors(fn, ret, propsFilter); 5107 return ret; 5108 }; 5109 5110 Promise.promisifyAll = function (target, options) { 5111 if (typeof target !== "function" && babelHelpers.typeof(target) !== "object") { 5112 throw new TypeError("the target of promisifyAll must be an object or a function\n\n See http://goo.gl/MqrFmX\n"); 5113 } 5114 5115 options = Object(options); 5116 var multiArgs = !!options.multiArgs; 5117 var suffix = options.suffix; 5118 if (typeof suffix !== "string") suffix = defaultSuffix; 5119 var filter = options.filter; 5120 if (typeof filter !== "function") filter = defaultFilter; 5121 var promisifier = options.promisifier; 5122 if (typeof promisifier !== "function") promisifier = makeNodePromisified; 5123 5124 if (!util.isIdentifier(suffix)) { 5125 throw new RangeError("suffix must be a valid identifier\n\n See http://goo.gl/MqrFmX\n"); 5126 } 5127 5128 var keys = util.inheritedDataKeys(target); 5129 5130 for (var i = 0; i < keys.length; ++i) { 5131 var value = target[keys[i]]; 5132 5133 if (keys[i] !== "constructor" && util.isClass(value)) { 5134 promisifyAll(value.prototype, suffix, filter, promisifier, multiArgs); 5135 promisifyAll(value, suffix, filter, promisifier, multiArgs); 5136 } 5137 } 5138 5139 return promisifyAll(target, suffix, filter, promisifier, multiArgs); 5140 }; 5141 }; 5142 }, { 5143 "./errors": 12, 5144 "./nodeback": 20, 5145 "./util": 36 5146 }], 5147 25: [function (_dereq_, module, exports) { 5148 5149 module.exports = function (Promise, PromiseArray, tryConvertToPromise, apiRejection) { 5150 var util = _dereq_("./util"); 5151 5152 var isObject = util.isObject; 5153 5154 var es5 = _dereq_("./es5"); 5155 5156 var Es6Map; 5157 if (typeof Map === "function") Es6Map = Map; 5158 5159 var mapToEntries = function () { 5160 var index = 0; 5161 var size = 0; 5162 5163 function extractEntry(value, key) { 5164 this[index] = value; 5165 this[index + size] = key; 5166 index++; 5167 } 5168 5169 return function mapToEntries(map) { 5170 size = map.size; 5171 index = 0; 5172 var ret = new Array(map.size * 2); 5173 map.forEach(extractEntry, ret); 5174 return ret; 5175 }; 5176 }(); 5177 5178 var entriesToMap = function entriesToMap(entries) { 5179 var ret = new Es6Map(); 5180 var length = entries.length / 2 | 0; 5181 5182 for (var i = 0; i < length; ++i) { 5183 var key = entries[length + i]; 5184 var value = entries[i]; 5185 ret.set(key, value); 5186 } 5187 5188 return ret; 5189 }; 5190 5191 function PropertiesPromiseArray(obj) { 5192 var isMap = false; 5193 var entries; 5194 5195 if (Es6Map !== undefined && obj instanceof Es6Map) { 5196 entries = mapToEntries(obj); 5197 isMap = true; 5198 } else { 5199 var keys = es5.keys(obj); 5200 var len = keys.length; 5201 entries = new Array(len * 2); 5202 5203 for (var i = 0; i < len; ++i) { 5204 var key = keys[i]; 5205 entries[i] = obj[key]; 5206 entries[i + len] = key; 5207 } 5208 } 5209 5210 this.constructor$(entries); 5211 this._isMap = isMap; 5212 5213 this._init$(undefined, isMap ? -6 : -3); 5214 } 5215 5216 util.inherits(PropertiesPromiseArray, PromiseArray); 5217 5218 PropertiesPromiseArray.prototype._init = function () {}; 5219 5220 PropertiesPromiseArray.prototype._promiseFulfilled = function (value, index) { 5221 this._values[index] = value; 5222 var totalResolved = ++this._totalResolved; 5223 5224 if (totalResolved >= this._length) { 5225 var val; 5226 5227 if (this._isMap) { 5228 val = entriesToMap(this._values); 5229 } else { 5230 val = {}; 5231 var keyOffset = this.length(); 5232 5233 for (var i = 0, len = this.length(); i < len; ++i) { 5234 val[this._values[i + keyOffset]] = this._values[i]; 5235 } 5236 } 5237 5238 this._resolve(val); 5239 5240 return true; 5241 } 5242 5243 return false;
5244 }; 5245 5246 PropertiesPromiseArray.prototype.shouldCopyValues = function () { 5247 return false; 5248 }; 5249 5250 PropertiesPromiseArray.prototype.getActualLength = function (len) { 5251 return len >> 1; 5252 }; 5253 5254 function props(promises) { 5255 var ret; 5256 var castValue = tryConvertToPromise(promises); 5257 5258 if (!isObject(castValue)) { 5259 return apiRejection("cannot await properties of a non-object\n\n See http://goo.gl/MqrFmX\n"); 5260 } else if (castValue instanceof Promise) { 5261 ret = castValue._then(Promise.props, undefined, undefined, undefined, undefined); 5262 } else { 5263 ret = new PropertiesPromiseArray(castValue).promise(); 5264 } 5265 5266 if (castValue instanceof Promise) { 5267 ret._propagateFrom(castValue, 2); 5268 } 5269 5270 return ret; 5271 } 5272 5273 Promise.prototype.props = function () { 5274 return props(this); 5275 }; 5276 5277 Promise.props = function (promises) { 5278 return props(promises); 5279 }; 5280 }; 5281 }, { 5282 "./es5": 13, 5283 "./util": 36 5284 }], 5285 26: [function (_dereq_, module, exports) { 5286 5287 function arrayMove(src, srcIndex, dst, dstIndex, len) { 5288 for (var j = 0; j < len; ++j) { 5289 dst[j + dstIndex] = src[j + srcIndex]; 5290 src[j + srcIndex] = void 0; 5291 } 5292 } 5293 5294 function Queue(capacity) { 5295 this._capacity = capacity; 5296 this._length = 0; 5297 this._front = 0; 5298 } 5299 5300 Queue.prototype._willBeOverCapacity = function (size) { 5301 return this._capacity < size; 5302 }; 5303 5304 Queue.prototype._pushOne = function (arg) { 5305 var length = this.length(); 5306 5307 this._checkCapacity(length + 1); 5308 5309 var i = this._front + length & this._capacity - 1; 5310 this[i] = arg; 5311 this._length = length + 1; 5312 }; 5313 5314 Queue.prototype.push = function (fn, receiver, arg) { 5315 var length = this.length() + 3; 5316 5317 if (this._willBeOverCapacity(length)) { 5318 this._pushOne(fn); 5319 5320 this._pushOne(receiver); 5321 5322 this._pushOne(arg); 5323 5324 return; 5325 } 5326 5327 var j = this._front + length - 3; 5328 5329 this._checkCapacity(length); 5330 5331 var wrapMask = this._capacity - 1; 5332 this[j + 0 & wrapMask] = fn; 5333 this[j + 1 & wrapMask] = receiver; 5334 this[j + 2 & wrapMask] = arg; 5335 this._length = length; 5336 }; 5337 5338 Queue.prototype.shift = function () { 5339 var front = this._front, 5340 ret = this[front]; 5341 this[front] = undefined; 5342 this._front = front + 1 & this._capacity - 1; 5343 this._length--; 5344 return ret; 5345 }; 5346 5347 Queue.prototype.length = function () { 5348 return this._length; 5349 }; 5350 5351 Queue.prototype._checkCapacity = function (size) { 5352 if (this._capacity < size) { 5353 this._resizeTo(this._capacity << 1); 5354 } 5355 }; 5356 5357 Queue.prototype._resizeTo = function (capacity) { 5358 var oldCapacity = this._capacity; 5359 this._capacity = capacity; 5360 var front = this._front; 5361 var length = this._length; 5362 var moveItemsCount = front + length & oldCapacity - 1; 5363 arrayMove(this, 0, this, oldCapacity, moveItemsCount); 5364 }; 5365 5366 module.exports = Queue; 5367 }, {}], 5368 27: [function (_dereq_, module, exports) { 5369 5370 module.exports = function (Promise, INTERNAL, tryConvertToPromise, apiRejection) { 5371 var util = _dereq_("./util"); 5372 5373 var raceLater = function raceLater(promise) { 5374 return promise.then(function (array) { 5375 return race(array, promise); 5376 }); 5377 }; 5378 5379 function race(promises, parent) { 5380 var maybePromise = tryConvertToPromise(promises); 5381 5382 if (maybePromise instanceof Promise) { 5383 return raceLater(maybePromise); 5384 } else { 5385 promises = util.asArray(promises); 5386 if (promises === null) return apiRejection("expecting an array or an iterable object but got " + util.classString(promises)); 5387 } 5388 5389 var ret = new Promise(INTERNAL); 5390 5391 if (parent !== undefined) { 5392 ret._propagateFrom(parent, 3); 5393 } 5394 5395 var fulfill = ret._fulfill; 5396 var reject = ret._reject; 5397 5398 for (var i = 0, len = promises.length; i < len; ++i) { 5399 var val = promises[i]; 5400 5401 if (val === undefined && !(i in promises)) { 5402 continue; 5403 } 5404 5405 Promise.cast(val)._then(fulfill, reject, undefined, ret, null); 5406 } 5407 5408 return ret; 5409 } 5410 5411 Promise.race = function (promises) { 5412 return race(promises, undefined); 5413 }; 5414 5415 Promise.prototype.race = function () { 5416 return race(this, undefined); 5417 }; 5418 }; 5419 }, { 5420 "./util": 36 5421 }
5421], 5422 28: [function (_dereq_, module, exports) { 5423 5424 module.exports = function (Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug) { 5425 var util = _dereq_("./util"); 5426 5427 var tryCatch = util.tryCatch; 5428 5429 function ReductionPromiseArray(promises, fn, initialValue, _each) { 5430 this.constructor$(promises); 5431 5432 var context = Promise._getContext(); 5433 5434 this._fn = util.contextBind(context, fn); 5435 5436 if (initialValue !== undefined) { 5437 initialValue = Promise.resolve(initialValue); 5438 5439 initialValue._attachCancellationCallback(this); 5440 } 5441 5442 this._initialValue = initialValue; 5443 this._currentCancellable = null; 5444 5445 if (_each === INTERNAL) { 5446 this._eachValues = Array(this._length); 5447 } else if (_each === 0) { 5448 this._eachValues = null; 5449 } else { 5450 this._eachValues = undefined; 5451 } 5452 5453 this._promise._captureStackTrace(); 5454 5455 this._init$(undefined, -5); 5456 } 5457 5458 util.inherits(ReductionPromiseArray, PromiseArray); 5459 5460 ReductionPromiseArray.prototype._gotAccum = function (accum) { 5461 if (this._eachValues !== undefined && this._eachValues !== null && accum !== INTERNAL) { 5462 this._eachValues.push(accum); 5463 } 5464 }; 5465 5466 ReductionPromiseArray.prototype._eachComplete = function (value) { 5467 if (this._eachValues !== null) { 5468 this._eachValues.push(value); 5469 } 5470 5471 return this._eachValues; 5472 }; 5473 5474 ReductionPromiseArray.prototype._init = function () {}; 5475 5476 ReductionPromiseArray.prototype._resolveEmptyArray = function () { 5477 this._resolve(this._eachValues !== undefined ? this._eachValues : this._initialValue); 5478 }; 5479 5480 ReductionPromiseArray.prototype.shouldCopyValues = function () { 5481 return false; 5482 }; 5483 5484 ReductionPromiseArray.prototype._resolve = function (value) { 5485 this._promise._resolveCallback(value); 5486 5487 this._values = null; 5488 }; 5489 5490 ReductionPromiseArray.prototype._resultCancelled = function (sender) { 5491 if (sender === this._initialValue) return this._cancel(); 5492 if (this._isResolved()) return; 5493 5494 this._resultCancelled$(); 5495 5496 if (this._currentCancellable instanceof Promise) { 5497 this._currentCancellable.cancel(); 5498 } 5499 5500 if (this._initialValue instanceof Promise) { 5501 this._initialValue.cancel(); 5502 } 5503 }; 5504 5505 ReductionPromiseArray.prototype._iterate = function (values) { 5506 this._values = values; 5507 var value; 5508 var i; 5509 var length = values.length; 5510 5511 if (this._initialValue !== undefined) { 5512 value = this._initialValue; 5513 i = 0; 5514 } else { 5515 value = Promise.resolve(values[0]); 5516 i = 1; 5517 } 5518 5519 this._currentCancellable = value; 5520 5521 for (var j = i; j < length; ++j) { 5522 var maybePromise = values[j]; 5523 5524 if (maybePromise instanceof Promise) { 5525 maybePromise.suppressUnhandledRejections(); 5526 } 5527 } 5528 5529 if (!value.isRejected()) { 5530 for (; i < length; ++i) { 5531 var ctx = { 5532 accum: null, 5533 value: values[i], 5534 index: i, 5535 length: length, 5536 array: this 5537 }; 5538 value = value._then(gotAccum, undefined, undefined, ctx, undefined); 5539 5540 if ((i & 127) === 0) { 5541 value._setNoAsyncGuarantee(); 5542 } 5543 } 5544 } 5545 5546 if (this._eachValues !== undefined) { 5547 value = value._then(this._eachComplete, undefined, undefined, this, undefined); 5548 } 5549 5550 value._then(completed, completed, undefined, value, this); 5551 }; 5552 5553 Promise.prototype.reduce = function (fn, initialValue) { 5554 return reduce(this, fn, initialValue, null); 5555 }; 5556 5557 Promise.reduce = function (promises, fn, initialValue, _each) { 5558 return reduce(promises, fn, initialValue, _each); 5559 }; 5560 5561 function completed(valueOrReason, array) { 5562 if (this.isFulfilled()) { 5563 array._resolve(valueOrReason); 5564 } else { 5565 array._reject(valueOrReason); 5566 } 5567 } 5568 5569 function reduce(promises, fn, initialValue, _each) { 5570 if (typeof fn !== "function") { 5571 return apiRejection("expecting a function but got " + util.classString(fn)); 5572 } 5573 5574 var array = new ReductionPromiseArray(promises, fn, initialValue, _each); 5575 return array.promise(); 5576 } 5577 5578 function gotAccum(accum) { 5579 this.accum = accum; 5580 5581 this.array._gotAccum(accum); 5582 5583 var value = tryConvertToPromise(this.value, this.array._promise); 5584 5585 if (value instanceof Promise) { 5586 this.array._currentCancellable = value; 5587 return value._then(gotValue, undefined, undefined, this, undefined); 5588 } else { 5589 return gotValue.call(this, value); 5590 } 5591 } 5592 5593 function gotValue(value) { 5594 var array = this.array; 5595 var promise = array._promise; 5596 var fn = tryCatch(array._fn); 5597 5598 promise._pushContext(); 5599 5600 var ret; 5601 5602 if (array._eachValues !== undefined) { 5603 ret = fn.call(promise._boundValue(), value, this.index, this.length); 5604 } else { 5605 ret = fn.call(promise._boundValue(), this.accum, value, this.index, this.length); 5606 } 5607 5608 if (ret instanceof Promise) { 5609 array._currentCancellable = ret; 5610 } 5611 5612 var promiseCreated = promise._popContext(); 5613 5614 debug.checkForgottenReturns(ret, promiseCreated, array._eachValues !== undefined ? "Promise.each" : "Promise.reduce", promise); 5615 return ret; 5616 } 5617 }; 5618 }, { 5619 "./util": 36 5620 }
5620], 5621 29: [function (_dereq_, module, exports) { 5622 5623 var util = _dereq_("./util"); 5624 5625 var schedule; 5626 5627 var noAsyncScheduler = function noAsyncScheduler() { 5628 throw new Error("No async scheduler available\n\n See http://goo.gl/MqrFmX\n"); 5629 }; 5630 5631 var NativePromise = util.getNativePromise(); 5632 5633 if (util.isNode && typeof MutationObserver === "undefined") { 5634 var GlobalSetImmediate = commonjsGlobal.setImmediate; 5635 var ProcessNextTick = process.nextTick; 5636 schedule = util.isRecentNode ? function (fn) { 5637 GlobalSetImmediate.call(commonjsGlobal, fn); 5638 } : function (fn) { 5639 ProcessNextTick.call(process, fn); 5640 }; 5641 } else if (typeof NativePromise === "function" && typeof NativePromise.resolve === "function") { 5642 var nativePromise = NativePromise.resolve(); 5643 5644 schedule = function schedule(fn) { 5645 nativePromise.then(fn); 5646 }; 5647 } else if (typeof MutationObserver !== "undefined" && !(typeof window !== "undefined" && window.navigator && (window.navigator.standalone || window.cordova)) && "classList" in document.documentElement) { 5648 schedule = function () { 5649 var div = document.createElement("div"); 5650 var opts = { 5651 attributes: true 5652 }; 5653 var toggleScheduled = false; 5654 var div2 = document.createElement("div"); 5655 var o2 = new MutationObserver(function () { 5656 div.classList.toggle("foo"); 5657 toggleScheduled = false; 5658 }); 5659 o2.observe(div2, opts); 5660 5661 var scheduleToggle = function scheduleToggle() { 5662 if (toggleScheduled) return; 5663 toggleScheduled = true; 5664 div2.classList.toggle("foo"); 5665 }; 5666 5667 return function schedule(fn) { 5668 var o = new MutationObserver(function () { 5669 o.disconnect(); 5670 fn(); 5671 }); 5672 o.observe(div, opts); 5673 scheduleToggle(); 5674 }; 5675 }(); 5676 } else if (typeof setImmediate !== "undefined") { 5677 schedule = function schedule(fn) { 5678 setImmediate(fn); 5679 }; 5680 } else if (typeof setTimeout !== "undefined") { 5681 schedule = function schedule(fn) { 5682 setTimeout(fn, 0); 5683 }; 5684 } else { 5685 schedule = noAsyncScheduler; 5686 } 5687 5688 module.exports = schedule; 5689 }, { 5690 "./util": 36 5691 }], 5692 30: [function (_dereq_, module, exports) { 5693 5694 module.exports = function (Promise, PromiseArray, debug) { 5695 var PromiseInspection = Promise.PromiseInspection; 5696 5697 var util = _dereq_("./util"); 5698 5699 function SettledPromiseArray(values) { 5700 this.constructor$(values); 5701 } 5702 5703 util.inherits(SettledPromiseArray, PromiseArray); 5704 5705 SettledPromiseArray.prototype._promiseResolved = function (index, inspection) { 5706 this._values[index] = inspection; 5707 var totalResolved = ++this._totalResolved; 5708 5709 if (totalResolved >= this._length) { 5710 this._resolve(this._values); 5711 5712 return true; 5713 } 5714 5715 return false; 5716 }; 5717 5718 SettledPromiseArray.prototype._promiseFulfilled = function (value, index) { 5719 var ret = new PromiseInspection(); 5720 ret._bitField = 33554432; 5721 ret._settledValueField = value; 5722 return this._promiseResolved(index, ret); 5723 }; 5724
5725 SettledPromiseArray.prototype._promiseRejected = function (reason, index) { 5726 var ret = new PromiseInspection(); 5727 ret._bitField = 16777216; 5728 ret._settledValueField = reason; 5729 return this._promiseResolved(index, ret); 5730 }; 5731 5732 Promise.settle = function (promises) { 5733 debug.deprecated(".settle()", ".reflect()"); 5734 return new SettledPromiseArray(promises).promise(); 5735 }; 5736 5737 Promise.allSettled = function (promises) { 5738 return new SettledPromiseArray(promises).promise(); 5739 }; 5740 5741 Promise.prototype.settle = function () { 5742 return Promise.settle(this); 5743 }; 5744 }; 5745 }, { 5746 "./util": 36 5747 }], 5748 31: [function (_dereq_, module, exports) { 5749 5750 module.exports = function (Promise, PromiseArray, apiRejection) { 5751 var util = _dereq_("./util"); 5752 5753 var RangeError = _dereq_("./errors").RangeError; 5754 5755 var AggregateError = _dereq_("./errors").AggregateError; 5756 5757 var isArray = util.isArray; 5758 var CANCELLATION = {}; 5759 5760 function SomePromiseArray(values) { 5761 this.constructor$(values); 5762 this._howMany = 0; 5763 this._unwrap = false; 5764 this._initialized = false; 5765 } 5766 5767 util.inherits(SomePromiseArray, PromiseArray); 5768 5769 SomePromiseArray.prototype._init = function () { 5770 if (!this._initialized) { 5771 return; 5772 } 5773 5774 if (this._howMany === 0) { 5775 this._resolve([]); 5776 5777 return; 5778 } 5779 5780 this._init$(undefined, -5); 5781 5782 var isArrayResolved = isArray(this._values); 5783 5784 if (!this._isResolved() && isArrayResolved && this._howMany > this._canPossiblyFulfill()) { 5785 this._reject(this._getRangeError(this.length())); 5786 } 5787 }; 5788 5789 SomePromiseArray.prototype.init = function () { 5790 this._initialized = true; 5791 5792 this._init(); 5793 }; 5794 5795 SomePromiseArray.prototype.setUnwrap = function () { 5796 this._unwrap = true; 5797 }; 5798 5799 SomePromiseArray.prototype.howMany = function () { 5800 return this._howMany; 5801 }; 5802 5803 SomePromiseArray.prototype.setHowMany = function (count) { 5804 this._howMany = count; 5805 }; 5806 5807 SomePromiseArray.prototype._promiseFulfilled = function (value) { 5808 this._addFulfilled(value); 5809 5810 if (this._fulfilled() === this.howMany()) { 5811 this._values.length = this.howMany(); 5812 5813 if (this.howMany() === 1 && this._unwrap) { 5814 this._resolve(this._values[0]); 5815 } else { 5816 this._resolve(this._values); 5817 } 5818 5819 return true; 5820 } 5821 5822 return false; 5823 }; 5824
5825 SomePromiseArray.prototype._promiseRejected = function (reason) { 5826 this._addRejected(reason); 5827 5828 return this._checkOutcome(); 5829 }; 5830 5831 SomePromiseArray.prototype._promiseCancelled = function () { 5832 if (this._values instanceof Promise || this._values == null) { 5833 return this._cancel(); 5834 } 5835 5836 this._addRejected(CANCELLATION); 5837 5838 return this._checkOutcome(); 5839 }; 5840 5841 SomePromiseArray.prototype._checkOutcome = function () { 5842 if (this.howMany() > this._canPossiblyFulfill()) { 5843 var e = new AggregateError(); 5844 5845 for (var i = this.length(); i < this._values.length; ++i) { 5846 if (this._values[i] !== CANCELLATION) { 5847 e.push(this._values[i]); 5848 } 5849 } 5850 5851 if (e.length > 0) { 5852 this._reject(e); 5853 } else { 5854 this._cancel(); 5855 } 5856 5857 return true; 5858 } 5859 5860 return false; 5861 }; 5862 5863 SomePromiseArray.prototype._fulfilled = function () { 5864 return this._totalResolved; 5865 }; 5866 5867 SomePromiseArray.prototype._rejected = function () { 5868 return this._values.length - this.length(); 5869 }; 5870 5871 SomePromiseArray.prototype._addRejected = function (reason) { 5872 this._values.push(reason); 5873 }; 5874 5875 SomePromiseArray.prototype._addFulfilled = function (value) { 5876 this._values[this._totalResolved++] = value; 5877 }; 5878 5879 SomePromiseArray.prototype._canPossiblyFulfill = function () { 5880 return this.length() - this._rejected(); 5881 }; 5882 5883 SomePromiseArray.prototype._getRangeError = function (count) { 5884 var message = "Input array must contain at least " + this._howMany + " items but contains only " + count + " items"; 5885 return new RangeError(message); 5886 }; 5887 5888 SomePromiseArray.prototype._resolveEmptyArray = function () { 5889 this._reject(this._getRangeError(0)); 5890 }; 5891 5892 function some(promises, howMany) { 5893 if ((howMany | 0) !== howMany || howMany < 0) { 5894 return apiRejection("expecting a positive integer\n\n See http://goo.gl/MqrFmX\n"); 5895 } 5896 5897 var ret = new SomePromiseArray(promises); 5898 var promise = ret.promise(); 5899 ret.setHowMany(howMany); 5900 ret.init(); 5901 return promise; 5902 } 5903 5904 Promise.some = function (promises, howMany) { 5905 return some(promises, howMany); 5906 }; 5907 5908 Promise.prototype.some = function (howMany) { 5909 return some(this, howMany); 5910 }; 5911 5912 Promise._SomePromiseArray = SomePromiseArray; 5913 }; 5914 }, { 5915 "./errors": 12, 5916 "./util": 36 5917 }], 5918 32: [function (_dereq_, module, exports) { 5919 5920 module.exports = function (Promise) { 5921 function PromiseInspection(promise) { 5922 if (promise !== undefined) { 5923 promise = promise._target(); 5924 this._bitField = promise._bitField; 5925 this._settledValueField = promise._isFateSealed() ? promise._settledValue() : undefined; 5926 } else { 5927 this._bitField = 0; 5928 this._settledValueField = undefined; 5929 } 5930 } 5931 5932 PromiseInspection.prototype._settledValue = function () { 5933 return this._settledValueField; 5934 }; 5935 5936 var value = PromiseInspection.prototype.value = function () { 5937 if (!this.isFulfilled()) { 5938 throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\n\n See http://goo.gl/MqrFmX\n"); 5939 } 5940 5941 return this._settledValue(); 5942 }; 5943 5944 var reason = PromiseInspection.prototype.error = PromiseInspection.prototype.reason = function () { 5945 if (!this.isRejected()) { 5946 throw new TypeError("cannot get rejection reason of a non-rejected promise\n\n See http://goo.gl/MqrFmX\n"); 5947 } 5948 5949 return this._settledValue(); 5950 }; 5951 5952 var isFulfilled = PromiseInspection.prototype.isFulfilled = function () { 5953 return (this._bitField & 33554432) !== 0; 5954 }; 5955 5956 var isRejected = PromiseInspection.prototype.isRejected = function () { 5957 return (this._bitField & 16777216) !== 0; 5958 }; 5959 5960 var isPending = PromiseInspection.prototype.isPending = function () { 5961 return (this._bitField & 50397184) === 0; 5962 }; 5963 5964 var isResolved = PromiseInspection.prototype.isResolved = function () { 5965 return (this._bitField & 50331648) !== 0; 5966 }; 5967 5968 PromiseInspection.prototype.isCancelled = function () { 5969 return (this._bitField & 8454144) !== 0; 5970 }; 5971 5972 Promise.prototype.__isCancelled = function () { 5973 return (this._bitField & 65536) === 65536; 5974 }; 5975 5976 Promise.prototype._isCancelled = function () { 5977 return this._target().__isCancelled(); 5978 }; 5979 5980 Promise.prototype.isCancelled = function () { 5981 return (this._target()._bitField & 8454144) !== 0; 5982 }; 5983 5984 Promise.prototype.isPending = function () { 5985 return isPending.call(this._target()); 5986 }; 5987 5988 Promise.prototype.isRejected = function () { 5989 return isRejected.call(this._target()); 5990 }; 5991 5992 Promise.prototype.isFulfilled = function () { 5993 return isFulfilled.call(this._target()); 5994 }; 5995 5996 Promise.prototype.isResolved = function () { 5997 return isResolved.call(this._target()); 5998 }; 5999 6000 Promise.prototype.value = function () { 6001 return value.call(this._target()); 6002 }; 6003 6004 Promise.prototype.reason = function () { 6005 var target = this._target(); 6006 6007 target._unsetRejectionIsUnhandled(); 6008 6009 return reason.call(target); 6010 }; 6011 6012 Promise.prototype._value = function () { 6013 return this._settledValue(); 6014 }; 6015 6016 Promise.prototype._reason = function () { 6017 this._unsetRejectionIsUnhandled(); 6018 6019 return this._settledValue(); 6020 }; 6021 6022 Promise.PromiseInspection = PromiseInspection; 6023 }; 6024 }, {}],
6025 33: [function (_dereq_, module, exports) { 6026 6027 module.exports = function (Promise, INTERNAL) { 6028 var util = _dereq_("./util"); 6029 6030 var errorObj = util.errorObj; 6031 var isObject = util.isObject; 6032 6033 function tryConvertToPromise(obj, context) { 6034 if (isObject(obj)) { 6035 if (obj instanceof Promise) return obj; 6036 var then = getThen(obj); 6037 6038 if (then === errorObj) { 6039 if (context) context._pushContext(); 6040 var ret = Promise.reject(then.e); 6041 if (context) context._popContext(); 6042 return ret; 6043 } else if (typeof then === "function") { 6044 if (isAnyBluebirdPromise(obj)) { 6045 var ret = new Promise(INTERNAL); 6046 6047 obj._then(ret._fulfill, ret._reject, undefined, ret, null); 6048 6049 return ret; 6050 } 6051 6052 return doThenable(obj, then, context); 6053 } 6054 } 6055 6056 return obj; 6057 } 6058 6059 function doGetThen(obj) { 6060 return obj.then; 6061 } 6062 6063 function getThen(obj) { 6064 try { 6065 return doGetThen(obj); 6066 } catch (e) { 6067 errorObj.e = e; 6068 return errorObj; 6069 } 6070 } 6071 6072 var hasProp = {}.hasOwnProperty; 6073 6074 function isAnyBluebirdPromise(obj) { 6075 try { 6076 return hasProp.call(obj, "_promise0"); 6077 } catch (e) { 6078 return false; 6079 } 6080 } 6081 6082 function doThenable(x, then, context) { 6083 var promise = new Promise(INTERNAL); 6084 var ret = promise; 6085 if (context) context._pushContext(); 6086 6087 promise._captureStackTrace(); 6088 6089 if (context) context._popContext(); 6090 var synchronous = true; 6091 var result = util.tryCatch(then).call(x, resolve, reject); 6092 synchronous = false; 6093 6094 if (promise && result === errorObj) { 6095 promise._rejectCallback(result.e, true, true); 6096 6097 promise = null; 6098 } 6099 6100 function resolve(value) { 6101 if (!promise) return; 6102 6103 promise._resolveCallback(value); 6104 6105 promise = null; 6106 } 6107 6108 function reject(reason) { 6109 if (!promise) return; 6110 6111 promise._rejectCallback(reason, synchronous, true); 6112 6113 promise = null; 6114 } 6115 6116 return ret; 6117 } 6118 6119 return tryConvertToPromise; 6120 }; 6121 }, { 6122 "./util": 36 6123 }], 6124 34: [function (_dereq_, module, exports) { 6125 6126 module.exports = function (Promise, INTERNAL, debug) { 6127 var util = _dereq_("./util"); 6128 6129 var TimeoutError = Promise.TimeoutError; 6130 6131 function HandleWrapper(handle) { 6132 this.handle = handle; 6133 } 6134 6135 HandleWrapper.prototype._resultCancelled = function () { 6136 clearTimeout(this.handle); 6137 }; 6138 6139 var afterValue = function afterValue(value) { 6140 return delay(+this).thenReturn(value); 6141 }; 6142 6143 var delay = Promise.delay = function (ms, value) { 6144 var ret; 6145 var handle; 6146 6147 if (value !== undefined) { 6148 ret = Promise.resolve(value)._then(afterValue, null, null, ms, undefined); 6149 6150 if (debug.cancellation() && value instanceof Promise) { 6151 ret._setOnCancel(value); 6152 } 6153 } else { 6154 ret = new Promise(INTERNAL); 6155 handle = setTimeout(function () { 6156 ret._fulfill(); 6157 }, +ms); 6158 6159 if (debug.cancellation()) { 6160 ret._setOnCancel(new HandleWrapper(handle)); 6161 } 6162 6163 ret._captureStackTrace(); 6164 } 6165 6166 ret._setAsyncGuaranteed(); 6167 6168 return ret; 6169 }; 6170 6171 Promise.prototype.delay = function (ms) { 6172 return delay(ms, this); 6173 }; 6174 6175 var afterTimeout = function afterTimeout(promise, message, parent) { 6176 var err; 6177 6178 if (typeof message !== "string") { 6179 if (message instanceof Error) { 6180 err = message; 6181 } else { 6182 err = new TimeoutError("operation timed out"); 6183 } 6184 } else { 6185 err = new TimeoutError(message); 6186 } 6187 6188 util.markAsOriginatingFromRejection(err); 6189 6190 promise._attachExtraTrace(err); 6191 6192 promise._reject(err); 6193 6194 if (parent != null) { 6195 parent.cancel(); 6196 } 6197 }; 6198 6199 function successClear(value) { 6200 clearTimeout(this.handle); 6201 return value; 6202 } 6203 6204 function failureClear(reason) { 6205 clearTimeout(this.handle); 6206 throw reason; 6207 } 6208 6209 Promise.prototype.timeout = function (ms, message) { 6210 ms = +ms; 6211 var ret, parent; 6212 var handleWrapper = new HandleWrapper(setTimeout(function timeoutTimeout() { 6213 if (ret.isPending()) { 6214 afterTimeout(ret, message, parent); 6215 } 6216 }, ms)); 6217 6218 if (debug.cancellation()) { 6219 parent = this.then(); 6220 ret = parent._then(successClear, failureClear, undefined, handleWrapper, undefined); 6221 6222 ret._setOnCancel(handleWrapper); 6223 } else { 6224 ret = this._then(successClear, failureClear, undefined, handleWrapper, undefined); 6225 } 6226 6227 return ret; 6228 }; 6229 }; 6230 }, { 6231 "./util": 36 6232 }
6232], 6233 35: [function (_dereq_, module, exports) { 6234 6235 module.exports = function (Promise, apiRejection, tryConvertToPromise, createContext, INTERNAL, debug) { 6236 var util = _dereq_("./util"); 6237 6238 var TypeError = _dereq_("./errors").TypeError; 6239 6240 var inherits = _dereq_("./util").inherits; 6241 6242 var errorObj = util.errorObj; 6243 var tryCatch = util.tryCatch; 6244 var NULL = {}; 6245 6246 function thrower(e) { 6247 setTimeout(function () { 6248 throw e; 6249 }, 0); 6250 } 6251 6252 function castPreservingDisposable(thenable) { 6253 var maybePromise = tryConvertToPromise(thenable); 6254 6255 if (maybePromise !== thenable && typeof thenable._isDisposable === "function" && typeof thenable._getDisposer === "function" && thenable._isDisposable()) { 6256 maybePromise._setDisposable(thenable._getDisposer()); 6257 } 6258 6259 return maybePromise; 6260 } 6261 6262 function dispose(resources, inspection) { 6263 var i = 0; 6264 var len = resources.length; 6265 var ret = new Promise(INTERNAL); 6266 6267 function iterator() { 6268 if (i >= len) return ret._fulfill(); 6269 var maybePromise = castPreservingDisposable(resources[i++]); 6270 6271 if (maybePromise instanceof Promise && maybePromise._isDisposable()) { 6272 try { 6273 maybePromise = tryConvertToPromise(maybePromise._getDisposer().tryDispose(inspection), resources.promise); 6274 } catch (e) { 6275 return thrower(e); 6276 } 6277 6278 if (maybePromise instanceof Promise) { 6279 return maybePromise._then(iterator, thrower, null, null, null); 6280 } 6281 } 6282 6283 iterator(); 6284 } 6285 6286 iterator(); 6287 return ret; 6288 } 6289 6290 function Disposer(data, promise, context) { 6291 this._data = data; 6292 this._promise = promise; 6293 this._context = context; 6294 } 6295 6296 Disposer.prototype.data = function () { 6297 return this._data; 6298 }; 6299 6300 Disposer.prototype.promise = function () { 6301 return this._promise; 6302 }; 6303 6304 Disposer.prototype.resource = function () { 6305 if (this.promise().isFulfilled()) { 6306 return this.promise().value(); 6307 } 6308 6309 return NULL; 6310 }; 6311 6312 Disposer.prototype.tryDispose = function (inspection) { 6313 var resource = this.resource(); 6314 var context = this._context; 6315 if (context !== undefined) context._pushContext(); 6316 var ret = resource !== NULL ? this.doDispose(resource, inspection) : null; 6317 if (context !== undefined) context._popContext(); 6318 6319 this._promise._unsetDisposable(); 6320 6321 this._data = null; 6322 return ret; 6323 }; 6324 6325 Disposer.isDisposer = function (d) { 6326 return d != null && typeof d.resource === "function" && typeof d.tryDispose === "function"; 6327 }; 6328 6329 function FunctionDisposer(fn, promise, context) { 6330 this.constructor$(fn, promise, context); 6331 } 6332 6333 inherits(FunctionDisposer, Disposer); 6334 6335 FunctionDisposer.prototype.doDispose = function (resource, inspection) { 6336 var fn = this.data(); 6337 return fn.call(resource, resource, inspection); 6338 }; 6339 6340 function maybeUnwrapDisposer(value) { 6341 if (Disposer.isDisposer(value)) { 6342 this.resources[this.index]._setDisposable(value); 6343 6344 return value.promise(); 6345 } 6346 6347 return value; 6348 } 6349 6350 function ResourceList(length) { 6351 this.length = length; 6352 this.promise = null; 6353 this[length - 1] = null; 6354 } 6355 6356 ResourceList.prototype._resultCancelled = function () { 6357 var len = this.length; 6358 6359 for (var i = 0; i < len; ++i) { 6360 var item = this[i]; 6361 6362 if (item instanceof Promise) { 6363 item.cancel(); 6364 } 6365 } 6366 }; 6367 6368 Promise.using = function () { 6369 var len = arguments.length; 6370 if (len < 2) return apiRejection("you must pass at least 2 arguments to Promise.using"); 6371 var fn = arguments[len - 1]; 6372 6373 if (typeof fn !== "function") { 6374 return apiRejection("expecting a function but got " + util.classString(fn)); 6375 } 6376 6377 var input; 6378 var spreadArgs = true; 6379 6380 if (len === 2 && Array.isArray(arguments[0])) { 6381 input = arguments[0]; 6382 len = input.length; 6383 spreadArgs = false;
6384 } else { 6385 input = arguments; 6386 len--; 6387 } 6388 6389 var resources = new ResourceList(len); 6390 6391 for (var i = 0; i < len; ++i) { 6392 var resource = input[i]; 6393 6394 if (Disposer.isDisposer(resource)) { 6395 var disposer = resource; 6396 resource = resource.promise(); 6397 6398 resource._setDisposable(disposer); 6399 } else { 6400 var maybePromise = tryConvertToPromise(resource); 6401 6402 if (maybePromise instanceof Promise) { 6403 resource = maybePromise._then(maybeUnwrapDisposer, null, null, { 6404 resources: resources, 6405 index: i 6406 }, undefined); 6407 } 6408 } 6409 6410 resources[i] = resource; 6411 } 6412 6413 var reflectedResources = new Array(resources.length); 6414 6415 for (var i = 0; i < reflectedResources.length; ++i) { 6416 reflectedResources[i] = Promise.resolve(resources[i]).reflect(); 6417 } 6418 6419 var resultPromise = Promise.all(reflectedResources).then(function (inspections) { 6420 for (var i = 0; i < inspections.length; ++i) { 6421 var inspection = inspections[i]; 6422 6423 if (inspection.isRejected()) { 6424 errorObj.e = inspection.error(); 6425 return errorObj; 6426 } else if (!inspection.isFulfilled()) { 6427 resultPromise.cancel(); 6428 return; 6429 } 6430 6431 inspections[i] = inspection.value(); 6432 } 6433 6434 promise._pushContext(); 6435 6436 fn = tryCatch(fn); 6437 var ret = spreadArgs ? fn.apply(undefined, inspections) : fn(inspections); 6438 6439 var promiseCreated = promise._popContext(); 6440 6441 debug.checkForgottenReturns(ret, promiseCreated, "Promise.using", promise); 6442 return ret; 6443 }); 6444 var promise = resultPromise.lastly(function () { 6445 var inspection = new Promise.PromiseInspection(resultPromise); 6446 return dispose(resources, inspection); 6447 }); 6448 resources.promise = promise; 6449 6450 promise._setOnCancel(resources); 6451 6452 return promise; 6453 }; 6454 6455 Promise.prototype._setDisposable = function (disposer) { 6456 this._bitField = this._bitField | 131072; 6457 this._disposer = disposer; 6458 }; 6459 6460 Promise.prototype._isDisposable = function () { 6461 return (this._bitField & 131072) > 0; 6462 }; 6463 6464 Promise.prototype._getDisposer = function () { 6465 return this._disposer; 6466 }; 6467 6468 Promise.prototype._unsetDisposable = function () { 6469 this._bitField = this._bitField & ~131072; 6470 this._disposer = undefined; 6471 }; 6472 6473 Promise.prototype.disposer = function (fn) { 6474 if (typeof fn === "function") { 6475 return new FunctionDisposer(fn, this, createContext()); 6476 } 6477 6478 throw new TypeError(); 6479 }; 6480 }; 6481 }, { 6482 "./errors": 12, 6483 "./util": 36 6484 }], 6485 36: [function (_dereq_, module, exports) { 6486 6487 var es5 = _dereq_("./es5"); 6488 6489 var canEvaluate = typeof navigator == "undefined"; 6490 var errorObj = { 6491 e: {} 6492 }; 6493 var tryCatchTarget; 6494 var globalObject = typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : typeof commonjsGlobal !== "undefined" ? commonjsGlobal : this !== undefined ? this : null; 6495 6496 function tryCatcher() { 6497 try { 6498 var target = tryCatchTarget; 6499 tryCatchTarget = null; 6500 return target.apply(this, arguments); 6501 } catch (e) { 6502 errorObj.e = e; 6503 return errorObj; 6504 } 6505 } 6506 6507 function tryCatch(fn) { 6508 tryCatchTarget = fn; 6509 return tryCatcher; 6510 } 6511 6512 var inherits = function inherits(Child, Parent) { 6513 var hasProp = {}.hasOwnProperty; 6514 6515 function T() { 6516 this.constructor = Child; 6517 this.constructor$ = Parent; 6518 6519 for (var propertyName in Parent.prototype) { 6520 if (hasProp.call(Parent.prototype, propertyName) && propertyName.charAt(propertyName.length - 1) !== "$") { 6521 this[propertyName + "$"] = Parent.prototype[propertyName]; 6522 } 6523 } 6524 } 6525 6526 T.prototype = Parent.prototype; 6527 Child.prototype = new T(); 6528 return Child.prototype; 6529 }; 6530 6531 function isPrimitive(val) { 6532 return val == null || val === true || val === false || typeof val === "string" || typeof val === "number"; 6533 } 6534 6535 function isObject(value) { 6536 return typeof value === "function" || babelHelpers.typeof(value) === "object" && value !== null; 6537 } 6538 6539 function maybeWrapAsError(maybeError) { 6540 if (!isPrimitive(maybeError)) return maybeError; 6541 return new Error(safeToString(maybeError)); 6542 } 6543 6544 function withAppended(target, appendee) { 6545 var len = target.length; 6546 var ret = new Array(len + 1); 6547 var i; 6548 6549 for (i = 0; i < len; ++i) { 6550 ret[i] = target[i]; 6551 } 6552 6553 ret[i] = appendee; 6554 return ret; 6555 } 6556 6557 function getDataPropertyOrDefault(obj, key, defaultValue) { 6558 if (es5.isES5) { 6559 var desc = Object.getOwnPropertyDescriptor(obj, key); 6560 6561 if (desc != null) { 6562 return desc.get == null && desc.set == null ? desc.value : defaultValue; 6563 } 6564 } else { 6565 return {}.hasOwnProperty.call(obj, key) ? obj[key] : undefined; 6566 } 6567 } 6568 6569 function notEnumerableProp(obj, name, value) { 6570 if (isPrimitive(obj)) return obj; 6571 var descriptor = { 6572 value: value, 6573 configurable: true, 6574 enumerable: false, 6575 writable: true 6576 }; 6577 es5.defineProperty(obj, name, descriptor); 6578 return obj; 6579 } 6580 6581 function thrower(r) { 6582 throw r; 6583 } 6584 6585 var inheritedDataKeys = function () { 6586 var excludedPrototypes = [Array.prototype, Object.prototype, Function.prototype]; 6587 6588 var isExcludedProto = function isExcludedProto(val) { 6589 for (var i = 0; i < excludedPrototypes.length; ++i) { 6590 if (excludedPrototypes[i] === val) { 6591 return true; 6592 } 6593 } 6594 6595 return false;
6596 }; 6597 6598 if (es5.isES5) { 6599 var getKeys = Object.getOwnPropertyNames; 6600 return function (obj) { 6601 var ret = []; 6602 var visitedKeys = Object.create(null); 6603 6604 while (obj != null && !isExcludedProto(obj)) { 6605 var keys; 6606 6607 try { 6608 keys = getKeys(obj); 6609 } catch (e) { 6610 return ret; 6611 } 6612 6613 for (var i = 0; i < keys.length; ++i) { 6614 var key = keys[i]; 6615 if (visitedKeys[key]) continue; 6616 visitedKeys[key] = true; 6617 var desc = Object.getOwnPropertyDescriptor(obj, key); 6618 6619 if (desc != null && desc.get == null && desc.set == null) { 6620 ret.push(key); 6621 } 6622 } 6623 6624 obj = es5.getPrototypeOf(obj); 6625 } 6626 6627 return ret; 6628 }; 6629 } else { 6630 var hasProp = {}.hasOwnProperty; 6631 return function (obj) { 6632 if (isExcludedProto(obj)) return []; 6633 var ret = []; 6634 /*jshint forin:false */ 6635 6636 enumeration: for (var key in obj) { 6637 if (hasProp.call(obj, key)) { 6638 ret.push(key); 6639 } else { 6640 for (var i = 0; i < excludedPrototypes.length; ++i) { 6641 if (hasProp.call(excludedPrototypes[i], key)) { 6642 continue enumeration; 6643 } 6644 } 6645 6646 ret.push(key); 6647 } 6648 } 6649 6650 return ret; 6651 }; 6652 } 6653 }(); 6654 6655 var thisAssignmentPattern = /this\s*\.\s*\S+\s*=/; 6656 6657 function isClass(fn) { 6658 try { 6659 if (typeof fn === "function") { 6660 var keys = es5.names(fn.prototype); 6661 var hasMethods = es5.isES5 && keys.length > 1; 6662 var hasMethodsOtherThanConstructor = keys.length > 0 && !(keys.length === 1 && keys[0] === "constructor"); 6663 var hasThisAssignmentAndStaticMethods = thisAssignmentPattern.test(fn + "") && es5.names(fn).length > 0; 6664 6665 if (hasMethods || hasMethodsOtherThanConstructor || hasThisAssignmentAndStaticMethods) { 6666 return true; 6667 } 6668 } 6669 6670 return false; 6671 } catch (e) { 6672 return false; 6673 } 6674 } 6675 6676 function toFastProperties(obj) { 6677 /*jshint -W027,-W055,-W031*/ 6678 function FakeConstructor() {} 6679 6680 FakeConstructor.prototype = obj; 6681 var receiver = new FakeConstructor(); 6682 6683 function ic() { 6684 return babelHelpers.typeof(receiver.foo); 6685 } 6686 6687 ic(); 6688 ic(); 6689 return obj; 6690 eval(obj); 6691 } 6692 6693 var rident = /^[a-z$_][a-z$_0-9]*$/i; 6694 6695 function isIdentifier(str) { 6696 return rident.test(str); 6697 } 6698 6699 function filledRange(count, prefix, suffix) { 6700 var ret = new Array(count); 6701 6702 for (var i = 0; i < count; ++i) { 6703 ret[i] = prefix + i + suffix; 6704 } 6705 6706 return ret; 6707 } 6708 6709 function safeToString(obj) { 6710 try { 6711 return obj + ""; 6712 } catch (e) { 6713 return "[no string representation]"; 6714 } 6715 } 6716 6717 function isError(obj) { 6718 return obj instanceof Error || obj !== null && babelHelpers.typeof(obj) === "object" && typeof obj.message === "string" && typeof obj.name === "string"; 6719 } 6720 6721 function markAsOriginatingFromRejection(e) { 6722 try { 6723 notEnumerableProp(e, "isOperational", true); 6724 } catch (ignore) {} 6725 } 6726 6727 function originatesFromRejection(e) { 6728 if (e == null) return false; 6729 return e instanceof Error["__BluebirdErrorTypes__"].OperationalError || e["isOperational"] === true; 6730 } 6731 6732 function canAttachTrace(obj) { 6733 return isError(obj) && es5.propertyIsWritable(obj, "stack"); 6734 } 6735 6736 var ensureErrorObject = function () { 6737 if (!("stack" in new Error())) { 6738 return function (value) { 6739 if (canAttachTrace(value)) return value; 6740 6741 try { 6742 throw new Error(safeToString(value)); 6743 } catch (err) { 6744 return err; 6745 } 6746 }; 6747 } else { 6748 return function (value) { 6749 if (canAttachTrace(value)) return value; 6750 return new Error(safeToString(value)); 6751 }; 6752 } 6753 }(); 6754 6755 function classString(obj) { 6756 return {}.toString.call(obj); 6757 } 6758 6759 function copyDescriptors(from, to, filter) { 6760 var keys = es5.names(from); 6761 6762 for (var i = 0; i < keys.length; ++i) { 6763 var key = keys[i]; 6764 6765 if (filter(key)) { 6766 try { 6767 es5.defineProperty(to, key, es5.getDescriptor(from, key)); 6768 } catch (ignore) {} 6769 } 6770 } 6771 } 6772 6773 var asArray = function asArray(v) { 6774 if (es5.isArray(v)) { 6775 return v; 6776 } 6777 6778 return null; 6779 }; 6780 6781 if (typeof Symbol !== "undefined" && Symbol.iterator) { 6782 var ArrayFrom = typeof Array.from === "function" ? function (v) { 6783 return Array.from(v); 6784 } : function (v) { 6785 var ret = []; 6786 var it = v[Symbol.iterator](); 6787 var itResult; 6788 6789 while (!(itResult = it.next()).done) {
6790 ret.push(itResult.value); 6791 } 6792 6793 return ret; 6794 }; 6795 6796 asArray = function asArray(v) { 6797 if (es5.isArray(v)) { 6798 return v; 6799 } else if (v != null && typeof v[Symbol.iterator] === "function") { 6800 return ArrayFrom(v); 6801 } 6802 6803 return null; 6804 }; 6805 } 6806 6807 var isNode = typeof process !== "undefined" && classString(process).toLowerCase() === "[object process]"; 6808 var hasEnvVariables = typeof process !== "undefined" && typeof process.env !== "undefined"; 6809 6810 function env(key) { 6811 return hasEnvVariables ? process.env[key] : undefined; 6812 } 6813 6814 function getNativePromise() { 6815 if (typeof Promise === "function") { 6816 try { 6817 var promise = new Promise(function () {}); 6818 6819 if (classString(promise) === "[object Promise]") { 6820 return Promise; 6821 } 6822 } catch (e) {} 6823 } 6824 } 6825 6826 var reflectHandler; 6827 6828 function contextBind(ctx, cb) { 6829 if (ctx === null || typeof cb !== "function" || cb === reflectHandler) { 6830 return cb; 6831 } 6832 6833 if (ctx.domain !== null) { 6834 cb = ctx.domain.bind(cb); 6835 } 6836 6837 var async = ctx.async; 6838 6839 if (async !== null) { 6840 var old = cb; 6841 6842 cb = function cb() { 6843 var args = new Array(2).concat([].slice.call(arguments)); 6844 args[0] = old; 6845 args[1] = this; 6846 return async.runInAsyncScope.apply(async, args); 6847 }; 6848 } 6849 6850 return cb; 6851 } 6852 6853 var ret = { 6854 setReflectHandler: function setReflectHandler(fn) { 6855 reflectHandler = fn; 6856 }, 6857 isClass: isClass, 6858 isIdentifier: isIdentifier, 6859 inheritedDataKeys: inheritedDataKeys, 6860 getDataPropertyOrDefault: getDataPropertyOrDefault, 6861 thrower: thrower, 6862 isArray: es5.isArray, 6863 asArray: asArray, 6864 notEnumerableProp: notEnumerableProp, 6865 isPrimitive: isPrimitive, 6866 isObject: isObject, 6867 isError: isError, 6868 canEvaluate: canEvaluate, 6869 errorObj: errorObj, 6870 tryCatch: tryCatch, 6871 inherits: inherits, 6872 withAppended: withAppended, 6873 maybeWrapAsError: maybeWrapAsError, 6874 toFastProperties: toFastProperties, 6875 filledRange: filledRange, 6876 toString: safeToString, 6877 canAttachTrace: canAttachTrace, 6878 ensureErrorObject: ensureErrorObject, 6879 originatesFromRejection: originatesFromRejection, 6880 markAsOriginatingFromRejection: markAsOriginatingFromRejection, 6881 classString: classString, 6882 copyDescriptors: copyDescriptors, 6883 isNode: isNode, 6884 hasEnvVariables: hasEnvVariables, 6885 env: env, 6886 global: globalObject, 6887 getNativePromise: getNativePromise, 6888 contextBind: contextBind 6889 }; 6890 6891 ret.isRecentNode = ret.isNode && function () { 6892 var version; 6893 6894 if (process.versions && process.versions.node) { 6895 version = process.versions.node.split(".").map(Number); 6896 } else if (process.version) { 6897 version = process.version.split(".").map(Number); 6898 } 6899 6900 return version[0] === 0 && version[1] > 10 || version[0] > 0; 6901 }(); 6902 6903 ret.nodeSupportsAsyncResource = ret.isNode && function () { 6904 var supportsAsync = false; 6905 6906 try { 6907 var res = _dereq_("async_hooks").AsyncResource; 6908 6909 supportsAsync = typeof res.prototype.runInAsyncScope === "function"; 6910 } catch (e) { 6911 supportsAsync = false; 6912 } 6913 6914 return supportsAsync; 6915 }(); 6916 6917 if (ret.isNode) ret.toFastProperties(process); 6918 6919 try { 6920 throw new Error(); 6921 } catch (e) { 6922 ret.lastLineError = e; 6923 } 6924 6925 module.exports = ret; 6926 }, { 6927 "./es5": 13, 6928 "async_hooks": undefined 6929 }] 6930 }, {}, [4])(4); 6931 }); 6932 6933 if (typeof window !== 'undefined' && window !== null) { 6934 window.P = window.Promise; 6935 } else if (typeof self !== 'undefined' && self !== null) { 6936 self.P = self.Promise; 6937 } 6938 }); 6939 6940 var es6Promise = createCommonjsModule(function (module, exports
6940) { 6941 /*! 6942 * @overview es6-promise - a tiny implementation of Promises/A+. 6943 * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald) 6944 * @license Licensed under MIT license 6945 * See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE 6946 * @version 4.0.5 6947 */ 6948 (function (global, factory) { 6949 (babelHelpers.typeof(exports)) === 'object' && 'object' !== 'undefined' ? module.exports = factory() : global.ES6Promise = factory(); 6950 })(commonjsGlobal, function () { 6951 6952 function objectOrFunction(x) { 6953 return typeof x === 'function' || babelHelpers.typeof(x) === 'object' && x !== null; 6954 } 6955 6956 function isFunction(x) { 6957 return typeof x === 'function'; 6958 } 6959 6960 var _isArray = undefined; 6961 6962 if (!Array.isArray) { 6963 _isArray = function _isArray(x) { 6964 return Object.prototype.toString.call(x) === '[object Array]'; 6965 }; 6966 } else { 6967 _isArray = Array.isArray; 6968 } 6969 6970 var isArray = _isArray; 6971 var len = 0; 6972 var vertxNext = undefined; 6973 var customSchedulerFn = undefined; 6974 6975 var asap = function asap(callback, arg) { 6976 queue[len] = callback; 6977 queue[len + 1] = arg; 6978 len += 2; 6979 6980 if (len === 2) { 6981 // If len is 2, that means that we need to schedule an async flush. 6982 // If additional callbacks are queued before the queue is flushed, they 6983 // will be processed by this flush that we are scheduling. 6984 if (customSchedulerFn) { 6985 customSchedulerFn(flush); 6986 } else { 6987 scheduleFlush(); 6988 } 6989 } 6990 }; 6991 6992 function setScheduler(scheduleFn) { 6993 customSchedulerFn = scheduleFn; 6994 } 6995 6996 function setAsap(asapFn) { 6997 asap = asapFn; 6998 } 6999 7000 var browserWindow = typeof window !== 'undefined' ? window : undefined; 7001 var browserGlobal = browserWindow || {}; 7002 var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver; 7003 var isNode = typeof self === 'undefined' && typeof process !== 'undefined' && {}.toString.call(process) === '[object process]'; // test for web worker but not in IE10 7004 7005 var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined'; // node 7006 7007 function useNextTick() { 7008 // node version 0.10.x displays a deprecation warning when nextTick is used recursively 7009 // see https://github.com/cujojs/when/issues/410 for details 7010 return function () { 7011 return process.nextTick(flush); 7012 }; 7013 } // vertx 7014 7015 7016 function useVertxTimer() { 7017 if (typeof vertxNext !== 'undefined') { 7018 return function () { 7019 vertxNext(flush); 7020 }; 7021 } 7022 7023 return useSetTimeout(); 7024 } 7025 7026 function useMutationObserver() { 7027 var iterations = 0; 7028 var observer = new BrowserMutationObserver(flush); 7029 var node = document.createTextNode(''); 7030 observer.observe(node, { 7031 characterData: true 7032 }); 7033 return function () { 7034 node.data = iterations = ++iterations % 2; 7035 }; 7036 } // web worker 7037 7038 7039 function useMessageChannel() { 7040 var channel = new MessageChannel(); 7041 channel.port1.onmessage = flush; 7042 return function () { 7043 return channel.port2.postMessage(0); 7044 }; 7045 } 7046 7047 function useSetTimeout() { 7048 // Store setTimeout reference so es6-promise will be unaffected by 7049 // other code modifying setTimeout (like sinon.useFakeTimers()) 7050 var globalSetTimeout = setTimeout; 7051 return function () { 7052 return globalSetTimeout(flush, 1); 7053 }; 7054 } 7055 7056 var queue = new Array(1000); 7057 7058 function flush() { 7059 for (var i = 0; i < len; i += 2) { 7060 var callback = queue[i]; 7061 var arg = queue[i + 1]; 7062 callback(arg); 7063 queue[i] = undefined; 7064 queue[i + 1] = undefined; 7065 } 7066 7067 len = 0; 7068 } 7069 7070 function attemptVertx() { 7071 try { 7072 var r = commonjsRequire; 7073 var vertx = r('vertx'); 7074 vertxNext = vertx.runOnLoop || vertx.runOnContext; 7075 return useVertxTimer(); 7076 } catch (e) { 7077 return useSetTimeout(); 7078 } 7079 } 7080 7081 var scheduleFlush = undefined; // Decide what async method to use to triggering processing of queued callbacks: 7082 7083 if (isNode) { 7084 scheduleFlush = useNextTick(); 7085 } else if (BrowserMutationObserver) { 7086 scheduleFlush = useMutationObserver(); 7087 } else if (isWorker) {
7088 scheduleFlush = useMessageChannel(); 7089 } else if (browserWindow === undefined && typeof commonjsRequire === 'function') { 7090 scheduleFlush = attemptVertx(); 7091 } else { 7092 scheduleFlush = useSetTimeout(); 7093 } 7094 7095 function then(onFulfillment, onRejection) { 7096 var _arguments = arguments; 7097 var parent = this; 7098 var child = new this.constructor(noop); 7099 7100 if (child[PROMISE_ID] === undefined) { 7101 makePromise(child); 7102 } 7103 7104 var _state = parent._state; 7105 7106 if (_state) { 7107 (function () { 7108 var callback = _arguments[_state - 1]; 7109 asap(function () { 7110 return invokeCallback(_state, child, callback, parent._result); 7111 }); 7112 })(); 7113 } else { 7114 subscribe(parent, child, onFulfillment, onRejection); 7115 } 7116 7117 return child; 7118 } 7119 /** 7120 `Promise.resolve` returns a promise that will become resolved with the 7121 passed `value`. It is shorthand for the following: 7122 7123 ```javascript 7124 let promise = new Promise(function(resolve, reject){ 7125 resolve(1); 7126 }); 7127 7128 promise.then(function(value){ 7129 // value === 1 7130 }); 7131 ``` 7132 7133 Instead of writing the above, your code now simply becomes the following: 7134 7135 ```javascript 7136 let promise = Promise.resolve(1); 7137 7138 promise.then(function(value){ 7139 // value === 1 7140 }); 7141 ``` 7142 7143 @method resolve 7144 @static 7145 @param {Any} value value that the returned promise will be resolved with 7146 Useful for tooling. 7147 @return {Promise} a promise that will become fulfilled with the given 7148 `value` 7149 */ 7150 7151 7152 function resolve(object) { 7153 /*jshint validthis:true */ 7154 var Constructor = this; 7155 7156 if (object && babelHelpers.typeof(object) === 'object' && object.constructor === Constructor) { 7157 return object; 7158 } 7159 7160 var promise = new Constructor(noop); 7161 7162 _resolve(promise, object); 7163 7164 return promise; 7165 } 7166 7167 var PROMISE_ID = Math.random().toString(36).substring(16); 7168 7169 function noop() {} 7170 7171 var PENDING = void 0; 7172 var FULFILLED = 1; 7173 var REJECTED = 2; 7174 var GET_THEN_ERROR = new ErrorObject(); 7175 7176 function selfFulfillment() { 7177 return new TypeError("You cannot resolve a promise with itself"); 7178 } 7179 7180 function cannotReturnOwn() { 7181 return new TypeError('A promises callback cannot return that same promise.'); 7182 } 7183 7184 function getThen(promise) { 7185 try { 7186 return promise.then; 7187 } catch (error) { 7188 GET_THEN_ERROR.error = error; 7189 return GET_THEN_ERROR; 7190 } 7191 } 7192 7193 function tryThen(then, value, fulfillmentHandler, rejectionHandler) { 7194 try { 7195 then.call(value, fulfillmentHandler, rejectionHandler); 7196 } catch (e) { 7197 return e; 7198 } 7199 } 7200 7201 function handleForeignThenable(promise, thenable, then) { 7202 asap(function (promise) { 7203 var sealed = false; 7204 var error = tryThen(then, thenable, function (value) { 7205 if (sealed) { 7206 return; 7207 } 7208 7209 sealed = true; 7210 7211 if (thenable !== value) { 7212 _resolve(promise, value); 7213 } else { 7214 fulfill(promise, value); 7215 } 7216 }, function (reason) { 7217 if (sealed) { 7218 return; 7219 } 7220 7221 sealed = true; 7222 7223 _reject(promise, reason); 7224 }, 'Settle: ' + (promise._label || ' unknown promise')); 7225 7226 if (!sealed && error) { 7227 sealed = true; 7228 7229 _reject(promise, error); 7230 } 7231 }, promise); 7232 } 7233 7234 function handleOwnThenable(promise, thenable) { 7235 if (thenable._state === FULFILLED) { 7236 fulfill(promise, thenable._result); 7237 } else if (thenable._state === REJECTED) { 7238 _reject(promise, thenable._result); 7239 } else { 7240 subscribe(thenable, undefined, function (value) { 7241 return _resolve(promise, value); 7242 }, function (reason) { 7243 return _reject(promise, reason); 7244 }); 7245 } 7246 } 7247 7248 function handleMaybeThenable(promise, maybeThenable, then$$) { 7249 if (maybeThenable.constructor === promise.constructor && then$$ === then && maybeThenable.constructor.resolve === resolve) { 7250 handleOwnThenable(promise, maybeThenable); 7251 } else { 7252 if (then$$ === GET_THEN_ERROR) { 7253 _reject(promise, GET_THEN_ERROR.error); 7254 } else if (then$$ === undefined) { 7255 fulfill(promise, maybeThenable); 7256 } else if (isFunction(then$$)) { 7257 handleForeignThenable(promise, maybeThenable, then$$); 7258 } else { 7259 fulfill(promise, maybeThenable); 7260 } 7261 } 7262 } 7263 7264 function _resolve(promise, value) { 7265 if (promise === value) { 7266 _reject(promise, selfFulfillment()); 7267 } else if (objectOrFunction(value)) { 7268 handleMaybeThenable(promise, value, getThen(value)); 7269 } else { 7270 fulfill(promise, value); 7271 } 7272 } 7273 7274 function publishRejection(promise) { 7275 if (promise._onerror) {
7276 promise._onerror(promise._result); 7277 } 7278 7279 publish(promise); 7280 } 7281 7282 function fulfill(promise, value) { 7283 if (promise._state !== PENDING) { 7284 return; 7285 } 7286 7287 promise._result = value; 7288 promise._state = FULFILLED; 7289 7290 if (promise._subscribers.length !== 0) { 7291 asap(publish, promise); 7292 } 7293 } 7294 7295 function _reject(promise, reason) { 7296 if (promise._state !== PENDING) { 7297 return; 7298 } 7299 7300 promise._state = REJECTED; 7301 promise._result = reason; 7302 asap(publishRejection, promise); 7303 } 7304 7305 function subscribe(parent, child, onFulfillment, onRejection) { 7306 var _subscribers = parent._subscribers; 7307 var length = _subscribers.length; 7308 parent._onerror = null; 7309 _subscribers[length] = child; 7310 _subscribers[length + FULFILLED] = onFulfillment; 7311 _subscribers[length + REJECTED] = onRejection; 7312 7313 if (length === 0 && parent._state) { 7314 asap(publish, parent); 7315 } 7316 } 7317 7318 function publish(promise) { 7319 var subscribers = promise._subscribers; 7320 var settled = promise._state; 7321 7322 if (subscribers.length === 0) { 7323 return; 7324 } 7325 7326 var child = undefined, 7327 callback = undefined, 7328 detail = promise._result; 7329 7330 for (var i = 0; i < subscribers.length; i += 3) { 7331 child = subscribers[i]; 7332 callback = subscribers[i + settled]; 7333 7334 if (child) { 7335 invokeCallback(settled, child, callback, detail); 7336 } else { 7337 callback(detail); 7338 } 7339 } 7340 7341 promise._subscribers.length = 0; 7342 } 7343 7344 function ErrorObject() { 7345 this.error = null; 7346 } 7347 7348 var TRY_CATCH_ERROR = new ErrorObject(); 7349 7350 function tryCatch(callback, detail) { 7351 try { 7352 return callback(detail); 7353 } catch (e) { 7354 TRY_CATCH_ERROR.error = e; 7355 return TRY_CATCH_ERROR; 7356 } 7357 } 7358 7359 function invokeCallback(settled, promise, callback, detail) { 7360 var hasCallback = isFunction(callback), 7361 value = undefined, 7362 error = undefined, 7363 succeeded = undefined, 7364 failed = undefined; 7365 7366 if (hasCallback) { 7367 value = tryCatch(callback, detail); 7368 7369 if (value === TRY_CATCH_ERROR) { 7370 failed = true; 7371 error = value.error; 7372 value = null; 7373 } else { 7374 succeeded = true; 7375 } 7376 7377 if (promise === value) { 7378 _reject(promise, cannotReturnOwn()); 7379 7380 return; 7381 } 7382 } else { 7383 value = detail; 7384 succeeded = true; 7385 } 7386 7387 if (promise._state !== PENDING) ; else if (hasCallback && succeeded) { 7388 _resolve(promise, value); 7389 } else if (failed) { 7390 _reject(promise, error); 7391 } else if (settled === FULFILLED) { 7392 fulfill(promise, value); 7393 } else if (settled === REJECTED) { 7394 _reject(promise, value); 7395 } 7396 } 7397 7398 function initializePromise(promise, resolver) { 7399 try { 7400 resolver(function resolvePromise(value) { 7401 _resolve(promise, value); 7402 }, function rejectPromise(reason) { 7403 _reject(promise, reason); 7404 }); 7405 } catch (e) { 7406 _reject(promise, e); 7407 } 7408 } 7409 7410 var id = 0; 7411 7412 function nextId() { 7413 return id++; 7414 } 7415 7416 function makePromise(promise) { 7417 promise[PROMISE_ID] = id++; 7418 promise._state = undefined; 7419 promise._result = undefined; 7420 promise._subscribers = []; 7421 } 7422 7423 function Enumerator(Constructor, input) { 7424 this._instanceConstructor = Constructor; 7425 this.promise = new Constructor(noop); 7426 7427 if (!this.promise[PROMISE_ID]) { 7428 makePromise(this.promise); 7429 } 7430 7431 if (isArray(input)) { 7432 this._input = input; 7433 this.length = input.length; 7434 this._remaining = input.length; 7435 this._result = new Array(this.length); 7436 7437 if (this.length === 0) { 7438 fulfill(this.promise, this._result); 7439 } else { 7440 this.length = this.length || 0; 7441 7442 this._enumerate(); 7443 7444 if (this._remaining === 0) { 7445 fulfill(this.promise, this._result); 7446 } 7447 } 7448 } else { 7449 _reject(this.promise, validationError()); 7450 } 7451 } 7452 7453 function validationError() { 7454 return new Error('Array Methods must be provided an Array'); 7455 } 7456 7457 Enumerator.prototype._enumerate = function () { 7458 var length = this.length; 7459 var _input = this._input; 7460 7461 for (var i = 0; this._state === PENDING && i < length; i++) { 7462 this._eachEntry(_input[i], i); 7463 } 7464 }; 7465 7466 Enumerator.prototype._eachEntry = function (entry, i) { 7467 var c = this._instanceConstructor; 7468 var resolve$$ = c.resolve; 7469 7470 if (resolve$$ === resolve) { 7471 var _then = getThen(entry); 7472 7473 if (_then === then && entry._state !== PENDING) { 7474 this._settledAt(entry._state, i, entry._result); 7475 } else if (typeof _then !== 'function') { 7476 this._remaining--; 7477 this._result[i] = entry; 7478 } else if (c === Promise) { 7479 var promise = new c(noop); 7480 handleMaybeThenable(promise, entry, _then); 7481 7482 this._willSettleAt(promise, i); 7483 } else {
vendor: 3,996 bytes, lines 7484-7617
7484 this._willSettleAt(new c(function (resolve$$) { 7485 return resolve$$(entry); 7486 }), i); 7487 } 7488 } else { 7489 this._willSettleAt(resolve$$(entry), i); 7490 } 7491 }; 7492 7493 Enumerator.prototype._settledAt = function (state, i, value) { 7494 var promise = this.promise; 7495 7496 if (promise._state === PENDING) { 7497 this._remaining--; 7498 7499 if (state === REJECTED) { 7500 _reject(promise, value); 7501 } else { 7502 this._result[i] = value; 7503 } 7504 } 7505 7506 if (this._remaining === 0) { 7507 fulfill(promise, this._result); 7508 } 7509 }; 7510 7511 Enumerator.prototype._willSettleAt = function (promise, i) { 7512 var enumerator = this; 7513 subscribe(promise, undefined, function (value) { 7514 return enumerator._settledAt(FULFILLED, i, value); 7515 }, function (reason) { 7516 return enumerator._settledAt(REJECTED, i, reason); 7517 }); 7518 }; 7519 /** 7520 `Promise.all` accepts an array of promises, and returns a new promise which 7521 is fulfilled with an array of fulfillment values for the passed promises, or 7522 rejected with the reason of the first passed promise to be rejected. It casts all 7523 elements of the passed iterable to promises as it runs this algorithm. 7524 7525 Example: 7526 7527 ```javascript 7528 let promise1 = resolve(1); 7529 let promise2 = resolve(2); 7530 let promise3 = resolve(3); 7531 let promises = [ promise1, promise2, promise3 ]; 7532 7533 Promise.all(promises).then(function(array){ 7534 // The array here would be [ 1, 2, 3 ]; 7535 }); 7536 ``` 7537 7538 If any of the `promises` given to `all` are rejected, the first promise 7539 that is rejected will be given as an argument to the returned promises's 7540 rejection handler. For example: 7541 7542 Example: 7543 7544 ```javascript 7545 let promise1 = resolve(1); 7546 let promise2 = reject(new Error("2")); 7547 let promise3 = reject(new Error("3")); 7548 let promises = [ promise1, promise2, promise3 ]; 7549 7550 Promise.all(promises).then(function(array){ 7551 // Code here never runs because there are rejected promises! 7552 }, function(error) { 7553 // error.message === "2" 7554 }); 7555 ``` 7556 7557 @method all 7558 @static 7559 @param {Array} entries array of promises 7560 @param {String} label optional string for labeling the promise. 7561 Useful for tooling. 7562 @return {Promise} promise that is fulfilled when all `promises` have been 7563 fulfilled, or rejected if any of them become rejected. 7564 @static 7565 */ 7566 7567 7568 function all(entries) { 7569 return new Enumerator(this, entries).promise; 7570 } 7571 /** 7572 `Promise.race` returns a new promise which is settled in the same way as the 7573 first passed promise to settle. 7574 7575 Example: 7576 7577 ```javascript 7578 let promise1 = new Promise(function(resolve, reject){ 7579 setTimeout(function(){ 7580 resolve('promise 1'); 7581 }, 200); 7582 }); 7583 7584 let promise2 = new Promise(function(resolve, reject){ 7585 setTimeout(function(){ 7586 resolve('promise 2'); 7587 }, 100); 7588 }); 7589 7590 Promise.race([promise1, promise2]).then(function(result){ 7591 // result === 'promise 2' because it was resolved before promise1 7592 // was resolved. 7593 }); 7594 ``` 7595 7596 `Promise.race` is deterministic in that only the state of the first 7597 settled promise matters. For example, even if other promises given to the 7598 `promises` array argument are resolved, but the first settled promise has 7599 become rejected before the other promises became fulfilled, the returned 7600 promise will become rejected: 7601 7602 ```javascript 7603 let promise1 = new Promise(function(resolve, reject){ 7604 setTimeout(function(){ 7605 resolve('promise 1'); 7606 }, 200); 7607 }); 7608 7609 let promise2 = new Promise(function(resolve, reject){ 7610 setTimeout(function(){ 7611 reject(new Error('promise 2')); 7612 }, 100); 7613 }); 7614 7615 Promise.race([promise1, promise2]).then(function(result){ 7616 // Code here never runs 7617 }, function(reason){
7618 // reason.message === 'promise 2' because promise 2 became rejected before 7619 // promise 1 became fulfilled 7620 }); 7621 ``` 7622 7623 An example real-world use case is implementing timeouts: 7624 7625 ```javascript 7626 Promise.race([ajax('foo.json'), timeout(5000)]) 7627 ``` 7628 7629 @method race 7630 @static 7631 @param {Array} promises array of promises to observe 7632 Useful for tooling. 7633 @return {Promise} a promise which settles in the same way as the first passed 7634 promise to settle. 7635 */ 7636 7637 7638 function race(entries) { 7639 /*jshint validthis:true */ 7640 var Constructor = this; 7641 7642 if (!isArray(entries)) { 7643 return new Constructor(function (_, reject) { 7644 return reject(new TypeError('You must pass an array to race.')); 7645 }); 7646 } else { 7647 return new Constructor(function (resolve, reject) { 7648 var length = entries.length; 7649 7650 for (var i = 0; i < length; i++) { 7651 Constructor.resolve(entries[i]).then(resolve, reject); 7652 } 7653 }); 7654 } 7655 } 7656 /** 7657 `Promise.reject` returns a promise rejected with the passed `reason`. 7658 It is shorthand for the following: 7659 7660 ```javascript 7661 let promise = new Promise(function(resolve, reject){ 7662 reject(new Error('WHOOPS')); 7663 }); 7664 7665 promise.then(function(value){ 7666 // Code here doesn't run because the promise is rejected! 7667 }, function(reason){ 7668 // reason.message === 'WHOOPS' 7669 }); 7670 ``` 7671 7672 Instead of writing the above, your code now simply becomes the following: 7673 7674 ```javascript 7675 let promise = Promise.reject(new Error('WHOOPS')); 7676 7677 promise.then(function(value){ 7678 // Code here doesn't run because the promise is rejected! 7679 }, function(reason){ 7680 // reason.message === 'WHOOPS' 7681 }); 7682 ``` 7683 7684 @method reject 7685 @static 7686 @param {Any} reason value that the returned promise will be rejected with. 7687 Useful for tooling. 7688 @return {Promise} a promise rejected with the given `reason`. 7689 */ 7690 7691 7692 function reject(reason) { 7693 /*jshint validthis:true */ 7694 var Constructor = this; 7695 var promise = new Constructor(noop); 7696 7697 _reject(promise, reason); 7698 7699 return promise; 7700 } 7701 7702 function needsResolver() { 7703 throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); 7704 } 7705 7706 function needsNew() { 7707 throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object c
7707onstructor cannot be called as a function."); 7708 } 7709 /** 7710 Promise objects represent the eventual result of an asynchronous operation. The 7711 primary way of interacting with a promise is through its `then` method, which 7712 registers callbacks to receive either a promise's eventual value or the reason 7713 why the promise cannot be fulfilled. 7714 7715 Terminology 7716 ----------- 7717 7718 - `promise` is an object or function with a `then` method whose behavior conforms to this specification. 7719 - `thenable` is an object or function that defines a `then` method. 7720 - `value` is any legal JavaScript value (including undefined, a thenable, or a promise). 7721 - `exception` is a value that is thrown using the throw statement. 7722 - `reason` is a value that indicates why a promise was rejected. 7723 - `settled` the final resting state of a promise, fulfilled or rejected. 7724 7725 A promise can be in one of three states: pending, fulfilled, or rejected. 7726 7727 Promises that are fulfilled have a fulfillment value and are in the fulfilled 7728 state. Promises that are rejected have a rejection reason and are in the 7729 rejected state. A fulfillment value is never a thenable. 7730 7731 Promises can also be said to *resolve* a value. If this value is also a 7732 promise, then the original promise's settled state will match the value's 7733 settled state. So a promise that *resolves* a promise that rejects will 7734 itself reject, and a promise that *resolves* a promise that fulfills will 7735 itself fulfill. 7736 7737 7738 Basic Usage: 7739 ------------ 7740 7741 ```js 7742 let promise = new Promise(function(resolve, reject) { 7743 // on success 7744 resolve(value); 7745 7746 // on failure 7747 reject(reason); 7748 }); 7749 7750 promise.then(function(value) { 7751 // on fulfillment 7752 }, function(reason) { 7753 // on rejection 7754 }); 7755 ``` 7756 7757 Advanced Usage: 7758 --------------- 7759 7760 Promises shine when abstracting away asynchronous interactions such as 7761 `XMLHttpRequest`s. 7762 7763 ```js 7764 function getJSON(url) { 7765 return new Promise(function(resolve, reject){ 7766 let xhr = new XMLHttpRequest(); 7767 7768 xhr.open('GET', url); 7769 xhr.onreadystatechange = handler; 7770 xhr.responseType = 'json'; 7771 xhr.setRequestHeader('Accept', 'application/json'); 7772 xhr.send(); 7773 7774 function handler() { 7775 if (this.readyState === this.DONE) { 7776 if (this.status === 200) { 7777 resolve(this.response); 7778 } else { 7779 reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']')); 7780 } 7781 } 7782 }; 7783 }); 7784 } 7785 7786 getJSON('/posts.json').then(function(json) { 7787 // on fulfillment 7788 }, function(reason) { 7789 // on rejection 7790 }); 7791 ``` 7792 7793 Unlike callbacks, promises are great composable primitives. 7794 7795 ```js 7796 Promise.all([ 7797 getJSON('/posts'), 7798 getJSON('/comments') 7799 ]).then(function(values){ 7800 values[0] // => postsJSON 7801 values[1] // => commentsJSON 7802 7803 return values; 7804 }); 7805 ``` 7806 7807 @class Promise 7808 @param {function} resolver 7809 Useful for tooling. 7810 @constructor 7811 */ 7812 7813 7814 function Promise(resolver) { 7815 this[PROMISE_ID] = nextId(); 7816 this._result = this._state = undefined; 7817 this._subscribers = []; 7818 7819 if (noop !== resolver) { 7820 typeof resolver !== 'function' && needsResolver(); 7821 this instanceof Promise ? initializePromise(this, resolver) : needsNew(); 7822 } 7823 } 7824 7825 Promise.all = all; 7826 Promise.race = race; 7827 Promise.resolve = resolve; 7828 Promise.reject = reject; 7829 Promise._setScheduler = setScheduler; 7830 Promise._setAsap = setAsap; 7831 Promise._asap = asap; 7832 Promise.prototype = { 7833 constructor: Promise, 7834 7835 /** 7836 The primary way of interacting with a promise is through its `then` method, 7837 which registers callbacks to receive either a promise's eventual value or the 7838 reason why the promise cannot be fulfilled. 7839 7840 ```js 7841 findUser().then(function(user){ 7842 // user is available 7843 }, function(reason){ 7844 // user is unavailable, and you are given the reason why 7845 }); 7846 ``` 7847 7848 Chaining 7849 -------- 7850 7851 The return value of `then` is itself a promise. This second, 'downstream' 7852 promise is resolved with the return value of the first promise's fulfillment 7853 or rejection handler, or rejected if the handler throws an exception. 7854 7855 ```js 7856 findUser().then(function (user) { 7857 return user.name; 7858 }, function (reason) { 7859 return 'default name'; 7860 }).then(function (userName) { 7861 // If `findUser` fulfilled, `userName` will be the user's name, otherwise it 7862 // will be `'default name'` 7863 }); 7864 7865 findUser().then(function (user) { 7866 throw new Error('Found user, but still unhappy'); 7867 }, function (reason) { 7868 throw new Error('`findUser` rejected and we're unhappy'); 7869 }).then(function (value) { 7870 // never reached 7871 }, function (reason) { 7872 // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'. 7873 // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'. 7874 }); 7875 ``` 7876 If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. 7877 7878 ```js 7879 findUser().then(function (user) { 7880 throw new PedagogicalException('Upstream error'); 7881 }).then(function (value) { 7882 // never reached 7883 }).then(function (value) { 7884 // never reached 7885 }, function (reason) { 7886 // The `PedgagocialException` is propagated all the way down to here 7887 }); 7888 ``` 7889 7890 Assimilation 7891 ------------ 7892 7893 Sometimes the value you want to propagate to a downstream promise can only be 7894 retrieved asynchronously. This can be achieved by returning a promise in the 7895 fulfillment or rejection handler. The downstream promise will then be pending 7896 until the returned promise is settled. This is called *assimilation*. 7897 7898 ```js 7899 findUser().then(function (user) { 7900 return findCommentsByAuthor(user); 7901 }).then(function (comments) { 7902 // The user's comments are now available 7903 }); 7904 ``` 7905 7906 If the assimliated promise rejects, then the downstream promise will also reject. 7907 7908 ```js 7909 findUser().then(function (user) { 7910 return findCommentsByAuthor(user); 7911 }).then(function (comments) { 7912 // If `findCommentsByAuthor` fulfills, we'll have the value here 7913 }, function (reason) { 7914 // If `findCommentsByAuthor` rejects, we'll have the reason here 7915 }); 7916 ``` 7917
7918 Simple Example 7919 -------------- 7920 7921 Synchronous Example 7922 7923 ```javascript 7924 let result; 7925 7926 try { 7927 result = findResult(); 7928 // success 7929 } catch(reason) { 7930 // failure 7931 } 7932 ``` 7933 7934 Errback Example 7935 7936 ```js 7937 findResult(function(result, err){ 7938 if (err) { 7939 // failure 7940 } else { 7941 // success 7942 } 7943 }); 7944 ``` 7945 7946 Promise Example; 7947 7948 ```javascript 7949 findResult().then(function(result){ 7950 // success 7951 }, function(reason){ 7952 // failure 7953 }); 7954 ``` 7955 7956 Advanced Example 7957 -------------- 7958 7959 Synchronous Example 7960 7961 ```javascript 7962 let author, books; 7963 7964 try { 7965 author = findAuthor(); 7966 books = findBooksByAuthor(author); 7967 // success 7968 } catch(reason) { 7969 // failure 7970 } 7971 ``` 7972 7973 Errback Example 7974 7975 ```js 7976 7977 function foundBooks(books) { 7978 7979 } 7980 7981 function failure(reason) { 7982 7983 } 7984 7985 findAuthor(function(author, err){ 7986 if (err) { 7987 failure(err); 7988 // failure 7989 } else { 7990 try { 7991 findBoooksByAuthor(author, function(books, err) { 7992 if (err) { 7993 failure(err); 7994 } else { 7995 try { 7996 foundBooks(books); 7997 } catch(reason) { 7998 failure(reason); 7999 } 8000 } 8001 }); 8002 } catch(error) { 8003 failure(err); 8004 } 8005 // success 8006 } 8007 }); 8008 ``` 8009 8010 Promise Example; 8011 8012 ```javascript 8013 findAuthor(). 8014 then(findBooksByAuthor). 8015 then(function(books){ 8016 // found books 8017 }).catch(function(reason){ 8018 // something went wrong 8019 }); 8020 ``` 8021 8022 @method then 8023 @param {Function} onFulfilled 8024 @param {Function} onRejected 8025 Useful for tooling. 8026 @return {Promise} 8027 */ 8028 then: then, 8029 8030 /** 8031 `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same 8032 as the catch block of a try/catch statement. 8033 8034 ```js 8035 function findAuthor(){ 8036 throw new Error('couldn't find that author'); 8037 } 8038 8039 // synchronous 8040 try { 8041 findAuthor(); 8042 } catch(reason) { 8043 // something went wrong 8044 } 8045 8046 // async with promises 8047 findAuthor().catch(function(reason){ 8048 // something went wrong 8049 }); 8050 ``` 8051 8052 @method catch 8053 @param {Function} onRejection 8054 Useful for tooling. 8055 @return {Promise} 8056 */ 8057 'catch': function _catch(onRejection) { 8058 return this.then(null, onRejection); 8059 } 8060 }; 8061 8062 function polyfill() { 8063 var local = undefined; 8064 8065 if (typeof commonjsGlobal !== 'undefined') { 8066 local = commonjsGlobal; 8067 } else if (typeof self !== 'undefined') { 8068 local = self; 8069 } else { 8070 try { 8071 local = Function('return this')(); 8072 } catch (e) { 8073 throw new Error('polyfill failed because global object is unavailable in this environment'); 8074 } 8075 } 8076 8077 var P = local.Promise; 8078 8079 if (P) { 8080 var promiseToString = null; 8081 8082 try { 8083 promiseToString = Object.prototype.toString.call(P.resolve()); 8084 } catch (e) {// silently ignored 8085 } 8086 8087 if (promiseToString === '[object Promise]' && !P.cast) { 8088 return; 8089 } 8090 } 8091 8092 local.Promise = Promise; 8093 } // Strange compat.. 8094 8095 8096 Promise.polyfill = polyfill; 8097 Promise.Promise = Promise; 8098 return Promise; 8099 }); 8100 }); 8101 8102 var keys = createCommonjsModule(function (module, exports) { 8103 exports = module.exports = typeof Object.keys === 'function' ? Object.keys : shim; 8104 exports.shim = shim; 8105 8106 function shim(obj) { 8107 var keys = []; 8108 8109 for (var key in obj) { 8110 keys.push(key); 8111 } 8112 8113 return keys; 8114 } 8115 }); 8116 var keys_1 = keys.shim; 8117 8118 var is_arguments = createCommonjsModule(function (module, exports
8118) { 8119 var supportsArgumentsClass = function () { 8120 return Object.prototype.toString.call(arguments); 8121 }() == '[object Arguments]'; 8122 8123 exports = module.exports = supportsArgumentsClass ? supported : unsupported; 8124 exports.supported = supported; 8125 8126 function supported(object) { 8127 return Object.prototype.toString.call(object) == '[object Arguments]'; 8128 } 8129 exports.unsupported = unsupported; 8130 8131 function unsupported(object) { 8132 return object && babelHelpers.typeof(object) == 'object' && typeof object.length == 'number' && Object.prototype.hasOwnProperty.call(object, 'callee') && !Object.prototype.propertyIsEnumerable.call(object, 'callee') || false; 8133 } 8134 }); 8135 var is_arguments_1 = is_arguments.supported; 8136 var is_arguments_2 = is_arguments.unsupported; 8137 8138 var deepEqual_1 = createCommonjsModule(function (module) { 8139 var pSlice = Array.prototype.slice; 8140 8141 8142 8143 8144 8145 var deepEqual = module.exports = function (actual, expected, opts) { 8146 if (!opts) opts = {}; // 7.1. All identical values are equivalent, as determined by ===. 8147 8148 if (actual === expected) { 8149 return true; 8150 } else if (actual instanceof Date && expected instanceof Date) { 8151 return actual.getTime() === expected.getTime(); // 7.3. Other pairs that do not both pass typeof value == 'object', 8152 // equivalence is determined by ==. 8153 } else if (!actual || !expected || babelHelpers.typeof(actual) != 'object' && babelHelpers.typeof(expected) != 'object') { 8154 return opts.strict ? actual === expected : actual == expected; // 7.4. For all other Object pairs, including Array objects, equivalence is 8155 // determined by having the same number of owned properties (as verified 8156 // with Object.prototype.hasOwnProperty.call), the same set of keys 8157 // (although not necessarily the same order), equivalent values for every 8158 // corresponding key, and an identical 'prototype' property. Note: this 8159 // accounts for both named and indexed properties on Arrays. 8160 } else { 8161 return objEquiv(actual, expected, opts); 8162 } 8163 }; 8164 8165 function isUndefinedOrNull(value) { 8166 return value === null || value === undefined; 8167 } 8168 8169 function isBuffer(x) { 8170 if (!x || babelHelpers.typeof(x) !== 'object' || typeof x.length !== 'number') return false; 8171 8172 if (typeof x.copy !== 'function' || typeof x.slice !== 'function') { 8173 return false; 8174 } 8175 8176 if (x.length > 0 && typeof x[0] !== 'number') return false; 8177 return true; 8178 } 8179 8180 function objEquiv(a, b, opts) { 8181 var i, key; 8182 if (isUndefinedOrNull(a) || isUndefinedOrNull(b)) return false; // an identical 'prototype' property. 8183 8184 if (a.prototype !== b.prototype) return false; //~~~I've managed to break Object.keys through screwy arguments passing. 8185 // Converting to array solves the problem. 8186 8187 if (is_arguments(a)) { 8188 if (!is_arguments(b)) { 8189 return false; 8190 } 8191 8192 a = pSlice.call(a); 8193 b = pSlice.call(b); 8194 return deepEqual(a, b, opts); 8195 } 8196 8197 if (isBuffer(a)) { 8198 if (!isBuffer(b)) { 8199 return false; 8200 } 8201 8202 if (a.length !== b.length) return false; 8203 8204 for (i = 0; i < a.length; i++) { 8205 if (a[i] !== b[i]) return false; 8206 } 8207 8208 return true; 8209 } 8210 8211 try { 8212 var ka = keys(a), 8213 kb = keys(b); 8214 } catch (e) { 8215 //happens when one is a string literal and the other isn't 8216 return false; 8217 } // having the same number of owned properties (keys incorporates 8218 // hasOwnProperty) 8219 8220 8221 if (ka.length != kb.length) return false; //the same set of keys (although not necessarily the same order), 8222 8223 ka.sort(); 8224 kb.sort(); //~~~cheap key test 8225 8226 for (i = ka.length - 1; i >= 0; i--) { 8227 if (ka[i] != kb[i]) return false; 8228 } //equivalent values for every corresponding key, and 8229 //~~~possibly expensive deep test 8230 8231 8232 for (i = ka.length - 1; i >= 0; i--) { 8233 key = ka[i]; 8234 if (!deepEqual(a[key], b[key], opts)) return false; 8235 } 8236 8237 return babelHelpers.typeof(a) === babelHelpers.typeof(b); 8238 } 8239 }); 8240 8241 var templates = { 8242 error: 'Error.', 8243 required: 'Required.', 8244 float: 'Must be a number.', 8245 integer: 'Must be an integer.', 8246 number: 'Must be a number.', 8247 lessThan: 'Must be less than {0}.', 8248 lessThanOrEqualTo: 'Must be less than or equal to {0}.', 8249 greaterThan: 'Must be greater than {0}.', 8250 greaterThanOrEqualTo: 'Must greater than or equal to {0}.', 8251 between: 'Must be between {0} and {1}.', 8252 size: 'Size must be {0}.', 8253 length: 'Length must be {0}.', 8254 minLength: 'Must have at least {0} characters.', 8255 maxLength: 'Must have up to {0} characters.', 8256 lengthBetween: 'Length must between {0} and {1}.', 8257 in: 'Must be {0}.', 8258 notIn: 'Must not be {0}.', 8259 match: 'Not matched.', 8260 regex: 'Invalid format.', 8261 digit: 'Must be a digit.', 8262 email: 'Invalid email.', 8263 url: 'Invalid url.', 8264 optionCombiner: function optionCombiner(options) { 8265 if (options.length > 2) { 8266 options = [options.slice(0, options.length - 1).join(', '), options[options.length - 1]]; 8267 } 8268 8269 return options.join(' or '); 8270 } 8271 }; 8272 8273 var utils = createCommonjsModule(function (module) { 8274 8275 // This implementation of debounce was taken from the blog of David Walsh. 8276 // See here: https://davidwalsh.name/javascript-debounce-function 8277 8278 8279 module.exports.debounce = function (func, wait, immediate) { 8280 var timeout; 8281 return function () { 8282 var context = this; 8283 var args = arguments; 8284 8285 var later = function later() { 8286 timeout = null; 8287 8288 if (!immediate) {
8289 func.apply(context, args); 8290 } 8291 }; 8292 8293 var callNow = immediate && !timeout; 8294 clearTimeout(timeout); 8295 timeout = setTimeout(later, wait); 8296 8297 if (callNow) { 8298 func.apply(context, args); 8299 } 8300 }; 8301 }; 8302 8303 module.exports.format = function (template) { 8304 var args = Array.prototype.slice.call(arguments, 1); 8305 return template.replace(/{(\d+)}/g, function (match, number) { 8306 return typeof args[number] != 'undefined' ? args[number] : match; 8307 }); 8308 }; 8309 8310 module.exports.isArray = function (arg) { 8311 if (typeof Array.isArray === 'function') { 8312 return Array.isArray(arg); 8313 } 8314 8315 return Object.prototype.toString.call(arg) === '[object Array]'; 8316 }; 8317 8318 module.exports.isEmpty = function (value) { 8319 if (module.exports.isArray(value)) { 8320 return !value.length; 8321 } else if (value === undefined || value === null) { 8322 return true; 8323 } else { 8324 return !String(value).trim().length; 8325 } 8326 }; 8327 8328 module.exports.isEqual = function (o1, o2) { 8329 return deepEqual_1(o1, o2); 8330 }; 8331 8332 module.exports.isFunction = function (arg) { 8333 return typeof arg === 'function'; 8334 }; 8335 8336 module.exports.isNaN = function (arg) { 8337 return /^\s*$/.test(arg) || isNaN(arg); 8338 }; 8339 8340 module.exports.isNull = function (arg) { 8341 return arg === null; 8342 }; 8343 8344 module.exports.isString = function (arg) { 8345 return typeof arg === 'string' || arg instanceof String; 8346 }; 8347 8348 module.exports.isUndefined = function (arg) { 8349 return typeof arg === 'undefined'; 8350 }; 8351 8352 module.exports.omit = function omit(obj, key) { 8353 var result = {}; 8354 8355 for (var name in obj) { 8356 if (name !== key) { 8357 result[name] = obj[name]; 8358 } 8359 } 8360 8361 return result; 8362 }; 8363 8364 module.exports.templates = templates; 8365 module.exports.mode = 'interactive'; // other values: conservative and manual 8366 }); 8367 var utils_1 = utils.debounce; 8368 var utils_2 = utils.format; 8369 var utils_3 = utils.isArray; 8370 var utils_4 = utils.isEmpty; 8371 var utils_5 = utils.isEqual; 8372 var utils_6 = utils.isFunction; 8373 var utils_7 = utils.isNaN; 8374 var utils_8 = utils.isNull; 8375 var utils_9 = utils.isString; 8376 var utils_10 = utils.isUndefined; 8377 var utils_11 = utils.omit; 8378 var utils_12 = utils.templates; 8379 var utils_13 = utils.mode; 8380 8381 var Promise$1 = es6Promise.Promise; 8382 8383 8384 8385 function ValidationBag() { 8386 this.sessionId = 0; // async validator will check this before adding error 8387 8388 this.resetting = 0; // do not allow to add error while reset is in progress 8389 8390 this.errors = []; 8391 this.validatingRecords = []; 8392 this.passedRecords = []; 8393 this.touchedRecords = []; 8394 this.activated = false; // set when $validate() is call, this flag works with the conservative mode 8395 } 8396 8397 ValidationBag.prototype._setVM = function (vm) { 8398 this._vm = vm; 8399 }; 8400 8401 ValidationBag.prototype.addError = function (field, message) { 8402 if (this.resetting) { 8403 return; 8404 } 8405 8406 this.errors.push({ 8407 field: field, 8408 message: message 8409 }); 8410 }; 8411 8412 ValidationBag.prototype.removeErrors = function (field) { 8413 if (utils.isUndefined(field)) { 8414 this.errors = []; 8415 } else { 8416 this.errors = this.errors.filter(function (e) { 8417 return e.field !== field; 8418 }); 8419 } 8420 }; 8421 8422 ValidationBag.prototype.hasError = function (field) { 8423 return utils.isUndefined(field) ? !!this.errors.length : !!this.firstError(field); 8424 }; 8425 8426 ValidationBag.prototype.firstError = function (field) { 8427 for (var i = 0; i < this.errors.length; i++) { 8428 if (utils.isUndefined(field) || this.errors[i].field === field) { 8429 return this.errors[i].message; 8430 } 8431 } 8432 8433 return null; 8434 }; 8435 8436 ValidationBag.prototype.allErrors = function (field) { 8437 return this.errors.filter(function (e) { 8438 return utils.isUndefined(field) || e.field === field; 8439 }).map(function (e) { 8440 return e.message; 8441 }); 8442 }; 8443 8444 ValidationBag.prototype.countErrors = function (field) { 8445 return utils.isUndefined(field) ? this.errors.length : this.errors.filter(function (e) { 8446 return field === e.field; 8447 }).length; 8448 }; 8449 8450 ValidationBag.prototype.setValidating = function (field, id) { 8451 if (this.resetting) { 8452 return; 8453 } 8454 8455 id = id || ValidationBag.newValidatingId();
8456 var existingValidatingRecords = this.validatingRecords.filter(function (validating) { 8457 return validating.field === field && validating.id === id; 8458 }); 8459 8460 if (!utils.isEmpty(existingValidatingRecords)) { 8461 throw new Error('Validating id already set: ' + id); 8462 } 8463 8464 this.validatingRecords.push({ 8465 field: field, 8466 id: id 8467 }); 8468 return id; 8469 }; 8470 8471 ValidationBag.prototype.resetValidating = function (field, id) { 8472 if (!field) { 8473 this.validatingRecords = []; 8474 return; 8475 } 8476 8477 function idMatched(validating) { 8478 return utils.isUndefined(id) ? true : validating.id === id; 8479 } 8480 8481 var hasMore = true; 8482 8483 while (hasMore) { 8484 var index = -1; 8485 8486 for (var i = 0; i < this.validatingRecords.length; i++) { 8487 if (this.validatingRecords[i].field === field && idMatched(this.validatingRecords[i])) { 8488 index = i; 8489 break; 8490 } 8491 } 8492 8493 if (index >= 0) { 8494 this.validatingRecords.splice(index, 1); 8495 } else { 8496 hasMore = false; 8497 } 8498 } 8499 }; 8500 8501 ValidationBag.prototype.isValidating = function (field, id) { 8502 function idMatched(validating) { 8503 return utils.isUndefined(id) ? true : validating.id === id; 8504 } 8505 8506 var existingValidatingRecords = this.validatingRecords.filter(function (validating) { 8507 return (utils.isUndefined(field) || validating.field === field) && idMatched(validating); 8508 }); 8509 return !utils.isEmpty(existingValidatingRecords); 8510 }; 8511 8512 ValidationBag.prototype.setPassed = function (field) { 8513 if (this.resetting) { 8514 return; 8515 } 8516 8517 setValue(this.passedRecords, field); 8518 }; 8519 8520 ValidationBag.prototype.resetPassed = function (field) { 8521 resetValue(this.passedRecords, field); 8522 }; 8523 8524 ValidationBag.prototype.isPassed = function (field) { 8525 return isValueSet(this.passedRecords, field); 8526 }; 8527 8528 ValidationBag.prototype.setTouched = function (field) { 8529 if (this.resetting) { 8530 return; 8531 } 8532 8533 setValue(this.touchedRecords, field); 8534 }; 8535 8536 ValidationBag.prototype.resetTouched = function (field) { 8537 resetValue(this.touchedRecords, field); 8538 }; 8539 8540 ValidationBag.prototype.isTouched = function (field) { 8541 return isValueSet(this.touchedRecords, field); 8542 }; 8543 8544 function setValue(records, field) { 8545 var existingRecords = records.filter(function (record) { 8546 return record.field === field; 8547 }); 8548 8549 if (!utils.isEmpty(existingRecords)) { 8550 existingRecords[0].value = true; 8551 } else { 8552 records.push({ 8553 field: field, 8554 value: true 8555 }); 8556 } 8557 } 8558 8559 function resetValue(records, field) { 8560 if (!field) { 8561 records.splice(0, records.length); 8562 return; 8563 } 8564 8565 var existingRecords = records.filter(function (record) { 8566 return record.field === field; 8567 }); 8568 8569 if (!utils.isEmpty(existingRecords)) { 8570 existingRecords[0].value = false; 8571 } 8572 } 8573 8574 function isValueSet(records, field) { 8575 var existingRecords = records.filter(function (record) { 8576 return record.field === field; 8577 }); 8578 return !utils.isEmpty(existingRecords) && existingRecords[0].value; 8579 } 8580 8581 ValidationBag.prototype.reset = function () { 8582 this.sessionId++; 8583 this.errors = []; 8584 this.validatingRecords = []; 8585 this.passedRecords = []; 8586 this.touchedRecords = []; 8587 8588 if (this._vm) { 8589 // prevent field updates at the same tick to change validation status 8590 this.resetting++; 8591 8592 this._vm.$nextTick(function () { 8593 this.resetting--; 8594 }.bind(this)); 8595 } 8596 8597 this.activated = false; 8598 }; // returns true if any error is added 8599 8600 8601 ValidationBag.prototype.setError = function (field, message) { 8602 if (this.resetting) { 8603 return; 8604 } 8605 8606 this.removeErrors(field); 8607 this.resetPassed(field); 8608 var messages = utils.isArray(message) ? message : [message]; 8609 8610 var addMessages = function (messages) { 8611 var hasError = false; 8612 messages.forEach(function (message) { 8613 if (message) { 8614 this.addError(field, message); 8615 hasError = true; 8616 } 8617 }, this); 8618 8619 if (!hasError) { 8620 this.setPassed(field); 8621 } 8622 8623 return hasError; 8624 }.bind(this); 8625 8626 var hasPromise = messages.filter(function (message) { 8627 return message && message.then; 8628 }).length > 0; 8629 8630 if (!hasPromise) { 8631 return Promise$1.resolve(addMessages(messages)); 8632 } else { 8633 // if message is promise, we are encountering async validation, set validating flag and wait for message to resolve 8634 // reset previous validating status for this field 8635 this.resetValidating(field);
8636 var validatingId = this.setValidating(field); 8637 8638 var always = function () { 8639 //console.log(validatingId + ' | ' + 'end'); 8640 this.resetValidating(field, validatingId); 8641 }.bind(this); //console.log(validatingId + ' | ' + 'start'); 8642 8643 8644 return Promise$1.all(messages).then(function (messages) { 8645 // check if the validating id is is still valid 8646 if (this.isValidating(field, validatingId)) { 8647 //console.log(validatingId + ' | ' + 'processed'); 8648 return addMessages(messages); 8649 } 8650 8651 return false; 8652 }.bind(this)).then(function (result) { 8653 always(); 8654 return result; 8655 }).catch(function (e) { 8656 always(); 8657 return Promise$1.reject(e); 8658 }.bind(this)); 8659 } 8660 }; 8661 8662 ValidationBag.prototype.checkRule = function (rule) { 8663 if (this.resetting) { 8664 return; 8665 } 8666 8667 return this.setError(rule._field, rule._messages); 8668 }; 8669 8670 var validatingId = 0; 8671 8672 ValidationBag.newValidatingId = function () { 8673 return (++validatingId).toString(); 8674 }; 8675 8676 var validationBag = ValidationBag; 8677 8678 function Rule(templates) { 8679 this._field = ''; 8680 this._value = undefined; 8681 this._messages = []; 8682 8683 if (templates) { 8684 // merge given template and utils.template 8685 this.templates = {}; 8686 Object.keys(utils.templates).forEach(function (key) { 8687 this.templates[key] = utils.templates[key]; 8688 }.bind(this)); 8689 Object.keys(templates).forEach(function (key) { 8690 this.templates[key] = templates[key]; 8691 }.bind(this)); 8692 } else { 8693 this.templates = utils.templates; 8694 } 8695 } 8696 8697 Rule.prototype.field = function (field) { 8698 this._field = field; 8699 return this; 8700 }; 8701 8702 Rule.prototype.value = function (value) { 8703 this._value = value; 8704 return this; 8705 }; 8706 8707 Rule.prototype.custom = function (callback, context) { 8708 var message = context ? callback.call(context) : callback(); 8709 8710 if (message) { 8711 if (message.then) { 8712 var that = this; 8713 message = Promise.resolve(message).then(function (result) { 8714 return result; 8715 }).catch(function (e) { 8716 console.error(e.toString()); 8717 return that.templates.error; 8718 }); 8719 } 8720 8721 this._messages.push(message); 8722 } 8723 8724 return this; 8725 }; 8726 8727 Rule.prototype._checkValue = function () { 8728 if (this._value === undefined) { 8729 throw new Error('Validator.value not set'); 8730 } 8731 8732 return this._value; 8733 }; 8734 8735 Rule.prototype.required = function (message) { 8736 var value = this._checkValue(); 8737 8738 if (utils.isEmpty(value)) { 8739 this._messages.push(message || this.templates.required); 8740 } 8741 8742 return this; 8743 }; 8744 8745 Rule.prototype.float = function (message) { 8746 var value = this._checkValue(); 8747 8748 var regex = /^([-+])?([0-9]+(\.[0-9]+)?|Infinity)$/; 8749 8750 if (!utils.isEmpty(value) && !regex.test(value)) { 8751 this._messages.push(message || this.templates.float); 8752 } 8753 8754 return this; 8755 }; 8756 8757 Rule.prototype.integer = function (message) { 8758 var value = this._checkValue(); 8759 8760 var regex = /^([-+])?([0-9]+|Infinity)$/; 8761 8762 if (!utils.isEmpty(value) && !regex.test(value)) { 8763 this._messages.push(message || this.templates.integer); 8764 } 8765 8766 return this; 8767 }; 8768 8769 Rule.prototype.lessThan = function (bound, message) { 8770 var value = this._checkValue(); 8771 8772 if (!utils.isEmpty(value)) { 8773 var number = parseFloat(value); 8774 8775 if (utils.isNaN(number)) { 8776 this._messages.push(message || this.templates.number); 8777 } else if (number >= bound) { 8778 this._messages.push(message || utils.format(this.templates.lessThan, bound)); 8779 } 8780 } 8781 8782 return this; 8783 }; 8784 8785 Rule.prototype.lessThanOrEqualTo = function (bound, message) { 8786 var value = this._checkValue(); 8787 8788 if (!utils.isEmpty(value)) { 8789 var number = parseFloat(value); 8790 8791 if (utils.isNaN(number)) { 8792 this._messages.push(message || this.templates.number); 8793 } else if (number > bound) { 8794 this._messages.push(message || utils.format(this.templates.lessThanOrEqualTo, bound)); 8795 } 8796 } 8797 8798 return this; 8799 }; 8800 8801 Rule.prototype.greaterThan = function (bound, message) { 8802 var value = this._checkValue(); 8803 8804 if (!utils.isEmpty(value)) { 8805 var number = parseFloat(value); 8806 8807 if (utils.isNaN(number)) { 8808 this._messages.push(message || this.templates.number); 8809 } else if (number <= bound) { 8810 this._messages.push(message || utils.format(this.templates.greaterThan, bound)); 8811 } 8812 } 8813 8814 return this; 8815 }; 8816 8817 Rule.prototype.greaterThanOrEqualTo = function (bound, message) { 8818 var value = this._checkValue(); 8819 8820 if (!utils.isEmpty(value)) { 8821 var number = parseFloat(value); 8822 8823 if (utils.isNaN(number)) { 8824 this._messages.push(message || this.templates.number); 8825 } else if (number < bound) { 8826 this._messages.push(message || utils.format(this.templates.greaterThanOrEqualTo, bound)); 8827 } 8828 } 8829 8830 return this; 8831 }; 8832 8833 Rule.prototype.between = function (lowBound, highBound, message) { 8834 var value = this._checkValue(); 8835 8836 if (!utils.isEmpty(value)) { 8837 var number = parseFloat(value); 8838 8839 if (utils.isNaN(number)) { 8840 this._messages.push(message || this.templates.number); 8841 } else if (number < lowBound || number > highBound) { 8842 this._messages.push(message || utils.format(this.templates.between, lowBound, highBound)); 8843 } 8844 } 8845 8846 return this; 8847 }; 8848 8849 Rule.prototype.size = function (size, message) { 8850 var value = this._checkValue(); 8851 8852 if (!utils.isEmpty(value) && utils.isArray(value) && value.length !== size) { 8853 this._messages.push(message || utils.format(this.templates.size, size)); 8854 } 8855 8856 return this; 8857 }; 8858 8859 Rule.prototype.length = function (length, message) { 8860 var value = this._checkValue(); 8861 8862 if (!utils.isEmpty(value) && String(value).length !== length) { 8863 this._messages.push(message || utils.format(this.templates.length, length)); 8864 } 8865 8866 return this; 8867 }; 8868 8869 Rule.prototype.minLength = function (length, message) { 8870 var value = this._checkValue(); 8871 8872 if (!utils.isEmpty(value) && String(value).length < length) { 8873 this._messages.push(message || utils.format(this.templates.minLength, length)); 8874 } 8875 8876 return this; 8877 }; 8878 8879 Rule.prototype.maxLength = function (length, message) { 8880 var value = this._checkValue(); 8881 8882 if (!utils.isEmpty(value) && String(value).length > length) { 8883 this._messages.push(message || utils.format(this.templates.maxLength, length)); 8884 } 8885 8886 return this; 8887 }; 8888 8889 Rule.prototype.lengthBetween = function (minLength, maxLength, message) { 8890 var value = this._checkValue(); 8891 8892 if (!utils.isEmpty(value)) { 8893 var string = String(value); 8894
8895 if (string.length < minLength || string.length > maxLength) { 8896 this._messages.push(message || utils.format(this.templates.lengthBetween, minLength, maxLength)); 8897 } 8898 } 8899 8900 return this; 8901 }; 8902 8903 Rule.prototype.in = function (options, message) { 8904 var value = this._checkValue(); 8905 8906 if (!utils.isEmpty(value) && options.indexOf(value) < 0) { 8907 this._messages.push(message || utils.format(this.templates.in, this.templates.optionCombiner(options))); 8908 } 8909 8910 return this; 8911 }; 8912 8913 Rule.prototype.notIn = function (options, message) { 8914 var value = this._checkValue(); 8915 8916 if (!utils.isEmpty(value) && options.indexOf(value) >= 0) { 8917 this._messages.push(message || utils.format(this.templates.notIn, this.templates.optionCombiner(options))); 8918 } 8919 8920 return this; 8921 }; 8922 8923 Rule.prototype.match = function (valueToCompare, message) { 8924 var value = this._checkValue(); 8925 8926 if (!utils.isEmpty(value) && value !== valueToCompare) { 8927 this._messages.push(message || this.templates.match); 8928 } 8929 8930 return this; 8931 }; 8932 8933 Rule.prototype.regex = function (regex, message) { 8934 var value = this._checkValue(); 8935 8936 if (!utils.isEmpty(value)) { 8937 if (utils.isString(regex)) { 8938 regex = new RegExp(regex); 8939 } 8940 8941 if (!regex.test(value)) { 8942 this._messages.push(message || this.templates.regex); 8943 } 8944 } 8945 8946 return this; 8947 }; 8948 8949 Rule.prototype.digit = function (message) { 8950 return this.regex(/^\d*$/, message || this.templates.digit); 8951 }; 8952 8953 Rule.prototype.email = function (message) { 8954 return this.regex(/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/, message || this.templates.email); 8955 }; 8956 8957 Rule.prototype.url = function (message) { 8958 return this.regex(/(http|https):\/\/[\w-]+(\.[\w-]+)+([\w.,@?^=%&:\/~+#-]*[\w@?^=%&\/~+#-])?/, message || this.templates.url); 8959 }; 8960 8961 Rule.prototype.hasImmediateError = function () { 8962 for (var i = 0; i < this._messages.length; i++) { 8963 if (this._messages[i] && !this._messages[i].then) { 8964 return true; 8965 } 8966 } 8967 8968 return false; 8969 }; 8970 8971 var rule = Rule; 8972 8973 var Validator = newValidator(); 8974 8975 Validator.create = function (options) { 8976 return newValidator(options); 8977 }; 8978 8979 function newValidator(options) { 8980 options = options || {}; 8981 var validator = {}; // clone methods from Rule to validator 8982 8983 Object.keys(rule.prototype).forEach(function (methodName) { 8984 validator[methodName] = function () { 8985 var rule$$1 = new rule(options.templates); 8986 return rule$$1[methodName].apply(rule$$1, arguments); 8987 }; 8988 }); 8989 validator.isEmpty = utils.isEmpty; 8990 validator.format = utils.format; 8991 return validator; 8992 } 8993 8994 var validator = Validator; 8995 8996 var mixin = { 8997 Promise: null, 8998 beforeMount: function beforeMount() { 8999 this.$setValidators(this.$options.validators); 9000 9001 if (this.validation) { 9002 // set vm to validation 9003 this.validation._setVM(this); 9004 } 9005 }, 9006 beforeDestroy: function beforeDestroy() { 9007 unwatch(this.$options.validatorsUnwatchCallbacks); 9008 }, 9009 data: function data() { 9010 if (this.$options.validators) { 9011 return { 9012 validation: new validationBag() 9013 }; 9014 } 9015 9016 return {}; 9017 }, 9018 methods: { 9019 $setValidators: function $setValidators(validators) { 9020 unwatch(this.$options.validatorsUnwatchCallbacks); // validate methods contains all application validate codes 9021 9022 var validateMethods = {}; 9023 this.$options.validateMethods = validateMethods; 9024 var unwatchCallbacks = []; 9025 this.$options.validatorsUnwatchCallbacks = unwatchCallbacks; // generate validate methods and watch properties change for validators 9026 9027 if (validators) { 9028 Object.keys(validators).forEach(function (key) { 9029 var properties = key.split(','); 9030 properties = properties.map(function (property) { 9031 return property.trim(); 9032 }); 9033 var getters = properties.map(function (property) { 9034 return generateGetter(this, property); 9035 }, this); 9036 var validator = validators[key]; 9037 var options = {}; 9038
9039 if (!utils.isFunction(validator)) { 9040 options = utils.omit(validator, 'validator'); 9041 validator = validator.validator; 9042 } 9043 9044 if (options.cache) { 9045 // cache the validation result, so that async validator can be fast when submitting the form 9046 var option = options.cache === 'last' ? 'last' : 'all'; 9047 validator = cache(validator, option); 9048 } 9049 9050 var validation = this.validation; 9051 9052 var validateMethod = function () { 9053 if (utils.mode === 'conservative' && !validation.activated) { 9054 // do nothing if in conservative mode and $validate() method is not called before 9055 return getPromise().resolve(false); 9056 } 9057 9058 var args = getters.map(function (getter) { 9059 return getter(); 9060 }); 9061 var rule = validator.apply(this, args); 9062 9063 if (rule) { 9064 if (!rule._field) { 9065 // field defaults to the first property 9066 rule.field(properties[0]); 9067 } 9068 9069 return this.validation.checkRule(rule); 9070 } else { 9071 return getPromise().resolve(false); 9072 } 9073 }.bind(this); // add to validate method list 9074 9075 9076 validateMethods[properties[0]] = validateMethod; // watch change and invoke validate method 9077 9078 var validateMethodForWatch = validateMethod; 9079 9080 if (options.debounce) { 9081 // TODO what if custom field name is used? 9082 var decoratedValidateMethod = function () { 9083 if (decoratedValidateMethod.sessionId !== this.validation.sessionId) { 9084 // skip validation if it's reset before 9085 return getPromise().resolve(false); 9086 } 9087 9088 return validateMethod.apply(this, arguments); 9089 }.bind(this); 9090 9091 var debouncedValidateMethod = utils.debounce(decoratedValidateMethod, parseInt(options.debounce)); 9092 var field = properties[0]; 9093 9094 validateMethodForWatch = function () { 9095 // eagerly resetting passed flag if debouncing is used. 9096 this.validation.resetPassed(field); // store sessionId 9097 9098 decoratedValidateMethod.sessionId = this.validation.sessionId; 9099 debouncedValidateMethod.apply(this, arguments); 9100 }.bind(this); 9101 } 9102 9103 if (utils.mode !== 'manual') { 9104 // have to call $validate() to trigger validation in manual mode, so don't watch, 9105 watchProperties(this, properties, validateMethodForWatch).forEach(function (unwatch) { 9106 unwatchCallbacks.push(unwatch); 9107 }); 9108 } 9109 }, this); 9110 } 9111 }, 9112 $validate: function $validate(fields) { 9113 if (this.validation._validate) { 9114 return this.validation._validate; 9115 } 9116 9117 this.validation.activated = true; 9118 var validateMethods = this.$options.validateMethods; 9119 9120 if (utils.isUndefined(fields)) { 9121 validateMethods = Object.keys(validateMethods).map(function (key) { 9122 return validateMethods[key]; 9123 }); 9124 } else { 9125 fields = utils.isArray(fields) ? fields : [fields]; 9126 validateMethods = fields.map(function (field) { 9127 return validateMethods[field]; 9128 }); 9129 } 9130 9131 if (utils.isEmpty(validateMethods)) { 9132 return getPromise().resolve(true); 9133 } else { 9134 var always = function () { 9135 this.validation._validate = null; 9136 }.bind(this); 9137 9138 this.validation._validate = getPromise().all(validateMethods.map(function (validateMethod) { 9139 return validateMethod(); 9140 })).then(function (results) { 9141 always(); 9142 return results.filter(function (result) { 9143 return !!result; 9144 }).length <= 0; 9145 }.bind(this)).catch(function (e) { 9146 always(); 9147 throw e; 9148 }); 9149 return this.validation._validate; 9150 } 9151 } 9152 } 9153 }; 9154 9155 function unwatch(list) { 9156 if (list) { 9157 list.forEach(function (unwatch) { 9158 unwatch(); 9159 }); 9160 } 9161 } 9162 9163 function generateGetter(vm, property) { 9164 var names = property.split('.'); 9165 return function () { 9166 var value = vm; 9167 9168 for (var i = 0; i < names.length; i++) { 9169 if (utils.isNull(value) || utils.isUndefined(value)) { 9170 break; 9171 } 9172 9173 value = value[names[i]]; 9174 } 9175 9176 return value; 9177 }; 9178 } 9179 9180 function watchProperties(vm, properties, callback) { 9181 return properties.map(function (property) { 9182 return vm.$watch(property, function () { 9183 vm.validation.setTouched(property); 9184 callback.call(); 9185 }); 9186 }); 9187 } 9188 9189 function cache(validator, option) { 9190 return function () { 9191 var cache = validator.cache;
9192 9193 if (!cache) { 9194 cache = []; 9195 validator.cache = cache; 9196 } 9197 9198 var args = Array.prototype.slice.call(arguments); 9199 var cachedResult = findInCache(cache, args); 9200 9201 if (!utils.isUndefined(cachedResult)) { 9202 return cachedResult; 9203 } 9204 9205 var result = validator.apply(this, args); 9206 9207 if (!utils.isUndefined(result)) { 9208 if (result.then) { 9209 return result.tab(function (promiseResult) { 9210 if (!utils.isUndefined(promiseResult)) { 9211 if (option !== 'all') { 9212 cache.splice(0, cache.length); 9213 } 9214 9215 cache.push({ 9216 args: args, 9217 result: promiseResult 9218 }); 9219 } 9220 }); 9221 } else { 9222 if (option !== 'all') { 9223 cache.splice(0, cache.length); 9224 } 9225 9226 cache.push({ 9227 args: args, 9228 result: result 9229 }); 9230 return result; 9231 } 9232 } 9233 }; 9234 } 9235 9236 function getPromise() { 9237 if (mixin.Promise) { 9238 return mixin.Promise; 9239 } 9240 9241 return es6Promise.Promise; 9242 } 9243 9244 function findInCache(cache, args) { 9245 var items = cache.filter(function (item) { 9246 return utils.isEqual(args, item.args); 9247 }); 9248 9249 if (!utils.isEmpty(items)) { 9250 return items[0].result; 9251 } 9252 } 9253 9254 var mixin_1 = mixin; 9255 9256 /* plugin install 9257 ----------------------------------- */ 9258 9259 9260 function install(Vue, options) { 9261 Vue.mixin(mixin_1); 9262 9263 if (options && options.templates) { 9264 extendTemplates(options.templates); 9265 } 9266 9267 if (options && options.mode) { 9268 setMode(options.mode); 9269 } 9270 9271 if (options && options.Promise) { 9272 mixin_1.Promise = options.Promise; 9273 } 9274 } 9275 9276 function extendTemplates(newTemplates) { 9277 Object.keys(newTemplates).forEach(function (key) { 9278 utils.templates[key] = newTemplates[key]; 9279 }); 9280 } 9281 9282 function setMode(mode) { 9283 if (mode !== 'interactive' && mode !== 'conservative' && mode !== 'manual') { 9284 throw new Error('Invalid mode: ' + mode); 9285 } 9286 9287 utils.mode = mode; 9288 } 9289 /* exports 9290 ----------------------------------- */ 9291 9292 9293 var name = 'SimpleVueValidator'; 9294 var ValidationBag_1 = validationBag; 9295 var Rule_1 = rule; 9296 var Validator_1 = validator; 9297 var mixin_1$1 = mixin_1; 9298 var install_1 = install; 9299 var extendTemplates_1 = extendTemplates; 9300 var setMode_1 = setMode; 9301 9302 var src = { 9303 name: name, 9304 ValidationBag: ValidationBag_1, 9305 Rule: Rule_1, 9306 Validator: Validator_1, 9307 mixin: mixin_1$1, 9308 install: install_1, 9309 extendTemplates: extendTemplates_1, 9310 setMode: setMode_1 9311 }; 9312 9313 var vueTheMask = createCommonjsModule(function (module, exports) { 9314 (function (e, t) { 9315 "object" == (babelHelpers.typeof(exports)) && "object" == (babelHelpers.typeof(module)) ? module.exports = t() : "object" == (babelHelpers.typeof(exports)) ? exports.VueTheMask = t() : e.VueTheMask = t(); 9316 })(commonjsGlobal, function () { 9317 return function (e) { 9318 function t(r) { 9319 if (n[r]) return n[r].exports; 9320 var a = n[r] = { 9321 i: r, 9322 l: !1, 9323 exports: {} 9324 }; 9325 return e[r].call(a.exports, a, a.exports, t), a.l = !0, a.exports; 9326 } 9327 9328 var n = {}; 9329 return t.m = e, t.c = n, t.i = function (e) { 9330 return e; 9331 }, t.d = function (e, n, r) { 9332 t.o(e, n) || Object.defineProperty(e, n, { 9333 configurable: !1, 9334 enumerable: !0, 9335 get: r 9336 }); 9337 }, t.n = function (e) { 9338 var n = e && e.__esModule ? function () { 9339 return e.default; 9340 } : function () { 9341 return e; 9342 }; 9343 return t.d(n, "a", n), n; 9344 }, t.o = function (e, t) { 9345 return Object.prototype.hasOwnProperty.call(e, t); 9346 }, t.p = ".", t(t.s = 10); 9347 }([function (e, t) { 9348 e.exports = { 9349 "#": { 9350 pattern: /\d/ 9351 }, 9352 X: { 9353 pattern: /[0-9a-zA-Z]/ 9354 }, 9355 S: { 9356 pattern: /[a-zA-Z]/ 9357 }, 9358 A: { 9359 pattern: /[a-zA-Z]/, 9360 transform: function transform(e) { 9361 return e.toLocaleUpperCase(); 9362 } 9363 }, 9364 a: { 9365 pattern: /[a-zA-Z]/, 9366 transform: function transform(e) { 9367 return e.toLocaleLowerCase(); 9368 } 9369 }, 9370 "!": { 9371 escape: !0 9372 } 9373 }; 9374 }, function (e, t, n) { 9375 9376 function r(e) { 9377 var t = document.createEvent("Event"); 9378 return t.initEvent(e, !0, !0), t;
9379 } 9380 9381 var a = n(2), 9382 o = n(0), 9383 i = n.n(o); 9384 9385 t.a = function (e, t) { 9386 var o = t.value; 9387 9388 if ((Array.isArray(o) || "string" == typeof o) && (o = { 9389 mask: o, 9390 tokens: i.a 9391 }), "INPUT" !== e.tagName.toLocaleUpperCase()) { 9392 var u = e.getElementsByTagName("input"); 9393 if (1 !== u.length) throw new Error("v-mask directive requires 1 input, found " + u.length); 9394 e = u[0]; 9395 } 9396 9397 e.oninput = function (t) { 9398 if (t.isTrusted) { 9399 var i = e.selectionEnd, 9400 u = e.value[i - 1]; 9401 9402 for (e.value = n.i(a.a)(e.value, o.mask, !0, o.tokens); i < e.value.length && e.value.charAt(i - 1) !== u;) { 9403 i++; 9404 } 9405 9406 e === document.activeElement && (e.setSelectionRange(i, i), setTimeout(function () { 9407 e.setSelectionRange(i, i); 9408 }, 0)), e.dispatchEvent(r("input")); 9409 } 9410 }; 9411 9412 var s = n.i(a.a)(e.value, o.mask, !0, o.tokens); 9413 s !== e.value && (e.value = s, e.dispatchEvent(r("input"))); 9414 }; 9415 }, function (e, t, n) { 9416 9417 var r = n(6), 9418 a = n(5); 9419 9420 t.a = function (e, t) { 9421 var o = !(arguments.length > 2 && void 0 !== arguments[2]) || arguments[2], 9422 i = arguments[3]; 9423 return Array.isArray(t) ? n.i(a.a)(r.a, t, i)(e, t, o, i) : n.i(r.a)(e, t, o, i); 9424 }; 9425 }, function (e, t, n) { 9426 9427 function r(e) { 9428 e.component(s.a.name, s.a), e.directive("mask", i.a); 9429 } 9430 9431 Object.defineProperty(t, "__esModule", { 9432 value: !0 9433 }); 9434 var a = n(0), 9435 o = n.n(a), 9436 i = n(1), 9437 u = n(7), 9438 s = n.n(u); 9439 n.d(t, "TheMask", function () { 9440 return s.a; 9441 }), n.d(t, "mask", function () { 9442 return i.a; 9443 }), n.d(t, "tokens", function () { 9444 return o.a; 9445 }), n.d(t, "version", function () { 9446 return c; 9447 }); 9448 var c = "0.11.1"; 9449 t.default = r, "undefined" != typeof window && window.Vue && window.Vue.use(r); 9450 }, function (e, t, n) { 9451 9452 Object.defineProperty(t, "__esModule", { 9453 value: !0 9454 }); 9455 var r = n(1), 9456 a = n(0), 9457 o = n.n(a), 9458 i = n(2); 9459 t.default = { 9460 name: "TheMask", 9461 props: { 9462 value: [String, Number], 9463 mask: { 9464 type: [String, Array], 9465 required: !0 9466 }, 9467 masked: { 9468 type: Boolean, 9469 default: !1 9470 }, 9471 tokens: { 9472 type: Object, 9473 default: function _default() { 9474 return o.a; 9475 } 9476 } 9477 }, 9478 directives: { 9479 mask: r.a 9480 }, 9481 data: function data() { 9482 return { 9483 lastValue: null, 9484 display: this.value 9485 }; 9486 }, 9487 watch: { 9488 value: function value(e) { 9489 e !== this.lastValue && (this.display = e); 9490 }, 9491 masked: function masked() { 9492 this.refresh(this.display); 9493 } 9494 }, 9495 computed: { 9496 config: function config() { 9497 return { 9498 mask: this.mask, 9499 tokens: this.tokens, 9500 masked: this.masked 9501 }; 9502 } 9503 }, 9504 methods: { 9505 onInput: function onInput(e) { 9506 e.isTrusted || this.refresh(e.target.value); 9507 }, 9508 refresh: function refresh(e) { 9509 this.display = e; 9510 var e = n.i(i.a)(e, this.mask, this.masked, this.tokens); 9511 e !== this.lastValue && (this.lastValue = e, this.$emit("input", e)); 9512 } 9513 } 9514 }; 9515 }, function (e, t, n) { 9516 9517 function r(e, t, n) { 9518 return t = t.sort(function (e, t) { 9519 return e.length - t.length; 9520 }), function (r, a) { 9521 for (var o = !(arguments.length > 2 && void 0 !== arguments[2]) || arguments[2], i = 0; i < t.length;) { 9522 var u = t[i]; 9523 i++; 9524 var s = t[i]; 9525 if (!(s && e(r, s, !0, n).length > u.length)) return e(r, u, o, n); 9526 } 9527 9528 return ""; 9529 }; 9530 } 9531 9532 t.a = r; 9533 }, function (e, t, n) { 9534 9535 function r(e, t) { 9536 var n = !(arguments.length > 2 && void 0 !== arguments[2]) || arguments[2], 9537 r = arguments[3]; 9538 e = e || "", t = t || ""; 9539 9540 for (var a = 0, o = 0, i = ""; a < t.length && o < e.length;) { 9541 var u = t[a], 9542 s = r[u], 9543 c = e[o]; 9544 s && !s.escape ? (s.pattern.test(c) && (i += s.transform ? s.transform(c) : c, a++), o++) : (s && s.escape && (a++, u = t[a]), n && (i += u), c === u && o++, a++); 9545 } 9546 9547 for (var f = ""; a < t.length && n;) { 9548 var u = t[a]; 9549 9550 if (r[u]) { 9551 f = ""; 9552 break; 9553 } 9554 9555 f += u, a++; 9556 } 9557 9558 return i + f; 9559 } 9560 9561 t.a = r; 9562 }, function (e, t, n) { 9563 var r = n(8)(n(4), n(9), null, null);
9564 e.exports = r.exports; 9565 }, function (e, t) { 9566 e.exports = function (e, t, n, r) { 9567 var a, 9568 o = e = e || {}, 9569 i = babelHelpers.typeof(e.default); 9570 "object" !== i && "function" !== i || (a = e, o = e.default); 9571 var u = "function" == typeof o ? o.options : o; 9572 9573 if (t && (u.render = t.render, u.staticRenderFns = t.staticRenderFns), n && (u._scopeId = n), r) { 9574 var s = u.computed || (u.computed = {}); 9575 Object.keys(r).forEach(function (e) { 9576 var t = r[e]; 9577 9578 s[e] = function () { 9579 return t; 9580 }; 9581 }); 9582 } 9583 9584 return { 9585 esModule: a, 9586 exports: o, 9587 options: u 9588 }; 9589 }; 9590 }, function (e, t) { 9591 e.exports = { 9592 render: function render() { 9593 var e = this, 9594 t = e.$createElement; 9595 return (e._self._c || t)("input", { 9596 directives: [{ 9597 name: "mask", 9598 rawName: "v-mask", 9599 value: e.config, 9600 expression: "config" 9601 }], 9602 attrs: { 9603 type: "text" 9604 }, 9605 domProps: { 9606 value: e.display 9607 }, 9608 on: { 9609 input: e.onInput 9610 } 9611 }); 9612 }, 9613 staticRenderFns: [] 9614 }; 9615 }, function (e, t, n) { 9616 e.exports = n(3); 9617 }]); 9618 }); 9619 }); 9620 9621 var VueTheMask = unwrapExports(vueTheMask); 9622 var vueTheMask_1 = vueTheMask.VueTheMask; 9623 9624 var Helper = /*#__PURE__*/function () { 9625 function Helper() { 9626 var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : { 9627 name: 'Helper' 9628 }; 9629 babelHelpers.classCallCheck(this, Helper); 9630 this.name = options.name; 9631 } 9632 9633 babelHelpers.createClass(Helper, [{ 9634 key: "setName", 9635 value: function setName(name$$1) { 9636 if (main_core.Type.isString(name$$1)) { 9637 this.name = name$$1; 9638 } 9639 } 9640 }, { 9641 key: "getName", 9642 value: function getName() { 9643 return this.name; 9644 } 9645 }, { 9646 key: "simpleVueValidator", 9647 value: function simpleVueValidator() { 9648 return src; 9649 } 9650 }, { 9651 key: "mask", 9652 value: function mask() { 9653 return VueTheMask; 9654 } 9655 }, { 9656 key: "axios", 9657 value: function axios() { 9658 return Axios; 9659 } 9660 }, { 9661 key: "promise", 9662 value: function promise() { 9663 return bluebird; 9664 } 9665 }]); 9666 return Helper; 9667 }(); 9668 9669 exports.Helper = Helper; 9670 9671}((this.BX.Asteq = this.BX.Asteq || {}),BX,BX)); 9672//# sourceMappingURL=Helper.bundle.js.map 9673 9674/* End */ 9675; 9676; /* Start:"a:4:{s:4:"full";s:86:"/local/templates/.default/components/itech/subscribe/.default/script.js?16093384932059";s:6:"source";s:71:"/local/templates/.default/components/itech/subscribe/.default/script.js";s:3:"min";s:0:"";s:3:"map";s:0:"";}"*/ 9677ItechSubcribe = function (options) { 9678 this.form = document.forms[options.form]; 9679 this.action = options.action; 9680 this.params = options.params; 9681 this.formGroup = options.formGroup; 9682 this.btn = document.querySelector('[data-entity="' + options.btn + '"]'); 9683 9684 BX.ready(BX.delegate(this.init, this)); 9685}; 9686 9687ItechSubcribe.prototype.init = function () { 9688 this.btn.addEventListener('click', function (e) { 9689 if (window.formGroups[this.formGroup].isValid) { 9690 BX.ready(BX.delegate(this.sendRequest, this)); 9691 } 9692 }.bind(this)); 9693}; 9694 9695ItechSubcribe.prototype.sendRequest = function () { 9696 var data = {}; 9697 this.btn.setAttribute("disabled", true); 9698 9699 for (var i = 0; i < this.form.elements.length; i++) { 9700 var element = this.form.elements[i]; 9701 var name = element.name.toString(); 9702 data[element.name.toString()] = element.value; 9703 } 9704 var url = this.action; 9705 9706 BX.ajax.post( 9707 url, 9708 data, 9709 function (data) { 9710 this.btn.removeAttribute("disabled"); 9711 data = JSON.parse(data); 9712 9713 var container = window.popups.formResult.container[0]; 9714 if (container != undefined) { 9715 9716 var title = container.querySelector('[data-entity="title"]'); 9717 if (title != undefined && data.title) { 9718 title.innerHTML = data.title; 9719 } 9720 9721 var body = container.querySelector('[data-entity="body"]'); 9722 if (body != undefined && data.msg) { 9723 body.innerHTML = '<p>' + data.msg + '</p>'; 9724 } 9725 9726 this.form.reset(); 9727 dataLayer.push({'event':'Podpiska', 'eventAction':'send'});
9728 ym(37064555,'reachGoal','subscribe'); 9729 window.popups.formResult.open(); 9730 9731 } 9732 9733 }.bind(this) 9734 ); 9735 9736}; 9737 9738ItechSubcribe.prototype.getEntity = function (name) { 9739 return this.form.querySelector("[data-entity='" + name + "']"); 9740}; 9741 9742 9743 9744/* End */ 9745; 9746; /* Start:"a:4:{s:4:"full";s:94:"/local/templates/.default/components/bitrix/system.auth.form/.default/script.js?15976823461522";s:6:"source";s:79:"/local/templates/.default/components/bitrix/system.auth.form/.default/script.js";s:3:"min";s:0:"";s:3:"map";s:0:"";}"*/ 9747BX.AuthFormComponent = { 9748 9749 init: function (options) { 9750 this.params = options.params; 9751 var form = document.forms[this.params.FORM_NAME]; 9752 this.submit = this.getEntity('submit-auth'); 9753 9754 this.submit.addEventListener('click', function (e) { 9755 if (window.formGroups.userEnter.isValid) { 9756 this.sendRequest(); 9757 } 9758 }.bind(this)); 9759 }, 9760 9761 sendRequest: function () { 9762 var form = document.forms[this.params.FORM_NAME]; 9763 var data = {}; 9764 var btn = this.submit; 9765 btn.setAttribute("disabled", true); 9766 for (var i = 0; i < form.elements.length; i++) { 9767 var element = form.elements[i]; 9768 var name = element.name.toString(); 9769 data[element.name.toString()] = element.value; 9770 } 9771 var url = this.params.ACTION_URL; 9772 9773 var errorNode = this.getEntity('error-block'); 9774 errorNode.innerHTML = ''; 9775 9776 BX.ajax.post( 9777 url, 9778 data, 9779 function (data) { 9780 btn.removeAttribute("disabled"); 9781 data = JSON.parse(data); 9782 if (data.status == true) { 9783 document.location.href = data.redirect; 9784 } else { 9785 errorNode.innerHTML = data.msg; 9786 } 9787 9788 }.bind(this) 9789 ); 9790 9791 }, 9792 9793 getEntity: function (name) { 9794 return document.querySelector("[data-entity='"+name+"']"); 9795 } 9796}; 9797 9798/* End */ 9799; 9800; /* Start:"a:4:{s:4:"full";s:93:"/local/templates/.default/components/bitrix/form.result.new/feedback/script.js?17643231072889";s:6:"source";s:78:"/local/templates/.default/components/bitrix/form.result.new/feedback/script.js";s:3:"min";s:0:"";s:3:"map";s:0:"";}"*/ 9801Feedback = { 9802 9803 init: function (options) { 9804 this.action = options.action; 9805 this.params = options.params; 9806 this.result = options.result; 9807 this.form = document.forms[this.result.arForm.VARNAME]; 9808 9809 this.submit = this.getEntity('submit-feedback'); 9810 9811 this.submit.addEventListener('click', function (e) { 9812 9813 if (window.formGroups.feedbackForm.isValid) { 9814 9815 /* grecaptcha.ready(() => { 9816 grecaptcha.execute('6LdElAAaAAAAAPzMM9eX7lR-9QH0Fhc-AzaAoKgw', {action: 'submit'}).then((token) => { 9817 BX.ajax.get( 9818 '/', 9819 { 9820 recaptcha_response: token, 9821 form_type: 'feedback', 9822 }, 9823 (data) => { 9824 var data = JSON.parse(data); 9825 if(data.result){ 9826 this.sendRequest(); 9827 } 9828 } 9829 ); 9830 }); 9831 }); */ 9832 9833 9834 this.sendRequest(); 9835 } 9836 }.bind(this)); 9837 }, 9838 9839 sendRequest: function () { 9840 9841 var data = {}; 9842 this.submit.setAttribute("disabled", true); 9843 9844 for (var i = 0; i < this.form.elements.length; i++) { 9845 var element = this.form.elements[i]; 9846 var name = element.name.toString(); 9847 data[element.name.toString()] = element.value; 9848 } 9849 var url = this.action; 9850 9851 BX.ajax.post( 9852 url, 9853 data, 9854 function (data) { 9855 this.submit.removeAttribute('disabled'); 9856 data = JSON.parse(data); 9857 9858 var container = window.popups.formResult.container[0]; 9859 if (container != undefined) { 9860 9861 var title = container.querySelector('[data-entity="title"]'); 9862 if (title != undefined) { 9863 title.innerHTML = data.title; 9864 } 9865 9866 var body = container.querySelector('[data-entity="body"]'); 9867 if (body != undefined) { 9868 body.innerHTML = '<p>
9868'+data.msg+'</p>'; 9869 } 9870 9871 this.form.reset(); 9872 dataLayer.push({'event':'Feedback', 'eventAction':'send'}); 9873 ym(37064555,'reachGoal','feedback'); 9874 window.popups.questionPopup.close(); 9875 window.popups.formResult.open(); 9876 } 9877 9878 }.bind(this) 9879 ); 9880 9881 }, 9882 9883 getEntity: function (name) { 9884 return this.form.querySelector("[data-entity='" + name + "']"); 9885 } 9886}; 9887/* End */ 9888; 9889; /* Start:"a:4:{s:4:"full";s:97:"/local/templates/.default/components/bitrix/form.result.new/request_call/script.js?16437932483281";s:6:"source";s:82:"/local/templates/.default/components/bitrix/form.result.new/request_call/script.js";s:3:"min";s:0:"";s:3:"map";s:0:"";}"*/ 9890RequestCall = { 9891 9892 init: function (options) { 9893 this.action = options.action; 9894 this.params = options.params; 9895 this.result = options.result; 9896 this.form = document.forms[this.result.arForm.VARNAME]; 9897 9898 this.submit = this.getEntity('submit-request'); 9899 9900 this.submit.addEventListener('click', function (e) { 9901 if (window.formGroups.callPopupForm.isValid){ 9902 /* grecaptcha.ready(() => { 9903 grecaptcha.execute('6LdElAAaAAAAAPzMM9eX7lR-9QH0Fhc-AzaAoKgw', {action: 'submit'}).then((token) => { 9904 9905 BX.ajax.get( 9906 '/', 9907 { 9908 recaptcha_response: token, 9909 form_type: 'request_call', 9910 }, 9911 (data) => { 9912 console.log(data) 9913 var data = JSON.parse(data); 9914 if(data.result){ 9915 this.sendRequest(); 9916 } 9917 } 9918 ); 9919 }); 9920 }); */ 9921 9922 this.sendRequest(); 9923 } 9924 }.bind(this)); 9925 }, 9926 9927 sendRequest: function () { 9928 9929 var data = {}; 9930 9931 this.submit.setAttribute("disabled", true); 9932 9933 for (var i = 0; i < this.form.elements.length; i++) { 9934 var element = this.form.elements[i]; 9935 var name = element.name.toString(); 9936 data[element.name.toString()] = element.value; 9937 } 9938 var url = this.action; 9939 9940 BX.ajax.post( 9941 url, 9942 data, 9943 function (data) { 9944 this.submit.removeAttribute('disabled'); 9945 data = JSON.parse(data); 9946 /*var resultNode = this.getEntity('result-block'); 9947 resultNode.innerText = data.msg; 9948 if(data.status){ 9949 resultNode.style.color = 'green'; 9950 } 9951 else{ 9952 resultNode.style.color = 'red'; 9953 } 9954 this.form.reset();*/ 9955 9956 var container = window.popups.formResult.container[0]; 9957 if (container != undefined) { 9958 9959 var title = container.querySelector('[data-entity="title"]'); 9960 if (title != undefined) { 9961 title.innerHTML = data.title; 9962 } 9963 9964 var body = container.querySelector('[data-entity="body"]'); 9965 if (body != undefined) { 9966 body.innerHTML = '<p>'+data.msg+'</p>'; 9967 } 9968 9969 this.form.reset(); 9970 dataLayer.push({'event':'Zakazat_zvonok', 'eventAction':'send'}); 9971 ym(37064555,'reachGoal','order-a-call'); 9972 window.popups.callPopup.close(); 9973 window.popups.formResult.open(); 9974 } 9975 9976 }.bind(this) 9977 ); 9978 9979 }, 9980 9981 getEntity: function (name) { 9982 return document.querySelector("[data-entity='" + name + "']"); 9983 } 9984}; 9985 9986 9987 9988/* End */ 9989; 9990; /* Start:"a:4:{s:4:"full";s:95:"/local/templates/.default/components/bitrix/form.result.new/ask_doctor/script.js?16539872122448";s:6:"source";s:80:"/local/templates/.default/components/bitrix/form.result.new/ask_doctor/script.js";s:3:"min";s:0:"";s:3:"map";s:0:"";}"*/ 9991QuestionForm = { 9992 9993 init: function (options) { 9994 this.action = options.action; 9995 this.params = options.params; 9996 this.result = options.result; 9997 this.form = document.forms[this.result.arForm.VARNAME]; 9998 9999 this.submit = this.getEntity('submit-ask'); 10000 10001 this.submit.addEventListener('click', function (e) { 10002 if (window.formGroups.questionsPopupForm.isValid) { 10003 grecaptcha.ready(function () { 10004 grecaptcha.execute(window.recaptchaKey, {action: 'submit'}).then(function (token) { 10005 this.sendRequest(token); 10006 }.bind(this)); 10007 }.bind(this)); 10008 10009 } 10010 }.bind(this)); 10011 }, 10012 10013 sendRequest: function (token) { 10014 var data = {}; 10015 this.submit.setAttribute("disabled", true); 10016 10017 for (var i = 0; i < this.form.elements.length; i++) { 10018 var element = this.form.elements[i]; 10019 var name = element.name.toString(); 10020 data[element.name.toString()] = element.value; 10021 } 10022 var url = this.action; 10023 10024 if (token) { 10025 data["g-recaptcha-response"] = token; 10026 } 10027 10028 BX.ajax.post( 10029 url, 10030 data, 10031 function (data) { 10032 this.submit.removeAttribute('disabled'); 10033 data = JSON.parse(data); 10034 10035 var container = window.popups.formResult.container[0]; 10036 if (container != undefined) { 10037 10038 var title = container.querySelector('[data-entity="title"]'); 10039 if (title != undefined) { 10040 title.innerHTML = data.title; 10041 } 10042 10043 var body = container.querySelector('[data-entity="body"]'); 10044 if (body != undefined) { 10045 body.innerHTML = '<p>' + data.msg + '</p>'; 10046 } 10047 10048 dataLayer.push({'event': 'Ask_question', 'eventAction': 'send'}); 10049 ym(37064555, 'reachGoal', 'question'); 10050 10051 this.form.reset(); 10052 window.popups.questionPopup.close(); 10053 window.popups.formResult.open(); 10054 } 10055 10056 }.bind(this) 10057 ); 10058 10059 }, 10060 10061 getEntity: function (name) { 10062 return this.form.querySelector("[data-entity='" + name + "']"); 10063 } 10064}; 10065 10066 10067 10068/* End */ 10069; 10070; /* Start:"a:4:{s:4:"full";s:107:"/local/templates/.default/components/bitrix/sale.location.selector.search/regions/script.
10070js?159768234611497";s:6:"source";s:91:"/local/templates/.default/components/bitrix/sale.location.selector.search/regions/script.js";s:3:"min";s:0:"";s:3:"map";s:0:"";}"*/ 10071BX.namespace('BX.Sale.component.location.selector'); 10072 10073if(typeof BX.Sale.component.location.selector.search == 'undefined' && typeof BX.ui != 'undefined' && typeof BX.ui.widget != 'undefined'){ 10074 10075 BX.Sale.component.location.selector.search = function(opts, nf){ 10076 10077 this.parentConstruct(BX.Sale.component.location.selector.search, opts); 10078 10079 BX.merge(this, { 10080 opts: { 10081 10082 usePagingOnScroll: true, 10083 pageSize: 10, 10084 //scrollThrottleTimeout: 100, 10085 arrowScrollAdditional: 2, 10086 pageUpWardOffset: 3, 10087 provideLinkBy: 'id', 10088 10089 bindEvents: { 10090 10091 'after-input-value-modify': function(){ 10092 10093 this.ctrls.fullRoute.value = ''; 10094 10095 }, 10096 'after-select-item': function(itemId){ 10097 10098 var so = this.opts; 10099 var cItem = this.vars.cache.nodes[itemId]; 10100 10101 var path = cItem.DISPLAY; 10102 if(typeof cItem.PATH == 'object'){ 10103 for(var i = 0; i < cItem.PATH.length; i++){ 10104 path += ', '+this.vars.cache.path[cItem.PATH[i]]; // deprecated 10105 } 10106 } 10107 10108 this.ctrls.inputs.fake.setAttribute('title', path); 10109 this.ctrls.fullRoute.value = path; 10110 10111 if(typeof this.opts.callback == 'string' && this.opts.callback.length > 0 && this.opts.callback in window) 10112 window[this.opts.callback].apply(this, [itemId, this]); 10113 }, 10114 'after-deselect-item': function(){ 10115 this.ctrls.fullRoute.value = ''; 10116 this.ctrls.inputs.fake.setAttribute('title', ''); 10117 }, 10118 'before-render-variant': function(itemData){ 10119 10120 if(itemData.PATH.length > 0){ 10121 var path = ''; 10122 for(var i = 0; i < itemData.PATH.length; i++) 10123 path += ', '+this.vars.cache.path[itemData.PATH[i]]; 10124 10125 itemData.PATH = path; 10126 }else 10127 itemData.PATH = ''; 10128 10129 var query = ''; 10130 10131 if(this.vars && this.vars.lastQuery && this.vars.lastQuery.QUERY) 10132 query = this.vars.lastQuery.QUERY; 10133 10134 if(BX.type.isNotEmptyString(query)){ 10135 var chunks = []; 10136 if(this.opts.wrapSeparate) 10137 chunks = query.split(/\s+/); 10138 else 10139 chunks = [query]; 10140 10141 itemData['=display_wrapped'] = BX.util.wrapSubstring(itemData.DISPLAY+itemData.PATH, chunks, this.opts.wrapTagName, true); 10142 }else 10143 itemData['=display_wrapped'] = BX.util.htmlspecialchars(itemData.DISPLAY); 10144 } 10145 } 10146 }, 10147 vars: { 10148 cache: { 10149 path: {}, 10150 nodesByCode: {} 10151 } 10152 }, 10153 sys: { 10154 code: 'sls' 10155 } 10156 }); 10157 10158 this.handleInitStack(nf, BX.Sale.component.location.selector.search, opts); 10159 } 10160 BX.extend(BX.Sale.component.location.selector.search, BX.ui.autoComplete); 10161 BX.merge(BX.Sale.component.location.selector.search.prototype, { 10162 10163 // member of stack of initializers, must be defined even if do nothing 10164 init: function(){ 10165 10166 // deprecated begin 10167 if(typeof this.opts.pathNames == 'object') 10168 BX.merge(this.vars.cache.path, this.opts.pathNames); 10169 // deprecated end 10170 10171 this.pushFuncStack('buildUpDOM', BX.Sale.component.location.selector.search); 10172 this.pushFuncStack('bindEvents', BX.Sale.component.location.selector.search); 10173 }, 10174 10175 buildUpDOM: function(){ 10176 10177 var sc = this.ctrls, 10178 so = this.opts, 10179 sv = this.vars, 10180 ctx = this, 10181 code = this.sys.code; 10182 10183 // full route node 10184 sc.fullRoute = BX.create('input', { 10185 props: { 10186 className: 'bx-ui-'+code+'-route input-text' 10187 }, 10188 attrs: { 10189 type: 'text', 10190 disabled: 'disabled', 10191 autocomplete: 'off' 10192 } 10193 }); 10194 10195 // todo: use metrics instead! 10196 BX.style(sc.fullRoute, 'paddingTop', BX.style(sc.inputs.fake, 'paddingTop')); 10197 BX.style(sc.fullRoute, 'paddingLeft', BX.style(sc.inputs.fake, 'paddingLeft')); 10198 BX.style(sc.fullRoute, 'paddingRight', '0px'); 10199 BX.style(sc.fullRoute, 'paddingBottom', '0px'); 10200 10201 BX.style(sc.fullRoute, 'marginTop', BX.style(sc.inputs.fake, 'marginTop')); 10202 BX.style(sc.fullRoute, 'marginLeft', BX.style(sc.inputs.fake, 'marginLeft')); 10203 BX.style(sc.fullRoute, 'marginRight', '0px'); 10204 BX.style(sc.fullRoute, 'marginBottom', '0px'); 10205 10206 if(BX.style(sc.inputs.fake, 'borderTopStyle') != 'none'){ 10207 BX.style(sc.fullRoute, 'borderTopStyle', 'solid'); 10208 BX.style(sc.fullRoute, 'borderTopColor', 'transparent'); 10209 BX.style(sc.fullRoute, 'borderTopWidth', BX.style(sc.inputs.fake, 'borderTopWidth')); 10210 } 10211 10212 if(BX.style(sc.inputs.fake, 'borderLeftStyle') != 'none'){ 10213 BX.style(sc.fullRoute, 'borderLeftStyle', 'solid'); 10214 BX.style(sc.fullRoute, 'borderLeftColor', 'transparent'); 10215 BX.style(sc.fullRoute, 'borderLeftWidth', BX.style(sc.inputs.fake, 'borderLeftWidth')); 10216 } 10217 10218 BX.prepend(sc.fullRoute, sc.container); 10219 10220 //sc.inputBlock = this.getControl('input-block'); 10221 //sc.loader = this.getControl('loader'); 10222 }, 10223 10224 bindEvents: function(){ 10225 10226 var ctx = this; 10227 10228 // quick links 10229 BX.bindDelegate(this.getControl('quick-locations', true), 'click', {tag: 'a'}, function(){ 10230 ctx.setValueByLocationId(BX.data(this, 'id')); 10231 }); 10232 10233 this.vars.outSideClickScope = this.ctrls.inputBlock; 10234 }, 10235 10236 ////////// PUBLIC: free to use outside 10237 10238 // location id is just a value in terms of autocomplete 10239 setValueByLocationId: function(id, autoSelect){ 10240 BX.Sale.component.location.selector.search.superclass.setValue.apply(this, [id, autoSelect]); 10241 }, 10242 10243 setValueByLocationIds: function(locationsData){ 10244 if(locationsData.IDS) 10245 { 10246 this.displayPage( 10247 { 10248 'VALUE': locationsData.IDS, 10249 'order': {'TYPE_ID': 'ASC', 'NAME.NAME': 'ASC'} 10250 } 10251 ); 10252 } 10253 }, 10254 10255 setValueByLocationCode: function(code, autoSelect){ 10256 10257 var sv = this.vars, 10258 so = this.opts, 10259 sc = this.ctrls, 10260 ctx = this; 10261 10262 this.hideError(); 10263 10264 if(code == null || code == false || typeof code == 'undefined' || code.toString().length == 0){ // deselect 10265 10266 this.resetVariables(); 10267 10268 BX.cleanNode(sc.vars); 10269 10270 if(BX.type.isElementNode(sc.nothingFound)) 10271 BX.hide(sc.nothingFound); 10272 10273 this.fireEvent('after-deselect-item'); 10274 this.fireEvent('after-clear-selection'); 10275 10276 return; 10277 }; 10278 10279 if(autoSelect !== false) 10280 sv.forceSelectSingeOnce = true; 10281 10282 if(typeof sv.cache.nodesByCode[code] == 'undefined'){ 10283 10284 // lazyload it... 10285 this.resetNavVariables(); 10286 10287 ctx.downloadBundle({CODE: code}, function(data){ 10288 10289 ctx.fillCache(data, false); // storing item in the cache 10290 10291 if(typeof sv.cache.nodesByCode[code] == 'undefined'){ // still not found 10292 ctx.showNothingFound(); 10293 }else{ 10294 10295 var value = sv.cache.nodesByCode[code].VALUE; 10296
10297 ////////////////// 10298 if(so.autoSelectIfOneVariant || sv.forceSelectSingeOnce) 10299 ctx.selectItem(value); 10300 else 10301 ctx.displayVariants([value]); 10302 ////////////////// 10303 } 10304 }, function(){ 10305 sv.forceSelectSingeOnce = false; 10306 }); 10307 10308 }else{ 10309 10310 var value = sv.cache.nodesByCode[code].VALUE; 10311 10312 if(sv.forceSelectSingeOnce) 10313 this.selectItem(value); 10314 else 10315 this.displayVariants([value]); 10316 10317 sv.forceSelectSingeOnce = false; 10318 } 10319 }, 10320 10321 getNodeByValue: function(value){ 10322 if(this.opts.provideLinkBy == 'id') 10323 return this.vars.cache.nodes[value]; 10324 else 10325 return this.vars.cache.nodesByCode[value]; 10326 }, 10327 10328 getNodeByLocationId: function(value){ 10329 return this.vars.cache.nodes[value]; 10330 }, 10331 10332 setValue: function(value){ 10333 10334 if(this.opts.provideLinkBy == 'id') 10335 BX.Sale.component.location.selector.search.superclass.setValue.apply(this, [value]); 10336 else 10337 this.setValueByLocationCode(value); 10338 }, 10339 10340 getValue: function(){ 10341 if(this.opts.provideLinkBy == 'id') 10342 return this.vars.value === false ? '' : this.vars.value; 10343 else{ 10344 return this.vars.value ? this.vars.cache.nodes[this.vars.value].CODE : ''; 10345 } 10346 }, 10347 10348 getSelectedPath: function(){ 10349 10350 var sv = this.vars, 10351 result = []; 10352 10353 if(typeof sv.value == 'undefined' || sv.value == false || sv.value == '') 10354 return result; 10355 10356 if(typeof sv.cache.nodes[sv.value] != 'undefined'){ 10357 var item = BX.clone(sv.cache.nodes[sv.value]); 10358 if(typeof item.TYPE_ID != 'undefined' && typeof this.opts.types != 'undefined') 10359 item.TYPE = this.opts.types[item.TYPE_ID].CODE; 10360 10361 var path = item.PATH; 10362 delete(item.PATH); 10363 result.push(item); 10364 10365 if(typeof path != 'undefined'){ 10366 for(var k in path){ 10367 var item = BX.clone(sv.cache.nodes[path[k]]); 10368 if(typeof item.TYPE_ID != 'undefined' && typeof this.opts.types != 'undefined') 10369 item.TYPE = this.opts.types[item.TYPE_ID].CODE; 10370 10371 delete(item.PATH); 10372 10373 result.push(item); 10374 } 10375 } 10376 } 10377 10378 return result; 10379 }, 10380 10381 ////////// PRIVATE: forbidden to use outside (for compatibility reasons) 10382 10383 setInitialValue: function(){ 10384 10385 if(this.opts.selectedItem !== false) // there will be always a value as ID, no matter what this.opts.provideLinkBy is equal to 10386 this.setValueByLocationId(this.opts.selectedItem); 10387 else if(this.ctrls.inputs.origin.value.length > 0) // there colud be eiter ID or CODE 10388 { 10389 if(this.opts.provideLinkBy == 'id') 10390 this.setValueByLocationId(this.ctrls.inputs.origin.value); 10391 else 10392 this.setValueByLocationCode(this.ctrls.inputs.origin.value); 10393 } 10394 }, 10395 10396 addItem2Cache: function(item){ 10397 this.vars.cache.nodes[item.VALUE] = item; 10398 this.vars.cache.nodesByCode[item.CODE] = item; 10399 }, 10400 10401 refineRequest: function(request){ 10402 10403 var filter = {}; 10404 if(typeof request['QUERY'] != 'undefined') // search by words 10405 filter['=PHRASE'] = request.QUERY; 10406 10407 if(typeof request['VALUE'] != 'undefined') // search by id 10408 filter['=ID'] = request.VALUE; 10409 10410 if(typeof request['CODE'] != 'undefined') // search by code 10411 filter['=CODE'] = request.CODE; 10412 10413 if(typeof this.opts.query.BEHAVIOUR.LANGUAGE_ID != 'undefined') 10414 filter['=NAME.LANGUAGE_ID'] = this.opts.query.BEHAVIOUR.LANGUAGE_ID; 10415 10416 if(BX.type.isNotEmptyString(this.opts.query.FILTER.SITE_ID)) 10417 filter['=SITE_ID'] = this.opts.query.FILTER.SITE_ID; 10418 10419 var result = { 10420 'select': { 10421 'VALUE': 'ID', 10422 'DISPLAY': 'NAME.NAME', 10423 '1': 'CODE', 10424 '2': 'TYPE_ID' 10425 }, 10426 'additionals': { 10427 '1': 'PATH' 10428 }, 10429 'filter': filter, 10430 'version': '2' 10431 }; 10432 10433 if(typeof request['order'] != 'undefined') 10434 result['order'] = request.order; 10435 10436 return result; 10437 }, 10438 10439 refineResponce: function(responce, request){ 10440 10441 if(typeof responce.ETC.PATH_ITEMS != 'undefined') 10442 { 10443 // deprecated begin 10444 for(var k in responce.ETC.PATH_ITEMS){ 10445 if(BX.type.isNotEmptyString(responce.ETC.PATH_ITEMS[k].DISPLAY)) 10446 this.vars.cache.path[k] = responce.ETC.PATH_ITEMS[k].DISPLAY; 10447 } 10448 // deprecated end 10449 10450 for(var k in responce.ITEMS){ 10451 10452 var item = responce.ITEMS[k]; 10453 10454 if(typeof item.PATH != 'undefined') 10455 { 10456 var subPath = BX.clone(item.PATH); 10457 for(var p in item.PATH) 10458 { 10459 var pItemId = item.PATH[p]; 10460 10461 subPath.shift(); 10462 if(typeof this.vars.cache.nodes[pItemId] == 'undefined' && typeof responce.ETC.PATH_ITEMS[pItemId] != 'undefined'){ 10463 10464 var pItem = BX.clone(responce.ETC.PATH_ITEMS[pItemId]); 10465 pItem.PATH = BX.clone(subPath); 10466 this.vars.cache.nodes[pItemId] = pItem; 10467 } 10468 } 10469 } 10470 } 10471 } 10472 10473 return responce.ITEMS; 10474 }, 10475 10476 refineItems: function(items){ 10477 return items; 10478 }, 10479 10480 refineItemDataForTemplate: function(itemData){ 10481 return itemData; 10482 }, 10483 10484 // custom value getter (obsolete method) 10485 getSelectorValue: function(value){ 10486 10487 if(this.opts.provideLinkBy == 'id') 10488 return value; 10489 10490 if(typeof this.vars.cache.nodes[value] != 'undefined') 10491 return this.vars.cache.nodes[value].CODE; 10492 else 10493 return ''; 10494 }, 10495 10496 // whenLoaderToggle: function(way){ 10497 // BX[way ? 'show' : 'hide'](this.ctrls.loader); 10498 // } 10499 10500 }); 10501} 10502 10503/* End */ 10504; 10505; /* Start:"a:4:{s:4:"full";s:88:"/local/templates/.default/components/itech/changepass/.default/script.js?159768234610587";s:6:"source";s:72:"/local/templates/.default/components/itech/changepass/.default/script.js";s:3:"min";s:0:"";s:3:"map";s:0:"";}"*/ 10506ChangePass = function (params) { 10507 10508 var asteq = new BX.Asteq.Helper(); 10509 var simpleVueValidator = asteq.simpleVueValidator(); 10510 var mask = asteq.mask(); 10511 BX.Vue.use(simpleVueValidator); 10512 BX.Vue.use(mask); 10513 10514 BX.Vue.component('changePass', { 10515 data: function () { 10516 return { 10517 step: 1, 10518 phone: '', 10519 code: '', 10520 password: '', 10521 cpassword: '', 10522 errorMsg: '', 10523 msg: '', 10524 time: null, 10525 disResend: false, 10526 newCodeTime: null, 10527 timer: null, 10528 timer2: null, 10529 disSend: false, 10530 fBtnSendCode:false, 10531 testTime: 10 10532 } 10533 }, 10534 mixins: [simpleVueValidator.mixin], 10535 validators: { 10536 'phone' : function (value) { 10537 return simpleVueValidator.Validator.value(value).required('Ðоле обÑзаÑелÑно Ð´Ð»Ñ Ð·Ð°Ð¿Ð¾Ð»Ð½ÐµÐ½Ð¸Ñ').custom(function () { 10538 if (!simpleVueValidator.Validator.isEmpty(value) && /\+7\s\(\d{3}\)\s\d{3}\s-\s\d{2}\s-\s\d{2}/.test(value)) { 10539 var data = {}; 10540 data['action'] = 'check'; 10541 data['phone'] = this.phone; 10542 10543 return this.sendCheck(data) 10544 .then(function (result) { 10545 var result = JSON.parse(result.target.response); 10546 if (!result.status) { 10547 return 'ÐолÑзоваÑÐµÐ»Ñ Ñ Ñаким номеÑом не найден'; 10548 } 10549 }); 10550 } 10551 }.bind(this)); 10552 } 10553 }, 10554 props: [ 10555 'action', 10556 ], 10557 methods: { 10558 getCode: function () { 10559 this.$validate() 10560 .then(function (success) { 10561 if (success) { 10562 10563 var data = {}; 10564 data['phone'] = this.phone; 10565 data['action'] = 'get'; 10566 10567 this.sendRequest(data); 10568 } 10569 }.bind(this)); 10570 }, 10571 sendCode: function () { 10572 10573 this.fBtnSendCode = true; 10574 10575 this.$validate().then(function (success) { 10576 if (success) { 10577 10578 this.errorMsg = ''; 10579 this.msg = ''; 10580 } 10581 10582 this.fBtnSendCode = false; 10583 }.bind(this)); 10584 }, 10585 sendCodeCheck: function (data) { 10586 return new Promise(function (resolve, reject) { 10587 10588 this.sendRequest(data).onload = function (data) { 10589 resolve(data); 10590 }; 10591 }.bind(this)); 10592 }, 10593 newPassword: function () { 10594 this.$validate().then(function (success) { 10595 if (success) { 10596 var data = {}; 10597 data['phone'] = this.phone;
10598 data['code'] = this.code; 10599 data['action'] = 'reset'; 10600 data['password'] = this.password; 10601 data['cpassword'] = this.cpassword; 10602 10603 this.sendRequest(data); 10604 } 10605 }.bind(this)); 10606 }, 10607 resendCode: function () { 10608 10609 this.errorMsg = ''; 10610 this.msg = ''; 10611 this.step = 1; 10612 }, 10613 sendCheck: function (data) { 10614 return new Promise(function (resolve, reject) { 10615 this.sendRequest(data).onload = function (data) { 10616 resolve(data); 10617 }; 10618 }.bind(this)); 10619 }, 10620 sendRequest: function (data) { 10621 var result = BX.ajax.post( 10622 this.action, 10623 data, 10624 function (data) { 10625 var data = JSON.parse(data); 10626 10627 if (data.step) { 10628 this.step = data.step; 10629 } 10630 10631 if (data.msg) { 10632 this.msg = data.msg; 10633 } 10634 10635 if (data.time) { 10636 this.time = data.time; 10637 10638 this.startTimer(); 10639 } 10640 10641 if (data.link) { 10642 document.location.href = data.link; 10643 } 10644 10645 if (data.errors) { 10646 this.errorMsg = data.errors; 10647 } 10648 10649 if (data.new_code_time) { 10650 10651 this.startTimer(); 10652 this.time = data.new_code_time; 10653 10654 this.disSend = true; 10655 } 10656 return 1; 10657 }.bind(this) 10658 ); 10659 10660 return result; 10661 }, 10662 startTimer: function(){ 10663 10664 if(this.timer) 10665 clearInterval(this.timer); 10666 10667 if(this.time>0){ 10668 10669 this.disSend = true; 10670 10671 this.disResend = true; 10672 } 10673 10674 this.timer = setInterval(function(){ 10675 10676 this.time--; 10677 10678 if(this.time<=0){ 10679 10680 clearInterval(this.timer); 10681 10682 this.disSend = false; 10683 10684 this.disResend = false; 10685 } 10686 10687 10688 }.bind(this),1000); 10689 } 10690 }, 10691 watch: { 10692 step: function (value) { 10693 10694 var validators = {}; 10695 10696 if (value === 1) { 10697 validators['phone'] = function (value) { 10698 return simpleVueValidator.Validator.value(value).required('Ðоле обÑзаÑелÑно Ð´Ð»Ñ Ð·Ð°Ð¿Ð¾Ð»Ð½ÐµÐ½Ð¸Ñ').custom(function () { 10699 if (!simpleVueValidator.Validator.isEmpty(value) && /\+7\s\(\d{3}\)\s\d{3}\s-\s\d{2}\s-\s\d{2}/.test(value)) { 10700 var data = {}; 10701 data['action'] = 'check'; 10702 data['phone'] = this.phone; 10703 10704 return this.sendCheck(data) 10705 .then(function (result) { 10706 var result = JSON.parse(result.target.response); 10707 if (!result.status) { 10708 return 'ÐолÑзоваÑÐµÐ»Ñ Ñ Ñаким номеÑом не найден'; 10709 } 10710 }); 10711 } 10712 }.bind(this)); 10713 }; 10714 } 10715 10716 if (value === 2) { 10717 validators['code'] = function (value) { 10718 10719 value = value.replace('_',''); 10720 10721 return simpleVueValidator.Validator.value(value).required('Ðоле обÑзаÑелÑно Ð´Ð»Ñ Ð·Ð°Ð¿Ð¾Ð»Ð½ÐµÐ½Ð¸Ñ').custom(function () { 10722 if (!simpleVueValidator.Validator.isEmpty(value) && value.length==4 && this.fBtnSendCode){ 10723 10724 var data = {}; 10725 data['phone'] = this.phone;
10726 data['code'] = this.code; 10727 data['action'] = 'code'; 10728 10729 return this.sendCodeCheck(data) 10730 .then(function (result) { 10731 var result = JSON.parse(result.target.response); 10732 10733 if(result.errors){ 10734 10735 return result.errors; 10736 } 10737 }); 10738 } 10739 }.bind(this)); 10740 }; 10741 } 10742 10743 if (value === 3) { 10744 10745 validators['password'] = function (value) { 10746 10747 return simpleVueValidator.Validator.value(value). 10748 minLength(6,'ÐаÑÐ¾Ð»Ñ Ð´Ð¾Ð»Ð¶ÐµÐ½ ÑодеÑжаÑÑ Ð°Ð½Ð³Ð»Ð¸Ð¹Ñкие бÑÐºÐ²Ñ Ð²ÐµÑÑ Ð½ÐµÐ³Ð¾ и нижнего ÑегиÑÑÑа (a-z, A-Z). ЦиÑÑÑ Ð¾Ñ 0 до 9. ÐаÑÐ¾Ð»Ñ Ð´Ð¾Ð»Ð¶ÐµÐ½ бÑÑÑ Ð´Ð»Ð¸Ð½Ð½ÐµÐµ 6 Ñимволов и до 16'). 10749 required('Ðоле обÑзаÑелÑно Ð´Ð»Ñ Ð·Ð°Ð¿Ð¾Ð»Ð½ÐµÐ½Ð¸Ñ').regex('^([a-z][A-Z][0-9]*)|([a-z][0-9]*[A-Z])|([A-Z][a-z][0-9]*)|([A-Z][0-9]*[a-z])|([0-9]*[a-z][A-Z])|([0-9]*[A-Z][a-z])$', 'ÐаÑÐ¾Ð»Ñ Ð´Ð¾Ð»Ð¶ÐµÐ½ ÑодеÑжаÑÑ Ð°Ð½Ð³Ð»Ð¸Ð¹Ñкие бÑÐºÐ²Ñ Ð²ÐµÑÑ Ð½ÐµÐ³Ð¾ и нижнего ÑегиÑÑÑа (a-z, A-Z). ЦиÑÑÑ Ð¾Ñ 0 до 9. ÐаÑÐ¾Ð»Ñ Ð´Ð¾Ð»Ð¶ÐµÐ½ бÑÑÑ Ð´Ð»Ð¸Ð½Ð½ÐµÐµ 6 Ñимволов и до 16'); 10750 } 10751 validators['cpassword, password'] = function (cpassword, password) { 10752 10753 return simpleVueValidator.Validator.value(cpassword).required('Ðоле обÑзаÑелÑно Ð´Ð»Ñ Ð·Ð°Ð¿Ð¾Ð»Ð½ÐµÐ½Ð¸Ñ').match(password, 'ÐаÑоли не ÑовпадаÑÑ') 10754 }; 10755 } 10756 10757 this.$setValidators(validators); 10758 } 10759 }, 10760 computed:{ 10761 showTime: function(){ 10762 10763 var minute = Math.floor(this.time/60); 10764 10765 var second = this.time%60 10766 10767 return (minute>9?minute:'0'+minute)+':'+(second>9?second:'0'+second); 10768 } 10769 }, 10770 mounted: function () { 10771 window.customInputMaskInit(); 10772 }, 10773 template: '#tpl-remind' 10774 }); 10775 10776 10777 return BX.Vue.create({ 10778 el: '#change-form', 10779 render: function (createElement) { 10780 return createElement( 10781 'changePass', { 10782 props: params, 10783 } 10784 ) 10785 }, 10786 }); 10787 10788}; 10789 10790/* End */ 10791; 10792; /* Start:"a:4:{s:4:"full";s:68:"/local/js/asteq/addpatient/dist/addpatient.bundle.js?161158313571294";s:6:"source";s:52:"/local/js/asteq/addpatient/dist/addpatient.bundle.js";s:3:"min";s:0:"";s:3:"map";s:0:"";}"*/ 10793this.BX = this.BX || {}; 10794(function (exports,ui_vue) { 10795 'use strict'; 10796 10797 var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; 10798 function commonjsRequire() { 10799 throw new Error('Dynamic requires are not currently supported by rollup-plugin-commonjs'); 10800 } 10801 function createCommonjsModule(fn, module) { 10802 return module = { 10803 exports: {} 10804 }, fn(module, module.exports), module.exports; 10805 } 10806 10807 var es6Promise = createCommonjsModule(function (module, exports) { 10808 /*! 10809 * @overview es6-promise - a tiny implementation of Promises/A+. 10810 * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald) 10811 * @license Licensed under MIT license 10812 * See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE 10813 * @version 4.0.5 10814 */ 10815 (function (global, factory) { 10816 (babelHelpers.typeof(exports)) === 'object' && 'object' !== 'undefined' ? module.exports = factory() : global.ES6Promise = factory(); 10817 })(commonjsGlobal, function () { 10818 10819 function objectOrFunction(x) { 10820 return typeof x === 'function' || babelHelpers.typeof(x) === 'object' && x !== null; 10821 } 10822 10823 function isFunction(x) { 10824 return typeof x === 'function'; 10825 } 10826 10827 var _isArray = undefined; 10828 10829 if (!Array.isArray) { 10830 _isArray = function _isArray(x) { 10831 return Object.prototype.toString.call(x) === '[object Array]'; 10832 }; 10833 } else { 10834 _isArray = Array.isArray; 10835 } 10836 10837 var isArray = _isArray; 10838 var len = 0; 10839 var vertxNext = undefined; 10840 var customSchedulerFn = undefined; 10841 10842 var asap = function asap(callback, arg) { 10843 queue[len] = callback; 10844 queue[len + 1] = arg;
10845 len += 2; 10846 10847 if (len === 2) { 10848 // If len is 2, that means that we need to schedule an async flush. 10849 // If additional callbacks are queued before the queue is flushed, they 10850 // will be processed by this flush that we are scheduling. 10851 if (customSchedulerFn) { 10852 customSchedulerFn(flush); 10853 } else { 10854 scheduleFlush(); 10855 } 10856 } 10857 }; 10858 10859 function setScheduler(scheduleFn) { 10860 customSchedulerFn = scheduleFn; 10861 } 10862 10863 function setAsap(asapFn) { 10864 asap = asapFn; 10865 } 10866 10867 var browserWindow = typeof window !== 'undefined' ? window : undefined; 10868 var browserGlobal = browserWindow || {}; 10869 var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver; 10870 var isNode = typeof self === 'undefined' && typeof process !== 'undefined' && {}.toString.call(process) === '[object process]'; // test for web worker but not in IE10 10871 10872 var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined'; // node 10873 10874 function useNextTick() { 10875 // node version 0.10.x displays a deprecation warning when nextTick is used recursively 10876 // see https://github.com/cujojs/when/issues/410 for details 10877 return function () { 10878 return process.nextTick(flush); 10879 }; 10880 } // vertx 10881 10882 10883 function useVertxTimer() { 10884 if (typeof vertxNext !== 'undefined') { 10885 return function () { 10886 vertxNext(flush); 10887 }; 10888 } 10889 10890 return useSetTimeout(); 10891 } 10892 10893 function useMutationObserver() { 10894 var iterations = 0; 10895 var observer = new BrowserMutationObserver(flush); 10896 var node = document.createTextNode(''); 10897 observer.observe(node, { 10898 characterData: true 10899 }); 10900 return function () { 10901 node.data = iterations = ++iterations % 2; 10902 }; 10903 } // web worker 10904 10905 10906 function useMessageChannel() { 10907 var channel = new MessageChannel(); 10908 channel.port1.onmessage = flush; 10909 return function () { 10910 return channel.port2.postMessage(0); 10911 }; 10912 } 10913 10914 function useSetTimeout() { 10915 // Store setTimeout reference so es6-promise will be unaffected by 10916 // other code modifying setTimeout (like sinon.useFakeTimers()) 10917 var globalSetTimeout = setTimeout; 10918 return function () { 10919 return globalSetTimeout(flush, 1); 10920 }; 10921 } 10922 10923 var queue = new Array(1000); 10924 10925 function flush() { 10926 for (var i = 0; i < len; i += 2) { 10927 var callback = queue[i]; 10928 var arg = queue[i + 1]; 10929 callback(arg); 10930 queue[i] = undefined; 10931 queue[i + 1] = undefined; 10932 } 10933 10934 len = 0; 10935 } 10936 10937 function attemptVertx() { 10938 try { 10939 var r = commonjsRequire; 10940 var vertx = r('vertx'); 10941 vertxNext = vertx.runOnLoop || vertx.runOnContext; 10942 return useVertxTimer(); 10943 } catch (e) { 10944 return useSetTimeout(); 10945 } 10946 } 10947 10948 var scheduleFlush = undefined; // Decide what async method to use to triggering processing of queued callbacks: 10949 10950 if (isNode) { 10951 scheduleFlush = useNextTick(); 10952 } else if (BrowserMutationObserver) { 10953 scheduleFlush = useMutationObserver(); 10954 } else if (isWorker) { 10955 scheduleFlush = useMessageChannel(); 10956 } else if (browserWindow === undefined && typeof commonjsRequire === 'function') { 10957 scheduleFlush = attemptVertx(); 10958 } else { 10959 scheduleFlush = useSetTimeout(); 10960 } 10961 10962 function then(onFulfillment, onRejection) { 10963 var _arguments = arguments; 10964 var parent = this; 10965 var child = new this.constructor(noop); 10966 10967 if (child[PROMISE_ID] === undefined) { 10968 makePromise(child); 10969 } 10970 10971 var _state = parent._state; 10972 10973 if (_state) { 10974 (function () { 10975 var callback = _arguments[_state - 1]; 10976 asap(function () { 10977 return invokeCallback(_state, child, callback, parent._result); 10978 }); 10979 })(); 10980 } else { 10981 subscribe(parent, child, onFulfillment, onRejection); 10982 } 10983 10984 return child; 10985 } 10986 /** 10987 `Promise.resolve` returns a promise that will become resolved with the 10988 passed `value`. It is shorthand for the following: 10989 10990 ```javascript 10991 let promise = new Promise(function(resolve, reject){ 10992 resolve(1); 10993 }); 10994 10995 promise.then(function(value){ 10996 // value === 1 10997 }); 10998 ``` 10999
11000 Instead of writing the above, your code now simply becomes the following: 11001 11002 ```javascript 11003 let promise = Promise.resolve(1); 11004 11005 promise.then(function(value){ 11006 // value === 1 11007 }); 11008 ``` 11009 11010 @method resolve 11011 @static 11012 @param {Any} value value that the returned promise will be resolved with 11013 Useful for tooling. 11014 @return {Promise} a promise that will become fulfilled with the given 11015 `value` 11016 */ 11017 11018 11019 function resolve(object) { 11020 /*jshint validthis:true */ 11021 var Constructor = this; 11022 11023 if (object && babelHelpers.typeof(object) === 'object' && object.constructor === Constructor) { 11024 return object; 11025 } 11026 11027 var promise = new Constructor(noop); 11028 11029 _resolve(promise, object); 11030 11031 return promise; 11032 } 11033 11034 var PROMISE_ID = Math.random().toString(36).substring(16); 11035 11036 function noop() {} 11037 11038 var PENDING = void 0; 11039 var FULFILLED = 1; 11040 var REJECTED = 2; 11041 var GET_THEN_ERROR = new ErrorObject(); 11042 11043 function selfFulfillment() { 11044 return new TypeError("You cannot resolve a promise with itself"); 11045 } 11046 11047 function cannotReturnOwn() { 11048 return new TypeError('A promises callback cannot return that same promise.'); 11049 } 11050 11051 function getThen(promise) { 11052 try { 11053 return promise.then; 11054 } catch (error) { 11055 GET_THEN_ERROR.error = error; 11056 return GET_THEN_ERROR; 11057 } 11058 } 11059 11060 function tryThen(then, value, fulfillmentHandler, rejectionHandler) { 11061 try { 11062 then.call(value, fulfillmentHandler, rejectionHandler); 11063 } catch (e) { 11064 return e; 11065 } 11066 } 11067 11068 function handleForeignThenable(promise, thenable, then) { 11069 asap(function (promise) { 11070 var sealed = false; 11071 var error = tryThen(then, thenable, function (value) { 11072 if (sealed) { 11073 return; 11074 } 11075 11076 sealed = true; 11077 11078 if (thenable !== value) { 11079 _resolve(promise, value); 11080 } else { 11081 fulfill(promise, value); 11082 } 11083 }, function (reason) { 11084 if (sealed) { 11085 return; 11086 } 11087 11088 sealed = true; 11089 11090 _reject(promise, reason); 11091 }, 'Settle: ' + (promise._label || ' unknown promise')); 11092 11093 if (!sealed && error) { 11094 sealed = true; 11095 11096 _reject(promise, error); 11097 } 11098 }, promise); 11099 } 11100 11101 function handleOwnThenable(promise, thenable) { 11102 if (thenable._state === FULFILLED) { 11103 fulfill(promise, thenable._result); 11104 } else if (thenable._state === REJECTED) { 11105 _reject(promise, thenable._result); 11106 } else { 11107 subscribe(thenable, undefined, function (value) { 11108 return _resolve(promise, value); 11109 }, function (reason) { 11110 return _reject(promise, reason); 11111 }); 11112 } 11113 } 11114 11115 function handleMaybeThenable(promise, maybeThenable, then$$) { 11116 if (maybeThenable.constructor === promise.constructor && then$$ === then && maybeThenable.constructor.resolve === resolve) { 11117 handleOwnThenable(promise, maybeThenable); 11118 } else { 11119 if (then$$ === GET_THEN_ERROR) { 11120 _reject(promise, GET_THEN_ERROR.error); 11121 } else if (then$$ === undefined) { 11122 fulfill(promise, maybeThenable); 11123 } else if (isFunction(then$$)) { 11124 handleForeignThenable(promise, maybeThenable, then$$); 11125 } else { 11126 fulfill(promise, maybeThenable); 11127 } 11128 } 11129 } 11130 11131 function _resolve(promise, value) { 11132 if (promise === value) { 11133 _reject(promise, selfFulfillment()); 11134 } else if (objectOrFunction(value)) { 11135 handleMaybeThenable(promise, value, getThen(value)); 11136 } else { 11137 fulfill(promise, value); 11138 } 11139 } 11140 11141 function publishRejection(promise) { 11142 if (promise._onerror) {
11143 promise._onerror(promise._result); 11144 } 11145 11146 publish(promise); 11147 } 11148 11149 function fulfill(promise, value) { 11150 if (promise._state !== PENDING) { 11151 return; 11152 } 11153 11154 promise._result = value; 11155 promise._state = FULFILLED; 11156 11157 if (promise._subscribers.length !== 0) { 11158 asap(publish, promise); 11159 } 11160 } 11161 11162 function _reject(promise, reason) { 11163 if (promise._state !== PENDING) { 11164 return; 11165 } 11166 11167 promise._state = REJECTED; 11168 promise._result = reason; 11169 asap(publishRejection, promise); 11170 } 11171 11172 function subscribe(parent, child, onFulfillment, onRejection) { 11173 var _subscribers = parent._subscribers; 11174 var length = _subscribers.length; 11175 parent._onerror = null; 11176 _subscribers[length] = child; 11177 _subscribers[length + FULFILLED] = onFulfillment; 11178 _subscribers[length + REJECTED] = onRejection; 11179 11180 if (length === 0 && parent._state) { 11181 asap(publish, parent); 11182 } 11183 } 11184 11185 function publish(promise) { 11186 var subscribers = promise._subscribers; 11187 var settled = promise._state; 11188 11189 if (subscribers.length === 0) { 11190 return; 11191 } 11192 11193 var child = undefined, 11194 callback = undefined, 11195 detail = promise._result; 11196 11197 for (var i = 0; i < subscribers.length; i += 3) { 11198 child = subscribers[i]; 11199 callback = subscribers[i + settled]; 11200 11201 if (child) { 11202 invokeCallback(settled, child, callback, detail); 11203 } else { 11204 callback(detail); 11205 } 11206 } 11207 11208 promise._subscribers.length = 0; 11209 } 11210 11211 function ErrorObject() { 11212 this.error = null; 11213 } 11214 11215 var TRY_CATCH_ERROR = new ErrorObject(); 11216 11217 function tryCatch(callback, detail) { 11218 try { 11219 return callback(detail); 11220 } catch (e) { 11221 TRY_CATCH_ERROR.error = e; 11222 return TRY_CATCH_ERROR; 11223 } 11224 } 11225 11226 function invokeCallback(settled, promise, callback, detail) { 11227 var hasCallback = isFunction(callback), 11228 value = undefined, 11229 error = undefined, 11230 succeeded = undefined, 11231 failed = undefined; 11232 11233 if (hasCallback) { 11234 value = tryCatch(callback, detail); 11235 11236 if (value === TRY_CATCH_ERROR) { 11237 failed = true; 11238 error = value.error; 11239 value = null; 11240 } else { 11241 succeeded = true; 11242 } 11243 11244 if (promise === value) { 11245 _reject(promise, cannotReturnOwn()); 11246 11247 return; 11248 } 11249 } else { 11250 value = detail; 11251 succeeded = true; 11252 } 11253 11254 if (promise._state !== PENDING) ; else if (hasCallback && succeeded) { 11255 _resolve(promise, value); 11256 } else if (failed) { 11257 _reject(promise, error); 11258 } else if (settled === FULFILLED) { 11259 fulfill(promise, value); 11260 } else if (settled === REJECTED) { 11261 _reject(promise, value); 11262 } 11263 } 11264 11265 function initializePromise(promise, resolver) { 11266 try { 11267 resolver(function resolvePromise(value) { 11268 _resolve(promise, value); 11269 }, function rejectPromise(reason) { 11270 _reject(promise, reason); 11271 }); 11272 } catch (e) { 11273 _reject(promise, e); 11274 } 11275 } 11276 11277 var id = 0; 11278 11279 function nextId() { 11280 return id++; 11281 } 11282 11283 function makePromise(promise) { 11284 promise[PROMISE_ID] = id++; 11285 promise._state = undefined; 11286 promise._result = undefined; 11287 promise._subscribers = []; 11288 } 11289 11290 function Enumerator(Constructor, input) { 11291 this._instanceConstructor = Constructor; 11292 this.promise = new Constructor(noop); 11293 11294 if (!this.promise[PROMISE_ID]) { 11295 makePromise(this.promise); 11296 } 11297 11298 if (isArray(input)) { 11299 this._input = input; 11300 this.length = input.length; 11301 this._remaining = input.length; 11302 this._result = new Array(this.length); 11303 11304 if (this.length === 0) { 11305 fulfill(this.promise, this._result); 11306 } else { 11307 this.length = this.length || 0; 11308 11309 this._enumerate(); 11310 11311 if (this._remaining === 0) { 11312 fulfill(this.promise, this._result); 11313 } 11314 } 11315 } else { 11316 _reject(this.promise, validationError()); 11317 } 11318 } 11319 11320 function validationError() { 11321 return new Error('Array Methods must be provided an Array'); 11322 } 11323 11324 Enumerator.prototype._enumerate = function () { 11325 var length = this.length; 11326 var _input = this._input; 11327 11328 for (var i = 0; this._state === PENDING && i < length; i++) { 11329 this._eachEntry(_input[i], i); 11330 } 11331 }; 11332 11333 Enumerator.prototype._eachEntry = function (entry, i) { 11334 var c = this._instanceConstructor; 11335 var resolve$$ = c.resolve; 11336 11337 if (resolve$$ === resolve) { 11338 var _then = getThen(entry); 11339 11340 if (_then === then && entry._state !== PENDING) { 11341 this._settledAt(entry._state, i, entry._result); 11342 } else if (typeof _then !== 'function') { 11343 this._remaining--; 11344 this._result[i] = entry; 11345 } else if (c === Promise) { 11346 var promise = new c(noop); 11347 handleMaybeThenable(promise, entry, _then); 11348 11349 this._willSettleAt(promise, i); 11350 } else {
vendor: 3,996 bytes, lines 11351-11484
11351 this._willSettleAt(new c(function (resolve$$) { 11352 return resolve$$(entry); 11353 }), i); 11354 } 11355 } else { 11356 this._willSettleAt(resolve$$(entry), i); 11357 } 11358 }; 11359 11360 Enumerator.prototype._settledAt = function (state, i, value) { 11361 var promise = this.promise; 11362 11363 if (promise._state === PENDING) { 11364 this._remaining--; 11365 11366 if (state === REJECTED) { 11367 _reject(promise, value); 11368 } else { 11369 this._result[i] = value; 11370 } 11371 } 11372 11373 if (this._remaining === 0) { 11374 fulfill(promise, this._result); 11375 } 11376 }; 11377 11378 Enumerator.prototype._willSettleAt = function (promise, i) { 11379 var enumerator = this; 11380 subscribe(promise, undefined, function (value) { 11381 return enumerator._settledAt(FULFILLED, i, value); 11382 }, function (reason) { 11383 return enumerator._settledAt(REJECTED, i, reason); 11384 }); 11385 }; 11386 /** 11387 `Promise.all` accepts an array of promises, and returns a new promise which 11388 is fulfilled with an array of fulfillment values for the passed promises, or 11389 rejected with the reason of the first passed promise to be rejected. It casts all 11390 elements of the passed iterable to promises as it runs this algorithm. 11391 11392 Example: 11393 11394 ```javascript 11395 let promise1 = resolve(1); 11396 let promise2 = resolve(2); 11397 let promise3 = resolve(3); 11398 let promises = [ promise1, promise2, promise3 ]; 11399 11400 Promise.all(promises).then(function(array){ 11401 // The array here would be [ 1, 2, 3 ]; 11402 }); 11403 ``` 11404 11405 If any of the `promises` given to `all` are rejected, the first promise 11406 that is rejected will be given as an argument to the returned promises's 11407 rejection handler. For example: 11408 11409 Example: 11410 11411 ```javascript 11412 let promise1 = resolve(1); 11413 let promise2 = reject(new Error("2")); 11414 let promise3 = reject(new Error("3")); 11415 let promises = [ promise1, promise2, promise3 ]; 11416 11417 Promise.all(promises).then(function(array){ 11418 // Code here never runs because there are rejected promises! 11419 }, function(error) { 11420 // error.message === "2" 11421 }); 11422 ``` 11423 11424 @method all 11425 @static 11426 @param {Array} entries array of promises 11427 @param {String} label optional string for labeling the promise. 11428 Useful for tooling. 11429 @return {Promise} promise that is fulfilled when all `promises` have been 11430 fulfilled, or rejected if any of them become rejected. 11431 @static 11432 */ 11433 11434 11435 function all(entries) { 11436 return new Enumerator(this, entries).promise; 11437 } 11438 /** 11439 `Promise.race` returns a new promise which is settled in the same way as the 11440 first passed promise to settle. 11441 11442 Example: 11443 11444 ```javascript 11445 let promise1 = new Promise(function(resolve, reject){ 11446 setTimeout(function(){ 11447 resolve('promise 1'); 11448 }, 200); 11449 }); 11450 11451 let promise2 = new Promise(function(resolve, reject){ 11452 setTimeout(function(){ 11453 resolve('promise 2'); 11454 }, 100); 11455 }); 11456 11457 Promise.race([promise1, promise2]).then(function(result){ 11458 // result === 'promise 2' because it was resolved before promise1 11459 // was resolved. 11460 }); 11461 ``` 11462 11463 `Promise.race` is deterministic in that only the state of the first 11464 settled promise matters. For example, even if other promises given to the 11465 `promises` array argument are resolved, but the first settled promise has 11466 become rejected before the other promises became fulfilled, the returned 11467 promise will become rejected: 11468 11469 ```javascript 11470 let promise1 = new Promise(function(resolve, reject){ 11471 setTimeout(function(){ 11472 resolve('promise 1'); 11473 }, 200); 11474 }); 11475 11476 let promise2 = new Promise(function(resolve, reject){ 11477 setTimeout(function(){ 11478 reject(new Error('promise 2')); 11479 }, 100); 11480 }); 11481 11482 Promise.race([promise1, promise2]).then(function(result){ 11483 // Code here never runs 11484 }, function(reason){
11485 // reason.message === 'promise 2' because promise 2 became rejected before 11486 // promise 1 became fulfilled 11487 }); 11488 ``` 11489 11490 An example real-world use case is implementing timeouts: 11491 11492 ```javascript 11493 Promise.race([ajax('foo.json'), timeout(5000)]) 11494 ``` 11495 11496 @method race 11497 @static 11498 @param {Array} promises array of promises to observe 11499 Useful for tooling. 11500 @return {Promise} a promise which settles in the same way as the first passed 11501 promise to settle. 11502 */ 11503 11504 11505 function race(entries) { 11506 /*jshint validthis:true */ 11507 var Constructor = this; 11508 11509 if (!isArray(entries)) { 11510 return new Constructor(function (_, reject) { 11511 return reject(new TypeError('You must pass an array to race.')); 11512 }); 11513 } else { 11514 return new Constructor(function (resolve, reject) { 11515 var length = entries.length; 11516 11517 for (var i = 0; i < length; i++) { 11518 Constructor.resolve(entries[i]).then(resolve, reject); 11519 } 11520 }); 11521 } 11522 } 11523 /** 11524 `Promise.reject` returns a promise rejected with the passed `reason`. 11525 It is shorthand for the following: 11526 11527 ```javascript 11528 let promise = new Promise(function(resolve, reject){ 11529 reject(new Error('WHOOPS')); 11530 }); 11531 11532 promise.then(function(value){ 11533 // Code here doesn't run because the promise is rejected! 11534 }, function(reason){ 11535 // reason.message === 'WHOOPS' 11536 }); 11537 ``` 11538 11539 Instead of writing the above, your code now simply becomes the following: 11540 11541 ```javascript 11542 let promise = Promise.reject(new Error('WHOOPS')); 11543 11544 promise.then(function(value){ 11545 // Code here doesn't run because the promise is rejected! 11546 }, function(reason){ 11547 // reason.message === 'WHOOPS' 11548 }); 11549 ``` 11550 11551 @method reject 11552 @static 11553 @param {Any} reason value that the returned promise will be rejected with. 11554 Useful for tooling. 11555 @return {Promise} a promise rejected with the given `reason`. 11556 */ 11557 11558 11559 function reject(reason) { 11560 /*jshint validthis:true */ 11561 var Constructor = this; 11562 var promise = new Constructor(noop); 11563 11564 _reject(promise, reason); 11565 11566 return promise; 11567 } 11568 11569 function needsResolver() { 11570 throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); 11571 } 11572 11573 function needsNew() { 11574 throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object c
11574onstructor cannot be called as a function."); 11575 } 11576 /** 11577 Promise objects represent the eventual result of an asynchronous operation. The 11578 primary way of interacting with a promise is through its `then` method, which 11579 registers callbacks to receive either a promise's eventual value or the reason 11580 why the promise cannot be fulfilled. 11581 11582 Terminology 11583 ----------- 11584 11585 - `promise` is an object or function with a `then` method whose behavior conforms to this specification. 11586 - `thenable` is an object or function that defines a `then` method. 11587 - `value` is any legal JavaScript value (including undefined, a thenable, or a promise). 11588 - `exception` is a value that is thrown using the throw statement. 11589 - `reason` is a value that indicates why a promise was rejected. 11590 - `settled` the final resting state of a promise, fulfilled or rejected. 11591 11592 A promise can be in one of three states: pending, fulfilled, or rejected. 11593 11594 Promises that are fulfilled have a fulfillment value and are in the fulfilled 11595 state. Promises that are rejected have a rejection reason and are in the 11596 rejected state. A fulfillment value is never a thenable. 11597 11598 Promises can also be said to *resolve* a value. If this value is also a 11599 promise, then the original promise's settled state will match the value's 11600 settled state. So a promise that *resolves* a promise that rejects will 11601 itself reject, and a promise that *resolves* a promise that fulfills will 11602 itself fulfill. 11603 11604 11605 Basic Usage: 11606 ------------ 11607 11608 ```js 11609 let promise = new Promise(function(resolve, reject) { 11610 // on success 11611 resolve(value); 11612 11613 // on failure 11614 reject(reason); 11615 }); 11616 11617 promise.then(function(value) { 11618 // on fulfillment 11619 }, function(reason) { 11620 // on rejection 11621 }); 11622 ``` 11623 11624 Advanced Usage: 11625 --------------- 11626 11627 Promises shine when abstracting away asynchronous interactions such as 11628 `XMLHttpRequest`s. 11629 11630 ```js 11631 function getJSON(url) { 11632 return new Promise(function(resolve, reject){ 11633 let xhr = new XMLHttpRequest(); 11634 11635 xhr.open('GET', url); 11636 xhr.onreadystatechange = handler; 11637 xhr.responseType = 'json'; 11638 xhr.setRequestHeader('Accept', 'application/json'); 11639 xhr.send(); 11640 11641 function handler() { 11642 if (this.readyState === this.DONE) { 11643 if (this.status === 200) { 11644 resolve(this.response); 11645 } else { 11646 reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']')); 11647 } 11648 } 11649 }; 11650 }); 11651 } 11652 11653 getJSON('/posts.json').then(function(json) { 11654 // on fulfillment 11655 }, function(reason) { 11656 // on rejection 11657 }); 11658 ``` 11659 11660 Unlike callbacks, promises are great composable primitives. 11661 11662 ```js 11663 Promise.all([ 11664 getJSON('/posts'), 11665 getJSON('/comments') 11666 ]).then(function(values){ 11667 values[0] // => postsJSON 11668 values[1] // => commentsJSON 11669 11670 return values; 11671 }); 11672 ``` 11673 11674 @class Promise 11675 @param {function} resolver 11676 Useful for tooling. 11677 @constructor 11678 */ 11679 11680 11681 function Promise(resolver) { 11682 this[PROMISE_ID] = nextId(); 11683 this._result = this._state = undefined; 11684 this._subscribers = []; 11685 11686 if (noop !== resolver) { 11687 typeof resolver !== 'function' && needsResolver(); 11688 this instanceof Promise ? initializePromise(this, resolver) : needsNew(); 11689 } 11690 } 11691 11692 Promise.all = all; 11693 Promise.race = race; 11694 Promise.resolve = resolve; 11695 Promise.reject = reject; 11696 Promise._setScheduler = setScheduler; 11697 Promise._setAsap = setAsap; 11698 Promise._asap = asap; 11699 Promise.prototype = { 11700 constructor: Promise, 11701 11702 /** 11703 The primary way of interacting with a promise is through its `then` method, 11704 which registers callbacks to receive either a promise's eventual value or the 11705 reason why the promise cannot be fulfilled. 11706 11707 ```js 11708 findUser().then(function(user){ 11709 // user is available 11710 }, function(reason){ 11711 // user is unavailable, and you are given the reason why 11712 }); 11713 ``` 11714 11715 Chaining 11716 -------- 11717 11718 The return value of `then` is itself a promise. This second, 'downstream' 11719 promise is resolved with the return value of the first promise's fulfillment 11720 or rejection handler, or rejected if the handler throws an exception. 11721 11722 ```js 11723 findUser().then(function (user) { 11724 return user.name; 11725 }, function (reason) { 11726 return 'default name'; 11727 }).then(function (userName) { 11728 // If `findUser` fulfilled, `userName` will be the user's name, otherwise it 11729 // will be `'default name'` 11730 }); 11731 11732 findUser().then(function (user) { 11733 throw new Error('Found user, but still unhappy'); 11734 }, function (reason) { 11735 throw new Error('`findUser` rejected and we're unhappy'); 11736 }).then(function (value) { 11737 // never reached 11738 }, function (reason) { 11739 // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'. 11740 // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'. 11741 }); 11742 ``` 11743 If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. 11744 11745 ```js 11746 findUser().then(function (user) { 11747 throw new PedagogicalException('Upstream error'); 11748 }).then(function (value) { 11749 // never reached 11750 }).then(function (value) { 11751 // never reached 11752 }, function (reason) { 11753 // The `PedgagocialException` is propagated all the way down to here 11754 }); 11755 ``` 11756 11757 Assimilation 11758 ------------ 11759 11760 Sometimes the value you want to propagate to a downstream promise can only be 11761 retrieved asynchronously. This can be achieved by returning a promise in the 11762 fulfillment or rejection handler. The downstream promise will then be pending 11763 until the returned promise is settled. This is called *assimilation*. 11764 11765 ```js 11766 findUser().then(function (user) { 11767 return findCommentsByAuthor(user); 11768 }).then(function (comments) { 11769 // The user's comments are now available 11770 }); 11771 ``` 11772 11773 If the assimliated promise rejects, then the downstream promise will also reject. 11774 11775 ```js 11776 findUser().then(function (user) { 11777 return findCommentsByAuthor(user); 11778 }).then(function (comments) { 11779 // If `findCommentsByAuthor` fulfills, we'll have the value here 11780 }, function (reason) { 11781 // If `findCommentsByAuthor` rejects, we'll have the reason here 11782 }); 11783 ``` 11784
11785 Simple Example 11786 -------------- 11787 11788 Synchronous Example 11789 11790 ```javascript 11791 let result; 11792 11793 try { 11794 result = findResult(); 11795 // success 11796 } catch(reason) { 11797 // failure 11798 } 11799 ``` 11800 11801 Errback Example 11802 11803 ```js 11804 findResult(function(result, err){ 11805 if (err) { 11806 // failure 11807 } else { 11808 // success 11809 } 11810 }); 11811 ``` 11812 11813 Promise Example; 11814 11815 ```javascript 11816 findResult().then(function(result){ 11817 // success 11818 }, function(reason){ 11819 // failure 11820 }); 11821 ``` 11822 11823 Advanced Example 11824 -------------- 11825 11826 Synchronous Example 11827 11828 ```javascript 11829 let author, books; 11830 11831 try { 11832 author = findAuthor(); 11833 books = findBooksByAuthor(author); 11834 // success 11835 } catch(reason) { 11836 // failure 11837 } 11838 ``` 11839 11840 Errback Example 11841 11842 ```js 11843 11844 function foundBooks(books) { 11845 11846 } 11847 11848 function failure(reason) { 11849 11850 } 11851 11852 findAuthor(function(author, err){ 11853 if (err) { 11854 failure(err); 11855 // failure 11856 } else { 11857 try { 11858 findBoooksByAuthor(author, function(books, err) { 11859 if (err) { 11860 failure(err); 11861 } else { 11862 try { 11863 foundBooks(books); 11864 } catch(reason) { 11865 failure(reason); 11866 } 11867 } 11868 }); 11869 } catch(error) { 11870 failure(err); 11871 } 11872 // success 11873 } 11874 }); 11875 ``` 11876 11877 Promise Example; 11878 11879 ```javascript 11880 findAuthor(). 11881 then(findBooksByAuthor). 11882 then(function(books){ 11883 // found books 11884 }).catch(function(reason){ 11885 // something went wrong 11886 }); 11887 ``` 11888 11889 @method then 11890 @param {Function} onFulfilled 11891 @param {Function} onRejected 11892 Useful for tooling. 11893 @return {Promise} 11894 */ 11895 then: then, 11896 11897 /** 11898 `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same 11899 as the catch block of a try/catch statement. 11900 11901 ```js 11902 function findAuthor(){ 11903 throw new Error('couldn't find that author'); 11904 } 11905 11906 // synchronous 11907 try { 11908 findAuthor(); 11909 } catch(reason) { 11910 // something went wrong 11911 } 11912 11913 // async with promises 11914 findAuthor().catch(function(reason){ 11915 // something went wrong 11916 }); 11917 ``` 11918 11919 @method catch 11920 @param {Function} onRejection 11921 Useful for tooling. 11922 @return {Promise} 11923 */ 11924 'catch': function _catch(onRejection) { 11925 return this.then(null, onRejection); 11926 } 11927 }; 11928 11929 function polyfill() { 11930 var local = undefined; 11931 11932 if (typeof commonjsGlobal !== 'undefined') { 11933 local = commonjsGlobal; 11934 } else if (typeof self !== 'undefined') { 11935 local = self; 11936 } else { 11937 try { 11938 local = Function('return this')(); 11939 } catch (e) { 11940 throw new Error('polyfill failed because global object is unavailable in this environment'); 11941 } 11942 } 11943 11944 var P = local.Promise; 11945 11946 if (P) { 11947 var promiseToString = null; 11948 11949 try { 11950 promiseToString = Object.prototype.toString.call(P.resolve()); 11951 } catch (e) {// silently ignored 11952 } 11953 11954 if (promiseToString === '[object Promise]' && !P.cast) { 11955 return; 11956 } 11957 } 11958 11959 local.Promise = Promise; 11960 } // Strange compat.. 11961 11962 11963 Promise.polyfill = polyfill; 11964 Promise.Promise = Promise; 11965 return Promise; 11966 }); 11967 }); 11968 11969 var keys = createCommonjsModule(function (module, exports) { 11970 exports = module.exports = typeof Object.keys === 'function' ? Object.keys : shim; 11971 exports.shim = shim; 11972 11973 function shim(obj) { 11974 var keys = []; 11975 11976 for (var key in obj) { 11977 keys.push(key); 11978 } 11979 11980 return keys; 11981 } 11982 }); 11983 var keys_1 = keys.shim; 11984 11985 var is_arguments = createCommonjsModule(function (module, exports
11985) { 11986 var supportsArgumentsClass = function () { 11987 return Object.prototype.toString.call(arguments); 11988 }() == '[object Arguments]'; 11989 11990 exports = module.exports = supportsArgumentsClass ? supported : unsupported; 11991 exports.supported = supported; 11992 11993 function supported(object) { 11994 return Object.prototype.toString.call(object) == '[object Arguments]'; 11995 } 11996 exports.unsupported = unsupported; 11997 11998 function unsupported(object) { 11999 return object && babelHelpers.typeof(object) == 'object' && typeof object.length == 'number' && Object.prototype.hasOwnProperty.call(object, 'callee') && !Object.prototype.propertyIsEnumerable.call(object, 'callee') || false; 12000 } 12001 }); 12002 var is_arguments_1 = is_arguments.supported; 12003 var is_arguments_2 = is_arguments.unsupported; 12004 12005 var deepEqual_1 = createCommonjsModule(function (module) { 12006 var pSlice = Array.prototype.slice; 12007 12008 12009 12010 12011 12012 var deepEqual = module.exports = function (actual, expected, opts) { 12013 if (!opts) opts = {}; // 7.1. All identical values are equivalent, as determined by ===. 12014 12015 if (actual === expected) { 12016 return true; 12017 } else if (actual instanceof Date && expected instanceof Date) { 12018 return actual.getTime() === expected.getTime(); // 7.3. Other pairs that do not both pass typeof value == 'object', 12019 // equivalence is determined by ==. 12020 } else if (!actual || !expected || babelHelpers.typeof(actual) != 'object' && babelHelpers.typeof(expected) != 'object') { 12021 return opts.strict ? actual === expected : actual == expected; // 7.4. For all other Object pairs, including Array objects, equivalence is 12022 // determined by having the same number of owned properties (as verified 12023 // with Object.prototype.hasOwnProperty.call), the same set of keys 12024 // (although not necessarily the same order), equivalent values for every 12025 // corresponding key, and an identical 'prototype' property. Note: this 12026 // accounts for both named and indexed properties on Arrays. 12027 } else { 12028 return objEquiv(actual, expected, opts); 12029 } 12030 }; 12031 12032 function isUndefinedOrNull(value) { 12033 return value === null || value === undefined; 12034 } 12035 12036 function isBuffer(x) { 12037 if (!x || babelHelpers.typeof(x) !== 'object' || typeof x.length !== 'number') return false; 12038 12039 if (typeof x.copy !== 'function' || typeof x.slice !== 'function') { 12040 return false; 12041 } 12042 12043 if (x.length > 0 && typeof x[0] !== 'number') return false; 12044 return true; 12045 } 12046 12047 function objEquiv(a, b, opts) { 12048 var i, key; 12049 if (isUndefinedOrNull(a) || isUndefinedOrNull(b)) return false; // an identical 'prototype' property. 12050 12051 if (a.prototype !== b.prototype) return false; //~~~I've managed to break Object.keys through screwy arguments passing. 12052 // Converting to array solves the problem. 12053 12054 if (is_arguments(a)) { 12055 if (!is_arguments(b)) { 12056 return false; 12057 } 12058 12059 a = pSlice.call(a); 12060 b = pSlice.call(b); 12061 return deepEqual(a, b, opts); 12062 } 12063 12064 if (isBuffer(a)) { 12065 if (!isBuffer(b)) { 12066 return false; 12067 } 12068 12069 if (a.length !== b.length) return false; 12070 12071 for (i = 0; i < a.length; i++) { 12072 if (a[i] !== b[i]) return false; 12073 } 12074 12075 return true; 12076 } 12077 12078 try { 12079 var ka = keys(a), 12080 kb = keys(b); 12081 } catch (e) { 12082 //happens when one is a string literal and the other isn't 12083 return false; 12084 } // having the same number of owned properties (keys incorporates 12085 // hasOwnProperty) 12086 12087 12088 if (ka.length != kb.length) return false; //the same set of keys (although not necessarily the same order), 12089 12090 ka.sort(); 12091 kb.sort(); //~~~cheap key test 12092 12093 for (i = ka.length - 1; i >= 0; i--) { 12094 if (ka[i] != kb[i]) return false; 12095 } //equivalent values for every corresponding key, and 12096 //~~~possibly expensive deep test 12097 12098 12099 for (i = ka.length - 1; i >= 0; i--) { 12100 key = ka[i]; 12101 if (!deepEqual(a[key], b[key], opts)) return false; 12102 } 12103 12104 return babelHelpers.typeof(a) === babelHelpers.typeof(b); 12105 } 12106 }); 12107 12108 var templates = { 12109 error: 'Error.', 12110 required: 'Required.', 12111 float: 'Must be a number.', 12112 integer: 'Must be an integer.', 12113 number: 'Must be a number.', 12114 lessThan: 'Must be less than {0}.', 12115 lessThanOrEqualTo: 'Must be less than or equal to {0}.', 12116 greaterThan: 'Must be greater than {0}.', 12117 greaterThanOrEqualTo: 'Must greater than or equal to {0}.', 12118 between: 'Must be between {0} and {1}.', 12119 size: 'Size must be {0}.', 12120 length: 'Length must be {0}.', 12121 minLength: 'Must have at least {0} characters.', 12122 maxLength: 'Must have up to {0} characters.', 12123 lengthBetween: 'Length must between {0} and {1}.', 12124 in: 'Must be {0}.', 12125 notIn: 'Must not be {0}.', 12126 match: 'Not matched.', 12127 regex: 'Invalid format.', 12128 digit: 'Must be a digit.', 12129 email: 'Invalid email.', 12130 url: 'Invalid url.', 12131 optionCombiner: function optionCombiner(options) { 12132 if (options.length > 2) { 12133 options = [options.slice(0, options.length - 1).join(', '), options[options.length - 1]]; 12134 } 12135 12136 return options.join(' or '); 12137 } 12138 }; 12139 12140 var utils = createCommonjsModule(function (module) { 12141 12142 // This implementation of debounce was taken from the blog of David Walsh. 12143 // See here: https://davidwalsh.name/javascript-debounce-function 12144 12145 12146 module.exports.debounce = function (func, wait, immediate) { 12147 var timeout; 12148 return function () { 12149 var context = this; 12150 var args = arguments; 12151 12152 var later = function later() { 12153 timeout = null; 12154 12155 if (!immediate) {
12156 func.apply(context, args); 12157 } 12158 }; 12159 12160 var callNow = immediate && !timeout; 12161 clearTimeout(timeout); 12162 timeout = setTimeout(later, wait); 12163 12164 if (callNow) { 12165 func.apply(context, args); 12166 } 12167 }; 12168 }; 12169 12170 module.exports.format = function (template) { 12171 var args = Array.prototype.slice.call(arguments, 1); 12172 return template.replace(/{(\d+)}/g, function (match, number) { 12173 return typeof args[number] != 'undefined' ? args[number] : match; 12174 }); 12175 }; 12176 12177 module.exports.isArray = function (arg) { 12178 if (typeof Array.isArray === 'function') { 12179 return Array.isArray(arg); 12180 } 12181 12182 return Object.prototype.toString.call(arg) === '[object Array]'; 12183 }; 12184 12185 module.exports.isEmpty = function (value) { 12186 if (module.exports.isArray(value)) { 12187 return !value.length; 12188 } else if (value === undefined || value === null) { 12189 return true; 12190 } else { 12191 return !String(value).trim().length; 12192 } 12193 }; 12194 12195 module.exports.isEqual = function (o1, o2) { 12196 return deepEqual_1(o1, o2); 12197 }; 12198 12199 module.exports.isFunction = function (arg) { 12200 return typeof arg === 'function'; 12201 }; 12202 12203 module.exports.isNaN = function (arg) { 12204 return /^\s*$/.test(arg) || isNaN(arg); 12205 }; 12206 12207 module.exports.isNull = function (arg) { 12208 return arg === null; 12209 }; 12210 12211 module.exports.isString = function (arg) { 12212 return typeof arg === 'string' || arg instanceof String; 12213 }; 12214 12215 module.exports.isUndefined = function (arg) { 12216 return typeof arg === 'undefined'; 12217 }; 12218 12219 module.exports.omit = function omit(obj, key) { 12220 var result = {}; 12221 12222 for (var name in obj) { 12223 if (name !== key) { 12224 result[name] = obj[name]; 12225 } 12226 } 12227 12228 return result; 12229 }; 12230 12231 module.exports.templates = templates; 12232 module.exports.mode = 'interactive'; // other values: conservative and manual 12233 }); 12234 var utils_1 = utils.debounce; 12235 var utils_2 = utils.format; 12236 var utils_3 = utils.isArray; 12237 var utils_4 = utils.isEmpty; 12238 var utils_5 = utils.isEqual; 12239 var utils_6 = utils.isFunction; 12240 var utils_7 = utils.isNaN; 12241 var utils_8 = utils.isNull; 12242 var utils_9 = utils.isString; 12243 var utils_10 = utils.isUndefined; 12244 var utils_11 = utils.omit; 12245 var utils_12 = utils.templates; 12246 var utils_13 = utils.mode; 12247 12248 var Promise$1 = es6Promise.Promise; 12249 12250 12251 12252 function ValidationBag() { 12253 this.sessionId = 0; // async validator will check this before adding error 12254 12255 this.resetting = 0; // do not allow to add error while reset is in progress 12256 12257 this.errors = []; 12258 this.validatingRecords = []; 12259 this.passedRecords = []; 12260 this.touchedRecords = []; 12261 this.activated = false; // set when $validate() is call, this flag works with the conservative mode 12262 } 12263 12264 ValidationBag.prototype._setVM = function (vm) { 12265 this._vm = vm; 12266 }; 12267 12268 ValidationBag.prototype.addError = function (field, message) { 12269 if (this.resetting) { 12270 return; 12271 } 12272 12273 this.errors.push({ 12274 field: field, 12275 message: message 12276 }); 12277 }; 12278 12279 ValidationBag.prototype.removeErrors = function (field) { 12280 if (utils.isUndefined(field)) { 12281 this.errors = []; 12282 } else { 12283 this.errors = this.errors.filter(function (e) { 12284 return e.field !== field; 12285 }); 12286 } 12287 }; 12288 12289 ValidationBag.prototype.hasError = function (field) { 12290 return utils.isUndefined(field) ? !!this.errors.length : !!this.firstError(field); 12291 }; 12292 12293 ValidationBag.prototype.firstError = function (field) { 12294 for (var i = 0; i < this.errors.length; i++) { 12295 if (utils.isUndefined(field) || this.errors[i].field === field) { 12296 return this.errors[i].message; 12297 } 12298 } 12299 12300 return null; 12301 }; 12302 12303 ValidationBag.prototype.allErrors = function (field) { 12304 return this.errors.filter(function (e) { 12305 return utils.isUndefined(field) || e.field === field; 12306 }).map(function (e) { 12307 return e.message; 12308 }); 12309 }; 12310 12311 ValidationBag.prototype.countErrors = function (field) { 12312 return utils.isUndefined(field) ? this.errors.length : this.errors.filter(function (e) { 12313 return field === e.field; 12314 }).length; 12315 }; 12316 12317 ValidationBag.prototype.setValidating = function (field, id) { 12318 if (this.resetting) { 12319 return; 12320 } 12321 12322 id = id || ValidationBag.newValidatingId();
12323 var existingValidatingRecords = this.validatingRecords.filter(function (validating) { 12324 return validating.field === field && validating.id === id; 12325 }); 12326 12327 if (!utils.isEmpty(existingValidatingRecords)) { 12328 throw new Error('Validating id already set: ' + id); 12329 } 12330 12331 this.validatingRecords.push({ 12332 field: field, 12333 id: id 12334 }); 12335 return id; 12336 }; 12337 12338 ValidationBag.prototype.resetValidating = function (field, id) { 12339 if (!field) { 12340 this.validatingRecords = []; 12341 return; 12342 } 12343 12344 function idMatched(validating) { 12345 return utils.isUndefined(id) ? true : validating.id === id; 12346 } 12347 12348 var hasMore = true; 12349 12350 while (hasMore) { 12351 var index = -1; 12352 12353 for (var i = 0; i < this.validatingRecords.length; i++) { 12354 if (this.validatingRecords[i].field === field && idMatched(this.validatingRecords[i])) { 12355 index = i; 12356 break; 12357 } 12358 } 12359 12360 if (index >= 0) { 12361 this.validatingRecords.splice(index, 1); 12362 } else { 12363 hasMore = false; 12364 } 12365 } 12366 }; 12367 12368 ValidationBag.prototype.isValidating = function (field, id) { 12369 function idMatched(validating) { 12370 return utils.isUndefined(id) ? true : validating.id === id; 12371 } 12372 12373 var existingValidatingRecords = this.validatingRecords.filter(function (validating) { 12374 return (utils.isUndefined(field) || validating.field === field) && idMatched(validating); 12375 }); 12376 return !utils.isEmpty(existingValidatingRecords); 12377 }; 12378 12379 ValidationBag.prototype.setPassed = function (field) { 12380 if (this.resetting) { 12381 return; 12382 } 12383 12384 setValue(this.passedRecords, field); 12385 }; 12386 12387 ValidationBag.prototype.resetPassed = function (field) { 12388 resetValue(this.passedRecords, field); 12389 }; 12390 12391 ValidationBag.prototype.isPassed = function (field) { 12392 return isValueSet(this.passedRecords, field); 12393 }; 12394 12395 ValidationBag.prototype.setTouched = function (field) { 12396 if (this.resetting) { 12397 return; 12398 } 12399 12400 setValue(this.touchedRecords, field); 12401 }; 12402 12403 ValidationBag.prototype.resetTouched = function (field) { 12404 resetValue(this.touchedRecords, field); 12405 }; 12406 12407 ValidationBag.prototype.isTouched = function (field) { 12408 return isValueSet(this.touchedRecords, field); 12409 }; 12410 12411 function setValue(records, field) { 12412 var existingRecords = records.filter(function (record) { 12413 return record.field === field; 12414 }); 12415 12416 if (!utils.isEmpty(existingRecords)) { 12417 existingRecords[0].value = true; 12418 } else { 12419 records.push({ 12420 field: field, 12421 value: true 12422 }); 12423 } 12424 } 12425 12426 function resetValue(records, field) { 12427 if (!field) { 12428 records.splice(0, records.length); 12429 return; 12430 } 12431 12432 var existingRecords = records.filter(function (record) { 12433 return record.field === field; 12434 }); 12435 12436 if (!utils.isEmpty(existingRecords)) { 12437 existingRecords[0].value = false; 12438 } 12439 } 12440 12441 function isValueSet(records, field) { 12442 var existingRecords = records.filter(function (record) { 12443 return record.field === field; 12444 }); 12445 return !utils.isEmpty(existingRecords) && existingRecords[0].value; 12446 } 12447 12448 ValidationBag.prototype.reset = function () { 12449 this.sessionId++; 12450 this.errors = []; 12451 this.validatingRecords = []; 12452 this.passedRecords = []; 12453 this.touchedRecords = []; 12454 12455 if (this._vm) { 12456 // prevent field updates at the same tick to change validation status 12457 this.resetting++; 12458 12459 this._vm.$nextTick(function () { 12460 this.resetting--; 12461 }.bind(this)); 12462 } 12463 12464 this.activated = false; 12465 }; // returns true if any error is added 12466 12467 12468 ValidationBag.prototype.setError = function (field, message) { 12469 if (this.resetting) { 12470 return; 12471 } 12472 12473 this.removeErrors(field); 12474 this.resetPassed(field); 12475 var messages = utils.isArray(message) ? message : [message]; 12476 12477 var addMessages = function (messages) { 12478 var hasError = false; 12479 messages.forEach(function (message) { 12480 if (message) { 12481 this.addError(field, message); 12482 hasError = true; 12483 } 12484 }, this); 12485 12486 if (!hasError) { 12487 this.setPassed(field); 12488 } 12489 12490 return hasError; 12491 }.bind(this); 12492 12493 var hasPromise = messages.filter(function (message) { 12494 return message && message.then; 12495 }).length > 0; 12496 12497 if (!hasPromise) { 12498 return Promise$1.resolve(addMessages(messages)); 12499 } else { 12500 // if message is promise, we are encountering async validation, set validating flag and wait for message to resolve 12501 // reset previous validating status for this field 12502 this.resetValidating(field);
12503 var validatingId = this.setValidating(field); 12504 12505 var always = function () { 12506 //console.log(validatingId + ' | ' + 'end'); 12507 this.resetValidating(field, validatingId); 12508 }.bind(this); //console.log(validatingId + ' | ' + 'start'); 12509 12510 12511 return Promise$1.all(messages).then(function (messages) { 12512 // check if the validating id is is still valid 12513 if (this.isValidating(field, validatingId)) { 12514 //console.log(validatingId + ' | ' + 'processed'); 12515 return addMessages(messages); 12516 } 12517 12518 return false; 12519 }.bind(this)).then(function (result) { 12520 always(); 12521 return result; 12522 }).catch(function (e) { 12523 always(); 12524 return Promise$1.reject(e); 12525 }.bind(this)); 12526 } 12527 }; 12528 12529 ValidationBag.prototype.checkRule = function (rule) { 12530 if (this.resetting) { 12531 return; 12532 } 12533 12534 return this.setError(rule._field, rule._messages); 12535 }; 12536 12537 var validatingId = 0; 12538 12539 ValidationBag.newValidatingId = function () { 12540 return (++validatingId).toString(); 12541 }; 12542 12543 var validationBag = ValidationBag; 12544 12545 function Rule(templates) { 12546 this._field = ''; 12547 this._value = undefined; 12548 this._messages = []; 12549 12550 if (templates) { 12551 // merge given template and utils.template 12552 this.templates = {}; 12553 Object.keys(utils.templates).forEach(function (key) { 12554 this.templates[key] = utils.templates[key]; 12555 }.bind(this)); 12556 Object.keys(templates).forEach(function (key) { 12557 this.templates[key] = templates[key]; 12558 }.bind(this)); 12559 } else { 12560 this.templates = utils.templates; 12561 } 12562 } 12563 12564 Rule.prototype.field = function (field) { 12565 this._field = field; 12566 return this; 12567 }; 12568 12569 Rule.prototype.value = function (value) { 12570 this._value = value; 12571 return this; 12572 }; 12573 12574 Rule.prototype.custom = function (callback, context) { 12575 var message = context ? callback.call(context) : callback(); 12576 12577 if (message) { 12578 if (message.then) { 12579 var that = this; 12580 message = Promise.resolve(message).then(function (result) { 12581 return result; 12582 }).catch(function (e) { 12583 console.error(e.toString()); 12584 return that.templates.error; 12585 }); 12586 } 12587 12588 this._messages.push(message); 12589 } 12590 12591 return this; 12592 }; 12593 12594 Rule.prototype._checkValue = function () { 12595 if (this._value === undefined) { 12596 throw new Error('Validator.value not set'); 12597 } 12598 12599 return this._value; 12600 }; 12601 12602 Rule.prototype.required = function (message) { 12603 var value = this._checkValue(); 12604 12605 if (utils.isEmpty(value)) { 12606 this._messages.push(message || this.templates.required); 12607 } 12608 12609 return this; 12610 }; 12611 12612 Rule.prototype.float = function (message) { 12613 var value = this._checkValue(); 12614 12615 var regex = /^([-+])?([0-9]+(\.[0-9]+)?|Infinity)$/; 12616 12617 if (!utils.isEmpty(value) && !regex.test(value)) { 12618 this._messages.push(message || this.templates.float); 12619 } 12620 12621 return this; 12622 }; 12623 12624 Rule.prototype.integer = function (message) { 12625 var value = this._checkValue(); 12626 12627 var regex = /^([-+])?([0-9]+|Infinity)$/; 12628 12629 if (!utils.isEmpty(value) && !regex.test(value)) { 12630 this._messages.push(message || this.templates.integer); 12631 } 12632 12633 return this; 12634 }; 12635 12636 Rule.prototype.lessThan = function (bound, message) { 12637 var value = this._checkValue(); 12638 12639 if (!utils.isEmpty(value)) { 12640 var number = parseFloat(value); 12641 12642 if (utils.isNaN(number)) { 12643 this._messages.push(message || this.templates.number); 12644 } else if (number >= bound) { 12645 this._messages.push(message || utils.format(this.templates.lessThan, bound)); 12646 } 12647 } 12648 12649 return this; 12650 }; 12651 12652 Rule.prototype.lessThanOrEqualTo = function (bound, message) { 12653 var value = this._checkValue(); 12654 12655 if (!utils.isEmpty(value)) { 12656 var number = parseFloat(value); 12657 12658 if (utils.isNaN(number)) { 12659 this._messages.push(message || this.templates.number); 12660 } else if (number > bound) { 12661 this._messages.push(message || utils.format(this.templates.lessThanOrEqualTo, bound)); 12662 } 12663 } 12664 12665 return this; 12666 }; 12667 12668 Rule.prototype.greaterThan = function (bound, message) { 12669 var value = this._checkValue(); 12670 12671 if (!utils.isEmpty(value)) { 12672 var number = parseFloat(value); 12673 12674 if (utils.isNaN(number)) { 12675 this._messages.push(message || this.templates.number); 12676 } else if (number <= bound) { 12677 this._messages.push(message || utils.format(this.templates.greaterThan, bound)); 12678 } 12679 } 12680 12681 return this; 12682 }; 12683 12684 Rule.prototype.greaterThanOrEqualTo = function (bound, message) { 12685 var value = this._checkValue(); 12686 12687 if (!utils.isEmpty(value)) { 12688 var number = parseFloat(value); 12689 12690 if (utils.isNaN(number)) { 12691 this._messages.push(message || this.templates.number); 12692 } else if (number < bound) { 12693 this._messages.push(message || utils.format(this.templates.greaterThanOrEqualTo, bound)); 12694 } 12695 } 12696 12697 return this; 12698 }; 12699 12700 Rule.prototype.between = function (lowBound, highBound, message) { 12701 var value = this._checkValue(); 12702 12703 if (!utils.isEmpty(value)) { 12704 var number = parseFloat(value); 12705 12706 if (utils.isNaN(number)) { 12707 this._messages.push(message || this.templates.number); 12708 } else if (number < lowBound || number > highBound) { 12709 this._messages.push(message || utils.format(this.templates.between, lowBound, highBound)); 12710 } 12711 } 12712 12713 return this; 12714 }; 12715 12716 Rule.prototype.size = function (size, message) { 12717 var value = this._checkValue(); 12718 12719 if (!utils.isEmpty(value) && utils.isArray(value) && value.length !== size) { 12720 this._messages.push(message || utils.format(this.templates.size, size)); 12721 } 12722 12723 return this; 12724 }; 12725 12726 Rule.prototype.length = function (length, message) { 12727 var value = this._checkValue(); 12728 12729 if (!utils.isEmpty(value) && String(value).length !== length) { 12730 this._messages.push(message || utils.format(this.templates.length, length)); 12731 } 12732 12733 return this; 12734 }; 12735 12736 Rule.prototype.minLength = function (length, message) { 12737 var value = this._checkValue(); 12738 12739 if (!utils.isEmpty(value) && String(value).length < length) { 12740 this._messages.push(message || utils.format(this.templates.minLength, length)); 12741 } 12742 12743 return this; 12744 }; 12745 12746 Rule.prototype.maxLength = function (length, message) { 12747 var value = this._checkValue(); 12748 12749 if (!utils.isEmpty(value) && String(value).length > length) { 12750 this._messages.push(message || utils.format(this.templates.maxLength, length)); 12751 } 12752 12753 return this; 12754 }; 12755 12756 Rule.prototype.lengthBetween = function (minLength, maxLength, message) { 12757 var value = this._checkValue(); 12758 12759 if (!utils.isEmpty(value)) { 12760 var string = String(value); 12761
12762 if (string.length < minLength || string.length > maxLength) { 12763 this._messages.push(message || utils.format(this.templates.lengthBetween, minLength, maxLength)); 12764 } 12765 } 12766 12767 return this; 12768 }; 12769 12770 Rule.prototype.in = function (options, message) { 12771 var value = this._checkValue(); 12772 12773 if (!utils.isEmpty(value) && options.indexOf(value) < 0) { 12774 this._messages.push(message || utils.format(this.templates.in, this.templates.optionCombiner(options))); 12775 } 12776 12777 return this; 12778 }; 12779 12780 Rule.prototype.notIn = function (options, message) { 12781 var value = this._checkValue(); 12782 12783 if (!utils.isEmpty(value) && options.indexOf(value) >= 0) { 12784 this._messages.push(message || utils.format(this.templates.notIn, this.templates.optionCombiner(options))); 12785 } 12786 12787 return this; 12788 }; 12789 12790 Rule.prototype.match = function (valueToCompare, message) { 12791 var value = this._checkValue(); 12792 12793 if (!utils.isEmpty(value) && value !== valueToCompare) { 12794 this._messages.push(message || this.templates.match); 12795 } 12796 12797 return this; 12798 }; 12799 12800 Rule.prototype.regex = function (regex, message) { 12801 var value = this._checkValue(); 12802 12803 if (!utils.isEmpty(value)) { 12804 if (utils.isString(regex)) { 12805 regex = new RegExp(regex); 12806 } 12807 12808 if (!regex.test(value)) { 12809 this._messages.push(message || this.templates.regex); 12810 } 12811 } 12812 12813 return this; 12814 }; 12815 12816 Rule.prototype.digit = function (message) { 12817 return this.regex(/^\d*$/, message || this.templates.digit); 12818 }; 12819 12820 Rule.prototype.email = function (message) { 12821 return this.regex(/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/, message || this.templates.email); 12822 }; 12823 12824 Rule.prototype.url = function (message) { 12825 return this.regex(/(http|https):\/\/[\w-]+(\.[\w-]+)+([\w.,@?^=%&:\/~+#-]*[\w@?^=%&\/~+#-])?/, message || this.templates.url); 12826 }; 12827 12828 Rule.prototype.hasImmediateError = function () { 12829 for (var i = 0; i < this._messages.length; i++) { 12830 if (this._messages[i] && !this._messages[i].then) { 12831 return true; 12832 } 12833 } 12834 12835 return false; 12836 }; 12837 12838 var rule = Rule; 12839 12840 var Validator = newValidator(); 12841 12842 Validator.create = function (options) { 12843 return newValidator(options); 12844 }; 12845 12846 function newValidator(options) { 12847 options = options || {}; 12848 var validator = {}; // clone methods from Rule to validator 12849 12850 Object.keys(rule.prototype).forEach(function (methodName) { 12851 validator[methodName] = function () { 12852 var rule$$1 = new rule(options.templates); 12853 return rule$$1[methodName].apply(rule$$1, arguments); 12854 }; 12855 }); 12856 validator.isEmpty = utils.isEmpty; 12857 validator.format = utils.format; 12858 return validator; 12859 } 12860 12861 var validator = Validator; 12862 12863 var mixin = { 12864 Promise: null, 12865 beforeMount: function beforeMount() { 12866 this.$setValidators(this.$options.validators); 12867 12868 if (this.validation) { 12869 // set vm to validation 12870 this.validation._setVM(this); 12871 } 12872 }, 12873 beforeDestroy: function beforeDestroy() { 12874 unwatch(this.$options.validatorsUnwatchCallbacks); 12875 }, 12876 data: function data() { 12877 if (this.$options.validators) { 12878 return { 12879 validation: new validationBag() 12880 }; 12881 } 12882 12883 return {}; 12884 }, 12885 methods: { 12886 $setValidators: function $setValidators(validators) { 12887 unwatch(this.$options.validatorsUnwatchCallbacks); // validate methods contains all application validate codes 12888 12889 var validateMethods = {}; 12890 this.$options.validateMethods = validateMethods; 12891 var unwatchCallbacks = []; 12892 this.$options.validatorsUnwatchCallbacks = unwatchCallbacks; // generate validate methods and watch properties change for validators 12893 12894 if (validators) { 12895 Object.keys(validators).forEach(function (key) { 12896 var properties = key.split(','); 12897 properties = properties.map(function (property) { 12898 return property.trim(); 12899 }); 12900 var getters = properties.map(function (property) { 12901 return generateGetter(this, property); 12902 }, this); 12903 var validator = validators[key]; 12904 var options = {}; 12905
12906 if (!utils.isFunction(validator)) { 12907 options = utils.omit(validator, 'validator'); 12908 validator = validator.validator; 12909 } 12910 12911 if (options.cache) { 12912 // cache the validation result, so that async validator can be fast when submitting the form 12913 var option = options.cache === 'last' ? 'last' : 'all'; 12914 validator = cache(validator, option); 12915 } 12916 12917 var validation = this.validation; 12918 12919 var validateMethod = function () { 12920 if (utils.mode === 'conservative' && !validation.activated) { 12921 // do nothing if in conservative mode and $validate() method is not called before 12922 return getPromise().resolve(false); 12923 } 12924 12925 var args = getters.map(function (getter) { 12926 return getter(); 12927 }); 12928 var rule = validator.apply(this, args); 12929 12930 if (rule) { 12931 if (!rule._field) { 12932 // field defaults to the first property 12933 rule.field(properties[0]); 12934 } 12935 12936 return this.validation.checkRule(rule); 12937 } else { 12938 return getPromise().resolve(false); 12939 } 12940 }.bind(this); // add to validate method list 12941 12942 12943 validateMethods[properties[0]] = validateMethod; // watch change and invoke validate method 12944 12945 var validateMethodForWatch = validateMethod; 12946 12947 if (options.debounce) { 12948 // TODO what if custom field name is used? 12949 var decoratedValidateMethod = function () { 12950 if (decoratedValidateMethod.sessionId !== this.validation.sessionId) { 12951 // skip validation if it's reset before 12952 return getPromise().resolve(false); 12953 } 12954 12955 return validateMethod.apply(this, arguments); 12956 }.bind(this); 12957 12958 var debouncedValidateMethod = utils.debounce(decoratedValidateMethod, parseInt(options.debounce)); 12959 var field = properties[0]; 12960 12961 validateMethodForWatch = function () { 12962 // eagerly resetting passed flag if debouncing is used. 12963 this.validation.resetPassed(field); // store sessionId 12964 12965 decoratedValidateMethod.sessionId = this.validation.sessionId; 12966 debouncedValidateMethod.apply(this, arguments); 12967 }.bind(this); 12968 } 12969 12970 if (utils.mode !== 'manual') { 12971 // have to call $validate() to trigger validation in manual mode, so don't watch, 12972 watchProperties(this, properties, validateMethodForWatch).forEach(function (unwatch) { 12973 unwatchCallbacks.push(unwatch); 12974 }); 12975 } 12976 }, this); 12977 } 12978 }, 12979 $validate: function $validate(fields) { 12980 if (this.validation._validate) { 12981 return this.validation._validate; 12982 } 12983 12984 this.validation.activated = true; 12985 var validateMethods = this.$options.validateMethods; 12986 12987 if (utils.isUndefined(fields)) { 12988 validateMethods = Object.keys(validateMethods).map(function (key) { 12989 return validateMethods[key]; 12990 }); 12991 } else { 12992 fields = utils.isArray(fields) ? fields : [fields]; 12993 validateMethods = fields.map(function (field) { 12994 return validateMethods[field]; 12995 }); 12996 } 12997 12998 if (utils.isEmpty(validateMethods)) { 12999 return getPromise().resolve(true); 13000 } else { 13001 var always = function () { 13002 this.validation._validate = null; 13003 }.bind(this); 13004 13005 this.validation._validate = getPromise().all(validateMethods.map(function (validateMethod) { 13006 return validateMethod(); 13007 })).then(function (results) { 13008 always(); 13009 return results.filter(function (result) { 13010 return !!result; 13011 }).length <= 0; 13012 }.bind(this)).catch(function (e) { 13013 always(); 13014 throw e; 13015 }); 13016 return this.validation._validate; 13017 } 13018 } 13019 } 13020 }; 13021 13022 function unwatch(list) { 13023 if (list) { 13024 list.forEach(function (unwatch) { 13025 unwatch(); 13026 }); 13027 } 13028 } 13029 13030 function generateGetter(vm, property) { 13031 var names = property.split('.'); 13032 return function () { 13033 var value = vm; 13034 13035 for (var i = 0; i < names.length; i++) { 13036 if (utils.isNull(value) || utils.isUndefined(value)) { 13037 break; 13038 } 13039 13040 value = value[names[i]]; 13041 } 13042 13043 return value; 13044 }; 13045 } 13046 13047 function watchProperties(vm, properties, callback) { 13048 return properties.map(function (property) { 13049 return vm.$watch(property, function () { 13050 vm.validation.setTouched(property); 13051 callback.call(); 13052 }); 13053 }); 13054 } 13055 13056 function cache(validator, option) { 13057 return function () { 13058 var cache = validator.cache;
13059 13060 if (!cache) { 13061 cache = []; 13062 validator.cache = cache; 13063 } 13064 13065 var args = Array.prototype.slice.call(arguments); 13066 var cachedResult = findInCache(cache, args); 13067 13068 if (!utils.isUndefined(cachedResult)) { 13069 return cachedResult; 13070 } 13071 13072 var result = validator.apply(this, args); 13073 13074 if (!utils.isUndefined(result)) { 13075 if (result.then) { 13076 return result.tab(function (promiseResult) { 13077 if (!utils.isUndefined(promiseResult)) { 13078 if (option !== 'all') { 13079 cache.splice(0, cache.length); 13080 } 13081 13082 cache.push({ 13083 args: args, 13084 result: promiseResult 13085 }); 13086 } 13087 }); 13088 } else { 13089 if (option !== 'all') { 13090 cache.splice(0, cache.length); 13091 } 13092 13093 cache.push({ 13094 args: args, 13095 result: result 13096 }); 13097 return result; 13098 } 13099 } 13100 }; 13101 } 13102 13103 function getPromise() { 13104 if (mixin.Promise) { 13105 return mixin.Promise; 13106 } 13107 13108 return es6Promise.Promise; 13109 } 13110 13111 function findInCache(cache, args) { 13112 var items = cache.filter(function (item) { 13113 return utils.isEqual(args, item.args); 13114 }); 13115 13116 if (!utils.isEmpty(items)) { 13117 return items[0].result; 13118 } 13119 } 13120 13121 var mixin_1 = mixin; 13122 13123 /* plugin install 13124 ----------------------------------- */ 13125 13126 13127 function install(Vue, options) { 13128 Vue.mixin(mixin_1); 13129 13130 if (options && options.templates) { 13131 extendTemplates(options.templates); 13132 } 13133 13134 if (options && options.mode) { 13135 setMode(options.mode); 13136 } 13137 13138 if (options && options.Promise) { 13139 mixin_1.Promise = options.Promise; 13140 } 13141 } 13142 13143 function extendTemplates(newTemplates) { 13144 Object.keys(newTemplates).forEach(function (key) { 13145 utils.templates[key] = newTemplates[key]; 13146 }); 13147 } 13148 13149 function setMode(mode) { 13150 if (mode !== 'interactive' && mode !== 'conservative' && mode !== 'manual') { 13151 throw new Error('Invalid mode: ' + mode); 13152 } 13153 13154 utils.mode = mode; 13155 } 13156 /* exports 13157 ----------------------------------- */ 13158 13159 13160 var name = 'SimpleVueValidator'; 13161 var ValidationBag_1 = validationBag; 13162 var Rule_1 = rule; 13163 var Validator_1 = validator; 13164 var mixin_1$1 = mixin_1; 13165 var install_1 = install; 13166 var extendTemplates_1 = extendTemplates; 13167 var setMode_1 = setMode; 13168 13169 var src = { 13170 name: name, 13171 ValidationBag: ValidationBag_1, 13172 Rule: Rule_1, 13173 Validator: Validator_1, 13174 mixin: mixin_1$1, 13175 install: install_1, 13176 extendTemplates: extendTemplates_1, 13177 setMode: setMode_1 13178 }; 13179 13180 var AddPatient = /*#__PURE__*/function () { 13181 function AddPatient() { 13182 var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : { 13183 el: '', 13184 params: {} 13185 }; 13186 babelHelpers.classCallCheck(this, AddPatient); 13187 this.params = options.params; 13188 if (options.el) this.vueComponent = this.createVueComponent(options.el); 13189 } 13190 13191 babelHelpers.createClass(AddPatient, [{ 13192 key: "createVueComponent", 13193 value: function createVueComponent(el) { 13194 var Validator = src.Validator; 13195 this.vueComponent = ui_vue.Vue.create({ 13196 el: el, 13197 data: function data() { 13198 return { 13199 ajaxUrl: null, 13200 age: 0, 13201 diagnosis: '', 13202 localization: '', 13203 duration: 0, 13204 sex: null, 13205 device: '', 13206 serialNumber: '', 13207 buyDate: '', 13208 orgName: '', 13209 treatment: '', 13210 procedure: '', 13211 name: '', 13212 buyedDevice: '', 13213 //COLLECTIONS 13214 devicesCollection: [], 13215 diagnosisCollection: [], 13216 localizationsCollection: [], 13217 proceduresCollection: [], 13218 treatmentsCollection: [] 13219 }; 13220 }, 13221 props: [], 13222 methods: { 13223 setParams: function setParams(params) { 13224 this.ajaxUrl = params.ajaxUrl; 13225 this.devicesCollection = params.devices; 13226 this.diagnosisCollection = params.diagnosis; 13227 this.localizationsCollection = params.localizations; 13228 this.proceduresCollection = params.procedures; 13229 this.treatmentsCollection = params.treatments; 13230 }, 13231 sendRequest: function sendRequest() { 13232 this.$validate().then(function (success) { 13233 var _this = this; 13234 13235 if (success) { 13236 var data = { 13237 'action': 'add', 13238 'age': this.age, 13239 'duration': this.duration, 13240 'buyDate': this.buyDate, 13241 'treatment': this.treatment, 13242 'orgName': this.orgName, 13243 'serialNumber': this.serialNumber, 13244 'device': this.device, 13245 'sex': this.sex, 13246 'name': this.name, 13247 'buyedDevice': this.buyedDevice 13248 }; 13249 var localizationId = this.localizationsCollection.filter(function (item) { 13250 return item.UF_NAME == _this.localization; 13251 }); 13252 13253 if (localizationId && localizationId[0]) { 13254 data['localization'] = localizationId[0].UF_XML_ID; 13255 } else { 13256 data['localization'] = this.localization; 13257 } 13258 13259 var diagnosisId = this.diagnosisCollection.filter(function (item) { 13260 return item.UF_NAME == _this.diagnosis; 13261 }); 13262 13263 if (diagnosisId && diagnosisId[0]) { 13264 data['diagnosis'] = diagnosisId[0].UF_XML_ID; 13265 } else { 13266 data['diagnosis'] = this.diagnosis; 13267 } 13268 13269 var procedureId = this.proceduresCollection.filter(function (item) { 13270 return item.UF_NAME == _this.procedure; 13271 }); 13272 13273 if (procedureId && procedureId[0]) { 13274 data['procedure'] = procedureId[0].UF_XML_ID; 13275 } else { 13276 data['procedure'] = this.procedure; 13277 } 13278 13279 BX.ajax.post(this.ajaxUrl, data, function (result) { 13280 if (result) { 13281 var jsonResult = JSON.parse(result); 13282 13283 if (jsonResult.status) { 13284 var container = window.popups.formResult.container[0]; 13285 13286 if (container != undefined) { 13287 var body = container.querySelector('[data-entity="body"]'); 13288 13289 if (body != undefined) { 13290 body.innerHTML = '<p>ÐаÑÐ¸ÐµÐ½Ñ ÑÑпеÑно добавлен!</p>'; 13291 } 13292 13293 window.popups.addPatient.close(); 13294 window.popups.formResult.open(); 13295 } 13296 } 13297 } 13298 }); 13299 } 13300 }.bind(this)); 13301 } 13302 }, 13303 mixins: [src.mixin], 13304 validators: { 13305 'age': function age(value) { 13306 return Validator.value(value).required('Ðоле обÑзаÑелÑно Ð´Ð»Ñ Ð·Ð°Ð¿Ð¾Ð»Ð½ÐµÐ½Ð¸Ñ').regex(/\d+/, 'ТолÑко ÑиÑÑÑ'); 13307 }, 13308 13309 /*'treatment': function (value) { 13310 return Validator.value(value).required('Ðоле обÑзаÑелÑно Ð´Ð»Ñ Ð·Ð°Ð¿Ð¾Ð»Ð½ÐµÐ½Ð¸Ñ'); 13311 },*/ 13312 'procedure': function procedure(value) { 13313 return Validator.value(value).required('Ðоле обÑзаÑелÑно Ð´Ð»Ñ Ð·Ð°Ð¿Ð¾Ð»Ð½ÐµÐ½Ð¸Ñ'); 13314 }, 13315 'name': function name$$1(value) { 13316 return Validator.value(value).required('Ðоле обÑзаÑелÑно Ð´Ð»Ñ Ð·Ð°Ð¿Ð¾Ð»Ð½ÐµÐ½Ð¸Ñ'); 13317 }, 13318 'diagnosis': function diagnosis(value) { 13319 return Validator.value(value).required('Ðоле обÑзаÑелÑно Ð´Ð»Ñ Ð·Ð°Ð¿Ð¾Ð»Ð½ÐµÐ½Ð¸Ñ'); 13320 }, 13321 'duration': function duration(value) { 13322 return Validator.value(value).required('Ðоле обÑзаÑелÑно Ð´Ð»Ñ Ð·Ð°Ð¿Ð¾Ð»Ð½ÐµÐ½Ð¸Ñ'); 13323 }, 13324 'localization': function localization(value) { 13325 return Validator.value(value).required('Ðоле обÑзаÑелÑно Ð´Ð»Ñ Ð·Ð°Ð¿Ð¾Ð»Ð½ÐµÐ½Ð¸Ñ'); 13326 }, 13327 'device': function device(value) { 13328 return Validator.value(value).required('Ðоле обÑзаÑелÑно Ð´Ð»Ñ Ð·Ð°Ð¿Ð¾Ð»Ð½ÐµÐ½Ð¸Ñ'); 13329 } 13330 /* 13331 'serialNumber': function (value) { 13332 return Validator.value(value).digit('ÐопÑÑкаеÑÑÑ Ð²Ð²Ð¾Ð´ ÑолÑко ÑиÑÑ').length(5, 'Ðлина ÑеÑийного номеÑа 5 ÑиÑÑ').required('Ðоле обÑзаÑелÑно Ð´Ð»Ñ Ð·Ð°Ð¿Ð¾Ð»Ð½ÐµÐ½Ð¸Ñ'); 13333 }, 13334 'buyDate': function (value) { 13335 return Validator.value(value).required('Ðоле обÑзаÑелÑно Ð´Ð»Ñ Ð·Ð°Ð¿Ð¾Ð»Ð½ÐµÐ½Ð¸Ñ'); 13336 }, 13337 'orgName': function (value) { 13338 return Validator.value(value).required('Ðоле обÑзаÑелÑно Ð´Ð»Ñ Ð·Ð°Ð¿Ð¾Ð»Ð½ÐµÐ½Ð¸Ñ'); 13339 },*/ 13340 13341 } 13342 }); 13343 this.vueComponent.setParams(this.params); 13344 return this.vueComponent; 13345 } 13346 }]); 13347 return AddPatient; 13348 }(); 13349 13350 exports.AddPatient = AddPatient; 13351 13352}((this.BX.Asteq = this.BX.Asteq || {}),BX)); 13353//# sourceMappingURL=addpatient.bundle.js.map 13354 13355/* End */ 13356;; /* /local/templates/redesign/kladr/jquery.fias.min.js?163816774812779*/ 13357; /* /frontend/rs.js?17289912601235*/ 13358; /* /local/templates/.default/components/bitrix/sale.basket.basket.line/redesign/script.
13358js?16381677485335*/ 13359; /* /local/templates/.default/components/bitrix/sale.basket.basket.line/mobile/script.js?15976823465335*/ 13360; /* /local/templates/.default/components/itech/garant/.default/script.js?178963287613606*/ 13361; /* /local/js/asteq/helper/dist/Helper.bundle.js?1597682347265687*/ 13362; /* /local/templates/.default/components/itech/subscribe/.default/script.js?16093384932059*/ 13363; /* /local/templates/.default/components/bitrix/system.auth.form/.default/script.js?15976823461522*/ 13364; /* /local/templates/.default/components/bitrix/form.result.new/feedback/script.js?17643231072889*/ 13365; /* /local/templates/.default/components/bitrix/form.result.new/request_call/script.js?16437932483281*/ 13366; /* /local/templates/.default/components/bitrix/form.result.new/ask_doctor/script.js?16539872122448*/ 13367; /* /local/templates/.default/components/bitrix/sale.location.selector.search/regions/script.js?159768234611497*/ 13368; /* /local/templates/.default/components/itech/changepass/.default/script.js?159768234610587*/ 13369; /* /local/js/asteq/addpatient/dist/addpatient.bundle.js?161158313571294*/
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.