@salla.sa/twilight 2.0.263 → 2.0.265

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).salla={})}(this,function(exports){"use strict";let notifier=function(e,t,i){return alert(e,t,i)},setNotifier=function(e){notifier=e},fire=function(e,t,i){return notifier(e,t,i)},error=function(e,t){return notifier(e,types.error,t)},info=function(e,t){return notifier(e,types.info,t)},success=function(e,t){return notifier(e,types.success,t)},logger=function(...e){return salla.config.get("trace_console")&&console.log(console.trace()),console.log(...["%cTwilight","color: #5cd5c4;font-weight:bold; border:1px solid #5cd5c4; padding: 2px 6px; border-radius: 5px;"].concat(...e))},setLogger=function(e){logger=e},log=function(...e){return logger(...e)},sallaInitiated=function(){let e=window.location.href.match(/([\?\&]danger=)[^&]+/g);e&&e.forEach(e=>{error(decodeURI(e.replace("?danger=","").replace("&danger=","")))})},types={error:"error",success:"success",info:"info"};var Notify={fire:fire,setNotifier:setNotifier,log:log,setLogger:setLogger,error:error,success:success,info:info,sallaInitiated:sallaInitiated,types:types};class BaseEvent{constructor(e){this.parent=e,this.events={},this.namespace="";e=/function (.{1,})\(/.exec(this.constructor.toString());this.className=(e&&1<e.length?e[1]:"").toLowerCase()}after_init(){this.createDynamicFunctions()}createDynamicFunctions(){Object.keys(this.events).forEach(e=>{this.createDynamicEventFuns(e),this.createDynamicListenerFuns(e)})}createDynamicEventFuns(i){if(!this[i]){let t=this;this[i]=function(...e){return t.dispatch(i,...e)}}}createDynamicListenerFuns(i){var e="on"+i.charAt(0).toUpperCase()+i.slice(1);if(!this[e]){let t=this;this[e]=function(e){return t.on(i,e)}}}getEventName(e){return e=this.events[e]||e,!this.namespace||e.includes("::")?e:this.namespace+this.parent.delimiter+e}dispatch(e,...t){return this.parent.dispatch(this.getEventName(e),...t)}on(e,t){this.parent.addListener(this.getEventName(e),t)}once(e,t){this.parent.once(this.getEventName(e),t)}register(e,t){this.on(e,t)}registerEventTemporary(e,t,i){i=i||1,emitter.many(e,i,t)}}class AuthEvents extends BaseEvent{constructor(e){super(e),this.namespace="auth",this.events={login:"login",logout:"logout",codeSent:"code.sent",codeNotSent:"code.not-sent",codeReSent:"code.re-sent",codeNotReSent:"code.not.re-sent",verified:"verified",verificationFailed:"verification.failed",loggedIn:"logged.in",registered:"registered",registrationFailed:"registration.failed",loggedOut:"logged.out",failedLogout:"failed.logout",tokenFetched:"token.fetched",refreshFailed:"refresh.failed"},this.after_init()}login(e){return e?(e.type&&this.setTypeActionOnVerified(e.type),this.next_event=e.next_event||null):this.next_event=null,this.dispatch("login",...arguments)}verified(e){return dataLayer&&(dataLayer[0].customer=e.customer),this.dispatch("verified",...arguments)}setTypeActionOnVerified(e){this.type_action_on_verified=e}getTypeActionOnVerified(){return this.type_action_on_verified||"redirect"}}class CartEvents extends BaseEvent{constructor(e){super(e),this.namespace="cart",this.events={latestFetched:"latest.fetched",latestFailed:"latest.failed",updated:"updated",itemUpdated:"item.updated",itemUpdatedFailed:"item.updated.failed",itemAdded:"item.added",itemAddedFailed:"item.added.failed",itemDeleted:"item.deleted",itemDeletedFailed:"item.deleted.failed",submitted:"submitted",submitFailed:"submit.failed",imageDeleted:"image.deleted",imageNotDeleted:"image.not.deleted",detailsFetched:"details.fetched",detailsNotFetched:"details.not.fetched",successReset:"success.reset",couponAdded:"coupon.added",couponDeleted:"coupon.deleted",couponAdditionFailed:"coupon.addition.failed",couponDeletionFailed:"coupon.deletion.failed"},this.after_init()}updated(e){return salla.cookie.set("fresh_summary",1),e&&"object"==typeof e?(e.offer&&salla.offer.event.existed(e.offer),salla.storage.set("cart.summary",{total:e.cart.total,sub_total:e.cart.sub_total,discount:e.cart.discount,real_shipping_cost:e.cart.real_shipping_cost,count:e.cart.count,shipping_cost:e.cart.free_shipping_bar?.has_free_shipping?0:e.cart.real_shipping_cost}),this.dispatch("updated",e.cart)):(salla.log("Cart summary not an object!",e),this.dispatch("updated"))}latestFetched(e){return this.updated(e.data),this.dispatch("latestFetched",e)}itemAdded(e,t){return this.updated(e.data),this.dispatch("itemAdded",e,t)}itemDeleted(e,t){return this.updated(e.data),this.dispatch("itemDeleted",e,t)}itemUpdated(e,t){return this.updated(e.data),this.dispatch("itemUpdated",e,t)}couponAdded(e,t){return this.updated(e.data),this.dispatch("couponAdded",e,t)}couponDeleted(e,t){return this.updated(e.data),this.dispatch("couponDeleted",e,t)}}class GiftEvents extends BaseEvent{constructor(e){super(e),this.namespace="gift",this.events={buyingSucceeded:"buying.succeeded",buyingFailed:"buying.failed"},this.after_init()}}class OrderEvents extends BaseEvent{constructor(e){super(e),this.namespace="order",this.events={canceled:"canceled",notCanceled:"not.canceled",orderCreated:"order.created",orderCreationFailed:"order.creation.failed",invoiceSent:"invoice.sent",invoiceNotSent:"invoice.not.sent"},this.after_init()}}class OfferEvents extends BaseEvent{constructor(e){super(e),this.namespace="offer",this.events={existed:"existed",increased:"increase",increaseFailed:"increase.failed",fetchDetailsFailed:"fetch.details.failed",detailsFetched:"details.fetched"},this.after_init()}}class ScopeEvents extends BaseEvent{constructor(e){super(e),this.namespace="scope",this.events={},this.after_init()}}class RatingEvents extends BaseEvent{constructor(e){super(e),this.namespace="rating",this.events={orderNotFetched:"order.not.fetched",orderFetched:"order.fetched",storeRated:"store.rated",storeFailed:"store.failed",productsRated:"products.rated",productsFailed:"products.failed",shippingRated:"shipping.rated",shippingFailed:"shipping.failed"},this.after_init()}}class CommentEvents extends BaseEvent{constructor(e){super(e),this.namespace="comment",this.events={added:"added",additionFailed:"addition.failed"},this.after_init()}}class LoyaltyEvents extends BaseEvent{constructor(e){super(e),this.namespace="loyalty",this.events={exchangeSucceeded:"exchange.succeeded",exchangeFailed:"exchange.failed"},this.after_init()}}class ProfileEvents extends BaseEvent{constructor(e){super(e),this.namespace="profile",this.events={updated:"updated",updateFailed:"update.failed",mobileUpdated:"mobile.updated",updateMobileFailed:"update.mobile.failed",emailUpdated:"email.updated",updateEmailFailed:"update.email.failed",verified:"verified",unverified:"unverified"},this.after_init()}}class ProductEvents extends BaseEvent{constructor(e){super(e),this.namespace="product",this.events={priceUpdated:"price.updated",priceUpdateFailed:"price.updated.failed",availabilitySubscribed:"availability.subscribed",availabilitySubscribeFailed:"availability.subscribe.failed",searchFailed:"search.failed",searchResults:"search.results"},this.after_init()}}class DocumentEvents extends BaseEvent{constructor(e){super(e),this.namespace="document",this.events={click:"click",change:"change",submit:"submit",keyup:"keyup",leaving:"leaving",request:"request",requestFailed:"request.failed"},this.after_init()}onClick(e,t){this.fireCallableFuns("click",e,t)}onChange(e,t){this.fireCallableFuns("change",e,t)}onSubmit(e,t){this.fireCallableFuns("submit",e,t)}onKeyup(e,t){this.fireCallableFuns("keyup",e,t)}fireCallableFuns(e,t,i){this.on(e,e=>{"function"!=typeof t?"function"==typeof i&&e.target.matches(t)&&i(e):t(e)})}fireEvent(e,t,...i){return this.fireEventForElements(e,t,!1,...i)}fireEventForAll(e,t,...i){return this.fireEventForElements(e,t,!0,...i)}fireEventForElements(e,t,i,...n){if("string"==typeof e){if(i)return document.querySelectorAll(e).forEach(e=>this.fireEventForElements(e,t,!1,...n));e=document.querySelector(e)}{if(e)return i=new CustomEvent(t,...n),e.dispatchEvent(i);salla.log("Failed To get element to fire event: "+t)}}}class WishlistEvents extends BaseEvent{constructor(e){super(e),this.namespace="wishlist",this.events={added:"added",removed:"removed",additionFailed:"addition.failed",removingFailed:"removing.failed"},this.after_init()}}class CurrencyEvents extends BaseEvent{constructor(e){super(e),this.namespace="currency",this.events={changed:"changed",failed:"failed",fetched:"fetched",failedToFetch:"failed.to.fetch"},this.after_init()}changed(...e){return salla.cart.api.latest().then(()=>this.dispatch("changed",...e))}}class TwilightEvents extends BaseEvent{constructor(e){super(e),this.namespace="twilight",this.events={initiated:"initiated"},this.after_init()}}var commonjsGlobal="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},eventemitter2$1={exports:{}},eventemitter2=(!function(e){function h(){this._events={},this._conf&&t.call(this,this._conf)}function t(e){e&&((this._conf=e).delimiter&&(this.delimiter=e.delimiter),e.maxListeners!==y&&(this._maxListeners=e.maxListeners),e.wildcard&&(this.wildcard=e.wildcard),e.newListener&&(this._newListener=e.newListener),e.removeListener&&(this._removeListener=e.removeListener),e.verboseMemoryLeak&&(this.verboseMemoryLeak=e.verboseMemoryLeak),e.ignoreErrors&&(this.ignoreErrors=e.ignoreErrors),this.wildcard&&(this.listenerTree={}))}function d(e,t){var i="(node) warning: possible EventEmitter memory leak detected. "+e+" listeners added. Use emitter.setMaxListeners() to increase limit.";this.verboseMemoryLeak&&(i+=" Event name: "+t+"."),"undefined"!=typeof process&&process.emitWarning?((t=new Error(i)).name="MaxListenersExceededWarning",t.emitter=this,t.count=e,process.emitWarning(t)):(console.error(i),console.trace&&console.trace())}function c(e,t,i){var n=arguments.length;switch(n){case 0:return[];case 1:return[e];case 2:return[e,t];case 3:return[e,t,i];default:for(var r=new Array(n);n--;)r[n]=arguments[n];return r}}function i(e,t){for(var i={},n=e.length,r=t?value.length:0,s=0;s<n;s++)i[e[s]]=s<r?t[s]:y;return i}function p(e,t,i){var n,r;if(this._emitter=e,this._target=t,this._listeners={},this._listenersCount=0,(i.on||i.off)&&(n=i.on,r=i.off),t.addEventListener?(n=t.addEventListener,r=t.removeEventListener):t.addListener?(n=t.addListener,r=t.removeListener):t.on&&(n=t.on,r=t.off),!n&&!r)throw Error("target does not implement any known event API");if("function"!=typeof n)throw TypeError("on method must be a function");if("function"!=typeof r)throw TypeError("off method must be a function");this._on=n,this._off=r;i=e._observers;i?i.push(this):e._observers=[this]}function f(e,t,i,n){var r=Object.assign({},t);if(!e)return r;if("object"!=typeof e)throw TypeError("options must be an object");var s,a,o,l=Object.keys(e),c=l.length;function u(e){throw Error('Invalid "'+s+'" option value'+(e?". Reason: "+e:""))}for(var h=0;h<c;h++){if(s=l[h],!n&&!b.call(t,s))throw Error('Unknown "'+s+'" option');(a=e[s])!==y&&(o=i[s],r[s]=o?o(a,u):a)}return r}function n(e,t){return"function"==typeof e&&e.hasOwnProperty("prototype")||t("value must be a constructor"),e}function r(r){var s="value must be type of "+r.join("|"),a=r.length,n=r[0],o=r[1];return 1===a?function(e,t){if(typeof e===n)return e;t(s)}:2===a?function(e,t){var i=typeof e;if(i===n||i===o)return e;t(s)}:function(e,t){for(var i=typeof e,n=a;0<n--;)if(i===r[n])return e;t(s)}}function l(a,o,l){var c,u,h,d=0,p=new a(function(t,i,e){function n(){u=u&&null,d&&(clearTimeout(d),d=0)}l=f(l,{timeout:0,overload:!1},{timeout:function(e,t){return("number"!=typeof(e*=1)||e<0||!Number.isFinite(e))&&t("timeout must be a positive number"),e}}),c=!l.overload&&"function"==typeof a.prototype.cancel&&"function"==typeof e;function r(e){n(),t(e)}function s(e){n(),i(e)}c?o(r,s,e):(u=[function(e){s(e||Error("canceled"))}],o(r,s,function(e){if(h)throw Error("Unable to subscribe on cancel event asynchronously");if("function"!=typeof e)throw TypeError("onCancel callback must be a function");u.push(e)}),h=!0),0<l.timeout&&(d=setTimeout(function(){var e=Error("timeout");e.code="ETIMEDOUT",d=0,p.cancel(e),i(e)},l.timeout))});return c||(p.cancel=function(e){if(u){for(var t=u.length,i=1;i<t;i++)u[i](e);u[0](e),u=null}}),p}function g(e){var t=this._observers;if(!t)return-1;for(var i=t.length,n=0;n<i;n++)if(t[n]._target===e)return n;return-1}function _(e,t,i,n,r){if(!i)return null;if(0===n){var s=typeof t;if("string"==s){var a,o,l=0,c=0,u=this.delimiter,h=u.length;if(-1!==(o=t.indexOf(u))){for(a=new Array(5);a[l++]=t.slice(c,o),-1!==(o=t.indexOf(u,c=o+h)););a[l++]=t.slice(c),t=a,r=l}else t=[t],r=1}else r="object"==s?t.length:(t=[t],1)}var d,p,f,g,m,v,y=null,b=t[n],w=t[n+1];if(n===r)i._listeners&&(y=("function"==typeof i._listeners?e&&e.push(i._listeners):e&&e.push.apply(e,i._listeners),[i]));else{if("*"===b){for(o=(m=x(i)).length;0<o--;)"_listeners"!==(d=m[o])&&(v=_(e,t,i[d],n+1,r))&&(y?y.push.apply(y,v):y=v);return y}if("**"===b){for((g=n+1===r||n+2===r&&"*"===w)&&i._listeners&&(y=_(e,t,i,r,r)),o=(m=x(i)).length;0<o--;)"_listeners"!==(d=m[o])&&((v="*"===d||"**"===d?(i[d]._listeners&&!g&&(v=_(e,t,i[d],r,r))&&(y?y.push.apply(y,v):y=v),_(e,t,i[d],n,r)):_(e,t,i[d],d===w?n+2:n,r))&&(y?y.push.apply(y,v):y=v));return y}i[b]&&(y=_(e,t,i[b],n+1,r))}if((s=i["*"])&&_(e,t,s,n+1,r),p=i["**"])if(n<r)for(p._listeners&&_(e,t,p,r,r),o=(m=x(p)).length;0<o--;)"_listeners"!==(d=m[o])&&(d===w?_(e,t,p[d],n+2,r):d===b?_(e,t,p[d],n+1,r):((f={})[d]=p[d],_(e,t,{"**":f},n+1,r)));else p._listeners?_(e,t,p,r,r):p["*"]&&p["*"]._listeners&&_(e,t,p["*"],r,r);return y}function u(e,t,i,n){for(var r,s,a,o=x(e),l=o.length,c=e._listeners;0<l--;)r=e[a=o[l]],s="_listeners"===a?i:i?i.concat(a):[a],a=n||"symbol"==typeof a,c&&t.push(a?s:s.join(this.delimiter)),"object"==typeof r&&u.call(this,r,t,s,a);return t}function m(e){for(var t,i,n,r=x(e),s=r.length;0<s--;)(t=e[i=r[s]])&&(n=!0,"_listeners"===i||m(t)||delete e[i]);return n}function v(e,t,i){this.emitter=e,this.event=t,this.listener=i}function s(e){this._events={},this._newListener=!1,this._removeListener=!1,this.verboseMemoryLeak=!1,t.call(this,e)}var y,b,w,S,E,a,A,x,o,L,F;b=Object.hasOwnProperty,w=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)},S="object"==typeof process&&"function"==typeof process.nextTick,E="function"==typeof Symbol,a="object"==typeof Reflect,A="function"==typeof setImmediate?setImmediate:setTimeout,x=E?a&&"function"==typeof Reflect.ownKeys?Reflect.ownKeys:function(e){var t=Object.getOwnPropertyNames(e);return t.push.apply(t,Object.getOwnPropertySymbols(e)),t}:Object.keys,Object.assign(p.prototype,{subscribe:function(i,n,r){function t(){var e=c.apply(null,arguments),t={data:e,name:n,original:i};r?!1!==r.call(a,t)&&o.emit.apply(o,[t.name].concat(e)):o.emit.apply(o,[n].concat(e))}var s=this,a=this._target,o=this._emitter,l=this._listeners;if(l[i])throw Error("Event '"+i+"' is already listening");this._listenersCount++,o._newListener&&o._removeListener&&!s._onNewListener?(this._onNewListener=function(e){e===n&&null===l[i]&&(l[i]=t,s._on.call(a,i,t))},o.on("newListener",this._onNewListener),this._onRemoveListener=function(e){e===n&&!o.hasListeners(e)&&l[i]&&(l[i]=null,s._off.call(a,i,t))},l[i]=null,o.on("removeListener",this._onRemoveListener)):(l[i]=t,s._on.call(a,i,t))},unsubscribe:function(e){var t,i,n,r=this,s=this._listeners,a=this._emitter,o=this._off,l=this._target;if(e&&"string"!=typeof e)throw TypeError("event must be a string");function c(){r._onNewListener&&(a.off("newListener",r._onNewListener),a.off("removeListener",r._onRemoveListener),r._onNewListener=null,r._onRemoveListener=null);var e=g.call(a,r);a._observers.splice(e,1)}if(e)(t=s[e])&&(o.call(l,e,t),delete s[e],--this._listenersCount||c());else{for(n=(i=x(s)).length;0<n--;)e=i[n],o.call(l,e,s[e]);this._listeners={},this._listenersCount=0,c()}}}),o=r(["function"]),L=r(["object","function"]),v.prototype.off=function(){return this.emitter.off(this.event,this.listener),this},(s.EventEmitter2=s).prototype.listenTo=function(c,e,u){if("object"!=typeof c)throw TypeError("target musts be an object");var h=this;function t(e){if("object"!=typeof e)throw TypeError("events must be an object");for(var t,i=u.reducers,n=g.call(h,c),r=-1===n?new p(h,c,u):h._observers[n],s=x(e),a=s.length,o="function"==typeof i,l=0;l<a;l++)t=s[l],r.subscribe(t,e[t]||t,o?i:i&&i[t])}return u=f(u,{on:y,off:y,reducers:y},{on:o,off:o,reducers:L}),w(e)?t(i(e)):t("string"==typeof e?i(e.split(/\s+/)):e),this},s.prototype.stopListeningTo=function(e,t){var i=this._observers;if(!i)return!1;var n,r=i.length,s=!1;if(e&&"object"!=typeof e)throw TypeError("target should be an object");for(;0<r--;)n=i[r],e&&n._target!==e||(n.unsubscribe(t),s=!0);return s},s.prototype.delimiter=".",s.prototype.setMaxListeners=function(e){e!==y&&(this._maxListeners=e,this._conf||(this._conf={}),this._conf.maxListeners=e)},s.prototype.getMaxListeners=function(){return this._maxListeners},s.prototype.event="",s.prototype.once=function(e,t,i){return this._once(e,t,!1,i)},s.prototype.prependOnceListener=function(e,t,i){return this._once(e,t,!0,i)},s.prototype._once=function(e,t,i,n){return this._many(e,1,t,i,n)},s.prototype.many=function(e,t,i,n){return this._many(e,t,i,!1,n)},s.prototype.prependMany=function(e,t,i,n){return this._many(e,t,i,!0,n)},s.prototype._many=function(e,t,i,n,r){var s=this;if("function"!=typeof i)throw new Error("many only accepts instances of Function");function a(){return 0==--t&&s.off(e,a),i.apply(this,arguments)}return a._origin=i,this._on(e,a,n,r)},s.prototype.emit=function(){if(!this._events&&!this._all)return!1;this._events||h.call(this);var e,t,i,n,r,s,a=arguments[0],o=this.wildcard;if("newListener"===a&&!this._newListener&&!this._events.newListener)return!1;if(o&&("newListener"!==(e=a)&&"removeListener"!==a&&"object"==typeof a)){if(i=a.length,E)for(n=0;n<i;n++)if("symbol"==typeof a[n]){s=!0;break}s||(a=a.join(this.delimiter))}var l,c=arguments.length;if(this._all&&this._all.length)for(n=0,i=(l=this._all.slice()).length;n<i;n++)switch(this.event=a,c){case 1:l[n].call(this,a);break;case 2:l[n].call(this,a,arguments[1]);break;case 3:l[n].call(this,a,arguments[1],arguments[2]);break;default:l[n].apply(this,arguments)}if(o)_.call(this,l=[],e,this.listenerTree,0,i);else{if("function"==typeof(l=this._events[a])){switch(this.event=a,c){case 1:l.call(this);break;case 2:l.call(this,arguments[1]);break;case 3:l.call(this,arguments[1],arguments[2]);break;default:for(t=new Array(c-1),r=1;r<c;r++)t[r-1]=arguments[r];l.apply(this,t)}return!0}l=l&&l.slice()}if(l&&l.length){if(3<c)for(t=new Array(c-1),r=1;r<c;r++)t[r-1]=arguments[r];for(n=0,i=l.length;n<i;n++)switch(this.event=a,c){case 1:l[n].call(this);break;case 2:l[n].call(this,arguments[1]);break;case 3:l[n].call(this,arguments[1],arguments[2]);break;default:l[n].apply(this,t)}return!0}if(this.ignoreErrors||this._all||"error"!==a)return!!this._all;throw arguments[1]instanceof Error?arguments[1]:new Error("Uncaught, unspecified 'error' event.")},s.prototype.emitAsync=function(){if(!this._events&&!this._all)return!1;this._events||h.call(this);var e,t,i,n,r,s,a=arguments[0],o=this.wildcard;if("newListener"===a&&!this._newListener&&!this._events.newListener)return Promise.resolve([!1]);if(o&&("newListener"!==(e=a)&&"removeListener"!==a&&"object"==typeof a)){if(n=a.length,E)for(r=0;r<n;r++)if("symbol"==typeof a[r]){t=!0;break}t||(a=a.join(this.delimiter))}var l,c=[],u=arguments.length;if(this._all)for(r=0,n=this._all.length;r<n;r++)switch(this.event=a,u){case 1:c.push(this._all[r].call(this,a));break;case 2:c.push(this._all[r].call(this,a,arguments[1]));break;case 3:c.push(this._all[r].call(this,a,arguments[1],arguments[2]));break;default:c.push(this._all[r].apply(this,arguments))}if(o?_.call(this,l=[],e,this.listenerTree,0):l=this._events[a],"function"==typeof l)switch(this.event=a,u){case 1:c.push(l.call(this));break;case 2:c.push(l.call(this,arguments[1]));break;case 3:c.push(l.call(this,arguments[1],arguments[2]));break;default:for(i=new Array(u-1),s=1;s<u;s++)i[s-1]=arguments[s];c.push(l.apply(this,i))}else if(l&&l.length){if(l=l.slice(),3<u)for(i=new Array(u-1),s=1;s<u;s++)i[s-1]=arguments[s];for(r=0,n=l.length;r<n;r++)switch(this.event=a,u){case 1:c.push(l[r].call(this));break;case 2:c.push(l[r].call(this,arguments[1]));break;case 3:c.push(l[r].call(this,arguments[1],arguments[2]));break;default:c.push(l[r].apply(this,i))}}else if(!this.ignoreErrors&&!this._all&&"error"===a)return arguments[1]instanceof Error?Promise.reject(arguments[1]):Promise.reject("Uncaught, unspecified 'error' event.");return Promise.all(c)},s.prototype.on=function(e,t,i){return this._on(e,t,!1,i)},s.prototype.prependListener=function(e,t,i){return this._on(e,t,!0,i)},s.prototype.onAny=function(e){return this._onAny(e,!1)},s.prototype.prependAny=function(e){return this._onAny(e,!0)},s.prototype.addListener=s.prototype.on,s.prototype._onAny=function(e,t){if("function"!=typeof e)throw new Error("onAny only accepts instances of Function");return this._all||(this._all=[]),t?this._all.unshift(e):this._all.push(e),this},s.prototype._on=function(e,t,i,n){if("function"==typeof e)return this._onAny(e,t),this;if("function"!=typeof t)throw new Error("on only accepts instances of Function");this._events||h.call(this);var r=this;return n!==y&&(t=(n=function(e,t,i){if(!0===i)r=!0;else if(!1===i)n=!0;else{if(!i||"object"!=typeof i)throw TypeError("options should be an object or true");var n=i.async,r=i.promisify,s=i.nextTick,a=i.objectify}if(n||s||r){var o=t,i=t._origin||t;if(s&&!S)throw Error("process.nextTick is not supported");r===y&&(r="AsyncFunction"===t.constructor.name),(t=function(){var e=arguments,t=this,i=this.event;return r?s?Promise.resolve():new Promise(function(e){A(e)}).then(function(){return t.event=i,o.apply(t,e)}):(s?process.nextTick:A)(function(){t.event=i,o.apply(t,e)})})._async=!0,t._origin=i}return[t,a?new v(this,e,t):this]}.call(this,e,t,n))[0],r=n[1]),this._newListener&&this.emit("newListener",e,t),this.wildcard?function(e,t,i){var n,r=0,s=0,a=this.delimiter,o=a.length;if("string"==typeof e)if(-1!==(u=e.indexOf(a))){for(n=new Array(5);n[r++]=e.slice(s,u),-1!==(u=e.indexOf(a,s=u+o)););n[r++]=e.slice(s)}else n=[e],r=1;else r=(n=e).length;if(1<r)for(u=0;u+1<r;u++)if("**"===n[u]&&"**"===n[u+1])return;for(var l,c=this.listenerTree,u=0;u<r;u++)if(c=c[l=n[u]]||(c[l]={}),u===r-1)return c._listeners?("function"==typeof c._listeners&&(c._listeners=[c._listeners]),i?c._listeners.unshift(t):c._listeners.push(t),!c._listeners.warned&&0<this._maxListeners&&c._listeners.length>this._maxListeners&&(c._listeners.warned=!0,d.call(this,c._listeners.length,l))):c._listeners=t,!0;return!0}.call(this,e,t,i):this._events[e]?("function"==typeof this._events[e]&&(this._events[e]=[this._events[e]]),i?this._events[e].unshift(t):this._events[e].push(t),!this._events[e].warned&&0<this._maxListeners&&this._events[e].length>this._maxListeners&&(this._events[e].warned=!0,d.call(this,this._events[e].length,e))):this._events[e]=t,r},s.prototype.off=function(e,t){if("function"!=typeof t)throw new Error("removeListener only takes instances of Function");var i=[];if(this.wildcard){var n="string"==typeof e?e.split(this.delimiter):e.slice();if(!(i=_.call(this,null,n,this.listenerTree,0)))return this}else{if(!this._events[e])return this;a=this._events[e],i.push({_listeners:a})}for(var r=0;r<i.length;r++){var s=i[r],a=s._listeners;if(w(a)){for(var o=-1,l=0,c=a.length;l<c;l++)if(a[l]===t||a[l].listener&&a[l].listener===t||a[l]._origin&&a[l]._origin===t){o=l;break}if(o<0)continue;return(this.wildcard?s._listeners:this._events[e]).splice(o,1),0===a.length&&(this.wildcard?delete s._listeners:delete this._events[e]),this._removeListener&&this.emit("removeListener",e,t),this}(a===t||a.listener&&a.listener===t||a._origin&&a._origin===t)&&(this.wildcard?delete s._listeners:delete this._events[e],this._removeListener&&this.emit("removeListener",e,t))}return this.listenerTree&&m(this.listenerTree),this},s.prototype.offAny=function(e){var t,i=0,n=0;if(e&&this._all&&0<this._all.length){for(i=0,n=(t=this._all).length;i<n;i++)if(e===t[i])return t.splice(i,1),this._removeListener&&this.emit("removeListenerAny",e),this}else{if(t=this._all,this._removeListener)for(i=0,n=t.length;i<n;i++)this.emit("removeListenerAny",t[i]);this._all=[]}return this},s.prototype.removeListener=s.prototype.off,s.prototype.removeAllListeners=function(e){if(e===y)return this._events&&h.call(this),this;if(this.wildcard){var t,i=_.call(this,null,e,this.listenerTree,0);if(!i)return this;for(t=0;t<i.length;t++)i[t]._listeners=null;this.listenerTree&&m(this.listenerTree)}else this._events&&(this._events[e]=null);return this},s.prototype.listeners=function(e){var t,i,n,r,s,a=this._events;if(e===y){if(this.wildcard)throw Error("event name required for wildcard emitter");if(!a)return[];for(r=(t=x(a)).length,n=[];0<r--;)"function"==typeof(i=a[t[r]])?n.push(i):n.push.apply(n,i);return n}if(this.wildcard){if(!(s=this.listenerTree))return[];var o=[],l="string"==typeof e?e.split(this.delimiter):e.slice();return _.call(this,o,l,s,0),o}return a&&(i=a[e])?"function"==typeof i?[i]:i:[]},s.prototype.eventNames=function(e){var t=this._events;return this.wildcard?u.call(this,this.listenerTree,[],null,e):t?x(t):[]},s.prototype.listenerCount=function(e){return this.listeners(e).length},s.prototype.hasListeners=function(e){if(this.wildcard)return i=[],t="string"==typeof e?e.split(this.delimiter):e.slice(),_.call(this,i,t,this.listenerTree,0),0<i.length;var t=this._events,i=this._all;return!!(i&&i.length||t&&(e===y?x(t).length:t[e]))},s.prototype.listenersAny=function(){return this._all||[]},s.prototype.waitFor=function(r,s){var a=this,e=typeof s;return"number"==e?s={timeout:s}:"function"==e&&(s={filter:s}),l((s=f(s,{timeout:0,filter:y,handleError:!1,Promise:Promise,overload:!1},{filter:o,Promise:n})).Promise,function(t,i,e){function n(){var e=s.filter;e&&!e.apply(a,arguments)||(a.off(r,n),s.handleError?(e=arguments[0])?i(e):t(c.apply(null,arguments).slice(1)):t(c.apply(null,arguments)))}e(function(){a.off(r,n)}),a._on(r,n,!1)},{timeout:s.timeout,overload:s.overload})},F=s.prototype,Object.defineProperties(s,{defaultMaxListeners:{get:function(){return F._maxListeners},set:function(e){if("number"!=typeof e||e<0||Number.isNaN(e))throw TypeError("n must be a non-negative number");F._maxListeners=e},enumerable:!0},once:{value:function(a,o,e){return l((e=f(e,{Promise:Promise,timeout:0,overload:!1},{Promise:n})).Promise,function(e,t,i){var n;if("function"==typeof a.addEventListener)return n=function(){e(c.apply(null,arguments))},i(function(){a.removeEventListener(o,n)}),a.addEventListener(o,n,{once:!0});function r(){s&&a.removeListener("error",s),e(c.apply(null,arguments))}var s;"error"!==o&&(s=function(e){a.removeListener(o,r),t(e)},a.once("error",s)),i(function(){s&&a.removeListener("error",s),a.removeListener(o,r)}),a.once(o,r)},{timeout:e.timeout,overload:e.overload})},writable:!0,configurable:!0}}),Object.defineProperties(F,{_maxListeners:{value:10,writable:!0,configurable:!0},_observers:{value:null,writable:!0,configurable:!0}}),e.exports=s}(eventemitter2$1),eventemitter2$1.exports);class InfiniteScrollEvents extends BaseEvent{constructor(e){super(e),this.namespace="infiniteScroll",this.events={scrollThreshold:"scroll.threshold",request:"request",load:"load",append:"append",error:"error",last:"last",history:"history"},this.after_init()}}class sallaEmitter extends eventemitter2{constructor(){super({wildcard:!0,delimiter:"::",newListener:!1,removeListener:!1,maxListeners:10,verboseMemoryLeak:!1,ignoreErrors:!1}),this.globalListners={},this.delimiter="::",this.auth=new AuthEvents(this),this.cart=new CartEvents(this),this.gift=new GiftEvents(this),this.order=new OrderEvents(this),this.offer=new OfferEvents(this),this.scope=new ScopeEvents(this),this.rating=new RatingEvents(this),this.comment=new CommentEvents(this),this.loyalty=new LoyaltyEvents(this),this.product=new ProductEvents(this),this.profile=new ProfileEvents(this),this.currency=new CurrencyEvents(this),this.document=new DocumentEvents(this),this.twilight=new TwilightEvents(this),this.wishlist=new WishlistEvents(this),this.infiniteScroll=new InfiniteScrollEvents(this),this.body=document.querySelector("body"),this.logableEvents=["cart::item.added.failed","cart::item.deleted.failed"],this.ingoreLogEvents=["document::click","document::keyup","document::change"],this.noneFireableActions=["document.request"],this.on("twilight::initiated",this.initiateSallaInAllClasses)}initiateSallaInAllClasses(){let i=this;Object.keys(salla).forEach(t=>{"object"==typeof(t=salla[t])&&(i.callSallaInitiate(t),Object.keys(t).forEach(e=>{i.callSallaInitiate(t[e])}))})}callSallaInitiate(e){e&&e.sallaInitiated&&!e.initiated&&(e.sallaInitiated(),e.initiated=!0)}createAndDispatch(e,...t){this.dispatch(e,...t)}dispatch(t,...i){let e=t.replace("::",".");if(!this.noneFireableActions.includes(e)&&"function"==typeof salla.call(e))return salla.log(`'salla.${e}(...)' triggered using event '${t}'`),e=e.split("."),void salla[e[0]][e[1]](...i);this.emit(t,...i),window.dataLayer=window.dataLayer||[],window.dataLayer.push(Object.assign({event:t},...i.values())),this.ingoreLogEvents.includes(t)||!salla.config.get("debug")&&!this.logableEvents.includes(t)||salla.notify.log("[Event] "+t,...i);let n=this;Object.keys(this.globalListners).forEach(function(e){n.globalListners[e](t,...i)}),this.dispatchMobileEvent(t,{...i.values()})}dispatchEvents(e){if(e&&"object"==typeof e)for(var[t,i]of Object.entries(e))this.dispatch(t,i);else salla.log("No Events To Dispatch!",e)}addListener(e,t){this.on(e,t)}addEventListener(e,t){this.addListener(e,t)}listen(e,t){this.addListener(e,t)}registerGlobalListener(e,t){this.globalListners[e]=t}dispatchMobileEvent(e,t={}){if(!(window.dataLayer&&dataLayer[0]&&dataLayer[0].page&&dataLayer[0].page.mobileApp))return"";if(window.webkit)try{window.webkit.messageHandlers.callbackHandler.postMessage(JSON.stringify({event:e,details:t}))}catch(e){console.log(e,"The native context does not exist yet")}else if(Android)try{Android.customEventWithData(e,JSON.stringify({details:t}))}catch(e){console.log(e,"The native context does not exist yet")}}}class BaseApi{constructor(e){this.parent=e,this.endpoints={},this.webEndpoints=[],this.namespace="BaseApi",this.endpointsMethods={},this.endpointsHeaders={};e=/function (.{1,})\(/.exec(this.constructor.toString());this.className=(e&&1<e.length?e[1]:"").toLowerCase(),this.debounce={request:void 0,time:300,enabled:!0,exclude:[]}}after_init(){}normalRequest(e,t,i=null){let n=this,r=Array.isArray(e),s=r?this.getUrl(...e):this.getUrl(e);e=r?e[0]:e,i=i||this.endpointsMethods[e]||"post";var a,o=this.endpointsHeaders[e];"get"===i&&t instanceof FormData&&(a={},Array.from(t.entries()).forEach(function(e){a[e[0]]=e[1]}),t={params:a}),o&&"get"===i&&(t=t?Object.assign(t,o):o);let l={namespace:this.namespace,action:e,url:s,payload:t,method:i,headers:o};try{salla.event.document.request(l)}catch(e){return salla.event.document.requestFailed(l),new Promise(()=>{throw e})}this.webEndpoints.includes(e)||"http"===s.substring(0,4)||(s=salla.config.get("store.api")+s);let c=event?.currentTarget,u=!1;return(u="SALLA-BUTTON"===c?.tagName?!0:u)&&c?.load(),this.parent[i](s,t,{headers:o}).then(e=>(u&&c?.stop(),e.data&&e.request&&(e=e.data),n.handleAfterResponseActions(e),e)).catch(e=>{throw u&&c?.stop(),salla.event.document.requestFailed(l,e),n.handleErrorResponse(e),e})}request(e,t,i=null){return!this.isFastRequestsAllowed()&&this.debounce.enabled?(this.debounce.request||(this.debounce.request=salla.helpers.debounce(this.normalRequest.bind(this),this.debounce.time)),this.debounce.request(e,t,i)):this.normalRequest(e,t,i)}getUrl(e){let t=this.endpoints[e]||e;var i=/{[^{}]+}/i;for(let e=1;e<arguments.length;e++)t=t.replace(i,arguments[e]);return t}handleAfterResponseActions(e){var t,i;e&&({data:i,googleTags:t=null}=e,i=i&&i.googleTags?i.googleTags:t,dataLayer&&i&&dataLayer.push(i),this.fireEventsForResponse(e),this.renderSections(e),this.showAlert(e),e.data?.token&&salla.event.auth.tokenFetched(e.data.token))}fireEventsForResponse(e){let t=e.events||e.data?.events||e.error?.events;(t="string"==typeof t?JSON.parse(t):t)&&Object.keys(t).forEach(e=>salla.event.dispatch(e,t[e]))}renderSections(i){i.sections&&Object.keys(i.sections).forEach(t=>{document.querySelectorAll(t.toSelector()).forEach(function(e){e.innerHTML=i.sections[t]})})}handleErrorResponse(e){if(e.response&&e.response.data)return e.response.data.error&&e.response.data.error.fields?this.handleInvalidFields(e):this.handleAfterResponseActions(e.response.data)}showAlert(e){if(e)return e.case&&e.msg?salla.notify.fire(e.msg,e.case,e):e.hasOwnProperty("success")&&e.data?.message?salla.notify.fire(e.data?.message,e.success?salla.notify.types.success:salla.notify.types.error,e):e.error&&e.error.message&&"FORBIDDEN"!==e.error.message?salla.error(e.error.message,e):void 0}handleInvalidFields(e){let i=e.response.data.error.fields,n=[];Object.keys(i).forEach(e=>{let t=i[e];Array.isArray(t)?t.forEach(e=>n.push(e)):n.push(t)});var t=(1<n.length?"* ":"")+n.join("\n* ");salla.error(t,e)}event(){return salla.event[this.className]}getPossibleValue(i,n,e=!1){if(i){if("object"!=typeof i)return i;let t;for(let e=0;e<n.length&&!(t=i[n[e]])&&!(i instanceof FormData&&(t=i.get(n[e])));e++);return"object"!=typeof(t=t||i)||e?t:void 0}}isFastRequestsAllowed(){return salla.config.get("fastRequests")}promise(i,n=!0){return new Promise((e,t)=>(n?e:t)(i))}errorPromise(e){return this.promise(e,!1)}successPromise(e){return this.promise(e,!0)}}class CartApi extends BaseApi{constructor(e){super(e),this.namespace="cart",this.endpoints={latest:"cart/latest",details:"cart/{cart}",quickAdd:"cart/{cart}/item/{product}/quick-add",addItem:"cart/{cart}/item/{product}/add",deleteItem:"cart/{cart}/item/{item}",updateItem:"cart/{cart}/item/{item}",deleteImage:"cart/{cart}/image/{image}",status:"cart/{cart}/status",addCoupon:"cart/{id}/coupon",deleteCoupon:"cart/{id}/coupon"},this.endpointsMethods={latest:"get",details:"get",status:"get",updateItem:"post",deleteItem:"delete",deleteImage:"delete",deleteCoupon:"put"},this.webEndpoints=["latest"],this.after_init()}async getCurrentCartId(){return salla.storage.get("cart.id")||(await this.latest()).data.cart.id}latest(){return this.request("latest",{params:{source:""}}).then(e=>(salla.storage.set("cart",e.data.cart),salla.event.cart.latestFetched(e),e)).catch(e=>{throw salla.storage.set("cart",""),salla.event.cart.latestFailed(e),e})}async details(){var e=await this.getCurrentCartId();return this.request(["details",e]).then(function(e){return salla.cart.event.detailsFetched(e),e}).catch(function(e){throw salla.cart.event.detailsNotFetched(e),e})}async quickAdd(e){return this.addItem(e)}async addItem(e){let t=this.getCartRequestData(e);if(!t.id)return e='There is no product "id"!',salla.cart.event.itemAddedFailed(e),this.errorPromise(e);var e=this.getPossibleValue(t.formData,["quantity","donating_amount"])?"addItem":"quickAdd",i=await this.getCurrentCartId();return this.request([e,i,t.id],t.formData).then(function(e){return salla.cart.event.itemAdded(e,t.id),e}).catch(function(e){throw salla.cart.event.itemAddedFailed(e,t.id),e})}async deleteItem(e){let t=this.getCartRequestData(e);if(!t.id)return e='There is no "id"!',salla.cart.event.itemDeletedFailed(e),this.errorPromise(e);e=await this.getCurrentCartId();return this.request(["deleteItem",e,t.id]).then(function(e){return salla.cart.event.itemDeleted(e,t.id),e}).catch(function(e){throw salla.cart.event.itemDeletedFailed(e,t.id),e})}async updateItem(e){let t=this.getCartRequestData(e);if(!t.id)return e='There is no "id"!',salla.cart.event.itemUpdatedFailed(e),this.errorPromise(e);e=await this.getCurrentCartId();return"object"==typeof t.formData&&("Object"===t.formData.constructor?.name?t.formData._method="PUT":t.formData.append("_method","PUT")),this.request(["updateItem",e,t.id],t.formData).then(function(e){return salla.cart.event.itemUpdated(e,t.id),e}).catch(function(e){throw salla.cart.event.itemUpdatedFailed(e,t.id),e})}async deleteImage(t){if(!(t=this.getPossibleValue(t,["id","image_id","photo_id"])))return e='There is no "id"!',salla.cart.event.imageNotDeleted(e),this.errorPromise(e);var e=await this.getCurrentCartId();return this.request(["deleteImage",e,t]).then(function(e){return salla.cart.event.imageDeleted(e,t),e}).catch(function(e){throw salla.cart.event.imageNotDeleted(e,t),e})}async status(e){return this.request(["status",e||await this.getCurrentCartId()])}async submit(){this.status(await this.getCurrentCartId()).then(e=>{var t,i=e.data.next_step.to;if(!["checkout","refresh","login"].includes(i))throw t="Can't find next_step );",salla.cart.event.submitFailed(t),t;if(salla.cart.event.submitted(e),"login"===i)return salla.auth.setCanRedirect(!1),salla.event.dispatch("login::open"),void salla.auth.event.onLoggedIn(e=>{salla.event.dispatch("login::close"),this.submit()});"checkout"===i?window.location.href=e.data.next_step.url+(window.ApplePaySession?"?has_apple_pay=true":""):window.location.reload()}).catch(function(e){throw salla.cart.event.submitFailed(e),e})}getCartRequestData(e){let t=e?.data||("object"==typeof e?e:void 0);return{id:e=t?this.getPossibleValue(t,["prod_id","item_id","id"]):e,formData:t="object"==typeof t?t:void 0}}handleAfterResponseActions(e){var t;if(403===e.status)throw salla.storage.remove("cart"),t=salla.lang.get("pages.checkout.try_again"),salla.error(t),t;super.handleAfterResponseActions(e)}reset(){salla.storage.remove("cart"),salla.cart.event.successReset()}async addCoupon(e){if(e=e.data||e,!(e=this.getPossibleValue(e,["coupon"]))){let e=new Error('There is no "Coupon Code"!');return e.name="EmptyCoupon",salla.event.cart.couponAdditionFailed(e),this.errorPromise(e)}let t=await salla.cart.api.getCurrentCartId();return this.request(["addCoupon",t],{coupon:e}).then(function(e){return salla.event.cart.couponAdded(e,t),e}).catch(function(e){throw salla.event.cart.couponAdditionFailed(e,t),e})}async deleteCoupon(){let t=await salla.cart.api.getCurrentCartId();return this.request(["deleteCoupon",t],{}).then(function(e){return salla.event.cart.couponDeleted(e,t),e}).catch(function(e){throw salla.event.cart.couponDeletionFailed(e,t),e})}}class GiftApi extends BaseApi{constructor(e){super(e),this.namespace="gift",this.endpoints={buy:"{id}/buy-as-gift"},this.webEndpoints=["buy"],this.after_init()}buy(t){var e;return(t=this.getGiftRequestData(t)).id?this.request(["buy",t.id],t.data).then(function(e){return salla.gift.event.buyingSucceeded(e,t.id),e}).catch(function(e){throw salla.gift.event.buyingFailed(e,t.id),e}):(e='There is no "id"!',salla.gift.event.buyingFailed(e),this.errorPromise(e))}getGiftRequestData(e){return{id:(e=e?.data||("object"==typeof e?e:void 0))?this.getPossibleValue(e,["id","product_id","prod_id","item_id"]):e,data:"object"==typeof e?e:void 0}}}class LoyalityApi extends BaseApi{constructor(e){super(e),this.namespace="loyalty",this.endpoints={exchange:"cart/prize/exchange_loyalty_point"},this.webEndpoints=["exchange"],this.after_init()}exchange(e){let t=e.data||{id:e};return t.id?(t.loyalty_prize_id=t.id,this.request("exchange",t).then(function(e){return salla.loyalty.event.exchangeSucceeded(e,t.id),e}).catch(function(e){throw salla.loyalty.event.exchangeFailed(e,t.id),e})):(salla.loyalty.event.exchangeFailed('There is no "id"!'),!1)}}class AuthApi extends BaseApi{constructor(e){super(e),this.namespace="auth",this.canRedirect_=!0,this.endpoints={login:"auth/{type}/send_verification",resend:"auth/resend_verification",verify:"auth/{type}/verify",register:"auth/register",logout:"logout",refresh:"auth/refresh"},this.webEndpoints=["logout","auth/jwt","refresh"],this.endpointsMethods={logout:"get"},this.after_init()}setCanRedirect(e){salla.api.auth.canRedirect_=e}canRedirect(){return salla.api.auth.canRedirect_}login(t,e){let i;return t.data&&(i=t.element,e=t.data,t=this.getPossibleValue(e,["type"])),e||"object"!=typeof t||(e=t),(t=this.getPossibleValue(t,["type"]))?this.request(["login",t],e).then(function(e){return salla.auth.event.codeSent.call(i,e,t),e}).catch(function(e){throw salla.auth.event.codeNotSent.call(i,e,t),e}):(e="Failed to know what's login type!",salla.auth.event.codeNotSent(e),this.errorPromise(e))}async verify(e,t=!0){var i=this.getPossibleValue(e,["type"]);if(!i)return n="Failed to know what's login type!",salla.auth.event.verificationFailed(n),this.errorPromise(n);salla.auth.event.next_event&&(e.next_event=salla.auth.event.next_event);var n=await this.request(["verify",i],e);return 200!==n?.status?(salla.auth.event.verificationFailed(n,i),this.errorPromise(n)):(t&&await this.request("auth/jwt"),"authenticated"===n.data?.case&&salla.auth.event.loggedIn(n),salla.auth.event.verified(n,i),this.successPromise(n))}resend(t){let e;return(t=t.data||t).type=t.type||"mobile","mobile"!==t.type||t.phone&&t.country_code?"email"!==t.type||t.email?this.request("resend",t).then(function(e){return salla.auth.event.codeReSent(e,t),e}).catch(function(e){throw salla.auth.event.codeNotReSent(e,t),e}):(salla.auth.event.codeNotReSent(e="There is no email!",t),this.errorPromise(e)):(salla.auth.event.codeNotReSent(e="There is no phone or country_code!",t),this.errorPromise(e))}register(e){let t;return e.data&&(t=e.element,e=e.data),salla.auth.event.next_event&&(e.next_event=salla.auth.event.next_event),this.request("register",e).then(function(e){return salla.auth.event.registered.call(t,e),"authenticated"===e.data?.case&&salla.auth.event.loggedIn(e),e}).catch(function(e){throw salla.auth.event.registrationFailed.call(t,e),e})}logout(){return this.request("logout").then(function(e){return salla.auth.event.loggedOut(e),salla.log("Reloading after 0.1 sec..."),setTimeout(()=>location.reload(),100),e}).catch(function(e){throw salla.auth.event.failedLogout(e),e})}refresh(){return this.request("refresh").catch(function(e){throw salla.auth.event.refreshFailed(e),e})}}class OrderApi extends BaseApi{constructor(e){super(e),this.namespace="order",this.endpoints={cancel:"orders/cancel/{id}",createCartFromOrder:"reorder/{id}",sendInvoice:"orders/send/{id}"},this.endpointsMethods={createCartFromOrder:"get"},this.after_init()}show(e,t=null){salla.event.dispatch("mobile::order.placed",{order_id:e||salla.config.get("page.id")}),location.href=t||location.href.replace("thankyou","order")}cancel(t){return t=t||salla.config.get("page.id"),this.request(["cancel",t],{params:{has_apple_pay:!!window.ApplePaySession}}).then(function(e){return salla.event.order.canceled(e,t),e}).catch(function(e){throw salla.event.order.notCanceled(e,t),e})}createCartFromOrder(t){return t=t||salla.config.get("page.id"),this.request(["createCartFromOrder",t]).then(function(e){return salla.storage.set("cart",{id:e.data.cart_id,user_id:salla.config.get("user.id")}),salla.event.order.orderCreated(e,t),window.location.href=e.data.url,e}).catch(function(e){throw salla.event.order.orderCreationFailed(e,t),e})}sendInvoice(e){let t=this.getPossibleValue(e,["id"])||salla.config.get("page.id");var i;return!t||isNaN(t)?(i="There is no id!",salla.order.event.invoiceNotSent(i),this.errorPromise(i)):this.request(["sendInvoice",t],e).then(e=>(salla.event.order.invoiceSent(e,t),e)).catch(e=>{throw salla.event.order.invoiceNotSent(e,t),e})}}class OfferApi extends BaseApi{constructor(e){super(e),this.namespace="offer",this.endpoints={increase:"products/special-offer-popup/{product_id}/increase",details:"products/{product_id}/specialoffer"},this.webEndpoints=["popup","increase"],this.endpointsMethods={increase:"get"},this.after_init()}details(t){var e;return(t=this.getPossibleValue(t.data|t,["product_id"]))?this.request(["details",t]).then(function(e){return salla.offer.event.detailsFetched(e,t),e}).catch(function(e){throw salla.offer.event.fetchDetailsFailed(e,t),e}):(e='There is no "product_id"!',salla.offer.event.fetchDetailsFailed(e),this.errorPromise(e))}increase(e){let t;return e&&e.data&&(t=e.data,e=this.getPossibleValue(t,["id","product_id"])),e?this.request(["increase",e],t).then(function(e){return salla.offer.event.increased(e),e}).catch(function(e){throw salla.offer.event.increaseFailed(e),e}):(salla.offer.event.increaseFailed('There is no "product_id"!'),!1)}}class ProductApi extends BaseApi{constructor(e){super(e),this.namespace="product",this.previousQuery="",this.endpoints={getPrice:"products/{id}/price",availabilitySubscribe:"products/{id}/availability-notify",search:"products/search",categories:"products/categories",purchaseNow:"checkout/quick-purchase/{id}"},this.webEndpoints=["purchaseNow"],this.after_init()}getPrice(t){var e=t.data||t;return t=this.getPossibleValue(e,["id","prod_id"]),this.request(["getPrice",t],"object"==typeof e?e:void 0).then(function(e){return salla.product.event.priceUpdated(e,t),e}).catch(function(e){throw salla.product.event.priceUpdateFailed(e,t),e})}availabilitySubscribe(t){var e=t.data||t;return t=this.getPossibleValue(e,["id","prod_id"]),this.request(["availabilitySubscribe",t],"object"==typeof e?e:void 0).then(function(e){return salla.product.event.availabilitySubscribed(e,t),e}).catch(function(e){throw salla.product.event.availabilitySubscribedFailed(e,t),e})}search(t){let e=t.data;var i;return e=e||{params:"string"==typeof t?{query:t}:t},(t=e instanceof FormData?e.get("query"):e.query||e.params?.query)?t===salla.api.product.previousQuery?(i="Query is same as previous one!",salla.product.event.searchFailed(i),salla.api.product.previousQuery=null,this.errorPromise(i)):(salla.api.product.previousQuery=t,this.request("search",e,"get").then(function(e){return salla.product.event.searchResults(e,t),e}).catch(function(e){throw salla.product.event.searchFailed(e,t),e})):(i='There is no "query"!',salla.product.event.searchFailed(i),this.errorPromise(i))}purchaseNow(e){if(salla.config.isGuest())return salla.auth.event.dispatch("login");let t=e.product_data,i=this.getPossibleValue(t,["id","prod_id"]);if(!e.is_applepay)return this.request(["quickPurchase",i],"object"==typeof t?t:void 0).then(function(e){return e}).catch(function(e){throw e});salla.event.dispatch("payments::apple-pay.start-transaction",{amount:e.total,currency:e.currency,requiredShippingContactFields:e.require_shipping?["postalAddress"]:null,shippingMethods:e.require_shipping?[]:null,supportedNetworks:e.applepay_supported_networks,validateMerchant:{url:baseUrl+"checkout/applepay/validate",onFailed:({})=>{console.log("validateMerchant Failed!")},onSuccess:e=>(console.log("validateMerchant Success"),this.request(["quickPurchase",i],"object"==typeof t?t:void 0))},authorized:{url:baseUrl+"/checkout/{id}/payments/submit",onFailed:e=>{console.log("authorized Failed!"),window.Salla.Payments.ApplePay.onCancel({},e.data.error.message)},onSuccess:e=>{console.log(e),window.location.href=e.redirect.url,console.log("authorized Success:: redirect to thank you page, order placed")}},shippingMethodSelected:e.require_shipping?{url:baseUrl+"/checkout/{id}/shipping/details",onFailed:e=>{console.log("select shipping method failed!")},onSuccess:e=>{console.log("select shipping method success")}}:null,shippingContactSelected:e.require_shipping?{url:baseUrl+"/checkout/{id}/address/add",onFailed:e=>{console.log("created contact failed!")},onSuccess:e=>{console.log("created contact success : ",e.data.address_id)}}:null,recalculateTotal:{url:baseUrl+"/checkout/{id}/payments/recalculate"},onError:function(e){console.log(e),salla.notify.error(e)}})}}class ProfileApi extends BaseApi{constructor(e){super(e),this.namespace="profile",this.endpoints={update:"profile/update",updateMobile:"profile/update_mobile",updateEmail:"profile/update_email",verify:"profile/verify"},this.after_init()}update(e){return this.request("update",e).then(e=>(salla.profile.event.updated(e),e)).catch(e=>{throw salla.event.profile.updateFailed(e),e})}updateMobile(e){return this.request("updateMobile",e).then(e=>(salla.profile.event.mobileUpdated(e),e)).catch(e=>{throw salla.event.profile.updateMobileFailed(e),e})}updateEmail(e){return this.request("updateEmail",e).then(e=>(salla.profile.event.emailUpdated(e),e)).catch(e=>{throw salla.event.profile.updateEmailFailed(e),e})}verify(e){return this.request("verify",e).then(e=>(salla.profile.event.verified(e),e)).catch(e=>{throw salla.event.profile.unVerified(e),e})}}class CommentApi extends BaseApi{constructor(e){super(e),this.namespace="comment",this.endpoints={add:"{type}/{id}/comments"},this.after_init()}add(e){e?.data&&(e=e.data);let t,{id:i,type:n,comment:r}=Object.fromEntries(e);return i?n&&["products","pages","product","page"].includes(n)?r?(n+=["product","page"].includes(n)?"s":"",this.request(["add",n,i],{comment:r}).then(function(e){return salla.event.comment.added(e,i),e}).catch(function(e){throw salla.event.comment.additionFailed(e,i),e})):(salla.event.comment.additionFailed(t="can't find comment content!"),this.errorPromise(t)):(salla.event.comment.additionFailed(t="Failed to get type one of:(products, product, page, pages)!"),this.errorPromise(t)):(salla.event.comment.additionFailed(t="Failed to get id!"),this.errorPromise(t))}}class CurrencyApi extends BaseApi{constructor(e){super(e),this.namespace="currency",this.endpoints={change:"/",list:"currencies"},this.endpointsMethods={change:"get",list:"get"},this.webEndpoints=["change"],this.after_init()}change(t){var e;return(t=this.getPossibleValue(t.data||t,["currency","code"]))?this.request("change",{params:{change_currency:"",currency:t}}).then(function(e){return salla.currency.event.changed(e,t),salla.cookie.set("fresh_summary",1),e}).catch(function(e){throw salla.currency.event.failed(e,t),e}):(e="Can't find currency code!",salla.currency.event.failed(e),this.errorPromise(e))}list(){return this.request("list").then(function(e){return salla.currency.event.fetched(e),e}).catch(function(e){throw salla.currency.event.failedToFetch(e),e})}}class DocumentApi extends BaseApi{constructor(e){super(e),this.namespace="document"}}class RatingApi extends BaseApi{constructor(e){super(e),this.namespace="rating",this.endpoints={store:"rating/store",products:"rating/products",shipping:"rating/shipping",order:"rating/{order_id}"},this.endpointsMethods={order:"get"},this.after_init()}order(t){var e="object"==typeof t?t:{};return(t=this.getPossibleValue(t,["order_id","id"]))?this.request(["order",t],e).then(function(e){return salla.event.rating.orderFetched(e,t),e}).catch(function(e){throw salla.event.rating.orderNotFetched(e,t),e}):(e='There is no "order_id"!',salla.event.rating.orderNotFetched(e),this.errorPromise(e))}store(t){var e;return(t=t.data||t)?this.request("store",t).then(function(e){return salla.event.rating.storeRated(e,t),e}).catch(function(e){throw salla.event.rating.storeFailed(e,t),e}):(e='There is no "data"!',salla.event.rating.storeFailed(e),this.errorPromise(e))}products(t){var e;return(t=t.data||t)?this.request("products",t).then(function(e){return salla.event.rating.productsRated(e,t),e}).catch(function(e){throw salla.event.rating.productsFailed(e,t),e}):(e='There is no "data"!',salla.event.rating.productsFailed(e),this.errorPromise(e))}shipping(t){var e;return(t=t.data||t)?this.request("shipping",t).then(function(e){return salla.event.rating.shippingRated(e,t),e}).catch(function(e){throw salla.event.rating.shippingFailed(e,t),e}):(e='There is no "data"!',salla.event.rating.shippingFailed(e),this.errorPromise(e))}}class SallaInit{constructor(e){salla.config.merge(e),e&&(e._token&&(salla.api.defaults.headers.common["X-CSRF-TOKEN"]=e._token),this.injectMaintenanceAlert(),this.injectThemePreviewAlert(),this.injectEditAlert(),salla.lang.loadStoreTranslations()),salla.twilight.event.initiated(e)}injectMaintenanceAlert(){salla.config.get("maintenance")&&(document.querySelector(".store-notify")?salla.log("store-notify Existed before!"):salla.lang.onLoaded(()=>{var e=document.createElement("div");e.classList.add("store-notify"),e.style="background-color: #d63031; color: #fff; padding: 10px 15px; text-align: center; font-size: 17px;",e.innerHTML=`<p style="margin:0 !important;">${salla.lang.get("blocks.header.maintenance_alert")}</p>`,document.body.prepend(e)}))}injectThemePreviewAlert(){"preview"===salla.config.get("theme.mode")&&(document.querySelector("#s-theme_preview_bar")?salla.log("s-theme_preview_bar Existed before!"):salla.lang.onLoaded(()=>{let e=document.createElement("div");e.id="s-theme_preview_bar",e.setAttribute("style","display: flex; justify-content: space-between; text-align: center; background-color: #232323; color: #fff; padding: 10px; font-size: 0.875rem; line-height: 1.25rem; position: relative;"),e.innerHTML=`
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).salla={})}(this,function(exports){"use strict";let notifier=function(e,t,i){return alert(e,t,i)},setNotifier=function(e){notifier=e},fire=function(e,t,i){return notifier(e,t,i)},error=function(e,t){return notifier(e,types.error,t)},info=function(e,t){return notifier(e,types.info,t)},success=function(e,t){return notifier(e,types.success,t)},logger=function(...e){return salla.config.get("trace_console")&&console.log(console.trace()),console.log(...["%cTwilight","color: #5cd5c4;font-weight:bold; border:1px solid #5cd5c4; padding: 2px 6px; border-radius: 5px;"].concat(...e))},setLogger=function(e){logger=e},log=function(...e){return logger(...e)},sallaInitiated=function(){let e=window.location.href.match(/([\?\&]danger=)[^&]+/g);e&&e.forEach(e=>{error(decodeURI(e.replace("?danger=","").replace("&danger=","")))})},types={error:"error",success:"success",info:"info"};var Notify={fire:fire,setNotifier:setNotifier,log:log,setLogger:setLogger,error:error,success:success,info:info,sallaInitiated:sallaInitiated,types:types};class BaseEvent{constructor(e){this.parent=e,this.events={},this.namespace="";e=/function (.{1,})\(/.exec(this.constructor.toString());this.className=(e&&1<e.length?e[1]:"").toLowerCase()}after_init(){this.createDynamicFunctions()}createDynamicFunctions(){Object.keys(this.events).forEach(e=>{this.createDynamicEventFuns(e),this.createDynamicListenerFuns(e)})}createDynamicEventFuns(i){if(!this[i]){let t=this;this[i]=function(...e){return t.dispatch(i,...e)}}}createDynamicListenerFuns(i){var e="on"+i.charAt(0).toUpperCase()+i.slice(1);if(!this[e]){let t=this;this[e]=function(e){return t.on(i,e)}}}getEventName(e){return e=this.events[e]||e,!this.namespace||e.includes("::")?e:this.namespace+this.parent.delimiter+e}dispatch(e,...t){return this.parent.dispatch(this.getEventName(e),...t)}on(e,t){this.parent.addListener(this.getEventName(e),t)}once(e,t){this.parent.once(this.getEventName(e),t)}register(e,t){this.on(e,t)}registerEventTemporary(e,t,i){i=i||1,emitter.many(e,i,t)}}class AuthEvents extends BaseEvent{constructor(e){super(e),this.namespace="auth",this.events={login:"login",logout:"logout",codeSent:"code.sent",codeNotSent:"code.not-sent",codeReSent:"code.re-sent",codeNotReSent:"code.not.re-sent",verified:"verified",verificationFailed:"verification.failed",loggedIn:"logged.in",registered:"registered",registrationFailed:"registration.failed",loggedOut:"logged.out",failedLogout:"failed.logout",tokenFetched:"token.fetched",refreshFailed:"refresh.failed"},this.after_init()}login(e){return e?(e.type&&this.setTypeActionOnVerified(e.type),this.next_event=e.next_event||null):this.next_event=null,this.dispatch("login",...arguments)}verified(e){return dataLayer&&(dataLayer[0].customer=e.customer),this.dispatch("verified",...arguments)}setTypeActionOnVerified(e){this.type_action_on_verified=e}getTypeActionOnVerified(){return this.type_action_on_verified||"redirect"}}class CartEvents extends BaseEvent{constructor(e){super(e),this.namespace="cart",this.events={latestFetched:"latest.fetched",latestFailed:"latest.failed",updated:"updated",itemUpdated:"item.updated",itemUpdatedFailed:"item.updated.failed",itemAdded:"item.added",itemAddedFailed:"item.added.failed",itemDeleted:"item.deleted",itemDeletedFailed:"item.deleted.failed",submitted:"submitted",submitFailed:"submit.failed",imageDeleted:"image.deleted",imageNotDeleted:"image.not.deleted",detailsFetched:"details.fetched",detailsNotFetched:"details.not.fetched",successReset:"success.reset",couponAdded:"coupon.added",couponDeleted:"coupon.deleted",couponAdditionFailed:"coupon.addition.failed",couponDeletionFailed:"coupon.deletion.failed"},this.after_init()}updated(e){return salla.cookie.set("fresh_summary",1),e&&"object"==typeof e?(e.offer&&salla.offer.event.existed(e.offer),salla.storage.set("cart.summary",{total:e.cart.total,sub_total:e.cart.sub_total,discount:e.cart.discount,real_shipping_cost:e.cart.real_shipping_cost,count:e.cart.count,shipping_cost:e.cart.free_shipping_bar?.has_free_shipping?0:e.cart.real_shipping_cost}),this.dispatch("updated",e.cart)):(salla.log("Cart summary not an object!",e),this.dispatch("updated"))}latestFetched(e){return this.updated(e.data),this.dispatch("latestFetched",e)}itemAdded(e,t){return this.updated(e.data),this.dispatch("itemAdded",e,t)}itemDeleted(e,t){return this.updated(e.data),this.dispatch("itemDeleted",e,t)}itemUpdated(e,t){return this.updated(e.data),this.dispatch("itemUpdated",e,t)}couponAdded(e,t){return this.updated(e.data),this.dispatch("couponAdded",e,t)}couponDeleted(e,t){return this.updated(e.data),this.dispatch("couponDeleted",e,t)}}class GiftEvents extends BaseEvent{constructor(e){super(e),this.namespace="gift",this.events={buyingSucceeded:"buying.succeeded",buyingFailed:"buying.failed"},this.after_init()}}class OrderEvents extends BaseEvent{constructor(e){super(e),this.namespace="order",this.events={canceled:"canceled",notCanceled:"not.canceled",orderCreated:"order.created",orderCreationFailed:"order.creation.failed",invoiceSent:"invoice.sent",invoiceNotSent:"invoice.not.sent"},this.after_init()}}class OfferEvents extends BaseEvent{constructor(e){super(e),this.namespace="offer",this.events={existed:"existed",increased:"increase",increaseFailed:"increase.failed",fetchDetailsFailed:"fetch.details.failed",detailsFetched:"details.fetched"},this.after_init()}}class ScopeEvents extends BaseEvent{constructor(e){super(e),this.namespace="scope",this.events={},this.after_init()}}class RatingEvents extends BaseEvent{constructor(e){super(e),this.namespace="rating",this.events={orderNotFetched:"order.not.fetched",orderFetched:"order.fetched",storeRated:"store.rated",storeFailed:"store.failed",productsRated:"products.rated",productsFailed:"products.failed",shippingRated:"shipping.rated",shippingFailed:"shipping.failed"},this.after_init()}}class CommentEvents extends BaseEvent{constructor(e){super(e),this.namespace="comment",this.events={added:"added",additionFailed:"addition.failed"},this.after_init()}}class LoyaltyEvents extends BaseEvent{constructor(e){super(e),this.namespace="loyalty",this.events={exchangeSucceeded:"exchange.succeeded",exchangeFailed:"exchange.failed"},this.after_init()}}class ProfileEvents extends BaseEvent{constructor(e){super(e),this.namespace="profile",this.events={updated:"updated",updateFailed:"update.failed",contactsUpdated:"contacts.updated",updateContactsFailed:"update.contacts.failed",verified:"verified",unverified:"unverified"},this.after_init()}}class ProductEvents extends BaseEvent{constructor(e){super(e),this.namespace="product",this.events={priceUpdated:"price.updated",priceUpdateFailed:"price.updated.failed",availabilitySubscribed:"availability.subscribed",availabilitySubscribeFailed:"availability.subscribe.failed",categoriesFetched:"categories.fetched",categoriesFailed:"categories.failed",searchFailed:"search.failed",searchResults:"search.results"},this.after_init()}}class DocumentEvents extends BaseEvent{constructor(e){super(e),this.namespace="document",this.events={click:"click",change:"change",submit:"submit",keyup:"keyup",leaving:"leaving",request:"request",requestFailed:"request.failed"},this.after_init()}onClick(e,t){this.fireCallableFuns("click",e,t)}onChange(e,t){this.fireCallableFuns("change",e,t)}onSubmit(e,t){this.fireCallableFuns("submit",e,t)}onKeyup(e,t){this.fireCallableFuns("keyup",e,t)}fireCallableFuns(e,t,i){this.on(e,e=>{"function"!=typeof t?"function"==typeof i&&e.target.matches(t)&&i(e):t(e)})}fireEvent(e,t,...i){return this.fireEventForElements(e,t,!1,...i)}fireEventForAll(e,t,...i){return this.fireEventForElements(e,t,!0,...i)}fireEventForElements(e,t,i,...n){if("string"==typeof e){if(i)return document.querySelectorAll(e).forEach(e=>this.fireEventForElements(e,t,!1,...n));e=document.querySelector(e)}{if(e)return i=new CustomEvent(t,...n),e.dispatchEvent(i);salla.log("Failed To get element to fire event: "+t)}}}class WishlistEvents extends BaseEvent{constructor(e){super(e),this.namespace="wishlist",this.events={added:"added",removed:"removed",additionFailed:"addition.failed",removingFailed:"removing.failed"},this.after_init()}}class CurrencyEvents extends BaseEvent{constructor(e){super(e),this.namespace="currency",this.events={changed:"changed",failed:"failed",fetched:"fetched",failedToFetch:"failed.to.fetch"},this.after_init()}changed(...e){return salla.cart.api.latest().then(()=>this.dispatch("changed",...e))}}class TwilightEvents extends BaseEvent{constructor(e){super(e),this.namespace="twilight",this.events={initiated:"initiated"},this.after_init()}}var commonjsGlobal="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},eventemitter2$1={exports:{}},eventemitter2=(!function(e){function h(){this._events={},this._conf&&t.call(this,this._conf)}function t(e){e&&((this._conf=e).delimiter&&(this.delimiter=e.delimiter),e.maxListeners!==y&&(this._maxListeners=e.maxListeners),e.wildcard&&(this.wildcard=e.wildcard),e.newListener&&(this._newListener=e.newListener),e.removeListener&&(this._removeListener=e.removeListener),e.verboseMemoryLeak&&(this.verboseMemoryLeak=e.verboseMemoryLeak),e.ignoreErrors&&(this.ignoreErrors=e.ignoreErrors),this.wildcard&&(this.listenerTree={}))}function d(e,t){var i="(node) warning: possible EventEmitter memory leak detected. "+e+" listeners added. Use emitter.setMaxListeners() to increase limit.";this.verboseMemoryLeak&&(i+=" Event name: "+t+"."),"undefined"!=typeof process&&process.emitWarning?((t=new Error(i)).name="MaxListenersExceededWarning",t.emitter=this,t.count=e,process.emitWarning(t)):(console.error(i),console.trace&&console.trace())}function c(e,t,i){var n=arguments.length;switch(n){case 0:return[];case 1:return[e];case 2:return[e,t];case 3:return[e,t,i];default:for(var r=new Array(n);n--;)r[n]=arguments[n];return r}}function i(e,t){for(var i={},n=e.length,r=t?value.length:0,s=0;s<n;s++)i[e[s]]=s<r?t[s]:y;return i}function p(e,t,i){var n,r;if(this._emitter=e,this._target=t,this._listeners={},this._listenersCount=0,(i.on||i.off)&&(n=i.on,r=i.off),t.addEventListener?(n=t.addEventListener,r=t.removeEventListener):t.addListener?(n=t.addListener,r=t.removeListener):t.on&&(n=t.on,r=t.off),!n&&!r)throw Error("target does not implement any known event API");if("function"!=typeof n)throw TypeError("on method must be a function");if("function"!=typeof r)throw TypeError("off method must be a function");this._on=n,this._off=r;i=e._observers;i?i.push(this):e._observers=[this]}function f(e,t,i,n){var r=Object.assign({},t);if(!e)return r;if("object"!=typeof e)throw TypeError("options must be an object");var s,a,o,l=Object.keys(e),c=l.length;function u(e){throw Error('Invalid "'+s+'" option value'+(e?". Reason: "+e:""))}for(var h=0;h<c;h++){if(s=l[h],!n&&!b.call(t,s))throw Error('Unknown "'+s+'" option');(a=e[s])!==y&&(o=i[s],r[s]=o?o(a,u):a)}return r}function n(e,t){return"function"==typeof e&&e.hasOwnProperty("prototype")||t("value must be a constructor"),e}function r(r){var s="value must be type of "+r.join("|"),a=r.length,n=r[0],o=r[1];return 1===a?function(e,t){if(typeof e===n)return e;t(s)}:2===a?function(e,t){var i=typeof e;if(i===n||i===o)return e;t(s)}:function(e,t){for(var i=typeof e,n=a;0<n--;)if(i===r[n])return e;t(s)}}function l(a,o,l){var c,u,h,d=0,p=new a(function(t,i,e){function n(){u=u&&null,d&&(clearTimeout(d),d=0)}l=f(l,{timeout:0,overload:!1},{timeout:function(e,t){return("number"!=typeof(e*=1)||e<0||!Number.isFinite(e))&&t("timeout must be a positive number"),e}}),c=!l.overload&&"function"==typeof a.prototype.cancel&&"function"==typeof e;function r(e){n(),t(e)}function s(e){n(),i(e)}c?o(r,s,e):(u=[function(e){s(e||Error("canceled"))}],o(r,s,function(e){if(h)throw Error("Unable to subscribe on cancel event asynchronously");if("function"!=typeof e)throw TypeError("onCancel callback must be a function");u.push(e)}),h=!0),0<l.timeout&&(d=setTimeout(function(){var e=Error("timeout");e.code="ETIMEDOUT",d=0,p.cancel(e),i(e)},l.timeout))});return c||(p.cancel=function(e){if(u){for(var t=u.length,i=1;i<t;i++)u[i](e);u[0](e),u=null}}),p}function g(e){var t=this._observers;if(!t)return-1;for(var i=t.length,n=0;n<i;n++)if(t[n]._target===e)return n;return-1}function _(e,t,i,n,r){if(!i)return null;if(0===n){var s=typeof t;if("string"==s){var a,o,l=0,c=0,u=this.delimiter,h=u.length;if(-1!==(o=t.indexOf(u))){for(a=new Array(5);a[l++]=t.slice(c,o),-1!==(o=t.indexOf(u,c=o+h)););a[l++]=t.slice(c),t=a,r=l}else t=[t],r=1}else r="object"==s?t.length:(t=[t],1)}var d,p,f,g,m,v,y=null,b=t[n],w=t[n+1];if(n===r)i._listeners&&(y=("function"==typeof i._listeners?e&&e.push(i._listeners):e&&e.push.apply(e,i._listeners),[i]));else{if("*"===b){for(o=(m=x(i)).length;0<o--;)"_listeners"!==(d=m[o])&&(v=_(e,t,i[d],n+1,r))&&(y?y.push.apply(y,v):y=v);return y}if("**"===b){for((g=n+1===r||n+2===r&&"*"===w)&&i._listeners&&(y=_(e,t,i,r,r)),o=(m=x(i)).length;0<o--;)"_listeners"!==(d=m[o])&&((v="*"===d||"**"===d?(i[d]._listeners&&!g&&(v=_(e,t,i[d],r,r))&&(y?y.push.apply(y,v):y=v),_(e,t,i[d],n,r)):_(e,t,i[d],d===w?n+2:n,r))&&(y?y.push.apply(y,v):y=v));return y}i[b]&&(y=_(e,t,i[b],n+1,r))}if((s=i["*"])&&_(e,t,s,n+1,r),p=i["**"])if(n<r)for(p._listeners&&_(e,t,p,r,r),o=(m=x(p)).length;0<o--;)"_listeners"!==(d=m[o])&&(d===w?_(e,t,p[d],n+2,r):d===b?_(e,t,p[d],n+1,r):((f={})[d]=p[d],_(e,t,{"**":f},n+1,r)));else p._listeners?_(e,t,p,r,r):p["*"]&&p["*"]._listeners&&_(e,t,p["*"],r,r);return y}function u(e,t,i,n){for(var r,s,a,o=x(e),l=o.length,c=e._listeners;0<l--;)r=e[a=o[l]],s="_listeners"===a?i:i?i.concat(a):[a],a=n||"symbol"==typeof a,c&&t.push(a?s:s.join(this.delimiter)),"object"==typeof r&&u.call(this,r,t,s,a);return t}function m(e){for(var t,i,n,r=x(e),s=r.length;0<s--;)(t=e[i=r[s]])&&(n=!0,"_listeners"===i||m(t)||delete e[i]);return n}function v(e,t,i){this.emitter=e,this.event=t,this.listener=i}function s(e){this._events={},this._newListener=!1,this._removeListener=!1,this.verboseMemoryLeak=!1,t.call(this,e)}var y,b,w,S,E,a,A,x,o,L,F;b=Object.hasOwnProperty,w=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)},S="object"==typeof process&&"function"==typeof process.nextTick,E="function"==typeof Symbol,a="object"==typeof Reflect,A="function"==typeof setImmediate?setImmediate:setTimeout,x=E?a&&"function"==typeof Reflect.ownKeys?Reflect.ownKeys:function(e){var t=Object.getOwnPropertyNames(e);return t.push.apply(t,Object.getOwnPropertySymbols(e)),t}:Object.keys,Object.assign(p.prototype,{subscribe:function(i,n,r){function t(){var e=c.apply(null,arguments),t={data:e,name:n,original:i};r?!1!==r.call(a,t)&&o.emit.apply(o,[t.name].concat(e)):o.emit.apply(o,[n].concat(e))}var s=this,a=this._target,o=this._emitter,l=this._listeners;if(l[i])throw Error("Event '"+i+"' is already listening");this._listenersCount++,o._newListener&&o._removeListener&&!s._onNewListener?(this._onNewListener=function(e){e===n&&null===l[i]&&(l[i]=t,s._on.call(a,i,t))},o.on("newListener",this._onNewListener),this._onRemoveListener=function(e){e===n&&!o.hasListeners(e)&&l[i]&&(l[i]=null,s._off.call(a,i,t))},l[i]=null,o.on("removeListener",this._onRemoveListener)):(l[i]=t,s._on.call(a,i,t))},unsubscribe:function(e){var t,i,n,r=this,s=this._listeners,a=this._emitter,o=this._off,l=this._target;if(e&&"string"!=typeof e)throw TypeError("event must be a string");function c(){r._onNewListener&&(a.off("newListener",r._onNewListener),a.off("removeListener",r._onRemoveListener),r._onNewListener=null,r._onRemoveListener=null);var e=g.call(a,r);a._observers.splice(e,1)}if(e)(t=s[e])&&(o.call(l,e,t),delete s[e],--this._listenersCount||c());else{for(n=(i=x(s)).length;0<n--;)e=i[n],o.call(l,e,s[e]);this._listeners={},this._listenersCount=0,c()}}}),o=r(["function"]),L=r(["object","function"]),v.prototype.off=function(){return this.emitter.off(this.event,this.listener),this},(s.EventEmitter2=s).prototype.listenTo=function(c,e,u){if("object"!=typeof c)throw TypeError("target musts be an object");var h=this;function t(e){if("object"!=typeof e)throw TypeError("events must be an object");for(var t,i=u.reducers,n=g.call(h,c),r=-1===n?new p(h,c,u):h._observers[n],s=x(e),a=s.length,o="function"==typeof i,l=0;l<a;l++)t=s[l],r.subscribe(t,e[t]||t,o?i:i&&i[t])}return u=f(u,{on:y,off:y,reducers:y},{on:o,off:o,reducers:L}),w(e)?t(i(e)):t("string"==typeof e?i(e.split(/\s+/)):e),this},s.prototype.stopListeningTo=function(e,t){var i=this._observers;if(!i)return!1;var n,r=i.length,s=!1;if(e&&"object"!=typeof e)throw TypeError("target should be an object");for(;0<r--;)n=i[r],e&&n._target!==e||(n.unsubscribe(t),s=!0);return s},s.prototype.delimiter=".",s.prototype.setMaxListeners=function(e){e!==y&&(this._maxListeners=e,this._conf||(this._conf={}),this._conf.maxListeners=e)},s.prototype.getMaxListeners=function(){return this._maxListeners},s.prototype.event="",s.prototype.once=function(e,t,i){return this._once(e,t,!1,i)},s.prototype.prependOnceListener=function(e,t,i){return this._once(e,t,!0,i)},s.prototype._once=function(e,t,i,n){return this._many(e,1,t,i,n)},s.prototype.many=function(e,t,i,n){return this._many(e,t,i,!1,n)},s.prototype.prependMany=function(e,t,i,n){return this._many(e,t,i,!0,n)},s.prototype._many=function(e,t,i,n,r){var s=this;if("function"!=typeof i)throw new Error("many only accepts instances of Function");function a(){return 0==--t&&s.off(e,a),i.apply(this,arguments)}return a._origin=i,this._on(e,a,n,r)},s.prototype.emit=function(){if(!this._events&&!this._all)return!1;this._events||h.call(this);var e,t,i,n,r,s,a=arguments[0],o=this.wildcard;if("newListener"===a&&!this._newListener&&!this._events.newListener)return!1;if(o&&("newListener"!==(e=a)&&"removeListener"!==a&&"object"==typeof a)){if(i=a.length,E)for(n=0;n<i;n++)if("symbol"==typeof a[n]){s=!0;break}s||(a=a.join(this.delimiter))}var l,c=arguments.length;if(this._all&&this._all.length)for(n=0,i=(l=this._all.slice()).length;n<i;n++)switch(this.event=a,c){case 1:l[n].call(this,a);break;case 2:l[n].call(this,a,arguments[1]);break;case 3:l[n].call(this,a,arguments[1],arguments[2]);break;default:l[n].apply(this,arguments)}if(o)_.call(this,l=[],e,this.listenerTree,0,i);else{if("function"==typeof(l=this._events[a])){switch(this.event=a,c){case 1:l.call(this);break;case 2:l.call(this,arguments[1]);break;case 3:l.call(this,arguments[1],arguments[2]);break;default:for(t=new Array(c-1),r=1;r<c;r++)t[r-1]=arguments[r];l.apply(this,t)}return!0}l=l&&l.slice()}if(l&&l.length){if(3<c)for(t=new Array(c-1),r=1;r<c;r++)t[r-1]=arguments[r];for(n=0,i=l.length;n<i;n++)switch(this.event=a,c){case 1:l[n].call(this);break;case 2:l[n].call(this,arguments[1]);break;case 3:l[n].call(this,arguments[1],arguments[2]);break;default:l[n].apply(this,t)}return!0}if(this.ignoreErrors||this._all||"error"!==a)return!!this._all;throw arguments[1]instanceof Error?arguments[1]:new Error("Uncaught, unspecified 'error' event.")},s.prototype.emitAsync=function(){if(!this._events&&!this._all)return!1;this._events||h.call(this);var e,t,i,n,r,s,a=arguments[0],o=this.wildcard;if("newListener"===a&&!this._newListener&&!this._events.newListener)return Promise.resolve([!1]);if(o&&("newListener"!==(e=a)&&"removeListener"!==a&&"object"==typeof a)){if(n=a.length,E)for(r=0;r<n;r++)if("symbol"==typeof a[r]){t=!0;break}t||(a=a.join(this.delimiter))}var l,c=[],u=arguments.length;if(this._all)for(r=0,n=this._all.length;r<n;r++)switch(this.event=a,u){case 1:c.push(this._all[r].call(this,a));break;case 2:c.push(this._all[r].call(this,a,arguments[1]));break;case 3:c.push(this._all[r].call(this,a,arguments[1],arguments[2]));break;default:c.push(this._all[r].apply(this,arguments))}if(o?_.call(this,l=[],e,this.listenerTree,0):l=this._events[a],"function"==typeof l)switch(this.event=a,u){case 1:c.push(l.call(this));break;case 2:c.push(l.call(this,arguments[1]));break;case 3:c.push(l.call(this,arguments[1],arguments[2]));break;default:for(i=new Array(u-1),s=1;s<u;s++)i[s-1]=arguments[s];c.push(l.apply(this,i))}else if(l&&l.length){if(l=l.slice(),3<u)for(i=new Array(u-1),s=1;s<u;s++)i[s-1]=arguments[s];for(r=0,n=l.length;r<n;r++)switch(this.event=a,u){case 1:c.push(l[r].call(this));break;case 2:c.push(l[r].call(this,arguments[1]));break;case 3:c.push(l[r].call(this,arguments[1],arguments[2]));break;default:c.push(l[r].apply(this,i))}}else if(!this.ignoreErrors&&!this._all&&"error"===a)return arguments[1]instanceof Error?Promise.reject(arguments[1]):Promise.reject("Uncaught, unspecified 'error' event.");return Promise.all(c)},s.prototype.on=function(e,t,i){return this._on(e,t,!1,i)},s.prototype.prependListener=function(e,t,i){return this._on(e,t,!0,i)},s.prototype.onAny=function(e){return this._onAny(e,!1)},s.prototype.prependAny=function(e){return this._onAny(e,!0)},s.prototype.addListener=s.prototype.on,s.prototype._onAny=function(e,t){if("function"!=typeof e)throw new Error("onAny only accepts instances of Function");return this._all||(this._all=[]),t?this._all.unshift(e):this._all.push(e),this},s.prototype._on=function(e,t,i,n){if("function"==typeof e)return this._onAny(e,t),this;if("function"!=typeof t)throw new Error("on only accepts instances of Function");this._events||h.call(this);var r=this;return n!==y&&(t=(n=function(e,t,i){if(!0===i)r=!0;else if(!1===i)n=!0;else{if(!i||"object"!=typeof i)throw TypeError("options should be an object or true");var n=i.async,r=i.promisify,s=i.nextTick,a=i.objectify}if(n||s||r){var o=t,i=t._origin||t;if(s&&!S)throw Error("process.nextTick is not supported");r===y&&(r="AsyncFunction"===t.constructor.name),(t=function(){var e=arguments,t=this,i=this.event;return r?s?Promise.resolve():new Promise(function(e){A(e)}).then(function(){return t.event=i,o.apply(t,e)}):(s?process.nextTick:A)(function(){t.event=i,o.apply(t,e)})})._async=!0,t._origin=i}return[t,a?new v(this,e,t):this]}.call(this,e,t,n))[0],r=n[1]),this._newListener&&this.emit("newListener",e,t),this.wildcard?function(e,t,i){var n,r=0,s=0,a=this.delimiter,o=a.length;if("string"==typeof e)if(-1!==(u=e.indexOf(a))){for(n=new Array(5);n[r++]=e.slice(s,u),-1!==(u=e.indexOf(a,s=u+o)););n[r++]=e.slice(s)}else n=[e],r=1;else r=(n=e).length;if(1<r)for(u=0;u+1<r;u++)if("**"===n[u]&&"**"===n[u+1])return;for(var l,c=this.listenerTree,u=0;u<r;u++)if(c=c[l=n[u]]||(c[l]={}),u===r-1)return c._listeners?("function"==typeof c._listeners&&(c._listeners=[c._listeners]),i?c._listeners.unshift(t):c._listeners.push(t),!c._listeners.warned&&0<this._maxListeners&&c._listeners.length>this._maxListeners&&(c._listeners.warned=!0,d.call(this,c._listeners.length,l))):c._listeners=t,!0;return!0}.call(this,e,t,i):this._events[e]?("function"==typeof this._events[e]&&(this._events[e]=[this._events[e]]),i?this._events[e].unshift(t):this._events[e].push(t),!this._events[e].warned&&0<this._maxListeners&&this._events[e].length>this._maxListeners&&(this._events[e].warned=!0,d.call(this,this._events[e].length,e))):this._events[e]=t,r},s.prototype.off=function(e,t){if("function"!=typeof t)throw new Error("removeListener only takes instances of Function");var i=[];if(this.wildcard){var n="string"==typeof e?e.split(this.delimiter):e.slice();if(!(i=_.call(this,null,n,this.listenerTree,0)))return this}else{if(!this._events[e])return this;a=this._events[e],i.push({_listeners:a})}for(var r=0;r<i.length;r++){var s=i[r],a=s._listeners;if(w(a)){for(var o=-1,l=0,c=a.length;l<c;l++)if(a[l]===t||a[l].listener&&a[l].listener===t||a[l]._origin&&a[l]._origin===t){o=l;break}if(o<0)continue;return(this.wildcard?s._listeners:this._events[e]).splice(o,1),0===a.length&&(this.wildcard?delete s._listeners:delete this._events[e]),this._removeListener&&this.emit("removeListener",e,t),this}(a===t||a.listener&&a.listener===t||a._origin&&a._origin===t)&&(this.wildcard?delete s._listeners:delete this._events[e],this._removeListener&&this.emit("removeListener",e,t))}return this.listenerTree&&m(this.listenerTree),this},s.prototype.offAny=function(e){var t,i=0,n=0;if(e&&this._all&&0<this._all.length){for(i=0,n=(t=this._all).length;i<n;i++)if(e===t[i])return t.splice(i,1),this._removeListener&&this.emit("removeListenerAny",e),this}else{if(t=this._all,this._removeListener)for(i=0,n=t.length;i<n;i++)this.emit("removeListenerAny",t[i]);this._all=[]}return this},s.prototype.removeListener=s.prototype.off,s.prototype.removeAllListeners=function(e){if(e===y)return this._events&&h.call(this),this;if(this.wildcard){var t,i=_.call(this,null,e,this.listenerTree,0);if(!i)return this;for(t=0;t<i.length;t++)i[t]._listeners=null;this.listenerTree&&m(this.listenerTree)}else this._events&&(this._events[e]=null);return this},s.prototype.listeners=function(e){var t,i,n,r,s,a=this._events;if(e===y){if(this.wildcard)throw Error("event name required for wildcard emitter");if(!a)return[];for(r=(t=x(a)).length,n=[];0<r--;)"function"==typeof(i=a[t[r]])?n.push(i):n.push.apply(n,i);return n}if(this.wildcard){if(!(s=this.listenerTree))return[];var o=[],l="string"==typeof e?e.split(this.delimiter):e.slice();return _.call(this,o,l,s,0),o}return a&&(i=a[e])?"function"==typeof i?[i]:i:[]},s.prototype.eventNames=function(e){var t=this._events;return this.wildcard?u.call(this,this.listenerTree,[],null,e):t?x(t):[]},s.prototype.listenerCount=function(e){return this.listeners(e).length},s.prototype.hasListeners=function(e){if(this.wildcard)return i=[],t="string"==typeof e?e.split(this.delimiter):e.slice(),_.call(this,i,t,this.listenerTree,0),0<i.length;var t=this._events,i=this._all;return!!(i&&i.length||t&&(e===y?x(t).length:t[e]))},s.prototype.listenersAny=function(){return this._all||[]},s.prototype.waitFor=function(r,s){var a=this,e=typeof s;return"number"==e?s={timeout:s}:"function"==e&&(s={filter:s}),l((s=f(s,{timeout:0,filter:y,handleError:!1,Promise:Promise,overload:!1},{filter:o,Promise:n})).Promise,function(t,i,e){function n(){var e=s.filter;e&&!e.apply(a,arguments)||(a.off(r,n),s.handleError?(e=arguments[0])?i(e):t(c.apply(null,arguments).slice(1)):t(c.apply(null,arguments)))}e(function(){a.off(r,n)}),a._on(r,n,!1)},{timeout:s.timeout,overload:s.overload})},F=s.prototype,Object.defineProperties(s,{defaultMaxListeners:{get:function(){return F._maxListeners},set:function(e){if("number"!=typeof e||e<0||Number.isNaN(e))throw TypeError("n must be a non-negative number");F._maxListeners=e},enumerable:!0},once:{value:function(a,o,e){return l((e=f(e,{Promise:Promise,timeout:0,overload:!1},{Promise:n})).Promise,function(e,t,i){var n;if("function"==typeof a.addEventListener)return n=function(){e(c.apply(null,arguments))},i(function(){a.removeEventListener(o,n)}),a.addEventListener(o,n,{once:!0});function r(){s&&a.removeListener("error",s),e(c.apply(null,arguments))}var s;"error"!==o&&(s=function(e){a.removeListener(o,r),t(e)},a.once("error",s)),i(function(){s&&a.removeListener("error",s),a.removeListener(o,r)}),a.once(o,r)},{timeout:e.timeout,overload:e.overload})},writable:!0,configurable:!0}}),Object.defineProperties(F,{_maxListeners:{value:10,writable:!0,configurable:!0},_observers:{value:null,writable:!0,configurable:!0}}),e.exports=s}(eventemitter2$1),eventemitter2$1.exports);class InfiniteScrollEvents extends BaseEvent{constructor(e){super(e),this.namespace="infiniteScroll",this.events={scrollThreshold:"scroll.threshold",request:"request",load:"load",append:"append",error:"error",last:"last",history:"history"},this.after_init()}}class sallaEmitter extends eventemitter2{constructor(){super({wildcard:!0,delimiter:"::",newListener:!1,removeListener:!1,maxListeners:10,verboseMemoryLeak:!1,ignoreErrors:!1}),this.globalListners={},this.delimiter="::",this.auth=new AuthEvents(this),this.cart=new CartEvents(this),this.gift=new GiftEvents(this),this.order=new OrderEvents(this),this.offer=new OfferEvents(this),this.scope=new ScopeEvents(this),this.rating=new RatingEvents(this),this.comment=new CommentEvents(this),this.loyalty=new LoyaltyEvents(this),this.product=new ProductEvents(this),this.profile=new ProfileEvents(this),this.currency=new CurrencyEvents(this),this.document=new DocumentEvents(this),this.twilight=new TwilightEvents(this),this.wishlist=new WishlistEvents(this),this.infiniteScroll=new InfiniteScrollEvents(this),this.body=document.querySelector("body"),this.logableEvents=["cart::item.added.failed","cart::item.deleted.failed"],this.ingoreLogEvents=["document::click","document::keyup","document::change"],this.noneFireableActions=["document.request"],this.on("twilight::initiated",this.initiateSallaInAllClasses)}initiateSallaInAllClasses(){let i=this;Object.keys(salla).forEach(t=>{"object"==typeof(t=salla[t])&&(i.callSallaInitiate(t),Object.keys(t).forEach(e=>{i.callSallaInitiate(t[e])}))})}callSallaInitiate(e){e&&e.sallaInitiated&&!e.initiated&&(e.sallaInitiated(),e.initiated=!0)}createAndDispatch(e,...t){this.dispatch(e,...t)}dispatch(t,...i){let e=t.replace("::",".");if(!this.noneFireableActions.includes(e)&&"function"==typeof salla.call(e))return salla.log(`'salla.${e}(...)' triggered using event '${t}'`),e=e.split("."),void salla[e[0]][e[1]](...i);this.emit(t,...i),window.dataLayer=window.dataLayer||[],window.dataLayer.push(Object.assign({event:t},...i.values())),this.ingoreLogEvents.includes(t)||!salla.config.get("debug")&&!this.logableEvents.includes(t)||salla.notify.log("[Event] "+t,...i);let n=this;Object.keys(this.globalListners).forEach(function(e){n.globalListners[e](t,...i)}),this.dispatchMobileEvent(t,{...i.values()})}dispatchEvents(e){if(e&&"object"==typeof e)for(var[t,i]of Object.entries(e))this.dispatch(t,i);else salla.log("No Events To Dispatch!",e)}addListener(e,t){this.on(e,t)}addEventListener(e,t){this.addListener(e,t)}listen(e,t){this.addListener(e,t)}registerGlobalListener(e,t){this.globalListners[e]=t}dispatchMobileEvent(e,t={}){if(!(window.dataLayer&&dataLayer[0]&&dataLayer[0].page&&dataLayer[0].page.mobileApp))return"";if(window.webkit)try{window.webkit.messageHandlers.callbackHandler.postMessage(JSON.stringify({event:e,details:t}))}catch(e){console.log(e,"The native context does not exist yet")}else if(Android)try{Android.customEventWithData(e,JSON.stringify({details:t}))}catch(e){console.log(e,"The native context does not exist yet")}}}class BaseApi{constructor(e){this.parent=e,this.endpoints={},this.webEndpoints=[],this.namespace="BaseApi",this.endpointsMethods={},this.endpointsHeaders={};e=/function (.{1,})\(/.exec(this.constructor.toString());this.className=(e&&1<e.length?e[1]:"").toLowerCase(),this.debounce={request:void 0,time:300,enabled:!0,exclude:[]}}after_init(){}normalRequest(e,t,i=null){let n=this,r=Array.isArray(e),s=r?this.getUrl(...e):this.getUrl(e);e=r?e[0]:e,i=i||this.endpointsMethods[e]||"post";var a,o=this.endpointsHeaders[e];"get"===i&&t instanceof FormData&&(a={},Array.from(t.entries()).forEach(function(e){a[e[0]]=e[1]}),t={params:a}),o&&"get"===i&&(t=t?Object.assign(t,o):o);let l={namespace:this.namespace,action:e,url:s,payload:t,method:i,headers:o};try{salla.event.document.request(l)}catch(e){return salla.event.document.requestFailed(l),new Promise(()=>{throw e})}this.webEndpoints.includes(e)||"http"===s.substring(0,4)||(s=salla.config.get("store.api")+s);let c=event?.currentTarget,u=!1;return(u="SALLA-BUTTON"===c?.tagName?!0:u)&&c?.load(),this.parent[i](s,t,{headers:o}).then(e=>(u&&c?.stop(),e.data&&e.request&&(e=e.data),n.handleAfterResponseActions(e),e)).catch(e=>{throw u&&c?.stop(),salla.event.document.requestFailed(l,e),n.handleErrorResponse(e),e})}request(e,t,i=null){return!this.isFastRequestsAllowed()&&this.debounce.enabled?(this.debounce.request||(this.debounce.request=salla.helpers.debounce(this.normalRequest.bind(this),this.debounce.time)),this.debounce.request(e,t,i)):this.normalRequest(e,t,i)}getUrl(e){let t=this.endpoints[e]||e;var i=/{[^{}]+}/i;for(let e=1;e<arguments.length;e++)t=t.replace(i,arguments[e]);return t}handleAfterResponseActions(e){var t,i;e&&({data:i,googleTags:t=null}=e,i=i&&i.googleTags?i.googleTags:t,dataLayer&&i&&dataLayer.push(i),this.fireEventsForResponse(e),this.renderSections(e),this.showAlert(e),e.data?.token&&salla.event.auth.tokenFetched(e.data.token))}fireEventsForResponse(e){let t=e.events||e.data?.events||e.error?.events;(t="string"==typeof t?JSON.parse(t):t)&&Object.keys(t).forEach(e=>salla.event.dispatch(e,t[e]))}renderSections(i){i.sections&&Object.keys(i.sections).forEach(t=>{document.querySelectorAll(t.toSelector()).forEach(function(e){e.innerHTML=i.sections[t]})})}handleErrorResponse(e){if(e.response&&e.response.data)return e.response.data.error&&e.response.data.error.fields?this.handleInvalidFields(e):this.handleAfterResponseActions(e.response.data)}showAlert(e){if(e)return e.case&&e.msg?salla.notify.fire(e.msg,e.case,e):e.hasOwnProperty("success")&&e.data?.message?salla.notify.fire(e.data?.message,e.success?salla.notify.types.success:salla.notify.types.error,e):e.error&&e.error.message&&"FORBIDDEN"!==e.error.message?salla.error(e.error.message,e):void 0}handleInvalidFields(e){let i=e.response.data.error.fields,n=[];Object.keys(i).forEach(e=>{let t=i[e];Array.isArray(t)?t.forEach(e=>n.push(e)):n.push(t)});var t=(1<n.length?"* ":"")+n.join("\n* ");salla.error(t,e)}event(){return salla.event[this.className]}getPossibleValue(i,n,e=!1){if(i){if("object"!=typeof i)return i;let t;for(let e=0;e<n.length&&!(t=i[n[e]])&&!(i instanceof FormData&&(t=i.get(n[e])));e++);return"object"!=typeof(t=t||i)||e?t:void 0}}isFastRequestsAllowed(){return salla.config.get("fastRequests")}promise(i,n=!0){return new Promise((e,t)=>(n?e:t)(i))}errorPromise(e){return this.promise(e,!1)}successPromise(e){return this.promise(e,!0)}}class CartApi extends BaseApi{constructor(e){super(e),this.namespace="cart",this.endpoints={latest:"cart/latest",details:"cart/{cart}",quickAdd:"cart/{cart}/item/{product}/quick-add",addItem:"cart/{cart}/item/{product}/add",deleteItem:"cart/{cart}/item/{item}",updateItem:"cart/{cart}/item/{item}",deleteImage:"cart/{cart}/image/{image}",status:"cart/{cart}/status",addCoupon:"cart/{id}/coupon",deleteCoupon:"cart/{id}/coupon"},this.endpointsMethods={latest:"get",details:"get",status:"get",updateItem:"post",deleteItem:"delete",deleteImage:"delete",deleteCoupon:"put"},this.webEndpoints=["latest"],this.after_init()}async getCurrentCartId(){return salla.storage.get("cart.id")||(await this.latest()).data.cart.id}latest(){return this.request("latest",{params:{source:""}}).then(e=>(salla.storage.set("cart",e.data.cart),salla.event.cart.latestFetched(e),e)).catch(e=>{throw salla.storage.set("cart",""),salla.event.cart.latestFailed(e),e})}async details(){var e=await this.getCurrentCartId();return this.request(["details",e]).then(function(e){return salla.cart.event.detailsFetched(e),e}).catch(function(e){throw salla.cart.event.detailsNotFetched(e),e})}async quickAdd(e){return this.addItem(e)}async addItem(e){let t=this.getCartRequestData(e);if(!t.id)return e='There is no product "id"!',salla.cart.event.itemAddedFailed(e),this.errorPromise(e);var e=this.getPossibleValue(t.formData,["quantity","donating_amount"])?"addItem":"quickAdd",i=await this.getCurrentCartId();return this.request([e,i,t.id],t.formData).then(function(e){return salla.cart.event.itemAdded(e,t.id),e}).catch(function(e){throw salla.cart.event.itemAddedFailed(e,t.id),e})}async deleteItem(e){let t=this.getCartRequestData(e);if(!t.id)return e='There is no "id"!',salla.cart.event.itemDeletedFailed(e),this.errorPromise(e);e=await this.getCurrentCartId();return this.request(["deleteItem",e,t.id]).then(function(e){return salla.cart.event.itemDeleted(e,t.id),e}).catch(function(e){throw salla.cart.event.itemDeletedFailed(e,t.id),e})}async updateItem(e){let t=this.getCartRequestData(e);if(!t.id)return e='There is no "id"!',salla.cart.event.itemUpdatedFailed(e),this.errorPromise(e);e=await this.getCurrentCartId();return"object"==typeof t.formData&&("Object"===t.formData.constructor?.name?t.formData._method="PUT":t.formData.append("_method","PUT")),this.request(["updateItem",e,t.id],t.formData).then(function(e){return salla.cart.event.itemUpdated(e,t.id),e}).catch(function(e){throw salla.cart.event.itemUpdatedFailed(e,t.id),e})}async deleteImage(t){if(!(t=this.getPossibleValue(t,["id","image_id","photo_id"])))return e='There is no "id"!',salla.cart.event.imageNotDeleted(e),this.errorPromise(e);var e=await this.getCurrentCartId();return this.request(["deleteImage",e,t]).then(function(e){return salla.cart.event.imageDeleted(e,t),e}).catch(function(e){throw salla.cart.event.imageNotDeleted(e,t),e})}async status(e){return this.request(["status",e||await this.getCurrentCartId()])}async submit(){this.status(await this.getCurrentCartId()).then(e=>{var t,i=e.data.next_step.to;if(!["checkout","refresh","login"].includes(i))throw t="Can't find next_step );",salla.cart.event.submitFailed(t),t;if(salla.cart.event.submitted(e),"login"===i)return salla.auth.setCanRedirect(!1),salla.event.dispatch("login::open"),void salla.auth.event.onLoggedIn(e=>{salla.event.dispatch("login::close"),this.submit()});"checkout"===i?window.location.href=e.data.next_step.url+(window.ApplePaySession?"?has_apple_pay=true":""):window.location.reload()}).catch(function(e){throw salla.cart.event.submitFailed(e),e})}getCartRequestData(e){let t=e?.data||("object"==typeof e?e:void 0);return{id:e=t?this.getPossibleValue(t,["prod_id","item_id","id"]):e,formData:t="object"==typeof t?t:void 0}}handleAfterResponseActions(e){var t;if(403===e.status)throw salla.storage.remove("cart"),t=salla.lang.get("pages.checkout.try_again"),salla.error(t),t;super.handleAfterResponseActions(e)}reset(){salla.storage.remove("cart"),salla.cart.event.successReset()}async addCoupon(e){if(e=e.data||e,!(e=this.getPossibleValue(e,["coupon"]))){let e=new Error('There is no "Coupon Code"!');return e.name="EmptyCoupon",salla.event.cart.couponAdditionFailed(e),this.errorPromise(e)}let t=await salla.cart.api.getCurrentCartId();return this.request(["addCoupon",t],{coupon:e}).then(function(e){return salla.event.cart.couponAdded(e,t),e}).catch(function(e){throw salla.event.cart.couponAdditionFailed(e,t),e})}async deleteCoupon(){let t=await salla.cart.api.getCurrentCartId();return this.request(["deleteCoupon",t],{}).then(function(e){return salla.event.cart.couponDeleted(e,t),e}).catch(function(e){throw salla.event.cart.couponDeletionFailed(e,t),e})}}class GiftApi extends BaseApi{constructor(e){super(e),this.namespace="gift",this.endpoints={buy:"{id}/buy-as-gift"},this.webEndpoints=["buy"],this.after_init()}buy(t){var e;return(t=this.getGiftRequestData(t)).id?this.request(["buy",t.id],t.data).then(function(e){return salla.gift.event.buyingSucceeded(e,t.id),e}).catch(function(e){throw salla.gift.event.buyingFailed(e,t.id),e}):(e='There is no "id"!',salla.gift.event.buyingFailed(e),this.errorPromise(e))}getGiftRequestData(e){return{id:(e=e?.data||("object"==typeof e?e:void 0))?this.getPossibleValue(e,["id","product_id","prod_id","item_id"]):e,data:"object"==typeof e?e:void 0}}}class LoyalityApi extends BaseApi{constructor(e){super(e),this.namespace="loyalty",this.endpoints={exchange:"cart/prize/exchange_loyalty_point"},this.webEndpoints=["exchange"],this.after_init()}exchange(e){let t=e.data||{id:e};return t.id?(t.loyalty_prize_id=t.id,this.request("exchange",t).then(function(e){return salla.loyalty.event.exchangeSucceeded(e,t.id),e}).catch(function(e){throw salla.loyalty.event.exchangeFailed(e,t.id),e})):(salla.loyalty.event.exchangeFailed('There is no "id"!'),!1)}}class AuthApi extends BaseApi{constructor(e){super(e),this.namespace="auth",this.canRedirect_=!0,this.endpoints={login:"auth/{type}/send_verification",resend:"auth/resend_verification",verify:"auth/{type}/verify",register:"auth/register",logout:"logout",refresh:"auth/refresh"},this.webEndpoints=["logout","auth/jwt","refresh"],this.endpointsMethods={logout:"get"},this.after_init()}setCanRedirect(e){salla.api.auth.canRedirect_=e}canRedirect(){return salla.api.auth.canRedirect_}login(t,e){let i;return t.data&&(i=t.element,e=t.data,t=this.getPossibleValue(e,["type"])),e||"object"!=typeof t||(e=t),(t=this.getPossibleValue(t,["type"]))?this.request(["login",t],e).then(function(e){return salla.auth.event.codeSent.call(i,e,t),e}).catch(function(e){throw salla.auth.event.codeNotSent.call(i,e,t),e}):(e="Failed to know what's login type!",salla.auth.event.codeNotSent(e),this.errorPromise(e))}async verify(e,t=!0){var i=this.getPossibleValue(e,["type"]);if(!i)return n="Failed to know what's login type!",salla.auth.event.verificationFailed(n),this.errorPromise(n);salla.auth.event.next_event&&(e.next_event=salla.auth.event.next_event);var n=await this.request(["verify",i],e);return 200!==n?.status?(salla.auth.event.verificationFailed(n,i),this.errorPromise(n)):(t&&await this.request("auth/jwt"),"authenticated"===n.data?.case&&salla.auth.event.loggedIn(n),salla.auth.event.verified(n,i),this.successPromise(n))}resend(t){let e;return(t=t.data||t).type=t.type||"mobile","mobile"!==t.type||t.phone&&t.country_code?"email"!==t.type||t.email?this.request("resend",t).then(function(e){return salla.auth.event.codeReSent(e,t),e}).catch(function(e){throw salla.auth.event.codeNotReSent(e,t),e}):(salla.auth.event.codeNotReSent(e="There is no email!",t),this.errorPromise(e)):(salla.auth.event.codeNotReSent(e="There is no phone or country_code!",t),this.errorPromise(e))}register(e){let t;return e.data&&(t=e.element,e=e.data),salla.auth.event.next_event&&(e.next_event=salla.auth.event.next_event),this.request("register",e).then(function(e){return salla.auth.event.registered.call(t,e),"authenticated"===e.data?.case&&salla.auth.event.loggedIn(e),e}).catch(function(e){throw salla.auth.event.registrationFailed.call(t,e),e})}logout(){return this.request("logout").then(function(e){return salla.auth.event.loggedOut(e),salla.log("Reloading after 0.1 sec..."),setTimeout(()=>location.reload(),100),e}).catch(function(e){throw salla.auth.event.failedLogout(e),e})}refresh(){return this.request("refresh").catch(function(e){throw salla.auth.event.refreshFailed(e),e})}}class OrderApi extends BaseApi{constructor(e){super(e),this.namespace="order",this.endpoints={cancel:"orders/cancel/{id}",createCartFromOrder:"reorder/{id}",sendInvoice:"orders/send/{id}"},this.endpointsMethods={createCartFromOrder:"get"},this.after_init()}show(e,t=null){salla.event.dispatch("mobile::order.placed",{order_id:e||salla.config.get("page.id")}),location.href=t||location.href.replace("thankyou","order")}cancel(t){return t=t||salla.config.get("page.id"),this.request(["cancel",t],{params:{has_apple_pay:!!window.ApplePaySession}}).then(function(e){return salla.event.order.canceled(e,t),e}).catch(function(e){throw salla.event.order.notCanceled(e,t),e})}createCartFromOrder(t){return t=t||salla.config.get("page.id"),this.request(["createCartFromOrder",t]).then(function(e){return salla.storage.set("cart",{id:e.data.cart_id,user_id:salla.config.get("user.id")}),salla.event.order.orderCreated(e,t),window.location.href=e.data.url,e}).catch(function(e){throw salla.event.order.orderCreationFailed(e,t),e})}sendInvoice(e){let t=this.getPossibleValue(e,["id"])||salla.config.get("page.id");var i;return!t||isNaN(t)?(i="There is no id!",salla.order.event.invoiceNotSent(i),this.errorPromise(i)):this.request(["sendInvoice",t],e).then(e=>(salla.event.order.invoiceSent(e,t),e)).catch(e=>{throw salla.event.order.invoiceNotSent(e,t),e})}}class OfferApi extends BaseApi{constructor(e){super(e),this.namespace="offer",this.endpoints={increase:"products/special-offer-popup/{product_id}/increase",details:"products/{product_id}/specialoffer"},this.webEndpoints=["popup","increase"],this.endpointsMethods={increase:"get"},this.after_init()}details(t){var e;return(t=this.getPossibleValue(t.data|t,["product_id"]))?this.request(["details",t]).then(function(e){return salla.offer.event.detailsFetched(e,t),e}).catch(function(e){throw salla.offer.event.fetchDetailsFailed(e,t),e}):(e='There is no "product_id"!',salla.offer.event.fetchDetailsFailed(e),this.errorPromise(e))}increase(e){let t;return e&&e.data&&(t=e.data,e=this.getPossibleValue(t,["id","product_id"])),e?this.request(["increase",e],t).then(function(e){return salla.offer.event.increased(e),e}).catch(function(e){throw salla.offer.event.increaseFailed(e),e}):(salla.offer.event.increaseFailed('There is no "product_id"!'),!1)}}class ProductApi extends BaseApi{constructor(e){super(e),this.namespace="product",this.previousQuery="",this.endpoints={getPrice:"products/{id}/price",availabilitySubscribe:"products/{id}/availability-notify",search:"products/search",categories:"products/categories/{?id}",purchaseNow:"checkout/quick-purchase/{id}"},this.webEndpoints=["purchaseNow"],this.after_init()}getPrice(t){var e=t.data||t;return t=this.getPossibleValue(e,["id","prod_id"]),this.request(["getPrice",t],"object"==typeof e?e:void 0).then(function(e){return salla.product.event.priceUpdated(e,t),e}).catch(function(e){throw salla.product.event.priceUpdateFailed(e,t),e})}categories(e){return this.request(["categories",e||""],null,"get").then(function(e){return salla.product.event.categoriesFetched(e),e}).catch(function(e){throw salla.product.event.categoriesFailed(e),e})}availabilitySubscribe(t){var e=t.data||t;return t=this.getPossibleValue(e,["id","prod_id"]),this.request(["availabilitySubscribe",t],"object"==typeof e?e:void 0).then(function(e){return salla.product.event.availabilitySubscribed(e,t),e}).catch(function(e){throw salla.product.event.availabilitySubscribedFailed(e,t),e})}search(t){let e=t.data;var i;return e=e||{params:"string"==typeof t?{query:t}:t},(t=e instanceof FormData?e.get("query"):e.query||e.params?.query)?t===salla.api.product.previousQuery?(i="Query is same as previous one!",salla.product.event.searchFailed(i),salla.api.product.previousQuery=null,this.errorPromise(i)):(salla.api.product.previousQuery=t,this.request("search",e,"get").then(function(e){return salla.product.event.searchResults(e,t),e}).catch(function(e){throw salla.product.event.searchFailed(e,t),e})):(i='There is no "query"!',salla.product.event.searchFailed(i),this.errorPromise(i))}purchaseNow(e){if(salla.config.isGuest())return salla.auth.event.dispatch("login");let t=e.product_data,i=this.getPossibleValue(t,["id","prod_id"]);if(!e.is_applepay)return this.request(["quickPurchase",i],"object"==typeof t?t:void 0).then(function(e){return e}).catch(function(e){throw e});salla.event.dispatch("payments::apple-pay.start-transaction",{amount:e.total,currency:e.currency,requiredShippingContactFields:e.require_shipping?["postalAddress"]:null,shippingMethods:e.require_shipping?[]:null,supportedNetworks:e.applepay_supported_networks,validateMerchant:{url:baseUrl+"checkout/applepay/validate",onFailed:({})=>{console.log("validateMerchant Failed!")},onSuccess:e=>(console.log("validateMerchant Success"),this.request(["quickPurchase",i],"object"==typeof t?t:void 0))},authorized:{url:baseUrl+"/checkout/{id}/payments/submit",onFailed:e=>{console.log("authorized Failed!"),window.Salla.Payments.ApplePay.onCancel({},e.data.error.message)},onSuccess:e=>{console.log(e),window.location.href=e.redirect.url,console.log("authorized Success:: redirect to thank you page, order placed")}},shippingMethodSelected:e.require_shipping?{url:baseUrl+"/checkout/{id}/shipping/details",onFailed:e=>{console.log("select shipping method failed!")},onSuccess:e=>{console.log("select shipping method success")}}:null,shippingContactSelected:e.require_shipping?{url:baseUrl+"/checkout/{id}/address/add",onFailed:e=>{console.log("created contact failed!")},onSuccess:e=>{console.log("created contact success : ",e.data.address_id)}}:null,recalculateTotal:{url:baseUrl+"/checkout/{id}/payments/recalculate"},onError:function(e){console.log(e),salla.notify.error(e)}})}}class ProfileApi extends BaseApi{constructor(e){super(e),this.namespace="profile",this.endpoints={update:"profile/update",updateContacts:"contacts/update",verify:"profile/verify"},this.after_init()}update(e){return this.request("update",e).then(e=>(salla.profile.event.updated(e),e)).catch(e=>{throw salla.event.profile.updateFailed(e),e})}updateContacts(e){return this.request("updateContacts",e).then(e=>(salla.profile.event.contactsUpdated(e),e)).catch(e=>{throw salla.event.profile.updateContactsFailed(e),e})}verify(e){return this.request("verify",e).then(e=>(salla.profile.event.verified(e),e)).catch(e=>{throw salla.event.profile.unVerified(e),e})}}class CommentApi extends BaseApi{constructor(e){super(e),this.namespace="comment",this.endpoints={add:"{type}/{id}/comments"},this.after_init()}add(e){e?.data&&(e=e.data);let t,{id:i,type:n,comment:r}=Object.fromEntries(e);return i?n&&["products","pages","product","page"].includes(n)?r?(n+=["product","page"].includes(n)?"s":"",this.request(["add",n,i],{comment:r}).then(function(e){return salla.event.comment.added(e,i),e}).catch(function(e){throw salla.event.comment.additionFailed(e,i),e})):(salla.event.comment.additionFailed(t="can't find comment content!"),this.errorPromise(t)):(salla.event.comment.additionFailed(t="Failed to get type one of:(products, product, page, pages)!"),this.errorPromise(t)):(salla.event.comment.additionFailed(t="Failed to get id!"),this.errorPromise(t))}}class CurrencyApi extends BaseApi{constructor(e){super(e),this.namespace="currency",this.endpoints={change:"/",list:"currencies"},this.endpointsMethods={change:"get",list:"get"},this.webEndpoints=["change"],this.after_init()}change(t){var e;return(t=this.getPossibleValue(t.data||t,["currency","code"]))?this.request("change",{params:{change_currency:"",currency:t}}).then(function(e){return salla.currency.event.changed(e,t),salla.cookie.set("fresh_summary",1),e}).catch(function(e){throw salla.currency.event.failed(e,t),e}):(e="Can't find currency code!",salla.currency.event.failed(e),this.errorPromise(e))}list(){return this.request("list").then(function(e){return salla.currency.event.fetched(e),e}).catch(function(e){throw salla.currency.event.failedToFetch(e),e})}}class DocumentApi extends BaseApi{constructor(e){super(e),this.namespace="document"}}class RatingApi extends BaseApi{constructor(e){super(e),this.namespace="rating",this.endpoints={store:"rating/store",products:"rating/products",shipping:"rating/shipping",order:"rating/{order_id}"},this.endpointsMethods={order:"get"},this.after_init()}order(t){var e="object"==typeof t?t:{};return(t=this.getPossibleValue(t,["order_id","id"]))?this.request(["order",t],e).then(function(e){return salla.event.rating.orderFetched(e,t),e}).catch(function(e){throw salla.event.rating.orderNotFetched(e,t),e}):(e='There is no "order_id"!',salla.event.rating.orderNotFetched(e),this.errorPromise(e))}store(t){var e;return(t=t.data||t)?this.request("store",t).then(function(e){return salla.event.rating.storeRated(e,t),e}).catch(function(e){throw salla.event.rating.storeFailed(e,t),e}):(e='There is no "data"!',salla.event.rating.storeFailed(e),this.errorPromise(e))}products(t){var e;return(t=t.data||t)?this.request("products",t).then(function(e){return salla.event.rating.productsRated(e,t),e}).catch(function(e){throw salla.event.rating.productsFailed(e,t),e}):(e='There is no "data"!',salla.event.rating.productsFailed(e),this.errorPromise(e))}shipping(t){var e;return(t=t.data||t)?this.request("shipping",t).then(function(e){return salla.event.rating.shippingRated(e,t),e}).catch(function(e){throw salla.event.rating.shippingFailed(e,t),e}):(e='There is no "data"!',salla.event.rating.shippingFailed(e),this.errorPromise(e))}}class SallaInit{constructor(e){salla.config.merge(e),e&&(e._token&&(salla.api.defaults.headers.common["X-CSRF-TOKEN"]=e._token),this.injectMaintenanceAlert(),this.injectThemePreviewAlert(),this.injectEditAlert(),salla.lang.loadStoreTranslations()),salla.twilight.event.initiated(e)}injectMaintenanceAlert(){salla.config.get("maintenance")&&(document.querySelector(".store-notify")?salla.log("store-notify Existed before!"):salla.lang.onLoaded(()=>{var e=document.createElement("div");e.classList.add("store-notify"),e.style="background-color: #d63031; color: #fff; padding: 10px 15px; text-align: center; font-size: 17px;",e.innerHTML=`<p style="margin:0 !important;">${salla.lang.get("blocks.header.maintenance_alert")}</p>`,document.body.prepend(e)}))}injectThemePreviewAlert(){"preview"===salla.config.get("theme.mode")&&(document.querySelector("#s-theme_preview_bar")?salla.log("s-theme_preview_bar Existed before!"):salla.lang.onLoaded(()=>{let e=document.createElement("div");e.id="s-theme_preview_bar",e.setAttribute("style","display: flex; justify-content: space-between; text-align: center; background-color: #232323; color: #fff; padding: 10px; font-size: 0.875rem; line-height: 1.25rem; position: relative;"),e.innerHTML=`
2
2
  <div style="display:flex; align-items:center;">
3
3
  <img width="32" src="https://assets.salla.sa/cp/assets/images/logo-new.png">
4
4
  <span style="margin:0 10px;">${salla.lang.get("blocks.header.preview_mode")}: <span style="background:rgba(255,255,255,0.25);border-radius:15px; padding:2px 15px 4px">${salla.config.get("theme.name")}</span></span>