@salla.sa/twilight 2.14.0-alpha.0 → 2.15.1-alpha.0
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?module.exports=t(require("lodash/get.js"),require("eventemitter2"),require("store/src/store-engine"),require("store/storages/localStorage"),require("store/storages/sessionStorage"),require("store/storages/cookieStorage"),require("store/storages/memoryStorage"),require("ev-emitter"),require("fizzy-ui-utils")):"function"==typeof define&&define.amd?define(["lodash/get.js","eventemitter2","store/src/store-engine","store/storages/localStorage","store/storages/sessionStorage","store/storages/cookieStorage","store/storages/memoryStorage","ev-emitter","fizzy-ui-utils"],t):(e="undefined"!=typeof globalThis?globalThis:e||self).Salla=t(e.t$1,e.eventemitter2,e.r$1,e.n$1,e.o$1,e.i,e.a,e.evEmitter,e.fizzyUiUtils)}(this,(function(e,t,r,a,n,i,s,o,l){"use strict";function c(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function u(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach((function(r){if("default"!==r){var a=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,a.get?a:{enumerable:!0,get:function(){return e[r]}})}})),t.default=e,Object.freeze(t)}var d=c(e),h=u(r),f=u(a),p=u(n),g=u(i),m=u(s),v=u(o),y=u(l),w="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{};function b(e,t){void 0===t&&(t=!1),e+="";for(var r,a=["٠","١","٢","٣","٤","٥","٦","٧","٨","٩"],n=["0","1","2","3","4","5","6","7","8","9"],i=(t=t||!Salla.config.get("store.settings.arabic_numbers_enabled"))?a:n,s=t?n:a,o=0;o<i.length;o++)r=new RegExp(i[o],"g"),e=e.replace(r,s[o]);return e.replace(t?"٫":".",t?".":"٫")}function S(e){var t=("".concat(e).match(/\./g)||[]).length;return t&&1!==t?S(e.replace(/\.(.+)\./g,".$1")):e}function E(e){return"".concat(e).startsWith("https://")||"".concat(e).startsWith("http://")}function _(e){if(E(e))return e;var t=Salla.config.get("store.url");return t||(t=window.location.href.split("/").slice(0,-1).join("/"),Salla.config.set("store.url",t)),t.rtrim("/")+"/"+(null==e?void 0:e.ltrim("/"))}function A(e,t,r){if(r=r||window.location.href,!t||!e)return r;var a=new RegExp("([?&])"+e+"=[^&]+[&]?","g");return(r=r.replace(a,"$1").split("#")[0].replace(/&$|\?$/,"")).includes("?")?r+="&":r+=(r.endsWith("/")?"":"/")+"?",(r+e+"="+encodeURIComponent(t)).replace(/&$|\?$/,"")}function F(e){return window.location.origin+"/"+(null==e?void 0:e.ltrim("/"))}function P(e){return E(e)?e:Salla.config.get("theme.assets")?Salla.config.get("theme.assets").replace(":path",null==e?void 0:e.ltrim("/")):F("themes/"+Salla.config.get("theme.name")+"/"+(null==e?void 0:e.ltrim("/")))}function x(e,t,r){var a,n=e[0];return r&&0==e.length?Array.isArray(r)?(r.push(t),r):[r,t]:Array.isArray(r)?(r.push(t),r):"string"==typeof r?[r,t]:r?(r[n]=x(e.slice(1),t,r[n]),r):n?((a={})[n]=x(e.slice(1),t),a):""===n?[t]:t}function T(){return window.self!==window.top}String.prototype.toStudlyCase=function(){return this.trim().replace(/([^a-zA-Z\d].)/g,(function(e){return e.toUpperCase().replace(/[^a-zA-Z\d]/g,"")}))},String.prototype.toDatasetName=function(){return this.startsWith("data-")?this.substr(5).toStudlyCase():this.toStudlyCase()},String.prototype.toSelector=function(){return this.trim().startsWith(".")||this.trim().startsWith("#")?this.toString():"#"+this.toString()},String.prototype.replaceArray=function(e,t){for(var r,a=this,n=0;n<e.length;n++)r=new RegExp(e[n],"g"),a=a.replace(r,t[n]);return a},String.prototype.rtrim=function(e){return void 0===e&&(e="\\s"),this.replace(new RegExp("["+e+"]*$"),"")},String.prototype.ltrim=function(e){return void 0===e&&(e="\\s"),this.replace(new RegExp("^["+e+"]*"),"")},String.prototype.digitsOnly=function(){return Salla.helpers.digitsOnly(this)};var R={digitsOnly:function(e){return b(e,!0).replace(/[^0-9.]/g,"").replace("..",".").rtrim(".")},inputDigitsOnly:function e(t,r){if(void 0===r&&(r=!1),"string"==typeof t)return document.querySelectorAll(t).forEach((function(t){return e(t,r)}));if(t){var a=Salla.helpers.digitsOnly(t.value);return t.min&&a<parseInt(t.min)?t.value=t.min:t.max&&a>parseInt(t.max)?t.value=t.max:t.maxLength>=1&&a.toString().length>t.maxLength?t.value=a.toString().substring(0,t.maxLength):t.value=r||t.dataset.hasOwnProperty("digitsWithDecimal")?S(a):a.replace(/\D/g,"")}Salla.logger.warn("Can't find Object With Id: "+t)},number:b,money:function(e){var t=Salla.config.currency(null==e?void 0:e.currency).symbol;return b(e="object"==typeof e?e.amount:e)+" "+t},isIframe:T,isPreview:function(){return T()},setNested:function(e,t,r){for(var a=e,n=t.split("."),i=n.length,s=0;s<i-1;s++){var o=n[s];a[o]||(a[o]={}),a=a[o]}return a[n[i-1]]=r,e},getNested:function(e,t,r){var a=d.default(e,t);return void 0!==a?a:r},inputData:function(e,t,r){if(void 0===r&&(r={}),e.includes("[")){var a=e.split("]").join("").split("["),n=a[0],i=r&&"object"==typeof r?r[n]:void 0;return{name:n,value:x(a.slice(1),t,i)}}return{name:e,value:t}},url:Object.freeze({__proto__:null,is_full_url:E,base:function(e){return E(e)?e:"https://"+new URL(_("/")).hostname+"/"+(null==e?void 0:e.ltrim("/"))},get:_,domain:function(e){return E(e)?e:"".concat(Salla.config.get("store.url",window.location.href.split("/").slice(0,-1).join("/")).rtrim("/"),"/").concat(null==e?void 0:e.ltrim("/"))},addParamToUrl:A,baseUrl:F,asset:P,cdn:function(e,t,r){var a="https://cdn.salla.network/";return(t||r)&&(t=t?",width=".concat(t):"",r=r?",height=".concat(r):"",a+="cdn-cgi/image/fit=scale-down".concat(t).concat(r,",onerror=redirect,format=auto/")),a+(null==e?void 0:e.ltrim("/"))},api:function(e){var t;return(null===(t=Salla.config.get("store.api",_("")))||void 0===t?void 0:t.rtrim("/"))+"/"+(null==e?void 0:e.ltrim("/"))},is_page:function(e){return e&&Salla.config.get("page.slug")===e},is_placeholder:function(e){return P(salla.config.get("theme.settings.placeholder"))===P(e)}}),addParamToUrl:A,debounce:function(e,t){t=t||100;var r,a=[];return function(){for(var n=[],i=0;i<arguments.length;i++)n[i]=arguments[i];return clearTimeout(r),r=setTimeout((function(){var t=e.apply(void 0,n);a.forEach((function(e){return e(t)})),a=[]}),t),new Promise((function(e){return a.push(e)}))}},hasApplePay:function(){var e;try{return!!(null===(e=window.ApplePaySession)||void 0===e?void 0:e.canMakePayments())&&!/snapchat/i.test(navigator.userAgent)}catch(e){return console.error(e),!1}}},C=function(e,t){return C=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},C(e,t)},O=function(){return O=Object.assign||function(e){for(var t,r=1,a=arguments.length;r<a;r++)for(var n in t=arguments[r])Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e},O.apply(this,arguments)};function k(e,t,r){if(r||2===arguments.length)for(var a,n=0,i=t.length;n<i;n++)!a&&n in t||(a||(a=Array.prototype.slice.call(t,0,n)),a[n]=t[n]);return e.concat(a||Array.prototype.slice.call(t))}"function"==typeof SuppressedError&&SuppressedError;var I,L,q,U,D=(I=console,L=[],q=[],U={log:function(e,t){if(I&&salla.config.isDebug()){L.push([t,e]),"trace"===salla.config.get("debug")&&(t="trace");var r=I.log,a=void 0===t?r:this.__dict__[t]||r,n=["%cTwilight","color: #5cd5c4;font-weight:bold; border:1px solid #5cd5c4; padding: 2px 6px; border-radius: 5px;"];q.forEach((function(e){n[0]+=e[0],n.push(e[1])}));var i={event:"#CFF680",backend:"#7b68ee"}[t];i&&(n[0]+="%c"+t[0].toUpperCase()+t.substring(1),n.push("margin-left: 5px;color: ".concat(i,";font-weight:bold; border:1px solid ").concat(i,"; padding: 2px 6px; border-radius: 5px;"))),a.call.apply(a,k([I],n.concat.apply(n,e),!1))}},__dict__:{trace:I.trace,debug:I.debug,info:I.info,warn:I.warn,error:I.error}},{event:function(){U.log(arguments,"event")},trace:function(){U.log(arguments,"trace")},debug:function(){U.log(arguments,"debug")},info:function(){U.log(arguments,"info")},warn:function(){U.log(arguments,"warn")},error:function(){U.log(arguments,"error")},log:function(){U.log(arguments,void 0)},backend:function(){U.log(arguments,"backend")},logs:function(e){[e].flat().forEach((function(e){return e&&U.log([e].flat(),"backend")}))},history:function(){return L.map((function(e){return I.log.apply(I,k([e[0]],e[1],!1))})),L},addPrefix:function(e){return Array.isArray(e)?q.unshift(e):this.warn("addPrefix receives array only!"),this}}),N=function(){function e(e,t){void 0===e&&(e={}),void 0===t&&(t={}),this.default_properties=t,this.properties_=O(O({},this.default_properties),e)}return e.prototype.merge=function(e){var t;return this.properties_=O(O({},this.properties_),e),this.properties_.store=O(O({},(null===(t=this.default_properties)||void 0===t?void 0:t.store)||{}),this.properties_.store),this},e.prototype.set=function(e,t){return e.includes(".")?(Salla.helpers.setNested(this.properties_,e,t),this):(this.properties_[e]=t,this)},e.prototype.currency=function(e){return void 0===e&&(e=void 0),e=e||this.get("user.currency_code"),this.get("currencies."+e)||Object.values(this.get("currencies"))[0]},e.prototype.get=function(e,t){return void 0===t&&(t=null),e.includes(".")?Salla.helpers.getNested(this.properties_,e,t):this.properties_.hasOwnProperty(e)?this.properties_[e]||t:t||void 0},e.prototype.all=function(){return this.properties_},e.prototype.isDebug=function(){return this.get("debug")||Salla.storage.get("debug")},e}(),j=function(e){function t(){var t=this;return(t=e.call(this,{wildcard:!0,delimiter:"::",newListener:!1,removeListener:!1,maxListeners:10,verboseMemoryLeak:!1,ignoreErrors:!1})||this).delimiter="::","undefined"!=typeof document&&(t.body=document.querySelector("body")),t.logableEvents=["cart::item.added.failed","cart::item.deleted.failed"],t.ingoreLogEvents=["document::click","document::keyup","document::change"],t.noneFireableActions=["document.request"],t}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function r(){this.constructor=e}C(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}(t,e),t.prototype.createAndDispatch=function(e){for(var t=[],r=1;r<arguments.length;r++)t[r-1]=arguments[r];this.dispatch.apply(this,k([e],t,!1))},t.prototype.emit=function(t){for(var r,a=[],n=1;n<arguments.length;n++)a[n-1]=arguments[n];var i=t.replace("::",".");if(!this.noneFireableActions.includes(i)&&Salla.call&&"function"==typeof Salla.call(i))return Salla.log("'Salla.".concat(i,"(...)' triggered using event '").concat(t,"'")),i=i.split("."),Array.isArray(a[0])&&(a=a[0]),void(r=salla[i[0]])[i[1]].apply(r,a);e.prototype.emit.apply(this,k([t],a,!1)),this.trackEvents.apply(this,k([t],a,!1))},t.prototype.emitAsync=function(t){for(var r=[],a=1;a<arguments.length;a++)r[a-1]=arguments[a];var n=e.prototype.emitAsync.apply(this,k([t],r,!1));try{this.trackEvents.apply(this,k([t],r,!1))}catch(e){Salla.logger.warn("error on tracking event (".concat(t,")"),r,e)}return n},t.prototype.trackEvents=function(e){for(var t,r=[],a=1;a<arguments.length;a++)r[a-1]=arguments[a];if("undefined"!=typeof window)try{window.dataLayer=window.dataLayer||[];var n={event:e};r.map((function(e){return"object"==typeof e&&(n=O(O({},n),e))})),window.dataLayer.push(n)}catch(e){salla.logger.error(e.message)}Salla.logger&&!this.ingoreLogEvents.includes(e)&&(t=Salla.logger).event.apply(t,k([e],r,!1)),this.dispatchMobileEvent.apply(this,k([e],r,!1))},t.prototype.dispatch=function(e){for(var t=[],r=1;r<arguments.length;r++)t[r-1]=arguments[r];return this.emit.apply(this,k([e],t,!1))},t.prototype.dispatchEvents=function(e){if(e)if("object"!=typeof e||Array.isArray(e))Salla.log("Events object is wrong, it should be object of {event:payload}",e);else for(var t=0,r=Object.entries(e);t<r.length;t++){var a=r[t],n=a[0],i=a[1];this.dispatch(n,i)}else Salla.log("No Events To Dispatch!",e)},t.prototype.addListener=function(e,t,r){return this.on(e,t,r)},t.prototype.addEventListener=function(e,t,r){return this.on(e,t,r)},t.prototype.listen=function(e,t){return this.on(e,t)},t.prototype.registerGlobalListener=function(e,t){return this.onAny(t)},t.prototype.dispatchMobileEvent=function(e,t){if(void 0===t&&(t={}),!("undefined"!=typeof window&&window.dataLayer&&window.dataLayer[0]&&window.dataLayer[0].page&&window.dataLayer[0].page.mobileApp))return"";if(window.webkit)try{window.webkit.messageHandlers.callbackHandler.postMessage(JSON.stringify({event:e,details:t}))}catch(e){Salla.log(e,"The native context does not exist yet")}else if(void 0!==window.Android)try{window.Android.customEventWithData(e,JSON.stringify({details:t}))}catch(e){Salla.log(e,"The native context does not exist yet")}},t}(t.EventEmitter2),B=h.createStore([f,p,g,m],[]),M=h.createStore([p],[]),H=h.createStore([g],[]),$=function(){function e(){var e=this;this.clearableItems=["cart","user","salla::wishlist","token"],Salla.event.on("storage::item.remove",(function(t){return e.remove(t)})),Salla.event.on("storage::item.set",(function(t,r){return e.set(t,r)})),this.store=B,this.session=M,this.cookie=H}return e.prototype.set=function(e,t){var r;if(e.includes(".")){var a=e.split(".")[0],n=((r={})[a]=this.store.get(a),r);return n=Salla.helpers.setNested(n,e,t),this.store.set(a,n[a])}return this.store.set(e,t)},e.prototype.remove=function(e){return this.store.remove(e)},e.prototype.clearAll=function(e){var t=this;if(void 0===e&&(e=!1),e)return this.store.clearAll();this.clearableItems.forEach((function(e){t.store.remove(e)}))},e.prototype.get=function(e,t){var r;if(e.includes(".")){var a=e.split(".")[0];return Salla.helpers.getNested(((r={})[a]=this.store.get(a),r),e)}return this.store.get(e,t)},e.prototype.prefixKey=function(e){return"".concat(Salla.config.get("theme.translations_hash"),"_").concat(e,"_").concat(Salla.config.get("store.id"))},e.prototype.setWithTTL=function(e,t,r,a){void 0===r&&(r=10),void 0===a&&(a="store");var n=this.prefixKey(e),i=(new Date).getTime()+60*r*1e3;return this[a].set(n,{value:t,expiry:i})},e.prototype.getWithTTL=function(e,t,r){void 0===t&&(t=null),void 0===r&&(r="store");var a=this.prefixKey(e),n=this[r].get(a);return n?(new Date).getTime()>n.expiry?(this[r].remove(a),t):n.value:t},e}(),z=function(){function e(){var e=this;this.keysToRemove=["__said","__ssid","theme_edit","ws_port"],this.dynamicKeysToRemove=["affiliate"],Salla.event.on("cookies::remove",(function(t){return e.remove(t)})),Salla.event.on("cookies::add",(function(t,r){return e.set(t,r)}))}return e.prototype.get=function(e){var t;return null===(t=document.cookie.split("; ").find((function(t){return t.startsWith(e+"=")})))||void 0===t?void 0:t.split("=")[1]},e.prototype.set=function(e,t,r){void 0===t&&(t=""),void 0===r&&(r=10);var a="";if(r){var n=new Date;n.setTime(n.getTime()+24*r*60*60*1e3),a="; expires="+n.toUTCString()}return document.cookie="".concat(e,"=").concat(t).concat(a,'"; path=/; secure; SameSite=Lax"'),this},e.prototype.remove=function(e){return document.cookie="".concat(e,"=; Max-Age=0; path=/;"),this},e.prototype.clearAll=function(e){return void 0===e&&(e=!1),this.clean(e)},e.prototype.clean=function(e){var t=this;return document.cookie.split(";").map((function(e){return e.split("=")[0].trim()})).filter((function(r){return e||t.keysToRemove.includes(r)||t.dynamicKeysToRemove.some((function(e){return r.startsWith(e)}))})).forEach((function(e){return t.remove(e)})),this},e}();"undefined"!=typeof window&&(window.salla=window.salla||window.Salla||{},window.Salla=window.salla),void 0!==w&&(w.salla=w.salla||w.Salla||{},w.Salla=w.salla),Salla.status="base",Salla.config=new N,Salla.logger=D,Salla.event=new j,Salla.helpers=R,Salla.storage=new $,Salla.cookie=new z,Salla.log=Salla.logger.log,Salla.money=Salla.helpers.money,Salla.url=Salla.helpers.url,Salla.versions={base:"2.13.118"};var Y=Salla;let W=function(e,t,r){return alert(e)},V=function(e,t){return W(e,G.error,t)},G={error:"error",success:"success",info:"info"};var Q={fire:function(e,t,r){return W(e,t,r)},setNotifier:function(e){W=e,salla.event.emit("twilight::notifier.changed")},error:V,success:function(e,t){return W(e,G.success,t)},info:function(e,t){return W(e,G.info,t)},sallaInitiated:function(){let e=window.location.href.match(/([\?\&]danger=)[^&]+/g);e&&(window.history.replaceState(null,document.title,window.location.pathname),salla.event.once("twilight::notifier.changed",(()=>{e.forEach((e=>{e=decodeURI(e.replace("?danger=","").replace("&danger=",""));let t=document.createElement("div");t.innerText=e,V(t.innerHTML),salla.event.emit("twilight::error",e)}))})))},types:G};class K{constructor(e,t){return this.api=e,this.event=t,new Proxy(this,{get:function(r,a){return"event"===a?t:"api"===a?e:e&&e[a]||r[a]}})}}Element.prototype.matches||(Element.prototype.matches=Element.prototype.msMatchesSelector),Element.prototype.closest||(Element.prototype.closest=function(e){for(var t=this;t;){if(t.matches(e))return t;t=t.parentElement}}),Element.prototype.getElementSallaData=function(e,...t){if(!this.getAttribute)return;if(this.hasAttribute("data-json"))try{return JSON.parse(this.getAttribute("data-json"))}catch(e){}let r=this.getAttribute("data-function");if(r&&window[r])return"function"==typeof window[r]?this.getFilteredData(window[r].call(this,...t)):this.getFilteredData(window[r]);let a=this.hasAttribute("data-form-selector")?document.querySelector(this.dataset.formSelector):void 0;if(a="FORM"===this.tagName?this:a||this.closest("form")||this.closest("[salla-form-data]")||this,a&&"FORM"===a.tagName)return this.getFilteredData(new FormData(a),null,a);let n=a.querySelectorAll("[name]");if(!n.length)return this.getFilteredData();let i=Object.assign({},this.dataset);return n.forEach((e=>{if(!["checkbox","radio"].includes(e.type)||e.checked)try{let t=Salla.helpers.inputData(e.name,e.value,i);i[t.name]=t.value}catch(t){Salla.log(e.name+" can't be send")}})),this.getFilteredData(i)},Element.prototype.canEventFireHook=function(e){return!!this.hasAttribute&&this.hasAttribute(Salla.api.hooksPrefix+e.type)},Element.prototype.hasAttributeStartsWith=function(e,t){e=e.toLowerCase();for(var r=0;r<this.attributes.length;r++){let a=this.attributes[r].name.toLowerCase();if(0===a.indexOf(e))return!t||a}return!1},HTMLFormElement.prototype.getAjaxFormData=function(e){var t=this.querySelectorAll('input[type="file"]');t.forEach((e=>{e.files.length||e.setAttribute("disabled","")}));var r=new FormData(this);return t.forEach((e=>{e.files.length||e.removeAttribute("disabled")})),{formData:this.getFilteredData(r,e),url:this.getAttribute("action"),method:this.getAttribute("method")||"post",events:{success:this.dataset.onSuccess,fail:this.dataset.onFail}}},Element.prototype.getFilteredData=function(e=null,t=null,r=null){return e=e||r?.dataset||this.dataset,r&&this.name&&void 0!==this.value&&(e=function(e,t,r){e instanceof FormData?e.append(t,r):e[t]=r;return e}(e,this.name,this.value)),["filterBeforeSubmit","filterBeforeSend"].forEach((a=>{let n=r?.dataset[a]||this.dataset[a];if(n){var i=window[n];if("function"==typeof i){if(!i(e,r||this,t)&&e)throw`Data failed to be pass verify function window.${n}(formData, element, event)!`;return i(e,r||this,t)}Salla.log("window."+n+"() not found!")}})),e},HTMLAnchorElement.prototype.getAjaxFormData=function(e){return{formData:this.getFilteredData(null,e),url:this.getAttribute("href"),method:this.dataset.type||"get",events:{success:this.dataset.onSuccess,fail:this.dataset.onFail}}};class J{constructor(){this.events={},this.namespace="";let e=/function (.{1,})\(/.exec(this.constructor.toString());this.className=(e&&e.length>1?e[1]:"").toLowerCase()}after_init(){this.createDynamicFunctions()}createDynamicFunctions(){Object.keys(this.events).forEach((e=>{this.createDynamicEventFuns(e),this.createDynamicListenerFuns(e)}))}createDynamicEventFuns(e){if(this[e])return;let t=this;this[e]=function(...r){return t.dispatch(e,...r)}}createDynamicListenerFuns(e){let t="on"+e.charAt(0).toUpperCase()+e.slice(1);if(this[t])return;let r=this;this[t]=function(t){return r.on(e,(async(...e)=>t(...e)))}}getEventName(e){return e=this.events[e]||e,!this.namespace||e.includes("::")?e:this.namespace+Salla.event.delimiter+e}dispatch(e,...t){return Salla.event.emitAsync(this.getEventName(e),...t)}on(e,t,r={}){return Salla.event.addListener(this.getEventName(e),t,r)}once(e,t){return Salla.event.once(this.getEventName(e),t)}}function X(e){e&&e.sallaInitiated&&!e.initiated&&(e.sallaInitiated(),e.initiated=!0)}Salla.event.auth=new class extends J{constructor(){super(),this.namespace="auth",this.events={login:"login",logout:"logout",codeSent:"code.sent",codeNotSent:"code.not-sent",verified:"verified",verificationFailed:"verification.failed",loggedIn:"logged.in",registered:"registered",registrationFailed:"registration.failed",loggedOut:"logged.out",failedLogout:"failed.logout",refreshFailed:"refresh.failed",tokenFetched:"token.fetched",tokenInvalid:"token.invalid"},this.after_init()}login(e){return e?(e.type&&this.setTypeActionOnVerified(e.type),this.next_event=e.next_event||null,this.dispatch("login",...arguments)):(this.next_event=null,this.dispatch("login",...arguments))}loggedIn(e){return Salla.profile.info().finally((()=>this.dispatch("loggedIn",e)))}setTypeActionOnVerified(e){this.type_action_on_verified=e}getTypeActionOnVerified(){return this.type_action_on_verified||"redirect"}},Salla.event.cart=new class extends J{constructor(){super(),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",priceQuoteSucceeded:"price-quote.succeeded",priceQuoteFailed:"price-quote.failed",offersFetched:"offers.fetched",offersFailed:"offers.failed",couponAdded:"coupon.added",couponDeleted:"coupon.deleted",couponAdditionFailed:"coupon.addition.failed",couponDeletionFailed:"coupon.deletion.failed",quickOrderSettingFetched:"quick-order.fetched",quickOrderSettingFailed:"quick-order.failed",quickOrderSucceeded:"quick-order.succeeded",quickOrderFailed:"quick-order.failed"},this.after_init()}updated(e){return Salla.cookie.set("fresh_summary",1),e&&"object"==typeof e?(e.offer&&salla.product.event.offerExisted(e.offer),e.redirect&&(salla.log("The current cart is purchased!"),salla.cart.api.reset()),e.cart?(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)):void salla.log("Failed to get the cart summary!")):(Salla.logger.info("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)}},Salla.event.order=new class extends J{constructor(){super(),this.namespace="order",this.events={canceled:"canceled",notCanceled:"not.canceled",orderCreated:"order.created",orderCreationFailed:"order.creation.failed",invoiceSent:"invoice.sent",invoiceNotSent:"invoice.not.sent",ordersFetched:"order.fetched",ordersNotFetched:"order.not.fetched"},this.after_init()}},Salla.event.scope=new class extends J{constructor(){super(),this.namespace="scope",this.events={fetched:"fetched",notFetched:"not.fetched",productAvailabilityFetched:"product-availability.fetched",productAvailabilityNotFetched:"product-availability.not.fetched",changeSucceeded:"changed",changeFailed:"not.changed"},this.after_init()}},Salla.event.rating=new class extends J{constructor(){super(),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()}},Salla.event.booking=new class extends J{constructor(){super(),this.namespace="booking",this.events={added:"added",additionFailed:"addition.failed"},this.after_init()}},Salla.event.comment=new class extends J{constructor(){super(),this.namespace="comment",this.events={added:"added",additionFailed:"addition.failed",fetched:"fetched",fetchFailed:"fetch.failed"},this.after_init()}},Salla.event.landing=new class extends J{constructor(){super(),this.namespace="landing",this.events={detailsFetched:"order.fetched",getDetailsFailed:"get.details.failed",orderCreated:"order.created",orderCreationFailed:"order.creation.failed",breadcrumbFetched:"breadcrumb.fetched",breadcrumbFetchFailed:"breadcrumb.fetch.failed"},this.after_init()}},Salla.event.loyalty=new class extends J{constructor(){super(),this.namespace="loyalty",this.events={exchangeSucceeded:"exchange.succeeded",exchangeFailed:"exchange.failed",programFetched:"program.fetched",programNotFetched:"program.not.fetched",resetSucceeded:"exchange-reset.succeeded",resetFailed:"exchange-reset.failed"},this.after_init()}exchangeSucceeded(e,t){return salla.cart.event.updated(e.data),this.dispatch("exchangeSucceeded",e,t)}resetSucceeded(e){return salla.cart.event.updated(e.data),this.dispatch("resetSucceeded",e)}},Salla.event.product=new class extends J{constructor(){super(),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",offerExisted:"offer.existed",fetchOffersFailed:"fetch.offers.failed",offersFetched:"offers.fetched",sizeGuideFetched:"size-guide.fetched",sizeGuideFetchFailed:"size-guide.failed",giftFetched:"gift.fetched",giftFetchFailed:"gift.failed",detailFetched:"detail.fetched",detailFetchFailed:"detail.failed",addGiftToCartSucceeded:"gift.add-to-cart.succeeded",addGiftToCartFailed:"gift.add-to-cart.failed",giftImageUploadSucceeded:"gift.image-upload.succeeded",giftImageUploadFailed:"gift.image-upload.failed",productListFetchSucceeded:"fetch.succeeded",productListFetchFailed:"fetch.failed",productOptionsFetched:"options.fetched",productOptionsNotFetched:"options.not.fetched"},this.after_init()}},Salla.event.profile=new class extends J{constructor(){super(),this.namespace="profile",this.events={updated:"updated",updateFailed:"update.failed",verificationCodeSent:"verification.code.sent",updateContactsFailed:"update.contacts.failed",verified:"verified",unverified:"unverified",infoFetched:"info.fetched",infoNotFetched:"info.not.fetched",settingsUpdated:"settings.updated",updateSettingsFailed:"update.settings.failed",deleted:"deleted",notDeleted:"not.deleted"},this.after_init()}},Salla.event.currency=new class extends J{constructor(){super(),this.namespace="currency",this.events={changed:"changed",failed:"failed",fetched:"fetched",failedToFetch:"failed.to.fetch"},this.after_init()}},Salla.event.document=new class extends J{constructor(){super(),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,r){this.on(e,(e=>{"function"!=typeof t?"function"==typeof r&&e.target.matches(t)&&r(e):t(e)}))}fireEvent(e,t,...r){return this.fireEventForElements(e,t,!1,...r)}fireEventForAll(e,t,...r){return this.fireEventForElements(e,t,!0,...r)}fireEventForElements(e,t,r,...a){if("string"==typeof e){if(r)return document.querySelectorAll(e).forEach((e=>this.fireEventForElements(e,t,!1,...a)));e=document.querySelector(e)}if(!e)return void salla.log("Failed To get element to fire event: "+t);const n=new CustomEvent(t,...a);return e.dispatchEvent(n)}},Salla.event.wishlist=new class extends J{constructor(){super(),this.namespace="wishlist",this.events={added:"added",removed:"removed",additionFailed:"addition.failed",removingFailed:"removing.failed"},this.after_init()}},Salla.event.infiniteScroll=new class extends J{constructor(){super(),this.namespace="infiniteScroll",this.events={scrollThreshold:"scroll.threshold",request:"request",load:"load",append:"append",error:"error",last:"last",history:"history"},this.after_init()}},Salla.event.notifications=new class extends J{constructor(){super(),this.namespace="notifications",this.events={fetched:"fetched",fetchFailed:"fetch.failed"},this.after_init()}},Salla.event.component=new class extends J{constructor(){super(),this.namespace="component",this.events={menuFetched:"menus.fetched",menuFetchFailed:"menus.fetch.failed",reviewsFetched:"reviews.fetched",reviewsFetchFailed:"reviews.fetch.failed"},this.after_init()}},Salla.event.advertisement=new class extends J{constructor(){super(),this.namespace="advertisement",this.events={fetched:"advertisement.fetched",fetchFailed:"advertisement.not.fetched"},this.after_init()}},Salla.event.navigation=new class extends J{constructor(){super(),this.namespace="navigation",this.events={breadcrumbFetched:"breadcrumb.fetched",breadcrumbFetchFailed:"breadcrumb.fetch.failed"},this.after_init()}},Salla.event.on("twilight::initiated",(()=>{Object.keys(Salla).forEach((e=>{"object"==typeof(e=Salla[e])&&(X(e),Object.keys(e).forEach((t=>{X(e[t])})))}))})),Salla.config.default_properties={debug:"undefined"!=typeof process&&"development"===process.env.NODE_ENV,token:null,fastRequests:!0,canLeave:!0,store:{api:"https://api.salla.dev/store/v1/"},currencies:{SAR:{code:"SAR",name:"ريال سعودي",symbol:"ر.س",amount:1,country_code:"sa"}}},Salla.config.merge(Salla.config.default_properties),Salla.config.triedToGetCurrencies_=!1,Salla.config.triedToGetLanguages_=!1,Salla.config.isUser=()=>"user"===Salla.config.get("user.type"),Salla.config.isGuest=()=>!Salla.config.isUser(),Salla.config.languages=async()=>{if(Salla.config.triedToGetLanguages_)return Salla.config.get("languages");Salla.config.triedToGetLanguages_=!0;let e=!0,t=[];return(await salla.document.api.request("languages",null,"get"))?.data?.map((r=>{e&&(t=[],e=!1),r.code=r.code||r.iso_code,r.url=salla.url.get(r.code),r.is_rtl=r.is_rtl||r.rtl,t.push(r)})),Salla.config.set("languages",t),t},Salla.config.currencies=async()=>{if(Salla.config.triedToGetCurrencies_)return Salla.config.get("currencies");Salla.config.triedToGetCurrencies_=!0;let e=!0,t={};return(await salla.currency.api.list())?.data?.map((r=>{e&&(t={},e=!1),r.country_code=r.code.substr(0,2).toLowerCase(),t[r.code]=r})),Salla.config.set("currencies",t),t};"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self&&self;function Z(e){return e&&Object.prototype.hasOwnProperty.call(e,"default")&&1===Object.keys(e).length?e.default:e}var ee,te={exports:{}},re={exports:{}},ae=Z(v),ne=Z(y);function ie(){return ee||(ee=1,function(e){!function(t,r){e.exports?e.exports=r(t,ae,ne):t.InfiniteScroll=r(t,t.EvEmitter,t.fizzyUIUtils)}(window,(function(e,t,r){let a=e.jQuery,n={};function i(e,t){let s=r.getQueryElement(e);if(s){if((e=s).infiniteScrollGUID){let r=n[e.infiniteScrollGUID];return r.option(t),r}this.element=e,this.options={...i.defaults},this.option(t),a&&(this.$element=a(this.element)),this.create()}else console.error("Bad element for InfiniteScroll: "+(s||e))}i.defaults={},i.create={},i.destroy={};let s=i.prototype;Object.assign(s,t.prototype);let o=0;s.create=function(){let e=this.guid=++o;if(this.element.infiniteScrollGUID=e,n[e]=this,this.pageIndex=1,this.loadCount=0,this.updateGetPath(),this.getPath&&this.getPath()){this.updateGetAbsolutePath(),this.log("initialized",[this.element.className]),this.callOnInit();for(let e in i.create)i.create[e].call(this)}else console.error("Disabling InfiniteScroll")},s.option=function(e){Object.assign(this.options,e)},s.callOnInit=function(){let e=this.options.onInit;e&&e.call(this,this)},s.dispatchEvent=function(e,t,r){this.log(e,r);let n=t?[t].concat(r):r;if(this.emitEvent(e,n),!a||!this.$element)return;let i=e+=".infiniteScroll";if(t){let r=a.Event(t);r.type=e,i=r}this.$element.trigger(i,r)};let l={initialized:e=>`on ${e}`,request:e=>`URL: ${e}`,load:(e,t)=>`${e.title||""}. URL: ${t}`,error:(e,t)=>`${e}. URL: ${t}`,append:(e,t,r)=>`${r.length} items. URL: ${t}`,last:(e,t)=>`URL: ${t}`,history:(e,t)=>`URL: ${t}`,pageIndex:function(e,t){return`current page determined to be: ${e} from ${t}`}};s.log=function(e,t){if(!this.options.debug)return;let r=`[InfiniteScroll] ${e}`,a=l[e];a&&(r+=". "+a.apply(this,t)),console.log(r)},s.updateMeasurements=function(){this.windowHeight=e.innerHeight;let t=this.element.getBoundingClientRect();this.top=t.top+e.scrollY},s.updateScroller=function(){let t=this.options.elementScroll;if(t){if(this.scroller=!0===t?this.element:r.getQueryElement(t),!this.scroller)throw new Error(`Unable to find elementScroll: ${t}`)}else this.scroller=e},s.updateGetPath=function(){let e=this.options.path;if(!e)return void console.error(`InfiniteScroll path option required. Set as: ${e}`);let t=typeof e;"function"!=t?"string"==t&&e.match("{{#}}")?this.updateGetPathTemplate(e):this.updateGetPathSelector(e):this.getPath=e},s.updateGetPathTemplate=function(e){this.getPath=()=>{let t=this.pageIndex+1;return e.replace("{{#}}",t)};let t=e.replace(/(\\\?|\?)/,"\\?").replace("{{#}}","(\\d\\d?\\d?)"),r=new RegExp(t),a=location.href.match(r);a&&(this.pageIndex=parseInt(a[1],10),this.log("pageIndex",[this.pageIndex,"template string"]))};let c=[/^(.*?\/?page\/?)(\d\d?\d?)(.*?$)/,/^(.*?\/?\?page=)(\d\d?\d?)(.*?$)/,/(.*?)(\d\d?\d?)(?!.*\d)(.*?$)/],u=i.getPathParts=function(e){if(e)for(let t of c){let r=e.match(t);if(r){let[,e,t,a]=r;return{begin:e,index:t,end:a}}}};s.updateGetPathSelector=function(e){let t=document.querySelector(e);if(!t)return void console.error(`Bad InfiniteScroll path option. Next link not found: ${e}`);let r=t.getAttribute("href"),a=u(r);if(!a)return void console.error(`InfiniteScroll unable to parse next link href: ${r}`);let{begin:n,index:i,end:s}=a;this.isPathSelector=!0,this.getPath=()=>n+(this.pageIndex+1)+s,this.pageIndex=parseInt(i,10)-1,this.log("pageIndex",[this.pageIndex,"next link"])},s.updateGetAbsolutePath=function(){let e=this.getPath();if(e.match(/^http/)||e.match(/^\//))return void(this.getAbsolutePath=this.getPath);let{pathname:t}=location,r=e.match(/^\?/),a=t.substring(0,t.lastIndexOf("/")),n=r?t:a+"/";this.getAbsolutePath=()=>n+this.getPath()},i.create.hideNav=function(){let e=r.getQueryElement(this.options.hideNav);e&&(e.style.display="none",this.nav=e)},i.destroy.hideNav=function(){this.nav&&(this.nav.style.display="")},s.destroy=function(){this.allOff();for(let e in i.destroy)i.destroy[e].call(this);delete this.element.infiniteScrollGUID,delete n[this.guid],a&&this.$element&&a.removeData(this.element,"infiniteScroll")},i.throttle=function(e,t){let r,a;return t=t||200,function(){let n=+new Date,i=arguments,s=()=>{r=n,e.apply(this,i)};r&&n<r+t?(clearTimeout(a),a=setTimeout(s,t)):s()}},i.data=function(e){let t=(e=r.getQueryElement(e))&&e.infiniteScrollGUID;return t&&n[t]},i.setJQuery=function(e){a=e},r.htmlInit(i,"infinite-scroll"),s._init=function(){};let{jQueryBridget:d}=e;return a&&d&&d("infiniteScroll",i,a),i}))}(re)),re.exports}re.exports;var se,oe={exports:{}};function le(){return se||(se=1,function(e){!function(t,r){e.exports?e.exports=r(t,ie()):r(t,t.InfiniteScroll)}(window,(function(e,t){let r=t.prototype;Object.assign(t.defaults,{loadOnScroll:!0,checkLastPage:!0,responseBody:"text",domParseResponse:!0}),t.create.pageLoad=function(){this.canLoad=!0,this.on("scrollThreshold",this.onScrollThresholdLoad),this.on("load",this.checkLastPage),this.options.outlayer&&this.on("append",this.onAppendOutlayer)},r.onScrollThresholdLoad=function(){this.options.loadOnScroll&&this.loadNextPage()};let a=new DOMParser;function n(e){let t=document.createDocumentFragment();return e&&t.append(...e),t}return r.loadNextPage=function(){if(this.isLoading||!this.canLoad)return;let{responseBody:e,domParseResponse:t,fetchOptions:r}=this.options,n=this.getAbsolutePath();this.isLoading=!0,"function"==typeof r&&(r=r());let i=fetch(n,r).then((r=>{if(!r.ok){let e=new Error(r.statusText);return this.onPageError(e,n,r),{response:r}}return r[e]().then((i=>("text"==e&&t&&(i=a.parseFromString(i,"text/html")),204==r.status?(this.lastPageReached(i,n),{body:i,response:r}):this.onPageLoad(i,n,r))))})).catch((e=>{this.onPageError(e,n)}));return this.dispatchEvent("request",null,[n,i]),i},r.onPageLoad=function(e,t,r){return this.options.append||(this.isLoading=!1),this.pageIndex++,this.loadCount++,this.dispatchEvent("load",null,[e,t,r]),this.appendNextPage(e,t,r)},r.appendNextPage=function(e,t,r){let{append:a,responseBody:i,domParseResponse:s}=this.options;if(!("text"==i&&s)||!a)return{body:e,response:r};let o=e.querySelectorAll(a),l={body:e,response:r,items:o};if(!o||!o.length)return this.lastPageReached(e,t),l;let c=n(o),u=()=>(this.appendItems(o,c),this.isLoading=!1,this.dispatchEvent("append",null,[e,t,o,r]),l);return this.options.outlayer?this.appendOutlayerItems(c,u):u()},r.appendItems=function(e,t){e&&e.length&&(function(e){let t=e.querySelectorAll("script");for(let e of t){let t=document.createElement("script"),r=e.attributes;for(let e of r)t.setAttribute(e.name,e.value);t.innerHTML=e.innerHTML,e.parentNode.replaceChild(t,e)}}(t=t||n(e)),this.element.appendChild(t))},r.appendOutlayerItems=function(r,a){let n=t.imagesLoaded||e.imagesLoaded;return n?new Promise((function(e){n(r,(function(){let t=a();e(t)}))})):(console.error("[InfiniteScroll] imagesLoaded required for outlayer option"),void(this.isLoading=!1))},r.onAppendOutlayer=function(e,t,r){this.options.outlayer.appended(r)},r.checkLastPage=function(e,t){let r,{checkLastPage:a,path:n}=this.options;if(a){if("function"==typeof n){if(!this.getPath())return void this.lastPageReached(e,t)}"string"==typeof a?r=a:this.isPathSelector&&(r=n),r&&e.querySelector&&(e.querySelector(r)||this.lastPageReached(e,t))}},r.lastPageReached=function(e,t){this.canLoad=!1,this.dispatchEvent("last",null,[e,t])},r.onPageError=function(e,t,r){return this.isLoading=!1,this.canLoad=!1,this.dispatchEvent("error",null,[e,t,r]),e},t.create.prefill=function(){if(!this.options.prefill)return;let e=this.options.append;e?(this.updateMeasurements(),this.updateScroller(),this.isPrefilling=!0,this.on("append",this.prefill),this.once("error",this.stopPrefill),this.once("last",this.stopPrefill),this.prefill()):console.error(`append option required for prefill. Set as :${e}`)},r.prefill=function(){let e=this.getPrefillDistance();this.isPrefilling=e>=0,this.isPrefilling?(this.log("prefill"),this.loadNextPage()):this.stopPrefill()},r.getPrefillDistance=function(){return this.options.elementScroll?this.scroller.clientHeight-this.scroller.scrollHeight:this.windowHeight-this.element.clientHeight},r.stopPrefill=function(){this.log("stopPrefill"),this.off("append",this.prefill)},t}))}(oe)),oe.exports}var ce,ue={exports:{}};function de(){return ce||(ce=1,function(e){!function(t,r){e.exports?e.exports=r(t,ie(),ne):r(t,t.InfiniteScroll,t.fizzyUIUtils)}(window,(function(e,t,r){let a=t.prototype;return Object.assign(t.defaults,{scrollThreshold:400}),t.create.scrollWatch=function(){this.pageScrollHandler=this.onPageScroll.bind(this),this.resizeHandler=this.onResize.bind(this);let e=this.options.scrollThreshold;(e||0===e)&&this.enableScrollWatch()},t.destroy.scrollWatch=function(){this.disableScrollWatch()},a.enableScrollWatch=function(){this.isScrollWatching||(this.isScrollWatching=!0,this.updateMeasurements(),this.updateScroller(),this.on("last",this.disableScrollWatch),this.bindScrollWatchEvents(!0))},a.disableScrollWatch=function(){this.isScrollWatching&&(this.bindScrollWatchEvents(!1),delete this.isScrollWatching)},a.bindScrollWatchEvents=function(t){let r=t?"addEventListener":"removeEventListener";this.scroller[r]("scroll",this.pageScrollHandler),e[r]("resize",this.resizeHandler)},a.onPageScroll=t.throttle((function(){this.getBottomDistance()<=this.options.scrollThreshold&&this.dispatchEvent("scrollThreshold")})),a.getBottomDistance=function(){let t,r;return this.options.elementScroll?(t=this.scroller.scrollHeight,r=this.scroller.scrollTop+this.scroller.clientHeight):(t=this.top+this.element.clientHeight,r=e.scrollY+this.windowHeight),t-r},a.onResize=function(){this.updateMeasurements()},r.debounceMethod(t,"onResize",150),t}))}(ue)),ue.exports}var he,fe={exports:{}};function pe(){return he||(he=1,function(e){!function(t,r){e.exports?e.exports=r(t,ie(),ne):r(t,t.InfiniteScroll,t.fizzyUIUtils)}(window,(function(e,t,r){let a=t.prototype;Object.assign(t.defaults,{history:"replace"});let n=document.createElement("a");return t.create.history=function(){if(!this.options.history)return;n.href=this.getAbsolutePath(),(n.origin||n.protocol+"//"+n.host)==location.origin?this.options.append?this.createHistoryAppend():this.createHistoryPageLoad():console.error(`[InfiniteScroll] cannot set history with different origin: ${n.origin} on ${location.origin} . History behavior disabled.`)},a.createHistoryAppend=function(){this.updateMeasurements(),this.updateScroller(),this.scrollPages=[{top:0,path:location.href,title:document.title}],this.scrollPage=this.scrollPages[0],this.scrollHistoryHandler=this.onScrollHistory.bind(this),this.unloadHandler=this.onUnload.bind(this),this.scroller.addEventListener("scroll",this.scrollHistoryHandler),this.on("append",this.onAppendHistory),this.bindHistoryAppendEvents(!0)},a.bindHistoryAppendEvents=function(t){let r=t?"addEventListener":"removeEventListener";this.scroller[r]("scroll",this.scrollHistoryHandler),e[r]("unload",this.unloadHandler)},a.createHistoryPageLoad=function(){this.on("load",this.onPageLoadHistory)},t.destroy.history=a.destroyHistory=function(){this.options.history&&this.options.append&&this.bindHistoryAppendEvents(!1)},a.onAppendHistory=function(e,t,r){if(!r||!r.length)return;let a=r[0],i=this.getElementScrollY(a);n.href=t,this.scrollPages.push({top:i,path:n.href,title:e.title})},a.getElementScrollY=function(t){if(this.options.elementScroll)return t.offsetTop-this.top;return t.getBoundingClientRect().top+e.scrollY},a.onScrollHistory=function(){let e=this.getClosestScrollPage();e!=this.scrollPage&&(this.scrollPage=e,this.setHistory(e.title,e.path))},r.debounceMethod(t,"onScrollHistory",150),a.getClosestScrollPage=function(){let t,r;t=this.options.elementScroll?this.scroller.scrollTop+this.scroller.clientHeight/2:e.scrollY+this.windowHeight/2;for(let e of this.scrollPages){if(e.top>=t)break;r=e}return r},a.setHistory=function(e,t){let r=this.options.history;r&&history[r+"State"]&&(history[r+"State"](null,e,t),this.options.historyTitle&&(document.title=e),this.dispatchEvent("history",null,[e,t]))},a.onUnload=function(){if(0===this.scrollPage.top)return;let t=e.scrollY-this.scrollPage.top+this.top;this.destroyHistory(),scrollTo(0,t)},a.onPageLoadHistory=function(e,t){this.setHistory(e.title,t)},t}))}(fe)),fe.exports}var ge,me={exports:{}};function ve(){return ge||(ge=1,function(e){!function(t,r){e.exports?e.exports=r(t,ie(),ne):r(t,t.InfiniteScroll,t.fizzyUIUtils)}(window,(function(e,t,r){class a{constructor(e,t){this.element=e,this.infScroll=t,this.clickHandler=this.onClick.bind(this),this.element.addEventListener("click",this.clickHandler),t.on("request",this.disable.bind(this)),t.on("load",this.enable.bind(this)),t.on("error",this.hide.bind(this)),t.on("last",this.hide.bind(this))}onClick(e){e.preventDefault(),this.infScroll.loadNextPage()}enable(){this.element.removeAttribute("disabled")}disable(){this.element.disabled="disabled"}hide(){this.element.style.display="none"}destroy(){this.element.removeEventListener("click",this.clickHandler)}}return t.create.button=function(){let e=r.getQueryElement(this.options.button);e&&(this.button=new a(e,this))},t.destroy.button=function(){this.button&&this.button.destroy()},t.Button=a,t}))}(me)),me.exports}var ye,we={exports:{}};function be(){return ye||(ye=1,function(e){!function(t,r){e.exports?e.exports=r(t,ie(),ne):r(t,t.InfiniteScroll,t.fizzyUIUtils)}(window,(function(e,t,r){let a=t.prototype;function n(e){s(e,"none")}function i(e){s(e,"block")}function s(e,t){e&&(e.style.display=t)}return t.create.status=function(){let e=r.getQueryElement(this.options.status);e&&(this.statusElement=e,this.statusEventElements={request:e.querySelector(".infinite-scroll-request"),error:e.querySelector(".infinite-scroll-error"),last:e.querySelector(".infinite-scroll-last")},this.on("request",this.showRequestStatus),this.on("error",this.showErrorStatus),this.on("last",this.showLastStatus),this.bindHideStatus("on"))},a.bindHideStatus=function(e){let t=this.options.append?"append":"load";this[e](t,this.hideAllStatus)},a.showRequestStatus=function(){this.showStatus("request")},a.showErrorStatus=function(){this.showStatus("error")},a.showLastStatus=function(){this.showStatus("last"),this.bindHideStatus("off")},a.showStatus=function(e){i(this.statusElement),this.hideStatusEventElements(),i(this.statusEventElements[e])},a.hideAllStatus=function(){n(this.statusElement),this.hideStatusEventElements()},a.hideStatusEventElements=function(){for(let e in this.statusEventElements){n(this.statusEventElements[e])}},t}))}(we)),we.exports}
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t(require("lodash/get.js"),require("eventemitter2"),require("store/src/store-engine"),require("store/storages/localStorage"),require("store/storages/sessionStorage"),require("store/storages/cookieStorage"),require("store/storages/memoryStorage"),require("ev-emitter"),require("fizzy-ui-utils")):"function"==typeof define&&define.amd?define(["lodash/get.js","eventemitter2","store/src/store-engine","store/storages/localStorage","store/storages/sessionStorage","store/storages/cookieStorage","store/storages/memoryStorage","ev-emitter","fizzy-ui-utils"],t):(e="undefined"!=typeof globalThis?globalThis:e||self).Salla=t(e.t$1,e.eventemitter2,e.r$1,e.n$1,e.o$1,e.i,e.a,e.evEmitter,e.fizzyUiUtils)}(this,(function(e,t,r,a,n,i,s,o,l){"use strict";function c(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function u(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach((function(r){if("default"!==r){var a=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,a.get?a:{enumerable:!0,get:function(){return e[r]}})}})),t.default=e,Object.freeze(t)}var d=c(e),h=u(r),f=u(a),p=u(n),g=u(i),m=u(s),v=u(o),y=u(l),w="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{};function b(e,t){void 0===t&&(t=!1),e+="";for(var r,a=["٠","١","٢","٣","٤","٥","٦","٧","٨","٩"],n=["0","1","2","3","4","5","6","7","8","9"],i=(t=t||!Salla.config.get("store.settings.arabic_numbers_enabled"))?a:n,s=t?n:a,o=0;o<i.length;o++)r=new RegExp(i[o],"g"),e=e.replace(r,s[o]);return e.replace(t?"٫":".",t?".":"٫")}function S(e){var t=("".concat(e).match(/\./g)||[]).length;return t&&1!==t?S(e.replace(/\.(.+)\./g,".$1")):e}function E(e){return"".concat(e).startsWith("https://")||"".concat(e).startsWith("http://")}function _(e){if(E(e))return e;var t=Salla.config.get("store.url");return t||(t=window.location.href.split("/").slice(0,-1).join("/"),Salla.config.set("store.url",t)),t.rtrim("/")+"/"+(null==e?void 0:e.ltrim("/"))}function A(e,t,r){if(r=r||window.location.href,!t||!e)return r;var a=new RegExp("([?&])"+e+"=[^&]+[&]?","g");return(r=r.replace(a,"$1").split("#")[0].replace(/&$|\?$/,"")).includes("?")?r+="&":r+=(r.endsWith("/")?"":"/")+"?",(r+e+"="+encodeURIComponent(t)).replace(/&$|\?$/,"")}function F(e){return window.location.origin+"/"+(null==e?void 0:e.ltrim("/"))}function P(e){return E(e)?e:Salla.config.get("theme.assets")?Salla.config.get("theme.assets").replace(":path",null==e?void 0:e.ltrim("/")):F("themes/"+Salla.config.get("theme.name")+"/"+(null==e?void 0:e.ltrim("/")))}function x(e,t,r){var a,n=e[0];return r&&0==e.length?Array.isArray(r)?(r.push(t),r):[r,t]:Array.isArray(r)?(r.push(t),r):"string"==typeof r?[r,t]:r?(r[n]=x(e.slice(1),t,r[n]),r):n?((a={})[n]=x(e.slice(1),t),a):""===n?[t]:t}function T(){return window.self!==window.top}String.prototype.toStudlyCase=function(){return this.trim().replace(/([^a-zA-Z\d].)/g,(function(e){return e.toUpperCase().replace(/[^a-zA-Z\d]/g,"")}))},String.prototype.toDatasetName=function(){return this.startsWith("data-")?this.substr(5).toStudlyCase():this.toStudlyCase()},String.prototype.toSelector=function(){return this.trim().startsWith(".")||this.trim().startsWith("#")?this.toString():"#"+this.toString()},String.prototype.replaceArray=function(e,t){for(var r,a=this,n=0;n<e.length;n++)r=new RegExp(e[n],"g"),a=a.replace(r,t[n]);return a},String.prototype.rtrim=function(e){return void 0===e&&(e="\\s"),this.replace(new RegExp("["+e+"]*$"),"")},String.prototype.ltrim=function(e){return void 0===e&&(e="\\s"),this.replace(new RegExp("^["+e+"]*"),"")},String.prototype.digitsOnly=function(){return Salla.helpers.digitsOnly(this)};var R={digitsOnly:function(e){return b(e,!0).replace(/[^0-9.]/g,"").replace("..",".").rtrim(".")},inputDigitsOnly:function e(t,r){if(void 0===r&&(r=!1),"string"==typeof t)return document.querySelectorAll(t).forEach((function(t){return e(t,r)}));if(t){var a=Salla.helpers.digitsOnly(t.value);return t.min&&a<parseInt(t.min)?t.value=t.min:t.max&&a>parseInt(t.max)?t.value=t.max:t.maxLength>=1&&a.toString().length>t.maxLength?t.value=a.toString().substring(0,t.maxLength):t.value=r||t.dataset.hasOwnProperty("digitsWithDecimal")?S(a):a.replace(/\D/g,"")}Salla.logger.warn("Can't find Object With Id: "+t)},number:b,money:function(e){var t=Salla.config.currency(null==e?void 0:e.currency).symbol;return b(e="object"==typeof e?e.amount:e)+" "+t},isIframe:T,isPreview:function(){return T()},setNested:function(e,t,r){for(var a=e,n=t.split("."),i=n.length,s=0;s<i-1;s++){var o=n[s];a[o]||(a[o]={}),a=a[o]}return a[n[i-1]]=r,e},getNested:function(e,t,r){var a=d.default(e,t);return void 0!==a?a:r},inputData:function(e,t,r){if(void 0===r&&(r={}),e.includes("[")){var a=e.split("]").join("").split("["),n=a[0],i=r&&"object"==typeof r?r[n]:void 0;return{name:n,value:x(a.slice(1),t,i)}}return{name:e,value:t}},url:Object.freeze({__proto__:null,is_full_url:E,base:function(e){return E(e)?e:"https://"+new URL(_("/")).hostname+"/"+(null==e?void 0:e.ltrim("/"))},get:_,domain:function(e){return E(e)?e:"".concat(Salla.config.get("store.url",window.location.href.split("/").slice(0,-1).join("/")).rtrim("/"),"/").concat(null==e?void 0:e.ltrim("/"))},addParamToUrl:A,baseUrl:F,asset:P,cdn:function(e,t,r){var a="https://cdn.salla.network/";return(t||r)&&(t=t?",width=".concat(t):"",r=r?",height=".concat(r):"",a+="cdn-cgi/image/fit=scale-down".concat(t).concat(r,",onerror=redirect,format=auto/")),a+(null==e?void 0:e.ltrim("/"))},api:function(e){var t;return(null===(t=Salla.config.get("store.api",_("")))||void 0===t?void 0:t.rtrim("/"))+"/"+(null==e?void 0:e.ltrim("/"))},is_page:function(e){return e&&Salla.config.get("page.slug")===e},is_placeholder:function(e){return P(salla.config.get("theme.settings.placeholder"))===P(e)}}),addParamToUrl:A,debounce:function(e,t){t=t||100;var r,a=[];return function(){for(var n=[],i=0;i<arguments.length;i++)n[i]=arguments[i];return clearTimeout(r),r=setTimeout((function(){var t=e.apply(void 0,n);a.forEach((function(e){return e(t)})),a=[]}),t),new Promise((function(e){return a.push(e)}))}},hasApplePay:function(){var e;try{return!!(null===(e=window.ApplePaySession)||void 0===e?void 0:e.canMakePayments())&&!/snapchat/i.test(navigator.userAgent)}catch(e){return console.error(e),!1}}},C=function(e,t){return C=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},C(e,t)},O=function(){return O=Object.assign||function(e){for(var t,r=1,a=arguments.length;r<a;r++)for(var n in t=arguments[r])Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e},O.apply(this,arguments)};function k(e,t,r){if(r||2===arguments.length)for(var a,n=0,i=t.length;n<i;n++)!a&&n in t||(a||(a=Array.prototype.slice.call(t,0,n)),a[n]=t[n]);return e.concat(a||Array.prototype.slice.call(t))}"function"==typeof SuppressedError&&SuppressedError;var I,L,q,D,U=(I=console,L=[],q=[],D={log:function(e,t){if(I&&salla.config.isDebug()){L.push([t,e]),"trace"===salla.config.get("debug")&&(t="trace");var r=I.log,a=void 0===t?r:this.__dict__[t]||r,n=["%cTwilight","color: #5cd5c4;font-weight:bold; border:1px solid #5cd5c4; padding: 2px 6px; border-radius: 5px;"];q.forEach((function(e){n[0]+=e[0],n.push(e[1])}));var i={event:"#CFF680",backend:"#7b68ee"}[t];i&&(n[0]+="%c"+t[0].toUpperCase()+t.substring(1),n.push("margin-left: 5px;color: ".concat(i,";font-weight:bold; border:1px solid ").concat(i,"; padding: 2px 6px; border-radius: 5px;"))),a.call.apply(a,k([I],n.concat.apply(n,e),!1))}},__dict__:{trace:I.trace,debug:I.debug,info:I.info,warn:I.warn,error:I.error}},{event:function(){D.log(arguments,"event")},trace:function(){D.log(arguments,"trace")},debug:function(){D.log(arguments,"debug")},info:function(){D.log(arguments,"info")},warn:function(){D.log(arguments,"warn")},error:function(){D.log(arguments,"error")},log:function(){D.log(arguments,void 0)},backend:function(){D.log(arguments,"backend")},logs:function(e){[e].flat().forEach((function(e){return e&&D.log([e].flat(),"backend")}))},history:function(){return L.map((function(e){return I.log.apply(I,k([e[0]],e[1],!1))})),L},addPrefix:function(e){return Array.isArray(e)?q.unshift(e):this.warn("addPrefix receives array only!"),this}}),N=function(){function e(e,t){void 0===e&&(e={}),void 0===t&&(t={}),this.default_properties=t,this.properties_=O(O({},this.default_properties),e)}return e.prototype.merge=function(e){var t;return this.properties_=O(O({},this.properties_),e),this.properties_.store=O(O({},(null===(t=this.default_properties)||void 0===t?void 0:t.store)||{}),this.properties_.store),this},e.prototype.set=function(e,t){return e.includes(".")?(Salla.helpers.setNested(this.properties_,e,t),this):(this.properties_[e]=t,this)},e.prototype.currency=function(e){return void 0===e&&(e=void 0),e=e||this.get("user.currency_code"),this.get("currencies."+e)||Object.values(this.get("currencies"))[0]},e.prototype.get=function(e,t){return void 0===t&&(t=null),e.includes(".")?Salla.helpers.getNested(this.properties_,e,t):this.properties_.hasOwnProperty(e)?this.properties_[e]||t:t||void 0},e.prototype.all=function(){return this.properties_},e.prototype.isDebug=function(){return this.get("debug")||Salla.storage.get("debug")},e}(),j=function(e){function t(){var t=this;return(t=e.call(this,{wildcard:!0,delimiter:"::",newListener:!1,removeListener:!1,maxListeners:10,verboseMemoryLeak:!1,ignoreErrors:!1})||this).delimiter="::","undefined"!=typeof document&&(t.body=document.querySelector("body")),t.logableEvents=["cart::item.added.failed","cart::item.deleted.failed"],t.ingoreLogEvents=["document::click","document::keyup","document::change"],t.noneFireableActions=["document.request"],t}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function r(){this.constructor=e}C(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}(t,e),t.prototype.createAndDispatch=function(e){for(var t=[],r=1;r<arguments.length;r++)t[r-1]=arguments[r];this.dispatch.apply(this,k([e],t,!1))},t.prototype.emit=function(t){for(var r,a=[],n=1;n<arguments.length;n++)a[n-1]=arguments[n];var i=t.replace("::",".");if(!this.noneFireableActions.includes(i)&&Salla.call&&"function"==typeof Salla.call(i))return Salla.log("'Salla.".concat(i,"(...)' triggered using event '").concat(t,"'")),i=i.split("."),Array.isArray(a[0])&&(a=a[0]),void(r=salla[i[0]])[i[1]].apply(r,a);e.prototype.emit.apply(this,k([t],a,!1)),this.trackEvents.apply(this,k([t],a,!1))},t.prototype.emitAsync=function(t){for(var r=[],a=1;a<arguments.length;a++)r[a-1]=arguments[a];var n=e.prototype.emitAsync.apply(this,k([t],r,!1));try{this.trackEvents.apply(this,k([t],r,!1))}catch(e){Salla.logger.warn("error on tracking event (".concat(t,")"),r,e)}return n},t.prototype.trackEvents=function(e){for(var t,r=[],a=1;a<arguments.length;a++)r[a-1]=arguments[a];if("undefined"!=typeof window)try{window.dataLayer=window.dataLayer||[];var n={event:e};r.map((function(e){return"object"==typeof e&&(n=O(O({},n),e))})),window.dataLayer.push(n)}catch(e){salla.logger.error(e.message)}Salla.logger&&!this.ingoreLogEvents.includes(e)&&(t=Salla.logger).event.apply(t,k([e],r,!1)),this.dispatchMobileEvent.apply(this,k([e],r,!1))},t.prototype.dispatch=function(e){for(var t=[],r=1;r<arguments.length;r++)t[r-1]=arguments[r];return this.emit.apply(this,k([e],t,!1))},t.prototype.dispatchEvents=function(e){if(e)if("object"!=typeof e||Array.isArray(e))Salla.log("Events object is wrong, it should be object of {event:payload}",e);else for(var t=0,r=Object.entries(e);t<r.length;t++){var a=r[t],n=a[0],i=a[1];this.dispatch(n,i)}else Salla.log("No Events To Dispatch!",e)},t.prototype.addListener=function(e,t,r){return this.on(e,t,r)},t.prototype.addEventListener=function(e,t,r){return this.on(e,t,r)},t.prototype.listen=function(e,t){return this.on(e,t)},t.prototype.registerGlobalListener=function(e,t){return this.onAny(t)},t.prototype.dispatchMobileEvent=function(e,t){if(void 0===t&&(t={}),!("undefined"!=typeof window&&window.dataLayer&&window.dataLayer[0]&&window.dataLayer[0].page&&window.dataLayer[0].page.mobileApp))return"";if(window.webkit)try{window.webkit.messageHandlers.callbackHandler.postMessage(JSON.stringify({event:e,details:t}))}catch(e){Salla.log(e,"The native context does not exist yet")}else if(void 0!==window.Android)try{window.Android.customEventWithData(e,JSON.stringify({details:t}))}catch(e){Salla.log(e,"The native context does not exist yet")}},t}(t.EventEmitter2),B=h.createStore([f,p,g,m],[]),M=h.createStore([p],[]),H=h.createStore([g],[]),$=function(){function e(){var e=this;this.clearableItems=["cart","user","salla::wishlist","token"],Salla.event.on("storage::item.remove",(function(t){return e.remove(t)})),Salla.event.on("storage::item.set",(function(t,r){return e.set(t,r)})),this.store=B,this.session=M,this.cookie=H}return e.prototype.set=function(e,t){var r;if(e.includes(".")){var a=e.split(".")[0],n=((r={})[a]=this.store.get(a),r);return n=Salla.helpers.setNested(n,e,t),this.store.set(a,n[a])}return this.store.set(e,t)},e.prototype.remove=function(e){return this.store.remove(e)},e.prototype.clearAll=function(e){var t=this;if(void 0===e&&(e=!1),e)return this.store.clearAll();this.clearableItems.forEach((function(e){t.store.remove(e)}))},e.prototype.get=function(e,t){var r;if(e.includes(".")){var a=e.split(".")[0];return Salla.helpers.getNested(((r={})[a]=this.store.get(a),r),e)}return this.store.get(e,t)},e.prototype.prefixKey=function(e){return"".concat(Salla.config.get("theme.translations_hash"),"_").concat(e,"_").concat(Salla.config.get("store.id"))},e.prototype.setWithTTL=function(e,t,r,a){void 0===r&&(r=10),void 0===a&&(a="store");var n=this.prefixKey(e),i=(new Date).getTime()+60*r*1e3;return this[a].set(n,{value:t,expiry:i})},e.prototype.getWithTTL=function(e,t,r){void 0===t&&(t=null),void 0===r&&(r="store");var a=this.prefixKey(e),n=this[r].get(a);return n?(new Date).getTime()>n.expiry?(this[r].remove(a),t):n.value:t},e}(),z=function(){function e(){var e=this;this.keysToRemove=["__said","__ssid","theme_edit","ws_port","s-token"],this.dynamicKeysToRemove=["affiliate"],Salla.event.on("cookies::remove",(function(t){return e.remove(t)})),Salla.event.on("cookies::add",(function(t,r){return e.set(t,r)}))}return e.prototype.get=function(e){var t;return null===(t=document.cookie.split("; ").find((function(t){return t.startsWith(e+"=")})))||void 0===t?void 0:t.split("=")[1]},e.prototype.set=function(e,t,r){void 0===t&&(t=""),void 0===r&&(r=10);var a="";if(r){var n=new Date;n.setTime(n.getTime()+24*r*60*60*1e3),a="; expires="+n.toUTCString()}var i=salla.helpers.isIframe()?"None":"Lax";return document.cookie="".concat(e,"=").concat(t).concat(a,"; path=/; SameSite=").concat(i,"; secure"),this},e.prototype.remove=function(e){var t=salla.helpers.isIframe()?"None":"Lax";return document.cookie="".concat(e,"=; Max-Age=0; path=/; SameSite=").concat(t,"; secure"),this},e.prototype.clearAll=function(e){return void 0===e&&(e=!1),this.clean(e)},e.prototype.clean=function(e){var t=this;return document.cookie.split(";").map((function(e){return e.split("=")[0].trim()})).filter((function(r){return e||t.keysToRemove.includes(r)||t.dynamicKeysToRemove.some((function(e){return r.startsWith(e)}))})).forEach((function(e){return t.remove(e)})),this},e}();"undefined"!=typeof window&&(window.salla=window.salla||window.Salla||{},window.Salla=window.salla),void 0!==w&&(w.salla=w.salla||w.Salla||{},w.Salla=w.salla),Salla.status="base",Salla.config=new N,Salla.logger=U,Salla.event=new j,Salla.helpers=R,Salla.storage=new $,Salla.cookie=new z,Salla.log=Salla.logger.log,Salla.money=Salla.helpers.money,Salla.url=Salla.helpers.url,Salla.versions={base:"2.15.0-alpha.0"};var Y=Salla;let W=function(e,t,r){return alert(e)},V=function(e,t){return W(e,G.error,t)},G={error:"error",success:"success",info:"info"};var Q={fire:function(e,t,r){return W(e,t,r)},setNotifier:function(e){W=e,salla.event.emit("twilight::notifier.changed")},error:V,success:function(e,t){return W(e,G.success,t)},info:function(e,t){return W(e,G.info,t)},sallaInitiated:function(){let e=window.location.href.match(/([\?\&]danger=)[^&]+/g);e&&(window.history.replaceState(null,document.title,window.location.pathname),salla.event.once("twilight::notifier.changed",(()=>{e.forEach((e=>{e=decodeURI(e.replace("?danger=","").replace("&danger=",""));let t=document.createElement("div");t.innerText=e,V(t.innerHTML),salla.event.emit("twilight::error",e)}))})))},types:G};class K{constructor(e,t){return this.api=e,this.event=t,new Proxy(this,{get:function(r,a){return"event"===a?t:"api"===a?e:e&&e[a]||r[a]}})}}Element.prototype.matches||(Element.prototype.matches=Element.prototype.msMatchesSelector),Element.prototype.closest||(Element.prototype.closest=function(e){for(var t=this;t;){if(t.matches(e))return t;t=t.parentElement}}),Element.prototype.getElementSallaData=function(e,...t){if(!this.getAttribute)return;if(this.hasAttribute("data-json"))try{return JSON.parse(this.getAttribute("data-json"))}catch(e){}let r=this.getAttribute("data-function");if(r&&window[r])return"function"==typeof window[r]?this.getFilteredData(window[r].call(this,...t)):this.getFilteredData(window[r]);let a=this.hasAttribute("data-form-selector")?document.querySelector(this.dataset.formSelector):void 0;if(a="FORM"===this.tagName?this:a||this.closest("form")||this.closest("[salla-form-data]")||this,a&&"FORM"===a.tagName)return this.getFilteredData(new FormData(a),null,a);let n=a.querySelectorAll("[name]");if(!n.length)return this.getFilteredData();let i=Object.assign({},this.dataset);return n.forEach((e=>{if(!["checkbox","radio"].includes(e.type)||e.checked)try{let t=Salla.helpers.inputData(e.name,e.value,i);i[t.name]=t.value}catch(t){Salla.log(e.name+" can't be send")}})),this.getFilteredData(i)},Element.prototype.canEventFireHook=function(e){return!!this.hasAttribute&&this.hasAttribute(Salla.api.hooksPrefix+e.type)},Element.prototype.hasAttributeStartsWith=function(e,t){e=e.toLowerCase();for(var r=0;r<this.attributes.length;r++){let a=this.attributes[r].name.toLowerCase();if(0===a.indexOf(e))return!t||a}return!1},HTMLFormElement.prototype.getAjaxFormData=function(e){var t=this.querySelectorAll('input[type="file"]');t.forEach((e=>{e.files.length||e.setAttribute("disabled","")}));var r=new FormData(this);return t.forEach((e=>{e.files.length||e.removeAttribute("disabled")})),{formData:this.getFilteredData(r,e),url:this.getAttribute("action"),method:this.getAttribute("method")||"post",events:{success:this.dataset.onSuccess,fail:this.dataset.onFail}}},Element.prototype.getFilteredData=function(e=null,t=null,r=null){return e=e||r?.dataset||this.dataset,r&&this.name&&void 0!==this.value&&(e=function(e,t,r){e instanceof FormData?e.append(t,r):e[t]=r;return e}(e,this.name,this.value)),["filterBeforeSubmit","filterBeforeSend"].forEach((a=>{let n=r?.dataset[a]||this.dataset[a];if(n){var i=window[n];if("function"==typeof i){if(!i(e,r||this,t)&&e)throw`Data failed to be pass verify function window.${n}(formData, element, event)!`;return i(e,r||this,t)}Salla.log("window."+n+"() not found!")}})),e},HTMLAnchorElement.prototype.getAjaxFormData=function(e){return{formData:this.getFilteredData(null,e),url:this.getAttribute("href"),method:this.dataset.type||"get",events:{success:this.dataset.onSuccess,fail:this.dataset.onFail}}};class J{constructor(){this.events={},this.namespace="";let e=/function (.{1,})\(/.exec(this.constructor.toString());this.className=(e&&e.length>1?e[1]:"").toLowerCase()}after_init(){this.createDynamicFunctions()}createDynamicFunctions(){Object.keys(this.events).forEach((e=>{this.createDynamicEventFuns(e),this.createDynamicListenerFuns(e)}))}createDynamicEventFuns(e){if(this[e])return;let t=this;this[e]=function(...r){return t.dispatch(e,...r)}}createDynamicListenerFuns(e){let t="on"+e.charAt(0).toUpperCase()+e.slice(1);if(this[t])return;let r=this;this[t]=function(t){return r.on(e,(async(...e)=>t(...e)))}}getEventName(e){return e=this.events[e]||e,!this.namespace||e.includes("::")?e:this.namespace+Salla.event.delimiter+e}dispatch(e,...t){return Salla.event.emitAsync(this.getEventName(e),...t)}on(e,t,r={}){return Salla.event.addListener(this.getEventName(e),t,r)}once(e,t){return Salla.event.once(this.getEventName(e),t)}}function X(e){e&&e.sallaInitiated&&!e.initiated&&(e.sallaInitiated(),e.initiated=!0)}Salla.event.auth=new class extends J{constructor(){super(),this.namespace="auth",this.events={login:"login",logout:"logout",codeSent:"code.sent",codeNotSent:"code.not-sent",verified:"verified",verificationFailed:"verification.failed",loggedIn:"logged.in",registered:"registered",registrationFailed:"registration.failed",loggedOut:"logged.out",failedLogout:"failed.logout",refreshFailed:"refresh.failed",tokenFetched:"token.fetched",tokenInvalid:"token.invalid"},this.after_init()}login(e){return e?(e.type&&this.setTypeActionOnVerified(e.type),this.next_event=e.next_event||null,this.dispatch("login",...arguments)):(this.next_event=null,this.dispatch("login",...arguments))}async loggedIn(e){return Salla.profile.info().finally((()=>this.dispatch("loggedIn",e)))}setTypeActionOnVerified(e){this.type_action_on_verified=e}getTypeActionOnVerified(){return this.type_action_on_verified||"redirect"}},Salla.event.cart=new class extends J{constructor(){super(),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",priceQuoteSucceeded:"price-quote.succeeded",priceQuoteFailed:"price-quote.failed",offersFetched:"offers.fetched",offersFailed:"offers.failed",couponAdded:"coupon.added",couponDeleted:"coupon.deleted",couponAdditionFailed:"coupon.addition.failed",couponDeletionFailed:"coupon.deletion.failed",quickOrderSettingFetched:"quick-order.fetched",quickOrderSettingFailed:"quick-order.failed",quickOrderSucceeded:"quick-order.succeeded",quickOrderFailed:"quick-order.failed"},this.after_init()}updated(e){return Salla.cookie.set("fresh_summary",1),e&&"object"==typeof e?(e.offer&&salla.product.event.offerExisted(e.offer),e.redirect&&(salla.log("The current cart is purchased!"),salla.cart.api.reset()),e.cart?(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)):void salla.log("Failed to get the cart summary!")):(Salla.logger.info("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)}},Salla.event.order=new class extends J{constructor(){super(),this.namespace="order",this.events={canceled:"canceled",notCanceled:"not.canceled",orderCreated:"order.created",orderCreationFailed:"order.creation.failed",invoiceSent:"invoice.sent",invoiceNotSent:"invoice.not.sent",ordersFetched:"order.fetched",ordersNotFetched:"order.not.fetched"},this.after_init()}},Salla.event.scope=new class extends J{constructor(){super(),this.namespace="scope",this.events={fetched:"fetched",notFetched:"not.fetched",productAvailabilityFetched:"product-availability.fetched",productAvailabilityNotFetched:"product-availability.not.fetched",changeSucceeded:"changed",changeFailed:"not.changed"},this.after_init()}},Salla.event.rating=new class extends J{constructor(){super(),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()}},Salla.event.booking=new class extends J{constructor(){super(),this.namespace="booking",this.events={added:"added",additionFailed:"addition.failed"},this.after_init()}},Salla.event.comment=new class extends J{constructor(){super(),this.namespace="comment",this.events={added:"added",additionFailed:"addition.failed",fetched:"fetched",fetchFailed:"fetch.failed"},this.after_init()}},Salla.event.landing=new class extends J{constructor(){super(),this.namespace="landing",this.events={detailsFetched:"order.fetched",getDetailsFailed:"get.details.failed",orderCreated:"order.created",orderCreationFailed:"order.creation.failed",breadcrumbFetched:"breadcrumb.fetched",breadcrumbFetchFailed:"breadcrumb.fetch.failed"},this.after_init()}},Salla.event.loyalty=new class extends J{constructor(){super(),this.namespace="loyalty",this.events={exchangeSucceeded:"exchange.succeeded",exchangeFailed:"exchange.failed",programFetched:"program.fetched",programNotFetched:"program.not.fetched",resetSucceeded:"exchange-reset.succeeded",resetFailed:"exchange-reset.failed"},this.after_init()}exchangeSucceeded(e,t){return salla.cart.event.updated(e.data),this.dispatch("exchangeSucceeded",e,t)}resetSucceeded(e){return salla.cart.event.updated(e.data),this.dispatch("resetSucceeded",e)}},Salla.event.product=new class extends J{constructor(){super(),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",offerExisted:"offer.existed",fetchOffersFailed:"fetch.offers.failed",offersFetched:"offers.fetched",sizeGuideFetched:"size-guide.fetched",sizeGuideFetchFailed:"size-guide.failed",giftFetched:"gift.fetched",giftFetchFailed:"gift.failed",detailFetched:"detail.fetched",detailFetchFailed:"detail.failed",addGiftToCartSucceeded:"gift.add-to-cart.succeeded",addGiftToCartFailed:"gift.add-to-cart.failed",giftImageUploadSucceeded:"gift.image-upload.succeeded",giftImageUploadFailed:"gift.image-upload.failed",productListFetchSucceeded:"fetch.succeeded",productListFetchFailed:"fetch.failed",productOptionsFetched:"options.fetched",productOptionsNotFetched:"options.not.fetched"},this.after_init()}},Salla.event.profile=new class extends J{constructor(){super(),this.namespace="profile",this.events={updated:"updated",updateFailed:"update.failed",verificationCodeSent:"verification.code.sent",updateContactsFailed:"update.contacts.failed",verified:"verified",unverified:"unverified",infoFetched:"info.fetched",infoNotFetched:"info.not.fetched",settingsUpdated:"settings.updated",updateSettingsFailed:"update.settings.failed",deleted:"deleted",notDeleted:"not.deleted"},this.after_init()}},Salla.event.currency=new class extends J{constructor(){super(),this.namespace="currency",this.events={changed:"changed",failed:"failed",fetched:"fetched",failedToFetch:"failed.to.fetch"},this.after_init()}},Salla.event.document=new class extends J{constructor(){super(),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,r){this.on(e,(e=>{"function"!=typeof t?"function"==typeof r&&e.target.matches(t)&&r(e):t(e)}))}fireEvent(e,t,...r){return this.fireEventForElements(e,t,!1,...r)}fireEventForAll(e,t,...r){return this.fireEventForElements(e,t,!0,...r)}fireEventForElements(e,t,r,...a){if("string"==typeof e){if(r)return document.querySelectorAll(e).forEach((e=>this.fireEventForElements(e,t,!1,...a)));e=document.querySelector(e)}if(!e)return void salla.log("Failed To get element to fire event: "+t);const n=new CustomEvent(t,...a);return e.dispatchEvent(n)}},Salla.event.wishlist=new class extends J{constructor(){super(),this.namespace="wishlist",this.events={added:"added",removed:"removed",additionFailed:"addition.failed",removingFailed:"removing.failed"},this.after_init()}},Salla.event.infiniteScroll=new class extends J{constructor(){super(),this.namespace="infiniteScroll",this.events={scrollThreshold:"scroll.threshold",request:"request",load:"load",append:"append",error:"error",last:"last",history:"history"},this.after_init()}},Salla.event.notifications=new class extends J{constructor(){super(),this.namespace="notifications",this.events={fetched:"fetched",fetchFailed:"fetch.failed"},this.after_init()}},Salla.event.component=new class extends J{constructor(){super(),this.namespace="component",this.events={menuFetched:"menus.fetched",menuFetchFailed:"menus.fetch.failed",reviewsFetched:"reviews.fetched",reviewsFetchFailed:"reviews.fetch.failed"},this.after_init()}},Salla.event.advertisement=new class extends J{constructor(){super(),this.namespace="advertisement",this.events={fetched:"advertisement.fetched",fetchFailed:"advertisement.not.fetched"},this.after_init()}},Salla.event.navigation=new class extends J{constructor(){super(),this.namespace="navigation",this.events={breadcrumbFetched:"breadcrumb.fetched",breadcrumbFetchFailed:"breadcrumb.fetch.failed"},this.after_init()}},Salla.event.on("twilight::initiated",(()=>{Object.keys(Salla).forEach((e=>{"object"==typeof(e=Salla[e])&&(X(e),Object.keys(e).forEach((t=>{X(e[t])})))}))})),Salla.config.default_properties={debug:"undefined"!=typeof process&&"development"===process.env.NODE_ENV,token:null,fastRequests:!0,canLeave:!0,store:{api:"https://api.salla.dev/store/v1/"},currencies:{SAR:{code:"SAR",name:"ريال سعودي",symbol:"ر.س",amount:1,country_code:"sa"}}},Salla.config.merge(Salla.config.default_properties),Salla.config.triedToGetCurrencies_=!1,Salla.config.triedToGetLanguages_=!1,Salla.config.isUser=()=>"user"===Salla.config.get("user.type"),Salla.config.isGuest=()=>!Salla.config.isUser(),Salla.config.languages=async()=>{if(Salla.config.triedToGetLanguages_)return Salla.config.get("languages");Salla.config.triedToGetLanguages_=!0;let e=!0,t=[];return(await salla.document.api.request("languages",null,"get"))?.data?.map((r=>{e&&(t=[],e=!1),r.code=r.code||r.iso_code,r.url=salla.url.get(r.code),r.is_rtl=r.is_rtl||r.rtl,t.push(r)})),Salla.config.set("languages",t),t},Salla.config.currencies=async()=>{if(Salla.config.triedToGetCurrencies_)return Salla.config.get("currencies");Salla.config.triedToGetCurrencies_=!0;let e=!0,t={};return(await salla.currency.api.list())?.data?.map((r=>{e&&(t={},e=!1),r.country_code=r.code.substr(0,2).toLowerCase(),t[r.code]=r})),Salla.config.set("currencies",t),t};"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self&&self;function Z(e){return e&&Object.prototype.hasOwnProperty.call(e,"default")&&1===Object.keys(e).length?e.default:e}var ee,te={exports:{}},re={exports:{}},ae=Z(v),ne=Z(y);function ie(){return ee||(ee=1,function(e){!function(t,r){e.exports?e.exports=r(t,ae,ne):t.InfiniteScroll=r(t,t.EvEmitter,t.fizzyUIUtils)}(window,(function(e,t,r){let a=e.jQuery,n={};function i(e,t){let s=r.getQueryElement(e);if(s){if((e=s).infiniteScrollGUID){let r=n[e.infiniteScrollGUID];return r.option(t),r}this.element=e,this.options={...i.defaults},this.option(t),a&&(this.$element=a(this.element)),this.create()}else console.error("Bad element for InfiniteScroll: "+(s||e))}i.defaults={},i.create={},i.destroy={};let s=i.prototype;Object.assign(s,t.prototype);let o=0;s.create=function(){let e=this.guid=++o;if(this.element.infiniteScrollGUID=e,n[e]=this,this.pageIndex=1,this.loadCount=0,this.updateGetPath(),this.getPath&&this.getPath()){this.updateGetAbsolutePath(),this.log("initialized",[this.element.className]),this.callOnInit();for(let e in i.create)i.create[e].call(this)}else console.error("Disabling InfiniteScroll")},s.option=function(e){Object.assign(this.options,e)},s.callOnInit=function(){let e=this.options.onInit;e&&e.call(this,this)},s.dispatchEvent=function(e,t,r){this.log(e,r);let n=t?[t].concat(r):r;if(this.emitEvent(e,n),!a||!this.$element)return;let i=e+=".infiniteScroll";if(t){let r=a.Event(t);r.type=e,i=r}this.$element.trigger(i,r)};let l={initialized:e=>`on ${e}`,request:e=>`URL: ${e}`,load:(e,t)=>`${e.title||""}. URL: ${t}`,error:(e,t)=>`${e}. URL: ${t}`,append:(e,t,r)=>`${r.length} items. URL: ${t}`,last:(e,t)=>`URL: ${t}`,history:(e,t)=>`URL: ${t}`,pageIndex:function(e,t){return`current page determined to be: ${e} from ${t}`}};s.log=function(e,t){if(!this.options.debug)return;let r=`[InfiniteScroll] ${e}`,a=l[e];a&&(r+=". "+a.apply(this,t)),console.log(r)},s.updateMeasurements=function(){this.windowHeight=e.innerHeight;let t=this.element.getBoundingClientRect();this.top=t.top+e.scrollY},s.updateScroller=function(){let t=this.options.elementScroll;if(t){if(this.scroller=!0===t?this.element:r.getQueryElement(t),!this.scroller)throw new Error(`Unable to find elementScroll: ${t}`)}else this.scroller=e},s.updateGetPath=function(){let e=this.options.path;if(!e)return void console.error(`InfiniteScroll path option required. Set as: ${e}`);let t=typeof e;"function"!=t?"string"==t&&e.match("{{#}}")?this.updateGetPathTemplate(e):this.updateGetPathSelector(e):this.getPath=e},s.updateGetPathTemplate=function(e){this.getPath=()=>{let t=this.pageIndex+1;return e.replace("{{#}}",t)};let t=e.replace(/(\\\?|\?)/,"\\?").replace("{{#}}","(\\d\\d?\\d?)"),r=new RegExp(t),a=location.href.match(r);a&&(this.pageIndex=parseInt(a[1],10),this.log("pageIndex",[this.pageIndex,"template string"]))};let c=[/^(.*?\/?page\/?)(\d\d?\d?)(.*?$)/,/^(.*?\/?\?page=)(\d\d?\d?)(.*?$)/,/(.*?)(\d\d?\d?)(?!.*\d)(.*?$)/],u=i.getPathParts=function(e){if(e)for(let t of c){let r=e.match(t);if(r){let[,e,t,a]=r;return{begin:e,index:t,end:a}}}};s.updateGetPathSelector=function(e){let t=document.querySelector(e);if(!t)return void console.error(`Bad InfiniteScroll path option. Next link not found: ${e}`);let r=t.getAttribute("href"),a=u(r);if(!a)return void console.error(`InfiniteScroll unable to parse next link href: ${r}`);let{begin:n,index:i,end:s}=a;this.isPathSelector=!0,this.getPath=()=>n+(this.pageIndex+1)+s,this.pageIndex=parseInt(i,10)-1,this.log("pageIndex",[this.pageIndex,"next link"])},s.updateGetAbsolutePath=function(){let e=this.getPath();if(e.match(/^http/)||e.match(/^\//))return void(this.getAbsolutePath=this.getPath);let{pathname:t}=location,r=e.match(/^\?/),a=t.substring(0,t.lastIndexOf("/")),n=r?t:a+"/";this.getAbsolutePath=()=>n+this.getPath()},i.create.hideNav=function(){let e=r.getQueryElement(this.options.hideNav);e&&(e.style.display="none",this.nav=e)},i.destroy.hideNav=function(){this.nav&&(this.nav.style.display="")},s.destroy=function(){this.allOff();for(let e in i.destroy)i.destroy[e].call(this);delete this.element.infiniteScrollGUID,delete n[this.guid],a&&this.$element&&a.removeData(this.element,"infiniteScroll")},i.throttle=function(e,t){let r,a;return t=t||200,function(){let n=+new Date,i=arguments,s=()=>{r=n,e.apply(this,i)};r&&n<r+t?(clearTimeout(a),a=setTimeout(s,t)):s()}},i.data=function(e){let t=(e=r.getQueryElement(e))&&e.infiniteScrollGUID;return t&&n[t]},i.setJQuery=function(e){a=e},r.htmlInit(i,"infinite-scroll"),s._init=function(){};let{jQueryBridget:d}=e;return a&&d&&d("infiniteScroll",i,a),i}))}(re)),re.exports}re.exports;var se,oe={exports:{}};function le(){return se||(se=1,function(e){!function(t,r){e.exports?e.exports=r(t,ie()):r(t,t.InfiniteScroll)}(window,(function(e,t){let r=t.prototype;Object.assign(t.defaults,{loadOnScroll:!0,checkLastPage:!0,responseBody:"text",domParseResponse:!0}),t.create.pageLoad=function(){this.canLoad=!0,this.on("scrollThreshold",this.onScrollThresholdLoad),this.on("load",this.checkLastPage),this.options.outlayer&&this.on("append",this.onAppendOutlayer)},r.onScrollThresholdLoad=function(){this.options.loadOnScroll&&this.loadNextPage()};let a=new DOMParser;function n(e){let t=document.createDocumentFragment();return e&&t.append(...e),t}return r.loadNextPage=function(){if(this.isLoading||!this.canLoad)return;let{responseBody:e,domParseResponse:t,fetchOptions:r}=this.options,n=this.getAbsolutePath();this.isLoading=!0,"function"==typeof r&&(r=r());let i=fetch(n,r).then((r=>{if(!r.ok){let e=new Error(r.statusText);return this.onPageError(e,n,r),{response:r}}return r[e]().then((i=>("text"==e&&t&&(i=a.parseFromString(i,"text/html")),204==r.status?(this.lastPageReached(i,n),{body:i,response:r}):this.onPageLoad(i,n,r))))})).catch((e=>{this.onPageError(e,n)}));return this.dispatchEvent("request",null,[n,i]),i},r.onPageLoad=function(e,t,r){return this.options.append||(this.isLoading=!1),this.pageIndex++,this.loadCount++,this.dispatchEvent("load",null,[e,t,r]),this.appendNextPage(e,t,r)},r.appendNextPage=function(e,t,r){let{append:a,responseBody:i,domParseResponse:s}=this.options;if(!("text"==i&&s)||!a)return{body:e,response:r};let o=e.querySelectorAll(a),l={body:e,response:r,items:o};if(!o||!o.length)return this.lastPageReached(e,t),l;let c=n(o),u=()=>(this.appendItems(o,c),this.isLoading=!1,this.dispatchEvent("append",null,[e,t,o,r]),l);return this.options.outlayer?this.appendOutlayerItems(c,u):u()},r.appendItems=function(e,t){e&&e.length&&(function(e){let t=e.querySelectorAll("script");for(let e of t){let t=document.createElement("script"),r=e.attributes;for(let e of r)t.setAttribute(e.name,e.value);t.innerHTML=e.innerHTML,e.parentNode.replaceChild(t,e)}}(t=t||n(e)),this.element.appendChild(t))},r.appendOutlayerItems=function(r,a){let n=t.imagesLoaded||e.imagesLoaded;return n?new Promise((function(e){n(r,(function(){let t=a();e(t)}))})):(console.error("[InfiniteScroll] imagesLoaded required for outlayer option"),void(this.isLoading=!1))},r.onAppendOutlayer=function(e,t,r){this.options.outlayer.appended(r)},r.checkLastPage=function(e,t){let r,{checkLastPage:a,path:n}=this.options;if(a){if("function"==typeof n){if(!this.getPath())return void this.lastPageReached(e,t)}"string"==typeof a?r=a:this.isPathSelector&&(r=n),r&&e.querySelector&&(e.querySelector(r)||this.lastPageReached(e,t))}},r.lastPageReached=function(e,t){this.canLoad=!1,this.dispatchEvent("last",null,[e,t])},r.onPageError=function(e,t,r){return this.isLoading=!1,this.canLoad=!1,this.dispatchEvent("error",null,[e,t,r]),e},t.create.prefill=function(){if(!this.options.prefill)return;let e=this.options.append;e?(this.updateMeasurements(),this.updateScroller(),this.isPrefilling=!0,this.on("append",this.prefill),this.once("error",this.stopPrefill),this.once("last",this.stopPrefill),this.prefill()):console.error(`append option required for prefill. Set as :${e}`)},r.prefill=function(){let e=this.getPrefillDistance();this.isPrefilling=e>=0,this.isPrefilling?(this.log("prefill"),this.loadNextPage()):this.stopPrefill()},r.getPrefillDistance=function(){return this.options.elementScroll?this.scroller.clientHeight-this.scroller.scrollHeight:this.windowHeight-this.element.clientHeight},r.stopPrefill=function(){this.log("stopPrefill"),this.off("append",this.prefill)},t}))}(oe)),oe.exports}var ce,ue={exports:{}};function de(){return ce||(ce=1,function(e){!function(t,r){e.exports?e.exports=r(t,ie(),ne):r(t,t.InfiniteScroll,t.fizzyUIUtils)}(window,(function(e,t,r){let a=t.prototype;return Object.assign(t.defaults,{scrollThreshold:400}),t.create.scrollWatch=function(){this.pageScrollHandler=this.onPageScroll.bind(this),this.resizeHandler=this.onResize.bind(this);let e=this.options.scrollThreshold;(e||0===e)&&this.enableScrollWatch()},t.destroy.scrollWatch=function(){this.disableScrollWatch()},a.enableScrollWatch=function(){this.isScrollWatching||(this.isScrollWatching=!0,this.updateMeasurements(),this.updateScroller(),this.on("last",this.disableScrollWatch),this.bindScrollWatchEvents(!0))},a.disableScrollWatch=function(){this.isScrollWatching&&(this.bindScrollWatchEvents(!1),delete this.isScrollWatching)},a.bindScrollWatchEvents=function(t){let r=t?"addEventListener":"removeEventListener";this.scroller[r]("scroll",this.pageScrollHandler),e[r]("resize",this.resizeHandler)},a.onPageScroll=t.throttle((function(){this.getBottomDistance()<=this.options.scrollThreshold&&this.dispatchEvent("scrollThreshold")})),a.getBottomDistance=function(){let t,r;return this.options.elementScroll?(t=this.scroller.scrollHeight,r=this.scroller.scrollTop+this.scroller.clientHeight):(t=this.top+this.element.clientHeight,r=e.scrollY+this.windowHeight),t-r},a.onResize=function(){this.updateMeasurements()},r.debounceMethod(t,"onResize",150),t}))}(ue)),ue.exports}var he,fe={exports:{}};function pe(){return he||(he=1,function(e){!function(t,r){e.exports?e.exports=r(t,ie(),ne):r(t,t.InfiniteScroll,t.fizzyUIUtils)}(window,(function(e,t,r){let a=t.prototype;Object.assign(t.defaults,{history:"replace"});let n=document.createElement("a");return t.create.history=function(){if(!this.options.history)return;n.href=this.getAbsolutePath(),(n.origin||n.protocol+"//"+n.host)==location.origin?this.options.append?this.createHistoryAppend():this.createHistoryPageLoad():console.error(`[InfiniteScroll] cannot set history with different origin: ${n.origin} on ${location.origin} . History behavior disabled.`)},a.createHistoryAppend=function(){this.updateMeasurements(),this.updateScroller(),this.scrollPages=[{top:0,path:location.href,title:document.title}],this.scrollPage=this.scrollPages[0],this.scrollHistoryHandler=this.onScrollHistory.bind(this),this.unloadHandler=this.onUnload.bind(this),this.scroller.addEventListener("scroll",this.scrollHistoryHandler),this.on("append",this.onAppendHistory),this.bindHistoryAppendEvents(!0)},a.bindHistoryAppendEvents=function(t){let r=t?"addEventListener":"removeEventListener";this.scroller[r]("scroll",this.scrollHistoryHandler),e[r]("unload",this.unloadHandler)},a.createHistoryPageLoad=function(){this.on("load",this.onPageLoadHistory)},t.destroy.history=a.destroyHistory=function(){this.options.history&&this.options.append&&this.bindHistoryAppendEvents(!1)},a.onAppendHistory=function(e,t,r){if(!r||!r.length)return;let a=r[0],i=this.getElementScrollY(a);n.href=t,this.scrollPages.push({top:i,path:n.href,title:e.title})},a.getElementScrollY=function(t){if(this.options.elementScroll)return t.offsetTop-this.top;return t.getBoundingClientRect().top+e.scrollY},a.onScrollHistory=function(){let e=this.getClosestScrollPage();e!=this.scrollPage&&(this.scrollPage=e,this.setHistory(e.title,e.path))},r.debounceMethod(t,"onScrollHistory",150),a.getClosestScrollPage=function(){let t,r;t=this.options.elementScroll?this.scroller.scrollTop+this.scroller.clientHeight/2:e.scrollY+this.windowHeight/2;for(let e of this.scrollPages){if(e.top>=t)break;r=e}return r},a.setHistory=function(e,t){let r=this.options.history;r&&history[r+"State"]&&(history[r+"State"](null,e,t),this.options.historyTitle&&(document.title=e),this.dispatchEvent("history",null,[e,t]))},a.onUnload=function(){if(0===this.scrollPage.top)return;let t=e.scrollY-this.scrollPage.top+this.top;this.destroyHistory(),scrollTo(0,t)},a.onPageLoadHistory=function(e,t){this.setHistory(e.title,t)},t}))}(fe)),fe.exports}var ge,me={exports:{}};function ve(){return ge||(ge=1,function(e){!function(t,r){e.exports?e.exports=r(t,ie(),ne):r(t,t.InfiniteScroll,t.fizzyUIUtils)}(window,(function(e,t,r){class a{constructor(e,t){this.element=e,this.infScroll=t,this.clickHandler=this.onClick.bind(this),this.element.addEventListener("click",this.clickHandler),t.on("request",this.disable.bind(this)),t.on("load",this.enable.bind(this)),t.on("error",this.hide.bind(this)),t.on("last",this.hide.bind(this))}onClick(e){e.preventDefault(),this.infScroll.loadNextPage()}enable(){this.element.removeAttribute("disabled")}disable(){this.element.disabled="disabled"}hide(){this.element.style.display="none"}destroy(){this.element.removeEventListener("click",this.clickHandler)}}return t.create.button=function(){let e=r.getQueryElement(this.options.button);e&&(this.button=new a(e,this))},t.destroy.button=function(){this.button&&this.button.destroy()},t.Button=a,t}))}(me)),me.exports}var ye,we={exports:{}};function be(){return ye||(ye=1,function(e){!function(t,r){e.exports?e.exports=r(t,ie(),ne):r(t,t.InfiniteScroll,t.fizzyUIUtils)}(window,(function(e,t,r){let a=t.prototype;function n(e){s(e,"none")}function i(e){s(e,"block")}function s(e,t){e&&(e.style.display=t)}return t.create.status=function(){let e=r.getQueryElement(this.options.status);e&&(this.statusElement=e,this.statusEventElements={request:e.querySelector(".infinite-scroll-request"),error:e.querySelector(".infinite-scroll-error"),last:e.querySelector(".infinite-scroll-last")},this.on("request",this.showRequestStatus),this.on("error",this.showErrorStatus),this.on("last",this.showLastStatus),this.bindHideStatus("on"))},a.bindHideStatus=function(e){let t=this.options.append?"append":"load";this[e](t,this.hideAllStatus)},a.showRequestStatus=function(){this.showStatus("request")},a.showErrorStatus=function(){this.showStatus("error")},a.showLastStatus=function(){this.showStatus("last"),this.bindHideStatus("off")},a.showStatus=function(e){i(this.statusElement),this.hideStatusEventElements(),i(this.statusEventElements[e])},a.hideAllStatus=function(){n(this.statusElement),this.hideStatusEventElements()},a.hideStatusEventElements=function(){for(let e in this.statusEventElements){n(this.statusEventElements[e])}},t}))}(we)),we.exports}
|
|
2
2
|
/*!
|
|
3
3
|
* Infinite Scroll v4.0.1
|
|
4
4
|
* Automatically add next page
|
|
@@ -16,5 +16,5 @@
|
|
|
16
16
|
* @license MIT https://github.com/rmariuzzo/Lang.js/blob/master/LICENSE
|
|
17
17
|
* @site https://github.com/rmariuzzo/Lang.js
|
|
18
18
|
* @author Rubens Mariuzzo <rubens@mariuzzo.com>
|
|
19
|
-
*/!function(e,t){e.exports=function(){function e(){if("undefined"!=typeof document&&document.documentElement)return document.documentElement.lang}function t(e){return"-Inf"===e?-1/0:"+Inf"===e||"Inf"===e||"*"===e?1/0:parseInt(e,10)}var r=/^({\s*(\-?\d+(\.\d+)?[\s*,\s*\-?\d+(\.\d+)?]*)\s*})|([\[\]])\s*(-Inf|\*|\-?\d+(\.\d+)?)\s*,\s*(\+?Inf|\*|\-?\d+(\.\d+)?)\s*([\[\]])$/,a=/({\s*(\-?\d+(\.\d+)?[\s*,\s*\-?\d+(\.\d+)?]*)\s*})|([\[\]])\s*(-Inf|\*|\-?\d+(\.\d+)?)\s*,\s*(\+?Inf|\*|\-?\d+(\.\d+)?)\s*([\[\]])/,n={locale:"en"},i=function(t){t=t||{},this.locale=t.locale||e()||n.locale,this.fallback=t.fallback,this.messages=t.messages};return i.prototype.setMessages=function(e){this.messages=e},i.prototype.getLocale=function(){return this.locale||this.fallback},i.prototype.setLocale=function(e){this.locale=e},i.prototype.getFallback=function(){return this.fallback},i.prototype.setFallback=function(e){this.fallback=e},i.prototype.has=function(e,t){return!("string"!=typeof e||!this.messages)&&null!==this._getMessage(e,t)},i.prototype.get=function(e,t,r){if(!this.has(e,r))return e;var a=this._getMessage(e,r);return null===a?e:(t&&(a=this._applyReplacements(a,t)),a)},i.prototype.trans=function(e,t){return this.get(e,t)},i.prototype.choice=function(e,t,r,n){(r=void 0!==r?r:{}).count=t;var i=this.get(e,r,n);if(null==i)return i;for(var s=i.split("|"),o=[],l=0;l<s.length;l++)if(s[l]=s[l].trim(),a.test(s[l])){var c=s[l].split(/\s/);o.push(c.shift()),s[l]=c.join(" ")}if(1===s.length)return i;for(var u=0;u<o.length;u++)if(this._testInterval(t,o[u]))return s[u];return n=n||this._getLocale(e),s[this._getPluralForm(t,n)]},i.prototype.transChoice=function(e,t,r){return this.choice(e,t,r)},i.prototype._parseKey=function(e,t){if("string"!=typeof e||"string"!=typeof t)return null;var r=e.split("."),a=r[0].replace(/\//g,".");return{source:t+"."+a,sourceFallback:this.getFallback()+"."+a,entries:r.slice(1)}},i.prototype._getMessage=function(e,t){if(t=t||this.getLocale(),e=this._parseKey(e,t),void 0===this.messages[e.source]&&void 0===this.messages[e.sourceFallback])return null;var r=this.messages[e.source],a=e.entries.slice(),n=a.join(".");if("string"!=typeof(r=void 0!==r?this._getValueInKey(r,n):void 0)&&this.messages[e.sourceFallback])for(r=this.messages[e.sourceFallback],a=e.entries.slice(),n="";a.length&&void 0!==r;)r[n=n?n.concat(".",a.shift()):a.shift()]&&(r=r[n],n="");return"string"!=typeof r?null:r},i.prototype._getValueInKey=function(e,t){if("string"==typeof e[t])return e[t];for(var r=(t=(t=t.replace(/\[(\w+)\]/g,".$1")).replace(/^\./,"")).split("."),a=0,n=r.length;a<n;++a){var i=r.slice(0,a+1).join("."),s=r.slice(a+1,r.length).join(".");if(e[i])return this._getValueInKey(e[i],s)}return e},i.prototype._getLocale=function(e){return e=this._parseKey(e,this.locale),this.messages[e.source]?this.locale:this.messages[e.sourceFallback]?this.fallback:null},i.prototype._findMessageInTree=function(e,t){for(;e.length&&void 0!==t;){var r=e.join(".");if(t[r]){t=t[r];break}t=t[e.shift()]}return t},i.prototype._sortReplacementKeys=function(e,t){return t.length-e.length},i.prototype._applyReplacements=function(e,t){return Object.keys(t).sort(this._sortReplacementKeys).forEach((function(r){e=e.replace(new RegExp(":"+r,"gi"),(function(e){var a=t[r];return e===e.toUpperCase()?a.toUpperCase():e===e.replace(/\w/i,(function(e){return e.toUpperCase()}))?a.charAt(0).toUpperCase()+a.slice(1):a}))})),e},i.prototype._testInterval=function(e,a){if("string"!=typeof a)throw"Invalid interval: should be a string.";var n=(a=a.trim()).match(r);if(!n)throw"Invalid interval: "+a;if(!n[2]){var i=(n=n.filter((function(e){return!!e})))[1],s=t(n[2]);s===1/0&&(s=-1/0);var o=t(n[3]),l=n[4];return("["===i?e>=s:e>s)&&("]"===l?e<=o:e<o)}for(var c=n[2].split(","),u=0;u<c.length;u++)if(parseInt(c[u],10)===e)return!0;return!1},i.prototype._getPluralForm=function(e,t){switch(t){case"az":case"bo":case"dz":case"id":case"ja":case"jv":case"ka":case"km":case"kn":case"ko":case"ms":case"th":case"tr":case"vi":case"zh":default:return 0;case"af":case"bn":case"bg":case"ca":case"da":case"de":case"el":case"en":case"eo":case"es":case"et":case"eu":case"fa":case"fi":case"fo":case"fur":case"fy":case"gl":case"gu":case"ha":case"he":case"hu":case"is":case"it":case"ku":case"lb":case"ml":case"mn":case"mr":case"nah":case"nb":case"ne":case"nl":case"nn":case"no":case"om":case"or":case"pa":case"pap":case"ps":case"pt":case"so":case"sq":case"sv":case"sw":case"ta":case"te":case"tk":case"ur":case"zu":return 1==e?0:1;case"am":case"bh":case"fil":case"fr":case"gun":case"hi":case"hy":case"ln":case"mg":case"nso":case"xbr":case"ti":case"wa":return 0===e||1===e?0:1;case"be":case"bs":case"hr":case"ru":case"sr":case"uk":return e%10==1&&e%100!=11?0:e%10>=2&&e%10<=4&&(e%100<10||e%100>=20)?1:2;case"cs":case"sk":return 1==e?0:e>=2&&e<=4?1:2;case"ga":return 1==e?0:2==e?1:2;case"lt":return e%10==1&&e%100!=11?0:e%10>=2&&(e%100<10||e%100>=20)?1:2;case"sl":return e%100==1?0:e%100==2?1:e%100==3||e%100==4?2:3;case"mk":return e%10==1?0:1;case"mt":return 1==e?0:0===e||e%100>1&&e%100<11?1:e%100>10&&e%100<20?2:3;case"lv":return 0===e?0:e%10==1&&e%100!=11?1:2;case"pl":return 1==e?0:e%10>=2&&e%10<=4&&(e%100<12||e%100>14)?1:2;case"cy":return 1==e?0:2==e?1:8==e||11==e?2:3;case"ro":return 1==e?0:0===e||e%100>0&&e%100<20?1:2;case"ar":return 0===e?0:1==e?1:2==e?2:e%100>=3&&e%100<=10?3:e%100>=11&&e%100<=99?4:5}},i}()}(Ee);var _e=Ee.exports;class Ae{constructor(){this.endpoints={},this.webEndpoints=[],this.namespace="BaseApi",this.endpointsMethods={},this.endpointsHeaders={};let e=/function (.{1,})\(/.exec(this.constructor.toString());this.className=(e&&e.length>1?e[1]:"").toLowerCase(),this.debounce={request:void 0,time:300,enabled:!0,exclude:[]}}after_init(){}normalRequest(e,t=void 0,r=null){let a=Array.isArray(e),n=a?this.getUrl(...e):this.getUrl(e);e=a?e[0]:e,r=r||this.endpointsMethods[e]||"post";let i=this.endpointsHeaders[e];if("get"===r&&t instanceof FormData){let e={};Array.from(t.entries()).forEach((function(t){e[t[0]]=t[1]})),t={params:e}}return i&&"get"===r&&(t=t?Object.assign(t,i):i),this.webEndpoints.includes(e)?n=salla.url.get(n):"http"!==n.substring(0,4)&&(n=salla.url.api(n)),Salla.api.request(n,t,r,{headers:i})}request(e,t=void 0,r=null){return!salla.api.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,r)):this.normalRequest(e,t,r)}getUrl(e){let t=this.endpoints[e]||e;const r=/{[^{}]+}/i;for(let e=1;e<arguments.length;e++)t=t.replace(r,arguments[e]);return t}event(){return salla.event[this.className]}}class Fe extends Ae{constructor(){super(),this.addToCartTries=0,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}",uploadImage:"cart/{cart}/image",status:"cart/{cart}/status",addCoupon:"cart/{id}/coupon",deleteCoupon:"cart/{id}/coupon",getQuickOrderSettings:"checkout/quick-order",createQuickOrder:"checkout/quick-order",priceQuote:"cart/{cartId}/price-quote",offers:"offers/cart/{cartId}"},this.endpointsMethods={latest:"get",details:"get",status:"get",updateItem:"post",deleteItem:"delete",deleteImage:"delete",deleteCoupon:"put",getQuickOrderSettings:"get",offers:"get"},this.webEndpoints=["latest"],this.latestCart=null,this.after_init(),salla.event.on("api::initiated",(()=>salla.api.cart.getCurrentCartId(!1,"api::initiated"))),salla.event.on("auth::token.fetched",this._checkCurrentCart),salla.event.on("auth::token.invalid",this._checkCurrentCart),salla.event.on("auth::verified",(()=>salla.api.cart.getCurrentCartId(!0,"auth::verified")),{async:!0}),salla.event.on("profile::info.fetched",this._checkCurrentCart),salla.event.on("twilight::error",(e=>(e.includes("Cart not available")||e.includes("السلة غير متاحة"))&&salla.cart.api.reset()))}_checkCurrentCart(){let e=salla.storage.get("cart"),t=salla.config.get("user")?.id,r=salla.config.get("store")?.id;e&&e.id&&(e.user_id!==t||e.store_id!==r)&&(salla.log("cart",{user_id:e.user_id,store_id:e.store_id}),salla.log("current",{user_id:t,store_id:r}),salla.log("Api:: case2 => The cart is not belong to current "+(e.user_id!==t?"user":"store")+"!"),salla.cart.api.reset())}async getCurrentCartId(e=!1,t="getCurrentCartId"){if(!e){if(salla.cart.api.latestCart)return salla.cart.api.latestCart.cart.id;let e=salla.storage.get("cart.id");if(e)return e}let r=await salla.cart.api.latest(t);return salla.cart.api.latestCart=r.data,salla.cart.api.latestCart.cart.id}getUploadImageEndpoint(e){return salla.url.api(this.getUrl("uploadImage",e||salla.storage.get("cart.id")))}latest(e="direct"){return this.request("latest",{params:{source:"",callerName:e}}).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(e,t=[]){return e=e||await salla.api.cart.getCurrentCartId(!1,"salla.api.cart.details"),this.request(["details",e],{params:{with:t}}).then((function(e){return salla.cart.event.detailsFetched(e),e})).catch((function(e){throw salla.cart.event.detailsNotFetched(e),e}))}async quickAdd(e,t){return this.addItem({id:e,quantity:t,endpoint:"quickAdd"})}async addItem(e){let t=this.getCartPayload(e);if(!t.id){let e='There is no product "id"!';return salla.cart.event.itemAddedFailed(e),salla.api.errorPromise(e)}let r=salla.form.getPossibleValue(t.payload,["endpoint"]);r&&["addItem","quickAdd"].includes(r)||(r=salla.form.getPossibleValue(t.payload,["quantity","donating_amount"])?"addItem":"quickAdd");let a=await salla.api.cart.getCurrentCartId(!1,"salla.api.cart.addItem");return this.request([r,a,t.id],t.payload).then((function(e){return salla.cart.api.addToCartTries=0,salla.cart.event.itemAdded(e,t.id),e})).catch((function(r){if(!salla.cart.api.addToCartTries)return salla.cart.api.addToCartTries++,salla.cart.reset(),salla.cart.api.addItem(e);throw salla.cart.event.itemAddedFailed(r,t.id),r}))}async deleteItem(e){let t=this.getCartPayload(e);if(!t.id){let e='There is no "id"!';return salla.cart.event.itemDeletedFailed(e),salla.api.errorPromise(e)}let r=await salla.api.cart.getCurrentCartId(!1,"salla.api.cart.deleteItem");return this.request(["deleteItem",r,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.getCartPayload(e);if(!t.id){let e='There is no "id"!';return salla.cart.event.itemUpdatedFailed(e),salla.api.errorPromise(e)}let r=await salla.api.cart.getCurrentCartId(!1,"salla.api.cart.updateItem");return"Object"===t.payload.constructor?.name?t.payload._method="PUT":t.payload.append("_method","PUT"),this.request(["updateItem",r,t.id],t.payload).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(e){if(!(e=salla.form.getPossibleValue(e,["id","image_id","photo_id"]))){let e='There is no "id"!';return salla.cart.event.imageNotDeleted(e),salla.api.errorPromise(e)}let t=await salla.api.cart.getCurrentCartId(!1,"salla.api.cart.deleteImage");return this.request(["deleteImage",t,e]).then((function(t){return salla.cart.event.imageDeleted(t,e),t})).catch((function(t){throw salla.cart.event.imageNotDeleted(t,e),t}))}async status(e){const t=(new Date).getTime(),r=Math.random().toString(36).substring(2,15);return this.request(["status",e||await salla.api.cart.getCurrentCartId(!1,"salla.api.cart.status")],{params:{has_apple_pay:salla.helpers.hasApplePay(),"s-hash":`${r}_${t}`}})}async submit(){if(salla.config.isGuest())return salla.log("it looks that the current user is not logged-in, lets login then submit"),salla.cart.loginOnCartPage();this.status(await salla.api.cart.getCurrentCartId(!1,"salla.api.cart.submit")).then((e=>{let t=e.data.next_step?.to;if(t||(window.history.pushState({},"",salla.url.addParamToUrl("reload","empty_next_step")),window.history.pushState({},"",salla.url.addParamToUrl("acitve",!1===e.data.active?"false":"true_or_undfined")),salla.cart.reset(),window.location.reload()),!["checkout","refresh","login"].includes(t)){let e="Can't find next_step );";throw salla.cart.reset(),salla.cart.event.submitFailed(e),e}return salla.cart.event.submitted(e),"login"===t?salla.cart.loginOnCartPage():"checkout"===t?window.location.href=e.data.next_step.url+(salla.helpers.hasApplePay()?"?has_apple_pay=true":""):(window.history.pushState({},"",salla.url.addParamToUrl("reload","refresh")),void window.location.reload())})).catch((function(e){salla.cart.api.tries=salla.cart.api.tries||0,salla.cart.reset();let t=404===e?.response?.data?.status;if(t&&0===salla.cart.api.tries)return salla.cart.api.tries++,salla.log("we recived that the current cart is not found, we will try to re-submit one more time"),salla.cart.submit();throw t&&salla.error(salla.lang.get("pages.checkout.try_again")),salla.cart.event.submitFailed(e),e}))}getCartPayload(e){let t=e?.data||("object"==typeof e?e:void 0);return e=t?salla.form.getPossibleValue(t,["prod_id","product_id","item_id","id"]):e,t="object"==typeof t?t:void 0,{id:e,payload:t}}normalRequest(e,t=void 0,r=null){return super.normalRequest(e,t,r).catch((async e=>{throw 403===e?.response?.status&&(this.reset(),salla.error(salla.lang.get("pages.checkout.try_again"))),e}))}reset(){salla.api.cart.latestCart=null,salla.storage.remove("cart"),salla.cart.event.successReset()}async addCoupon(e){if(e=e.data||e,!(e=salla.form.getPossibleValue(e,["coupon"]))){let e=new Error('There is no "Coupon Code"!');return e.name="EmptyCoupon",salla.event.cart.couponAdditionFailed(e),salla.api.errorPromise(e)}let t=await salla.cart.api.getCurrentCartId(!1,"salla.api.cart.addCoupon");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 e=await salla.cart.api.getCurrentCartId(!1,"salla.api.cart.deleteCoupon");return this.request(["deleteCoupon",e],{}).then((function(t){return salla.event.cart.couponDeleted(t,e),t})).catch((function(t){throw salla.event.cart.couponDeletionFailed(t,e),t}))}getQuickOrderSettings(){return this.request("getQuickOrderSettings").then((e=>(salla.event.cart.quickOrderSettingFetched(e),e))).catch((e=>{throw salla.event.cart.quickOrderSettingFailed(e),e}))}createQuickOrder(e){return this.request("createQuickOrder",e).then((e=>(salla.event.cart.quickOrderSucceeded(e),e))).catch((e=>{throw salla.event.cart.quickOrderFailed(e),e}))}async priceQuote(e){return salla.config.isGuest()?(salla.auth.api.setAfterLoginEvent("cart::priceQuote",e),void salla.event.dispatch("login::open")):this.request(["priceQuote",e||await salla.api.cart.getCurrentCartId(!1,"salla.api.cart.priceQuote")]).then((e=>(salla.cart.api.reset(),salla.event.cart.priceQuoteSucceeded(e).then((()=>(setTimeout((()=>window.location.href=salla.url.get("/")),1e3),e)))))).catch((e=>salla.event.cart.priceQuoteFailed(e).then((()=>{throw 404===e.error?.code&&window.location.reload(),e}))))}loginOnCartPage(){salla.auth.setCanRedirect(!1),salla.event.dispatch("login::open"),salla.auth.event.onLoggedIn((e=>{salla.event.dispatch("login::close"),salla.cart.submit()}))}async offers(){const e=await salla.cart.api.getCurrentCartId(!1,"salla.api.cart.offers");return this.request(["offers",e]).then((e=>(salla.event.cart.offersFetched(e),e))).catch((e=>{throw salla.event.cart.offersFailed(e),e}))}}class Pe extends Ae{constructor(){super(),this.namespace="loyalty",this.endpoints={getProgram:"loyalty",exchange:"loyalty/exchange",reset:"loyalty/exchange"},this.endpointsMethods={getProgram:"get",reset:"put"},this.after_init()}getProgram(){return this.request("getProgram").then((e=>(salla.loyalty.event.programFetched(e),e))).catch((e=>{throw salla.loyalty.event.programNotFetched(e),e}))}async exchange(e,t=null){if(!(e=salla.form.getPossibleValue(e,["id","loyalty_prize_id","prize_id"]))){let e="Unable to find cart id. Please provide one.";return salla.loyalty.event.exchangeFailed(e),salla.api.errorPromise(e)}if(!(t=t||await salla.cart.getCurrentCartId(!1,"salla.api.loyalty.exchange"))){let e="Unable to find cart id. Please provide one.";return salla.loyalty.event.exchangeFailed(e),salla.api.errorPromise(e)}return this.request("exchange",{loyalty_prize_id:e,cart_id:t}).then((function(t){return salla.loyalty.event.exchangeSucceeded(t,e),t})).catch((function(t){throw salla.loyalty.event.exchangeFailed(t,e),t}))}async reset(e=null){if(!(e=e||await salla.cart.getCurrentCartId(!1,"salla.api.loyalty.reset"))){let e="Unable to find cart id. Please provide one.";return salla.loyalty.event.resetFailed(e),salla.api.errorPromise(e)}return this.request("reset",{cart_id:e}).then((e=>(salla.loyalty.event.resetSucceeded(e),e))).catch((e=>{throw salla.loyalty.event.resetFailed(e),e}))}}class xe extends Ae{constructor(){super(),this.namespace="auth",this.canRedirect_=!0,this.afterLoginEvent={event:null,payload:null},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.inIframe=salla.helpers.isIframe(),this.after_init()}setAfterLoginEvent(e,t){salla.api.auth.afterLoginEvent={event:e,payload:t}}setCanRedirect(e){salla.api.auth.canRedirect_=e}canRedirect(){return salla.api.auth.canRedirect_&&!salla.api.auth.afterLoginEvent.event}login(e){e?.data&&(e=e.data);let t=salla.form.getPossibleValue(e,["type"]);if(!["email","mobile"].includes(t)){let e="Login type should be in: [email, mobile]";return salla.auth.event.codeNotSent(e),salla.api.errorPromise(e)}return this.request(["login",t],e).then((function(e){return salla.auth.event.codeSent(e,t),e})).catch((function(e){throw salla.auth.event.codeNotSent(e,t),e}))}async verify(e,t=!0){let r=salla.form.getPossibleValue(e,["type"]);if(!r){let e="Failed to know what's login type!";return salla.auth.event.verificationFailed(e),salla.api.errorPromise(e)}t=!1!==salla.form.getPossibleValue(e,["supportWebAuth"])&&t,salla.auth.event.next_event&&(e.next_event=salla.auth.event.next_event);let a=await salla.auth.api.request(["verify",r],e);return 200!==a?.status?(salla.auth.event.verificationFailed(a,r),salla.api.errorPromise(a)):salla.auth.api.handlAfterAuthenticatedResponse(a,t)}async handlAfterAuthenticatedResponse(e,t){e.data||(e={data:e});let r="authenticated"===e.data?.case;return r&&salla.auth.event.tokenFetched(e.data.token),t&&!this.inIframe&&await salla.auth.api.request("auth/jwt",{callerName:"salla.auth.api.handlAfterAuthenticatedResponse"}),r&&salla.auth.event.loggedIn(e).then((()=>salla.auth.api.afterUserLogin())),await salla.auth.event.verified(e,e.data.verification.type),salla.api.successPromise(e)}resend(e){let t;return(e=e.data||e).type=e.type||"mobile","mobile"!==e.type||e.phone&&e.country_code?"email"!==e.type||e.email?this.request("resend",e).then((function(t){return salla.auth.event.codeSent(t,e),t})).catch((function(t){throw salla.auth.event.codeNotSent(t,e),t})):(salla.auth.event.codeNotSent(t="There is no email!",e),salla.api.errorPromise(t)):(salla.auth.event.codeNotSent(t="There is no phone or country_code!",e),salla.api.errorPromise(t))}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((async e=>(salla.auth.event.registered.call(t,e),"authenticated"===e.data?.case&&(salla.auth.event.tokenFetched(e.data.token),!this.inIframe&&await salla.auth.request("auth/jwt",{callerName:"salla.auth.api.register"}),salla.auth.event.loggedIn(e),salla.auth.api.afterUserLogin()),e))).catch((function(e){throw salla.auth.event.registrationFailed.call(t,e),e}))}handleIframeReadyAction(e,t){e.contentWindow?.postMessage({source:"logout",type:"init",data:{id:salla.config.get("store.id"),lang:"ar",appUrl:t,apiUrl:salla.config.get("store.api").replace(/\/+$/,""),settings:salla.config.all()}},"*")}appendIframeAndLogout(){return new Promise((e=>{let t=salla.config.get("login.url","https://accounts.salla.com");const r=document.createElement("iframe");r.style.display="none",r.src=`${t}/logout`;const a=n=>{if("login"!==n.data.source)return;let i=n.data.type.replace("iframe::","");if(salla.log("iframe::logout-iframe message received",n.data),["logged-out","ready"].includes(i)){if("ready"===i)return this.handleIframeReadyAction(r,t);window.removeEventListener("message",a),r.remove(),e()}};window.addEventListener("message",a),document.body.appendChild(r)}))}logout(e="twilight"){return salla.storage.clearAll(),salla.cookie.clearAll(),e=encodeURI(e),salla.auth.event.loggedOut().then((()=>this.appendIframeAndLogout())).then((()=>{let t=salla.url.get(`logout?from=${e}`);console.log(`Going to ${t}, to do any thing before this action use: salla.auth.even.onLoggedOut(()=>{...})`);try{location.href=t}catch(e){salla.log(e)}})).catch((e=>console.error("Error during logout:",e)))}refresh(){return this.request("refresh").then((function(e){return salla.auth.event.tokenFetched(e.data.token),e})).catch((function(e){throw salla.auth.event.refreshFailed(e),e}))}afterUserLogin(){this.afterLoginEvent.event&&salla.event.emit(this.afterLoginEvent.event,this.afterLoginEvent.payload)}}class Te extends Ae{constructor(){super(),this.namespace="order",this.endpoints={cancel:"orders/cancel/{id}",createCartFromOrder:"reorder/{id}",sendInvoice:"orders/send/{id}",fetch:"orders"},this.endpointsMethods={createCartFromOrder:"get",fetch:"get"},this.after_init()}show(e){let t=salla.form.getPossibleValue(e?.data||e,["id","order_id"]);salla.event.dispatch("mobile::order.placed",{order_id:t}),location.href=salla.form.getPossibleValue(e?.data||e,["url"])}cancel(e){return e=e||Salla.config.get("page.id"),this.request(["cancel",e],{params:{has_apple_pay:salla.helpers.hasApplePay()}}).then((function(t){return salla.event.order.canceled(t,e),t})).catch((function(t){throw salla.event.order.notCanceled(t,e),t}))}createCartFromOrder(e){return e=e||salla.config.get("page.id"),this.request(["createCartFromOrder",e]).then((function(t){return salla.cart.reset(),salla.event.order.orderCreated(t,e),window.location.href=t.data.url,t})).catch((function(t){throw salla.event.order.orderCreationFailed(t,e),t}))}sendInvoice(e){let t=salla.form.getPossibleValue(e,["id"])||salla.config.get("page.id");if(!t||isNaN(t)){let e="There is no id!";return salla.order.event.invoiceNotSent(e),salla.api.errorPromise(e)}return this.request(["sendInvoice",t],e).then((e=>(salla.event.order.invoiceSent(e,t),e))).catch((e=>{throw salla.event.order.invoiceNotSent(e,t),e}))}fetch(e){return this.request(["fetch"],{params:e}).then((function(e){return salla.event.order.ordersFetched(e),e})).catch((function(e){throw salla.event.order.ordersNotFetched(e),e}))}}class Re extends Ae{constructor(){super(),this.namespace="product",this.previousQuery="",this.endpoints={getPrice:"products/{id}/price",availabilitySubscribe:"products/{id}/availability-notify",search:"products/search",details:"products/{product_id}/details",categories:"products/categories/{?id}",offers:"products/{product_id}/specialoffer",getSizeGuides:"products/{prod_id}/size-guides",giftDetail:"products/{product_id}/buy-as-gift",giftToCart:"products/{product_id}/buy-as-gift",giftImage:"products/buy-as-gift/image",buyNow:"products/{product_id}/buy-now",fetch:"products",fetchOptions:"products/options"},this.endpointsMethods={details:"get",giftDetail:"get",fetch:"get",offers:"get",fetchOptions:"get"},this.after_init()}getPrice(e){let t=e.data||e,r=salla.form.getPossibleValue(t,["id","prod_id","product_id"]);return this.request(["getPrice",r],"object"==typeof t?t:void 0).then((function(e){return salla.product.event.priceUpdated(e,r),e})).catch((function(e){throw salla.product.event.priceUpdateFailed(e,r),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(e){let t=e.data||e;return e=salla.form.getPossibleValue(t,["id","prod_id"]),this.request(["availabilitySubscribe",e],"object"==typeof t?t:void 0).then((function(t){return salla.product.event.availabilitySubscribed(t,e),t})).catch((function(t){throw salla.product.event.availabilitySubscribeFailed(t,e),t}))}search(e){let t=e.data;if(t||(t={params:"string"==typeof e?{query:e}:e}),!(e=t instanceof FormData?t.get("query"):t.query||t.params?.query)){let e='There is no "query"!';return salla.product.event.searchFailed(e),salla.api.errorPromise(e)}if(e===salla.api.product.previousQuery){let e="Query is same as previous one!";return salla.product.event.searchFailed(e),salla.api.product.previousQuery=null,salla.api.errorPromise(e)}return salla.api.product.previousQuery=e,this.request("search",t,"get").then((function(t){return salla.product.event.searchResults(t,e),t})).catch((function(t){throw salla.product.event.searchFailed(t,e),t}))}offers(e){if(!(e=salla.form.getPossibleValue(e?.data|e,["product_id","id"]))){let e='There is no "product_id"!';return salla.product.event.fetchOffersFailed(e),salla.api.errorPromise(e)}return this.request(["offers",e]).then((function(t){return salla.product.event.offersFetched(t,e),t})).catch((function(t){throw salla.product.event.fetchOffersFailed(t,e),t}))}getSizeGuides(e){return this.request(`products/${e}/size-guides`,null,"get").then((t=>(salla.product.event.sizeGuideFetched(t,e),t))).catch((t=>{throw salla.product.event.sizeGuideFetchFailed(t,e),t}))}getGiftDetails(e){return this.request(["giftDetail",e]).then((t=>(salla.product.event.giftFetched(t,e),t))).catch((t=>{throw salla.product.event.giftFetchFailed(t,e),t}))}getDetails(e,t=[]){if(!Array.isArray(t)){let e="withItems should be array.";return salla.product.event.detailFetchFailed(e),salla.api.errorPromise(e)}if(!e){let e="productId is not passed.";return salla.product.event.detailFetchFailed(e),salla.api.errorPromise(e)}return this.request(["details",e],{params:{with:t}}).then((function(t){return salla.product.event.detailFetched(t,e),t})).catch((function(t){throw salla.product.event.availabilitySubscribeFailed(t,e),t}))}addGiftToCart(e,t,r=!1){return this.request(["giftToCart",e],t).then((t=>(salla.product.event.addGiftToCartSucceeded(t,e),r&&(window.location.href=t.redirect),t))).catch((t=>{throw salla.product.event.addGiftToCartFailed(t,e),t}))}uploadGiftImage(e){return this.request("giftImage",e).then((e=>(salla.product.event.giftImageUploadSucceeded(e),e))).catch((e=>{throw salla.product.event.giftImageUploadFailed(e),e}))}fetch(e){if(!e.source){const e="Source cannot be empty. Please provide one.";return salla.product.event.productListFetchFailed(e),salla.api.errorPromise(e)}const t=!e.source_value,r="string"==typeof e.source_value&&"[]"===e.source_value,a=Array.isArray(e.source_value)&&!e.source_value.length;if((t||r||a)&&!["offers","latest","sales","wishlist","top-rated"].includes(e.source)){const e="Source value cannot be empty. Please provide one.";return salla.product.event.productListFetchFailed(e),salla.api.errorPromise(e)}if(["categories","brands","tags","selected"].includes(e.source)&&!Array.isArray(e.source_value)){const e="SourceValue type error. Expected an array.";return salla.product.event.productListFetchFailed(e),salla.api.errorPromise(e)}if("search"===e.source&&"string"!=typeof e.source_value){const e="SourceValue type error. Expected a string.";return salla.product.event.productListFetchFailed(e),salla.api.errorPromise(e)}if("related"===e.source&&isNaN(e.source_value)){const e="SourceValue type error. Expected a number.";return salla.product.event.productListFetchFailed(e),salla.api.errorPromise(e)}return this.request(this.endpoints.fetch,{params:e},"get").then((async t=>{if(salla.product.event.productListFetchSucceeded(t),e.includes&&e.includes.includes("options")&&t.data){const e=t.data.map((e=>e.id)),r=await this.fetchOptions(e);this.updateProductOptions(t.data,r.data)}return t})).catch((e=>{throw salla.product.event.productListFetchFailed(e),e}))}updateProductOptions(e,t){const r=new Map(t.map((e=>[e.id,e.options])));for(const t of e)t.options=r.get(t.id)}fetchOptions(e){if(!e||0===e.length){const e="At least one product ID is required. Please provide a valid list of product IDs.";return salla.product.event.productOptionsNotFetched(e),salla.api.errorPromise(e)}const t={selected:e};return this.request(this.endpoints.fetchOptions,{params:t},"get").then((e=>(salla.product.event.productOptionsFetched(e),e))).catch((e=>{throw salla.product.event.productOptionsNotFetched(e),e}))}}class Ce extends Ae{constructor(){super(),this.namespace="profile",this.endpoints={info:"auth/user",update:"profile/update",updateContacts:"profile/contacts/update",updateSettings:"profile/settings",verify:"profile/verify",delete:"profile"},this.endpointsMethods={delete:"delete"},this.after_init()}info(){return this.request("info",null,"get").then((e=>{let t={id:e.data.id,type:"user",email:e.data.email,mobile:e.data.phone.code+e.data.phone.number,country_code:e.data.phone.country,language_code:e.data.language,currency_code:e.data.currency,notifications:e.data.notifications,pending_orders:e.data.pending_orders,avatar:e.data.avatar,first_name:e.data.first_name,last_name:e.data.last_name,fetched_at:Date.now()};return salla.config.set("user",t),salla.storage.set("user",t),salla.profile.event.infoFetched(e),e})).catch((e=>{throw salla.profile.event.infoNotFetched(e),e}))}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.verificationCodeSent(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}))}updateSettings(e){return this.request("updateSettings",e).then((e=>(salla.event.profile.settingsUpdated(e),e))).catch((e=>{throw salla.event.profile.updateSettingsFailed(e),e}))}delete(){return this.request("delete").then((e=>(salla.storage.clearAll(),salla.cookie.clearAll(),salla.event.profile.deleted(e),window.location.href=salla.url.get("logout"),e))).catch((e=>{throw salla.event.profile.notDeleted(e),e}))}}class Oe extends Ae{constructor(){super(),this.namespace="comment",this.endpoints={addComment:"{type}/{id}/comments",comments:"/comments"},this.after_init()}add(e){if(e?.data&&(e=e.data),"string"==typeof(e=this.getCommentPayload(e,!0)))return salla.event.comment.additionFailed(e),salla.api.errorPromise(e);if(!e.comment){let e="can't find comment content!";return salla.event.comment.additionFailed(e),salla.api.errorPromise(e)}return this.request(["addComment",e.type,e.id],{comment:e.comment}).then((function(t){return salla.event.comment.added(t,e.id),t})).catch((function(t){throw salla.event.comment.additionFailed(t,e.id),t}))}getCommentPayload(e,t=!1){let r={};if(["id","type","comment","per_page","page","sort"].forEach((t=>{let a=salla.form.getPossibleValue(e,[t]);a&&(r[t]=a)})),!t){let t=e.ids;if(t&&(r.ids=Array.isArray(t)?t:[t]),!r.ids||!r.ids.length)return"Failed to get ids!"}return r.type&&["products","pages","product","page"].includes(r.type)?(r.type+=["product","page"].includes(r.type)?"s":"",r):"Failed to get type one of:(products, product, page, pages)!"}fetchComments(e){if("string"==typeof(e=this.getCommentPayload(e)))return salla.event.comment.fetchFailed(e),salla.api.errorPromise(e);const t={per_page:e.per_page||5,page:e.page||1,type:e.type,ids:e.ids};return e.sort&&(t.sort=e.sort),this.request(["comments"],{params:t},"get").then((function(t){return salla.event.comment.fetched(t,e),t})).catch((function(t){throw salla.event.comment.fetchFailed(t,e),t}))}getPageComments(e,t=1,r=5,a){return this.fetchComments({ids:[e],type:"pages",page:t,per_page:r,sort:a})}getProductComments(e,t=1,r=5,a){return this.fetchComments({ids:[e],type:"products",page:t,per_page:r,sort:a})}}class ke extends Ae{constructor(){super(),this.namespace="currency",this.endpoints={change:"/",list:"currencies"},this.endpointsMethods={change:"get",list:"get"},this.webEndpoints=["change"],this.after_init()}change(e){if(!(e=salla.form.getPossibleValue(e.data||e,["currency","code"]))){let e="Can't find currency code!";return salla.currency.event.failed(e),salla.api.errorPromise(e)}return this.request("change",{params:{change_currency:"",currency:e}}).then((function(t){return salla.cookie.set("fresh_summary",1),salla.storage.set("cart",""),salla.currency.event.changed(t,e),t})).catch((function(t){throw salla.currency.event.failed(t,e),t}))}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 Ie extends Ae{constructor(){super(),this.namespace="document"}}class Le extends Ae{constructor(){super(),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(e){let t="object"==typeof e?e:{},r=salla.form.getPossibleValue(e?.data||e,["order_id","id"]);if(!r){let e='There is no "order_id"!';return salla.event.rating.orderNotFetched(e),salla.api.errorPromise(e)}return this.request(["order",r],t).then((function(e){return salla.event.rating.orderFetched(e,r),e})).catch((function(e){throw salla.event.rating.orderNotFetched(e,r),e}))}store(e){if(!(e=e?.data||e)){let e='There is no "data"!';return salla.event.rating.storeFailed(e),salla.api.errorPromise(e)}return this.request("store",e).then((function(t){return salla.event.rating.storeRated(t,e),t})).catch((function(t){throw salla.event.rating.storeFailed(t,e),t}))}products(e){if(!(e=e?.data||e)){let e='There is no "data"!';return salla.event.rating.productsFailed(e),salla.api.errorPromise(e)}return this.request("products",e).then((function(t){return salla.event.rating.productsRated(t,e),t})).catch((function(t){throw salla.event.rating.productsFailed(t,e),t}))}shipping(e){if(!(e=e?.data||e)){let e='There is no "data"!';return salla.event.rating.shippingFailed(e),salla.api.errorPromise(e)}return this.request("shipping",e).then((function(t){return salla.event.rating.shippingRated(t,e),t})).catch((function(t){throw salla.event.rating.shippingFailed(t,e),t}))}}class qe extends Ae{constructor(){super(),this.namespace="wishlist",this.endpoints={add:"products/favorites/{id}",remove:"products/favorites/{id}"},this.endpointsMethods={remove:"delete"},this.after_init()}toggle(e){return salla.storage.get("salla::wishlist",[]).includes(e)?this.remove(e):this.add(e)}add(e){let t;return salla.config.isGuest()?(salla.wishlist.event.additionFailed(t=salla.lang.get("common.messages.must_login")),salla.error(t),salla.api.errorPromise(t)):(e=salla.form.getPossibleValue(e?.data||e,["product_id","id"]))?this.request(["add",e]).then((t=>(this.updateWishlistStorage(e),salla.wishlist.event.added(t,e),t))).catch((function(t){throw salla.wishlist.event.additionFailed(t,e),t})):(salla.wishlist.event.additionFailed(t="Failed to get product id!"),salla.api.errorPromise(t))}remove(e){let t;return salla.config.isGuest()?(salla.wishlist.event.additionFailed(t=salla.lang.get("common.messages.must_login")),salla.error(t),salla.api.errorPromise(t)):(e=salla.form.getPossibleValue(e?.data||e,["product_id","id"]))?this.request(["remove",e]).then((t=>(this.updateWishlistStorage(e,!1),salla.wishlist.event.removed(t,e),t))).catch((function(t){throw salla.wishlist.event.removingFailed(t,e),t})):(salla.wishlist.event.removingFailed(t="Failed to get id!"),salla.api.errorPromise(t))}updateWishlistStorage(e,t=!0){let r=salla.storage.get("salla::wishlist",[]);t?r.push(e):r.splice(r.indexOf(e),1),salla.storage.set("salla::wishlist",r)}}class Ue extends Ae{constructor(){super(),this.namespace="scopes",this.endpoints={get:"scopes",change:"scopes",getProductAvailability:"scopes/availability?product_id={id}"},this.after_init()}get(){return this.request("scopes",null,"get").then((e=>(salla.scope.event.fetched(e),e))).catch((e=>{throw salla.scope.event.notFetched(e),e}))}change(e){return this.request("scopes",e).then((e=>(salla.scope.event.changeSucceeded(e),e))).catch((e=>{throw salla.scope.event.changeFailed(e),e}))}getProductAvailability(e=null){return this.request(`scopes/availability?product_id=${e}`,null,"get").then((t=>(salla.scope.event.productAvailabilityFetched(t,e),t))).catch((e=>{throw salla.scope.event.productAvailabilityNotFetched(e),e}))}}class De extends Ae{constructor(){super(),this.namespace="booking",this.endpoints={add:"cart/booking/product/{id}"},this.endpointsMethods={add:"get"}}async add(e,t=!0){if(!e){let e="Please provide product id.";return salla.booking.event.additionFailed(e),salla.api.errorPromise(e)}return this.request(["add",e]).then((function(e){return salla.booking.event.added(e),t&&"booking"===e.data.redirect.to&&(window.location.href=e.data.redirect.url),e})).catch((function(e){throw salla.booking.event.additionFailed(e),e}))}}class Ne extends Ae{constructor(){super(),this.namespace="landing",this.endpoints={getDetails:"landing/{landing_page_id}",createCartFromPage:"landing/{landing_page_id}",breadcrumbs:"breadcrumbs"},this.endpointsMethods={getDetails:"get",breadcrumbs:"get"},this.after_init()}getDetails(e){if(!e){let e="page landing id not passed";return salla.event.landing.getDetailsFailed(e),salla.api.errorPromise(e)}return this.request(["getDetails",e]).then((function(t){return salla.event.landing.detailsFetched(t,e),t})).catch((function(t){throw salla.event.landing.getDetailsFailed(t,e),t}))}createCartFromPage(e){if(!e){let e="page landing id not passed";return salla.event.landing.orderCreationFailed(e),salla.api.errorPromise(e)}return salla.config.isGuest()?(salla.auth.api.setAfterLoginEvent("landing::createCartFromPage",e),salla.event.dispatch("login::open"),salla.api.successPromise("")):this.request(["createCartFromPage",e]).then((function(t){return salla.event.landing.orderCreated(t,e).then((()=>location.href=t.data.url)),t})).catch((function(t){throw salla.event.landing.orderCreationFailed(t,e),t}))}fetchBreadcrumbs(e){if(!e.page){let e="The 'page' parameter is required for the Breadcrumb API. Please provide a valid 'page' parameter.";return salla.event.landing.breadcrumbFetchFailed(e),salla.api.errorPromise(e)}if("product.single"===e.page&&!e.id&&!e.parent_id){let e="The 'id' and 'parent_id' parameters are required when the 'page' parameter is set to 'product.single'. Please provide valid values for both parameters.";return salla.event.landing.breadcrumbFetchFailed(e),salla.api.errorPromise(e)}if(["product.index","customer.orders.single","product.index.tag","page-single","landing-page","brands.single","blog.single","blog.index.author","blog.index.category","blog.index.tag"].includes(e.page)&&!e.id){let t=`The 'id' parameter is required when the 'page' parameter is set to ${e.page}. Please provide valid value for the 'ID' parameter.`;return salla.event.landing.breadcrumbFetchFailed(t),salla.api.errorPromise(t)}return this.request("breadcrumbs",{params:e}).then((function(e){return salla.event.landing.breadcrumbFetched(e),e})).catch((function(e){throw salla.event.landing.breadcrumbFetchFailed(e),e}))}}class je extends Ae{constructor(){super(),this.namespace="notifications",this.endpoints={fetch:"notifications"},this.endpointsMethods={fetch:"get"},this.after_init()}fetch(e){return this.request(["fetch"],{params:e}).then((function(e){return salla.event.notifications.fetched(e),e})).catch((function(e){throw salla.event.notifications.fetchFailed(e),e}))}}var Be,Me={exports:{}},He=function(e,t){return function(){for(var r=new Array(arguments.length),a=0;a<r.length;a++)r[a]=arguments[a];return e.apply(t,r)}},$e=He,ze=Object.prototype.toString,Ye=(Be=Object.create(null),function(e){var t=ze.call(e);return Be[t]||(Be[t]=t.slice(8,-1).toLowerCase())});function We(e){return e=e.toLowerCase(),function(t){return Ye(t)===e}}function Ve(e){return Array.isArray(e)}function Ge(e){return void 0===e}var Qe=We("ArrayBuffer");function Ke(e){return null!==e&&"object"==typeof e}function Je(e){if("object"!==Ye(e))return!1;var t=Object.getPrototypeOf(e);return null===t||t===Object.prototype}var Xe=We("Date"),Ze=We("File"),et=We("Blob"),tt=We("FileList");function rt(e){return"[object Function]"===ze.call(e)}var at=We("URLSearchParams");function nt(e,t){if(null!=e)if("object"!=typeof e&&(e=[e]),Ve(e))for(var r=0,a=e.length;r<a;r++)t.call(null,e[r],r,e);else for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.call(null,e[n],n,e)}var it,st=(it="undefined"!=typeof Uint8Array&&Object.getPrototypeOf(Uint8Array),function(e){return it&&e instanceof it}),ot={isArray:Ve,isArrayBuffer:Qe,isBuffer:function(e){return null!==e&&!Ge(e)&&null!==e.constructor&&!Ge(e.constructor)&&"function"==typeof e.constructor.isBuffer&&e.constructor.isBuffer(e)},isFormData:function(e){var t="[object FormData]";return e&&("function"==typeof FormData&&e instanceof FormData||ze.call(e)===t||rt(e.toString)&&e.toString()===t)},isArrayBufferView:function(e){return"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&Qe(e.buffer)},isString:function(e){return"string"==typeof e},isNumber:function(e){return"number"==typeof e},isObject:Ke,isPlainObject:Je,isUndefined:Ge,isDate:Xe,isFile:Ze,isBlob:et,isFunction:rt,isStream:function(e){return Ke(e)&&rt(e.pipe)},isURLSearchParams:at,isStandardBrowserEnv:function(){return("undefined"==typeof navigator||"ReactNative"!==navigator.product&&"NativeScript"!==navigator.product&&"NS"!==navigator.product)&&("undefined"!=typeof window&&"undefined"!=typeof document)},forEach:nt,merge:function e(){var t={};function r(r,a){Je(t[a])&&Je(r)?t[a]=e(t[a],r):Je(r)?t[a]=e({},r):Ve(r)?t[a]=r.slice():t[a]=r}for(var a=0,n=arguments.length;a<n;a++)nt(arguments[a],r);return t},extend:function(e,t,r){return nt(t,(function(t,a){e[a]=r&&"function"==typeof t?$e(t,r):t})),e},trim:function(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")},stripBOM:function(e){return 65279===e.charCodeAt(0)&&(e=e.slice(1)),e},inherits:function(e,t,r,a){e.prototype=Object.create(t.prototype,a),e.prototype.constructor=e,r&&Object.assign(e.prototype,r)},toFlatObject:function(e,t,r){var a,n,i,s={};t=t||{};do{for(n=(a=Object.getOwnPropertyNames(e)).length;n-- >0;)s[i=a[n]]||(t[i]=e[i],s[i]=!0);e=Object.getPrototypeOf(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},kindOf:Ye,kindOfTest:We,endsWith:function(e,t,r){e=String(e),(void 0===r||r>e.length)&&(r=e.length),r-=t.length;var a=e.indexOf(t,r);return-1!==a&&a===r},toArray:function(e){if(!e)return null;var t=e.length;if(Ge(t))return null;for(var r=new Array(t);t-- >0;)r[t]=e[t];return r},isTypedArray:st,isFileList:tt},lt=ot;function ct(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}var ut=function(e,t,r){if(!t)return e;var a;if(r)a=r(t);else if(lt.isURLSearchParams(t))a=t.toString();else{var n=[];lt.forEach(t,(function(e,t){null!=e&&(lt.isArray(e)?t+="[]":e=[e],lt.forEach(e,(function(e){lt.isDate(e)?e=e.toISOString():lt.isObject(e)&&(e=JSON.stringify(e)),n.push(ct(t)+"="+ct(e))})))})),a=n.join("&")}if(a){var i=e.indexOf("#");-1!==i&&(e=e.slice(0,i)),e+=(-1===e.indexOf("?")?"?":"&")+a}return e},dt=ot;function ht(){this.handlers=[]}ht.prototype.use=function(e,t,r){return this.handlers.push({fulfilled:e,rejected:t,synchronous:!!r&&r.synchronous,runWhen:r?r.runWhen:null}),this.handlers.length-1},ht.prototype.eject=function(e){this.handlers[e]&&(this.handlers[e]=null)},ht.prototype.forEach=function(e){dt.forEach(this.handlers,(function(t){null!==t&&e(t)}))};var ft=ht;function pt(){throw new Error("setTimeout has not been defined")}function gt(){throw new Error("clearTimeout has not been defined")}var mt=pt,vt=gt;function yt(e){if(mt===setTimeout)return setTimeout(e,0);if((mt===pt||!mt)&&setTimeout)return mt=setTimeout,setTimeout(e,0);try{return mt(e,0)}catch(t){try{return mt.call(null,e,0)}catch(t){return mt.call(this,e,0)}}}"function"==typeof global.setTimeout&&(mt=setTimeout),"function"==typeof global.clearTimeout&&(vt=clearTimeout);var wt,bt=[],St=!1,Et=-1;function _t(){St&&wt&&(St=!1,wt.length?bt=wt.concat(bt):Et=-1,bt.length&&At())}function At(){if(!St){var e=yt(_t);St=!0;for(var t=bt.length;t;){for(wt=bt,bt=[];++Et<t;)wt&&wt[Et].run();Et=-1,t=bt.length}wt=null,St=!1,function(e){if(vt===clearTimeout)return clearTimeout(e);if((vt===gt||!vt)&&clearTimeout)return vt=clearTimeout,clearTimeout(e);try{return vt(e)}catch(t){try{return vt.call(null,e)}catch(t){return vt.call(this,e)}}}(e)}}function Ft(e,t){this.fun=e,this.array=t}Ft.prototype.run=function(){this.fun.apply(null,this.array)};function Pt(){}var xt=Pt,Tt=Pt,Rt=Pt,Ct=Pt,Ot=Pt,kt=Pt,It=Pt;var Lt=global.performance||{},qt=Lt.now||Lt.mozNow||Lt.msNow||Lt.oNow||Lt.webkitNow||function(){return(new Date).getTime()};var Ut=new Date;var Dt,Nt,jt={nextTick:function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var r=1;r<arguments.length;r++)t[r-1]=arguments[r];bt.push(new Ft(e,t)),1!==bt.length||St||yt(At)},title:"browser",browser:!0,env:{},argv:[],version:"",versions:{},on:xt,addListener:Tt,once:Rt,off:Ct,removeListener:Ot,removeAllListeners:kt,emit:It,binding:function(e){throw new Error("process.binding is not supported")},cwd:function(){return"/"},chdir:function(e){throw new Error("process.chdir is not supported")},umask:function(){return 0},hrtime:function(e){var t=.001*qt.call(Lt),r=Math.floor(t),a=Math.floor(t%1*1e9);return e&&(r-=e[0],(a-=e[1])<0&&(r--,a+=1e9)),[r,a]},platform:"browser",release:{},config:{},uptime:function(){return(new Date-Ut)/1e3}},Bt=jt,Mt=ot;function Ht(){if(Nt)return Dt;Nt=1;var e=ot;function t(e,t,r,a,n){Error.call(this),this.message=e,this.name="AxiosError",t&&(this.code=t),r&&(this.config=r),a&&(this.request=a),n&&(this.response=n)}e.inherits(t,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:this.config,code:this.code,status:this.response&&this.response.status?this.response.status:null}}});var r=t.prototype,a={};return["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED"].forEach((function(e){a[e]={value:e}})),Object.defineProperties(t,a),Object.defineProperty(r,"isAxiosError",{value:!0}),t.from=function(a,n,i,s,o,l){var c=Object.create(r);return e.toFlatObject(a,c,(function(e){return e!==Error.prototype})),t.call(c,a.message,n,i,s,o),c.name=a.name,l&&Object.assign(c,l),c},Dt=t}var $t={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},zt=[],Yt=[],Wt="undefined"!=typeof Uint8Array?Uint8Array:Array,Vt=!1;function Gt(){Vt=!0;for(var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",t=0;t<64;++t)zt[t]=e[t],Yt[e.charCodeAt(t)]=t;Yt["-".charCodeAt(0)]=62,Yt["_".charCodeAt(0)]=63}function Qt(e,t,r){for(var a,n,i=[],s=t;s<r;s+=3)a=(e[s]<<16)+(e[s+1]<<8)+e[s+2],i.push(zt[(n=a)>>18&63]+zt[n>>12&63]+zt[n>>6&63]+zt[63&n]);return i.join("")}function Kt(e){var t;Vt||Gt();for(var r=e.length,a=r%3,n="",i=[],s=16383,o=0,l=r-a;o<l;o+=s)i.push(Qt(e,o,o+s>l?l:o+s));return 1===a?(t=e[r-1],n+=zt[t>>2],n+=zt[t<<4&63],n+="=="):2===a&&(t=(e[r-2]<<8)+e[r-1],n+=zt[t>>10],n+=zt[t>>4&63],n+=zt[t<<2&63],n+="="),i.push(n),i.join("")}function Jt(e,t,r,a,n){var i,s,o=8*n-a-1,l=(1<<o)-1,c=l>>1,u=-7,d=r?n-1:0,h=r?-1:1,f=e[t+d];for(d+=h,i=f&(1<<-u)-1,f>>=-u,u+=o;u>0;i=256*i+e[t+d],d+=h,u-=8);for(s=i&(1<<-u)-1,i>>=-u,u+=a;u>0;s=256*s+e[t+d],d+=h,u-=8);if(0===i)i=1-c;else{if(i===l)return s?NaN:1/0*(f?-1:1);s+=Math.pow(2,a),i-=c}return(f?-1:1)*s*Math.pow(2,i-a)}function Xt(e,t,r,a,n,i){var s,o,l,c=8*i-n-1,u=(1<<c)-1,d=u>>1,h=23===n?Math.pow(2,-24)-Math.pow(2,-77):0,f=a?0:i-1,p=a?1:-1,g=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(o=isNaN(t)?1:0,s=u):(s=Math.floor(Math.log(t)/Math.LN2),t*(l=Math.pow(2,-s))<1&&(s--,l*=2),(t+=s+d>=1?h/l:h*Math.pow(2,1-d))*l>=2&&(s++,l/=2),s+d>=u?(o=0,s=u):s+d>=1?(o=(t*l-1)*Math.pow(2,n),s+=d):(o=t*Math.pow(2,d-1)*Math.pow(2,n),s=0));n>=8;e[r+f]=255&o,f+=p,o/=256,n-=8);for(s=s<<n|o,c+=n;c>0;e[r+f]=255&s,f+=p,s/=256,c-=8);e[r+f-p]|=128*g}var Zt={}.toString,er=Array.isArray||function(e){return"[object Array]"==Zt.call(e)};function tr(){return ar.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function rr(e,t){if(tr()<t)throw new RangeError("Invalid typed array length");return ar.TYPED_ARRAY_SUPPORT?(e=new Uint8Array(t)).__proto__=ar.prototype:(null===e&&(e=new ar(t)),e.length=t),e}function ar(e,t,r){if(!(ar.TYPED_ARRAY_SUPPORT||this instanceof ar))return new ar(e,t,r);if("number"==typeof e){if("string"==typeof t)throw new Error("If encoding is specified then the first argument must be a string");return sr(this,e)}return nr(this,e,t,r)}function nr(e,t,r,a){if("number"==typeof t)throw new TypeError('"value" argument must not be a number');return"undefined"!=typeof ArrayBuffer&&t instanceof ArrayBuffer?function(e,t,r,a){if(t.byteLength,r<0||t.byteLength<r)throw new RangeError("'offset' is out of bounds");if(t.byteLength<r+(a||0))throw new RangeError("'length' is out of bounds");t=void 0===r&&void 0===a?new Uint8Array(t):void 0===a?new Uint8Array(t,r):new Uint8Array(t,r,a);ar.TYPED_ARRAY_SUPPORT?(e=t).__proto__=ar.prototype:e=or(e,t);return e}(e,t,r,a):"string"==typeof t?function(e,t,r){"string"==typeof r&&""!==r||(r="utf8");if(!ar.isEncoding(r))throw new TypeError('"encoding" must be a valid string encoding');var a=0|ur(t,r);e=rr(e,a);var n=e.write(t,r);n!==a&&(e=e.slice(0,n));return e}(e,t,r):function(e,t){if(cr(t)){var r=0|lr(t.length);return 0===(e=rr(e,r)).length||t.copy(e,0,0,r),e}if(t){if("undefined"!=typeof ArrayBuffer&&t.buffer instanceof ArrayBuffer||"length"in t)return"number"!=typeof t.length||(a=t.length)!=a?rr(e,0):or(e,t);if("Buffer"===t.type&&er(t.data))return or(e,t.data)}var a;throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")}(e,t)}function ir(e){if("number"!=typeof e)throw new TypeError('"size" argument must be a number');if(e<0)throw new RangeError('"size" argument must not be negative')}function sr(e,t){if(ir(t),e=rr(e,t<0?0:0|lr(t)),!ar.TYPED_ARRAY_SUPPORT)for(var r=0;r<t;++r)e[r]=0;return e}function or(e,t){var r=t.length<0?0:0|lr(t.length);e=rr(e,r);for(var a=0;a<r;a+=1)e[a]=255&t[a];return e}function lr(e){if(e>=tr())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+tr().toString(16)+" bytes");return 0|e}function cr(e){return!(null==e||!e._isBuffer)}function ur(e,t){if(cr(e))return e.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e.byteLength;"string"!=typeof e&&(e=""+e);var r=e.length;if(0===r)return 0;for(var a=!1;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":case void 0:return $r(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return zr(e).length;default:if(a)return $r(e).length;t=(""+t).toLowerCase(),a=!0}}function dr(e,t,r){var a=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return Pr(this,t,r);case"utf8":case"utf-8":return Er(this,t,r);case"ascii":return Ar(this,t,r);case"latin1":case"binary":return Fr(this,t,r);case"base64":return Sr(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return xr(this,t,r);default:if(a)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),a=!0}}function hr(e,t,r){var a=e[t];e[t]=e[r],e[r]=a}function fr(e,t,r,a,n){if(0===e.length)return-1;if("string"==typeof r?(a=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,isNaN(r)&&(r=n?0:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(n)return-1;r=e.length-1}else if(r<0){if(!n)return-1;r=0}if("string"==typeof t&&(t=ar.from(t,a)),cr(t))return 0===t.length?-1:pr(e,t,r,a,n);if("number"==typeof t)return t&=255,ar.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?n?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):pr(e,[t],r,a,n);throw new TypeError("val must be string, number or Buffer")}function pr(e,t,r,a,n){var i,s=1,o=e.length,l=t.length;if(void 0!==a&&("ucs2"===(a=String(a).toLowerCase())||"ucs-2"===a||"utf16le"===a||"utf-16le"===a)){if(e.length<2||t.length<2)return-1;s=2,o/=2,l/=2,r/=2}function c(e,t){return 1===s?e[t]:e.readUInt16BE(t*s)}if(n){var u=-1;for(i=r;i<o;i++)if(c(e,i)===c(t,-1===u?0:i-u)){if(-1===u&&(u=i),i-u+1===l)return u*s}else-1!==u&&(i-=i-u),u=-1}else for(r+l>o&&(r=o-l),i=r;i>=0;i--){for(var d=!0,h=0;h<l;h++)if(c(e,i+h)!==c(t,h)){d=!1;break}if(d)return i}return-1}function gr(e,t,r,a){r=Number(r)||0;var n=e.length-r;a?(a=Number(a))>n&&(a=n):a=n;var i=t.length;if(i%2!=0)throw new TypeError("Invalid hex string");a>i/2&&(a=i/2);for(var s=0;s<a;++s){var o=parseInt(t.substr(2*s,2),16);if(isNaN(o))return s;e[r+s]=o}return s}function mr(e,t,r,a){return Yr($r(t,e.length-r),e,r,a)}function vr(e,t,r,a){return Yr(function(e){for(var t=[],r=0;r<e.length;++r)t.push(255&e.charCodeAt(r));return t}(t),e,r,a)}function yr(e,t,r,a){return vr(e,t,r,a)}function wr(e,t,r,a){return Yr(zr(t),e,r,a)}function br(e,t,r,a){return Yr(function(e,t){for(var r,a,n,i=[],s=0;s<e.length&&!((t-=2)<0);++s)a=(r=e.charCodeAt(s))>>8,n=r%256,i.push(n),i.push(a);return i}(t,e.length-r),e,r,a)}function Sr(e,t,r){return 0===t&&r===e.length?Kt(e):Kt(e.slice(t,r))}function Er(e,t,r){r=Math.min(e.length,r);for(var a=[],n=t;n<r;){var i,s,o,l,c=e[n],u=null,d=c>239?4:c>223?3:c>191?2:1;if(n+d<=r)switch(d){case 1:c<128&&(u=c);break;case 2:128==(192&(i=e[n+1]))&&(l=(31&c)<<6|63&i)>127&&(u=l);break;case 3:i=e[n+1],s=e[n+2],128==(192&i)&&128==(192&s)&&(l=(15&c)<<12|(63&i)<<6|63&s)>2047&&(l<55296||l>57343)&&(u=l);break;case 4:i=e[n+1],s=e[n+2],o=e[n+3],128==(192&i)&&128==(192&s)&&128==(192&o)&&(l=(15&c)<<18|(63&i)<<12|(63&s)<<6|63&o)>65535&&l<1114112&&(u=l)}null===u?(u=65533,d=1):u>65535&&(u-=65536,a.push(u>>>10&1023|55296),u=56320|1023&u),a.push(u),n+=d}return function(e){var t=e.length;if(t<=_r)return String.fromCharCode.apply(String,e);var r="",a=0;for(;a<t;)r+=String.fromCharCode.apply(String,e.slice(a,a+=_r));return r}(a)}ar.TYPED_ARRAY_SUPPORT=void 0===global.TYPED_ARRAY_SUPPORT||global.TYPED_ARRAY_SUPPORT,tr(),ar.poolSize=8192,ar._augment=function(e){return e.__proto__=ar.prototype,e},ar.from=function(e,t,r){return nr(null,e,t,r)},ar.TYPED_ARRAY_SUPPORT&&(ar.prototype.__proto__=Uint8Array.prototype,ar.__proto__=Uint8Array),ar.alloc=function(e,t,r){return function(e,t,r,a){return ir(t),t<=0?rr(e,t):void 0!==r?"string"==typeof a?rr(e,t).fill(r,a):rr(e,t).fill(r):rr(e,t)}(null,e,t,r)},ar.allocUnsafe=function(e){return sr(null,e)},ar.allocUnsafeSlow=function(e){return sr(null,e)},ar.isBuffer=function(e){return null!=e&&(!!e._isBuffer||Wr(e)||function(e){return"function"==typeof e.readFloatLE&&"function"==typeof e.slice&&Wr(e.slice(0,0))}(e))},ar.compare=function(e,t){if(!cr(e)||!cr(t))throw new TypeError("Arguments must be Buffers");if(e===t)return 0;for(var r=e.length,a=t.length,n=0,i=Math.min(r,a);n<i;++n)if(e[n]!==t[n]){r=e[n],a=t[n];break}return r<a?-1:a<r?1:0},ar.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},ar.concat=function(e,t){if(!er(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return ar.alloc(0);var r;if(void 0===t)for(t=0,r=0;r<e.length;++r)t+=e[r].length;var a=ar.allocUnsafe(t),n=0;for(r=0;r<e.length;++r){var i=e[r];if(!cr(i))throw new TypeError('"list" argument must be an Array of Buffers');i.copy(a,n),n+=i.length}return a},ar.byteLength=ur,ar.prototype._isBuffer=!0,ar.prototype.swap16=function(){var e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var t=0;t<e;t+=2)hr(this,t,t+1);return this},ar.prototype.swap32=function(){var e=this.length;if(e%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var t=0;t<e;t+=4)hr(this,t,t+3),hr(this,t+1,t+2);return this},ar.prototype.swap64=function(){var e=this.length;if(e%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var t=0;t<e;t+=8)hr(this,t,t+7),hr(this,t+1,t+6),hr(this,t+2,t+5),hr(this,t+3,t+4);return this},ar.prototype.toString=function(){var e=0|this.length;return 0===e?"":0===arguments.length?Er(this,0,e):dr.apply(this,arguments)},ar.prototype.equals=function(e){if(!cr(e))throw new TypeError("Argument must be a Buffer");return this===e||0===ar.compare(this,e)},ar.prototype.inspect=function(){var e="";return this.length>0&&(e=this.toString("hex",0,50).match(/.{2}/g).join(" "),this.length>50&&(e+=" ... ")),"<Buffer "+e+">"},ar.prototype.compare=function(e,t,r,a,n){if(!cr(e))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===r&&(r=e?e.length:0),void 0===a&&(a=0),void 0===n&&(n=this.length),t<0||r>e.length||a<0||n>this.length)throw new RangeError("out of range index");if(a>=n&&t>=r)return 0;if(a>=n)return-1;if(t>=r)return 1;if(this===e)return 0;for(var i=(n>>>=0)-(a>>>=0),s=(r>>>=0)-(t>>>=0),o=Math.min(i,s),l=this.slice(a,n),c=e.slice(t,r),u=0;u<o;++u)if(l[u]!==c[u]){i=l[u],s=c[u];break}return i<s?-1:s<i?1:0},ar.prototype.includes=function(e,t,r){return-1!==this.indexOf(e,t,r)},ar.prototype.indexOf=function(e,t,r){return fr(this,e,t,r,!0)},ar.prototype.lastIndexOf=function(e,t,r){return fr(this,e,t,r,!1)},ar.prototype.write=function(e,t,r,a){if(void 0===t)a="utf8",r=this.length,t=0;else if(void 0===r&&"string"==typeof t)a=t,r=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t|=0,isFinite(r)?(r|=0,void 0===a&&(a="utf8")):(a=r,r=void 0)}var n=this.length-t;if((void 0===r||r>n)&&(r=n),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");a||(a="utf8");for(var i=!1;;)switch(a){case"hex":return gr(this,e,t,r);case"utf8":case"utf-8":return mr(this,e,t,r);case"ascii":return vr(this,e,t,r);case"latin1":case"binary":return yr(this,e,t,r);case"base64":return wr(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return br(this,e,t,r);default:if(i)throw new TypeError("Unknown encoding: "+a);a=(""+a).toLowerCase(),i=!0}},ar.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var _r=4096;function Ar(e,t,r){var a="";r=Math.min(e.length,r);for(var n=t;n<r;++n)a+=String.fromCharCode(127&e[n]);return a}function Fr(e,t,r){var a="";r=Math.min(e.length,r);for(var n=t;n<r;++n)a+=String.fromCharCode(e[n]);return a}function Pr(e,t,r){var a=e.length;(!t||t<0)&&(t=0),(!r||r<0||r>a)&&(r=a);for(var n="",i=t;i<r;++i)n+=Hr(e[i]);return n}function xr(e,t,r){for(var a=e.slice(t,r),n="",i=0;i<a.length;i+=2)n+=String.fromCharCode(a[i]+256*a[i+1]);return n}function Tr(e,t,r){if(e%1!=0||e<0)throw new RangeError("offset is not uint");if(e+t>r)throw new RangeError("Trying to access beyond buffer length")}function Rr(e,t,r,a,n,i){if(!cr(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>n||t<i)throw new RangeError('"value" argument is out of bounds');if(r+a>e.length)throw new RangeError("Index out of range")}function Cr(e,t,r,a){t<0&&(t=65535+t+1);for(var n=0,i=Math.min(e.length-r,2);n<i;++n)e[r+n]=(t&255<<8*(a?n:1-n))>>>8*(a?n:1-n)}function Or(e,t,r,a){t<0&&(t=4294967295+t+1);for(var n=0,i=Math.min(e.length-r,4);n<i;++n)e[r+n]=t>>>8*(a?n:3-n)&255}function kr(e,t,r,a,n,i){if(r+a>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function Ir(e,t,r,a,n){return n||kr(e,0,r,4),Xt(e,t,r,a,23,4),r+4}function Lr(e,t,r,a,n){return n||kr(e,0,r,8),Xt(e,t,r,a,52,8),r+8}ar.prototype.slice=function(e,t){var r,a=this.length;if((e=~~e)<0?(e+=a)<0&&(e=0):e>a&&(e=a),(t=void 0===t?a:~~t)<0?(t+=a)<0&&(t=0):t>a&&(t=a),t<e&&(t=e),ar.TYPED_ARRAY_SUPPORT)(r=this.subarray(e,t)).__proto__=ar.prototype;else{var n=t-e;r=new ar(n,void 0);for(var i=0;i<n;++i)r[i]=this[i+e]}return r},ar.prototype.readUIntLE=function(e,t,r){e|=0,t|=0,r||Tr(e,t,this.length);for(var a=this[e],n=1,i=0;++i<t&&(n*=256);)a+=this[e+i]*n;return a},ar.prototype.readUIntBE=function(e,t,r){e|=0,t|=0,r||Tr(e,t,this.length);for(var a=this[e+--t],n=1;t>0&&(n*=256);)a+=this[e+--t]*n;return a},ar.prototype.readUInt8=function(e,t){return t||Tr(e,1,this.length),this[e]},ar.prototype.readUInt16LE=function(e,t){return t||Tr(e,2,this.length),this[e]|this[e+1]<<8},ar.prototype.readUInt16BE=function(e,t){return t||Tr(e,2,this.length),this[e]<<8|this[e+1]},ar.prototype.readUInt32LE=function(e,t){return t||Tr(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},ar.prototype.readUInt32BE=function(e,t){return t||Tr(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},ar.prototype.readIntLE=function(e,t,r){e|=0,t|=0,r||Tr(e,t,this.length);for(var a=this[e],n=1,i=0;++i<t&&(n*=256);)a+=this[e+i]*n;return a>=(n*=128)&&(a-=Math.pow(2,8*t)),a},ar.prototype.readIntBE=function(e,t,r){e|=0,t|=0,r||Tr(e,t,this.length);for(var a=t,n=1,i=this[e+--a];a>0&&(n*=256);)i+=this[e+--a]*n;return i>=(n*=128)&&(i-=Math.pow(2,8*t)),i},ar.prototype.readInt8=function(e,t){return t||Tr(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},ar.prototype.readInt16LE=function(e,t){t||Tr(e,2,this.length);var r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},ar.prototype.readInt16BE=function(e,t){t||Tr(e,2,this.length);var r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},ar.prototype.readInt32LE=function(e,t){return t||Tr(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},ar.prototype.readInt32BE=function(e,t){return t||Tr(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},ar.prototype.readFloatLE=function(e,t){return t||Tr(e,4,this.length),Jt(this,e,!0,23,4)},ar.prototype.readFloatBE=function(e,t){return t||Tr(e,4,this.length),Jt(this,e,!1,23,4)},ar.prototype.readDoubleLE=function(e,t){return t||Tr(e,8,this.length),Jt(this,e,!0,52,8)},ar.prototype.readDoubleBE=function(e,t){return t||Tr(e,8,this.length),Jt(this,e,!1,52,8)},ar.prototype.writeUIntLE=function(e,t,r,a){(e=+e,t|=0,r|=0,a)||Rr(this,e,t,r,Math.pow(2,8*r)-1,0);var n=1,i=0;for(this[t]=255&e;++i<r&&(n*=256);)this[t+i]=e/n&255;return t+r},ar.prototype.writeUIntBE=function(e,t,r,a){(e=+e,t|=0,r|=0,a)||Rr(this,e,t,r,Math.pow(2,8*r)-1,0);var n=r-1,i=1;for(this[t+n]=255&e;--n>=0&&(i*=256);)this[t+n]=e/i&255;return t+r},ar.prototype.writeUInt8=function(e,t,r){return e=+e,t|=0,r||Rr(this,e,t,1,255,0),ar.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&e,t+1},ar.prototype.writeUInt16LE=function(e,t,r){return e=+e,t|=0,r||Rr(this,e,t,2,65535,0),ar.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):Cr(this,e,t,!0),t+2},ar.prototype.writeUInt16BE=function(e,t,r){return e=+e,t|=0,r||Rr(this,e,t,2,65535,0),ar.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):Cr(this,e,t,!1),t+2},ar.prototype.writeUInt32LE=function(e,t,r){return e=+e,t|=0,r||Rr(this,e,t,4,4294967295,0),ar.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e):Or(this,e,t,!0),t+4},ar.prototype.writeUInt32BE=function(e,t,r){return e=+e,t|=0,r||Rr(this,e,t,4,4294967295,0),ar.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):Or(this,e,t,!1),t+4},ar.prototype.writeIntLE=function(e,t,r,a){if(e=+e,t|=0,!a){var n=Math.pow(2,8*r-1);Rr(this,e,t,r,n-1,-n)}var i=0,s=1,o=0;for(this[t]=255&e;++i<r&&(s*=256);)e<0&&0===o&&0!==this[t+i-1]&&(o=1),this[t+i]=(e/s>>0)-o&255;return t+r},ar.prototype.writeIntBE=function(e,t,r,a){if(e=+e,t|=0,!a){var n=Math.pow(2,8*r-1);Rr(this,e,t,r,n-1,-n)}var i=r-1,s=1,o=0;for(this[t+i]=255&e;--i>=0&&(s*=256);)e<0&&0===o&&0!==this[t+i+1]&&(o=1),this[t+i]=(e/s>>0)-o&255;return t+r},ar.prototype.writeInt8=function(e,t,r){return e=+e,t|=0,r||Rr(this,e,t,1,127,-128),ar.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=255&e,t+1},ar.prototype.writeInt16LE=function(e,t,r){return e=+e,t|=0,r||Rr(this,e,t,2,32767,-32768),ar.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):Cr(this,e,t,!0),t+2},ar.prototype.writeInt16BE=function(e,t,r){return e=+e,t|=0,r||Rr(this,e,t,2,32767,-32768),ar.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):Cr(this,e,t,!1),t+2},ar.prototype.writeInt32LE=function(e,t,r){return e=+e,t|=0,r||Rr(this,e,t,4,2147483647,-2147483648),ar.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):Or(this,e,t,!0),t+4},ar.prototype.writeInt32BE=function(e,t,r){return e=+e,t|=0,r||Rr(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),ar.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):Or(this,e,t,!1),t+4},ar.prototype.writeFloatLE=function(e,t,r){return Ir(this,e,t,!0,r)},ar.prototype.writeFloatBE=function(e,t,r){return Ir(this,e,t,!1,r)},ar.prototype.writeDoubleLE=function(e,t,r){return Lr(this,e,t,!0,r)},ar.prototype.writeDoubleBE=function(e,t,r){return Lr(this,e,t,!1,r)},ar.prototype.copy=function(e,t,r,a){if(r||(r=0),a||0===a||(a=this.length),t>=e.length&&(t=e.length),t||(t=0),a>0&&a<r&&(a=r),a===r)return 0;if(0===e.length||0===this.length)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(r<0||r>=this.length)throw new RangeError("sourceStart out of bounds");if(a<0)throw new RangeError("sourceEnd out of bounds");a>this.length&&(a=this.length),e.length-t<a-r&&(a=e.length-t+r);var n,i=a-r;if(this===e&&r<t&&t<a)for(n=i-1;n>=0;--n)e[n+t]=this[n+r];else if(i<1e3||!ar.TYPED_ARRAY_SUPPORT)for(n=0;n<i;++n)e[n+t]=this[n+r];else Uint8Array.prototype.set.call(e,this.subarray(r,r+i),t);return i},ar.prototype.fill=function(e,t,r,a){if("string"==typeof e){if("string"==typeof t?(a=t,t=0,r=this.length):"string"==typeof r&&(a=r,r=this.length),1===e.length){var n=e.charCodeAt(0);n<256&&(e=n)}if(void 0!==a&&"string"!=typeof a)throw new TypeError("encoding must be a string");if("string"==typeof a&&!ar.isEncoding(a))throw new TypeError("Unknown encoding: "+a)}else"number"==typeof e&&(e&=255);if(t<0||this.length<t||this.length<r)throw new RangeError("Out of range index");if(r<=t)return this;var i;if(t>>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(i=t;i<r;++i)this[i]=e;else{var s=cr(e)?e:$r(new ar(e,a).toString()),o=s.length;for(i=0;i<r-t;++i)this[i+t]=s[i%o]}return this};var qr,Ur,Dr,Nr,jr,Br,Mr=/[^+\/0-9A-Za-z-_]/g;function Hr(e){return e<16?"0"+e.toString(16):e.toString(16)}function $r(e,t){var r;t=t||1/0;for(var a=e.length,n=null,i=[],s=0;s<a;++s){if((r=e.charCodeAt(s))>55295&&r<57344){if(!n){if(r>56319){(t-=3)>-1&&i.push(239,191,189);continue}if(s+1===a){(t-=3)>-1&&i.push(239,191,189);continue}n=r;continue}if(r<56320){(t-=3)>-1&&i.push(239,191,189),n=r;continue}r=65536+(n-55296<<10|r-56320)}else n&&(t-=3)>-1&&i.push(239,191,189);if(n=null,r<128){if((t-=1)<0)break;i.push(r)}else if(r<2048){if((t-=2)<0)break;i.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;i.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;i.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return i}function zr(e){return function(e){var t,r,a,n,i,s;Vt||Gt();var o=e.length;if(o%4>0)throw new Error("Invalid string. Length must be a multiple of 4");i="="===e[o-2]?2:"="===e[o-1]?1:0,s=new Wt(3*o/4-i),a=i>0?o-4:o;var l=0;for(t=0,r=0;t<a;t+=4,r+=3)n=Yt[e.charCodeAt(t)]<<18|Yt[e.charCodeAt(t+1)]<<12|Yt[e.charCodeAt(t+2)]<<6|Yt[e.charCodeAt(t+3)],s[l++]=n>>16&255,s[l++]=n>>8&255,s[l++]=255&n;return 2===i?(n=Yt[e.charCodeAt(t)]<<2|Yt[e.charCodeAt(t+1)]>>4,s[l++]=255&n):1===i&&(n=Yt[e.charCodeAt(t)]<<10|Yt[e.charCodeAt(t+1)]<<4|Yt[e.charCodeAt(t+2)]>>2,s[l++]=n>>8&255,s[l++]=255&n),s}(function(e){if((e=function(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")}(e).replace(Mr,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function Yr(e,t,r,a){for(var n=0;n<a&&!(n+r>=t.length||n>=e.length);++n)t[n+r]=e[n];return n}function Wr(e){return!!e.constructor&&"function"==typeof e.constructor.isBuffer&&e.constructor.isBuffer(e)}function Vr(){if(Ur)return qr;Ur=1;var e=ot;return qr=function(t,r){r=r||new FormData;var a=[];function n(t){return null===t?"":e.isDate(t)?t.toISOString():e.isArrayBuffer(t)||e.isTypedArray(t)?"function"==typeof Blob?new Blob([t]):ar.from(t):t}return function t(i,s){if(e.isPlainObject(i)||e.isArray(i)){if(-1!==a.indexOf(i))throw Error("Circular reference detected in "+s);a.push(i),e.forEach(i,(function(a,i){if(!e.isUndefined(a)){var o,l=s?s+"."+i:i;if(a&&!s&&"object"==typeof a)if(e.endsWith(i,"{}"))a=JSON.stringify(a);else if(e.endsWith(i,"[]")&&(o=e.toArray(a)))return void o.forEach((function(t){!e.isUndefined(t)&&r.append(l,n(t))}));t(a,l)}})),a.pop()}else r.append(s,n(i))}(t),r},qr}function Gr(){if(Nr)return Dr;Nr=1;var e=Ht();return Dr=function(t,r,a){var n=a.config.validateStatus;a.status&&n&&!n(a.status)?r(new e("Request failed with status code "+a.status,[e.ERR_BAD_REQUEST,e.ERR_BAD_RESPONSE][Math.floor(a.status/100)-4],a.config,a.request,a)):t(a)}}function Qr(){if(Br)return jr;Br=1;var e=ot;return jr=e.isStandardBrowserEnv()?{write:function(t,r,a,n,i,s){var o=[];o.push(t+"="+encodeURIComponent(r)),e.isNumber(a)&&o.push("expires="+new Date(a).toGMTString()),e.isString(n)&&o.push("path="+n),e.isString(i)&&o.push("domain="+i),!0===s&&o.push("secure"),document.cookie=o.join("; ")},read:function(e){var t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove:function(e){this.write(e,"",Date.now()-864e5)}}:{write:function(){},read:function(){return null},remove:function(){}}}var Kr,Jr,Xr,Zr,ea,ta,ra,aa,na,ia,sa,oa,la=function(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)},ca=function(e,t){return t?e.replace(/\/+$/,"")+"/"+t.replace(/^\/+/,""):e},ua=function(e,t){return e&&!la(t)?ca(e,t):t};function da(){if(Jr)return Kr;Jr=1;var e=ot,t=["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"];return Kr=function(r){var a,n,i,s={};return r?(e.forEach(r.split("\n"),(function(r){if(i=r.indexOf(":"),a=e.trim(r.substr(0,i)).toLowerCase(),n=e.trim(r.substr(i+1)),a){if(s[a]&&t.indexOf(a)>=0)return;s[a]="set-cookie"===a?(s[a]?s[a]:[]).concat([n]):s[a]?s[a]+", "+n:n}})),s):s},Kr}function ha(){if(Zr)return Xr;Zr=1;var e=ot;return Xr=e.isStandardBrowserEnv()?function(){var t,r=/(msie|trident)/i.test(navigator.userAgent),a=document.createElement("a");function n(e){var t=e;return r&&(a.setAttribute("href",t),t=a.href),a.setAttribute("href",t),{href:a.href,protocol:a.protocol?a.protocol.replace(/:$/,""):"",host:a.host,search:a.search?a.search.replace(/^\?/,""):"",hash:a.hash?a.hash.replace(/^#/,""):"",hostname:a.hostname,port:a.port,pathname:"/"===a.pathname.charAt(0)?a.pathname:"/"+a.pathname}}return t=n(window.location.href),function(r){var a=e.isString(r)?n(r):r;return a.protocol===t.protocol&&a.host===t.host}}():function(){return!0}}function fa(){if(ta)return ea;ta=1;var e=Ht();function t(t){e.call(this,null==t?"canceled":t,e.ERR_CANCELED),this.name="CanceledError"}return ot.inherits(t,e,{__CANCEL__:!0}),ea=t}function pa(){return aa?ra:(aa=1,ra=function(e){var t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""})}function ga(){if(ia)return na;ia=1;var e=ot,t=Gr(),r=Qr(),a=ut,n=ua,i=da(),s=ha(),o=$t,l=Ht(),c=fa(),u=pa();return na=function(d){return new Promise((function(h,f){var p,g=d.data,m=d.headers,v=d.responseType;function y(){d.cancelToken&&d.cancelToken.unsubscribe(p),d.signal&&d.signal.removeEventListener("abort",p)}e.isFormData(g)&&e.isStandardBrowserEnv()&&delete m["Content-Type"];var w=new XMLHttpRequest;if(d.auth){var b=d.auth.username||"",S=d.auth.password?unescape(encodeURIComponent(d.auth.password)):"";m.Authorization="Basic "+btoa(b+":"+S)}var E=n(d.baseURL,d.url);function _(){if(w){var e="getAllResponseHeaders"in w?i(w.getAllResponseHeaders()):null,r={data:v&&"text"!==v&&"json"!==v?w.response:w.responseText,status:w.status,statusText:w.statusText,headers:e,config:d,request:w};t((function(e){h(e),y()}),(function(e){f(e),y()}),r),w=null}}if(w.open(d.method.toUpperCase(),a(E,d.params,d.paramsSerializer),!0),w.timeout=d.timeout,"onloadend"in w?w.onloadend=_:w.onreadystatechange=function(){w&&4===w.readyState&&(0!==w.status||w.responseURL&&0===w.responseURL.indexOf("file:"))&&setTimeout(_)},w.onabort=function(){w&&(f(new l("Request aborted",l.ECONNABORTED,d,w)),w=null)},w.onerror=function(){f(new l("Network Error",l.ERR_NETWORK,d,w,w)),w=null},w.ontimeout=function(){var e=d.timeout?"timeout of "+d.timeout+"ms exceeded":"timeout exceeded",t=d.transitional||o;d.timeoutErrorMessage&&(e=d.timeoutErrorMessage),f(new l(e,t.clarifyTimeoutError?l.ETIMEDOUT:l.ECONNABORTED,d,w)),w=null},e.isStandardBrowserEnv()){var A=(d.withCredentials||s(E))&&d.xsrfCookieName?r.read(d.xsrfCookieName):void 0;A&&(m[d.xsrfHeaderName]=A)}"setRequestHeader"in w&&e.forEach(m,(function(e,t){void 0===g&&"content-type"===t.toLowerCase()?delete m[t]:w.setRequestHeader(t,e)})),e.isUndefined(d.withCredentials)||(w.withCredentials=!!d.withCredentials),v&&"json"!==v&&(w.responseType=d.responseType),"function"==typeof d.onDownloadProgress&&w.addEventListener("progress",d.onDownloadProgress),"function"==typeof d.onUploadProgress&&w.upload&&w.upload.addEventListener("progress",d.onUploadProgress),(d.cancelToken||d.signal)&&(p=function(e){w&&(f(!e||e&&e.type?new c:e),w.abort(),w=null)},d.cancelToken&&d.cancelToken.subscribe(p),d.signal&&(d.signal.aborted?p():d.signal.addEventListener("abort",p))),g||(g=null);var F=u(E);F&&-1===["http","https","file"].indexOf(F)?f(new l("Unsupported protocol "+F+":",l.ERR_BAD_REQUEST,d)):w.send(g)}))},na}var ma=ot,va=function(e,t){Mt.forEach(e,(function(r,a){a!==t&&a.toUpperCase()===t.toUpperCase()&&(e[t]=r,delete e[a])}))},ya=Ht(),wa=$t,ba=Vr(),Sa={"Content-Type":"application/x-www-form-urlencoded"};function Ea(e,t){!ma.isUndefined(e)&&ma.isUndefined(e["Content-Type"])&&(e["Content-Type"]=t)}var _a,Aa={transitional:wa,adapter:(("undefined"!=typeof XMLHttpRequest||void 0!==Bt&&"[object process]"===Object.prototype.toString.call(Bt))&&(_a=ga()),_a),transformRequest:[function(e,t){if(va(t,"Accept"),va(t,"Content-Type"),ma.isFormData(e)||ma.isArrayBuffer(e)||ma.isBuffer(e)||ma.isStream(e)||ma.isFile(e)||ma.isBlob(e))return e;if(ma.isArrayBufferView(e))return e.buffer;if(ma.isURLSearchParams(e))return Ea(t,"application/x-www-form-urlencoded;charset=utf-8"),e.toString();var r,a=ma.isObject(e),n=t&&t["Content-Type"];if((r=ma.isFileList(e))||a&&"multipart/form-data"===n){var i=this.env&&this.env.FormData;return ba(r?{"files[]":e}:e,i&&new i)}return a||"application/json"===n?(Ea(t,"application/json"),function(e,t,r){if(ma.isString(e))try{return(t||JSON.parse)(e),ma.trim(e)}catch(e){if("SyntaxError"!==e.name)throw e}return(r||JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){var t=this.transitional||Aa.transitional,r=t&&t.silentJSONParsing,a=t&&t.forcedJSONParsing,n=!r&&"json"===this.responseType;if(n||a&&ma.isString(e)&&e.length)try{return JSON.parse(e)}catch(e){if(n){if("SyntaxError"===e.name)throw ya.from(e,ya.ERR_BAD_RESPONSE,this,null,this.response);throw e}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:oa?sa:(oa=1,sa=null)},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*"}}};ma.forEach(["delete","get","head"],(function(e){Aa.headers[e]={}})),ma.forEach(["post","put","patch"],(function(e){Aa.headers[e]=ma.merge(Sa)}));var Fa,Pa,xa=Aa,Ta=ot,Ra=xa;function Ca(){return Pa?Fa:(Pa=1,Fa=function(e){return!(!e||!e.__CANCEL__)})}var Oa=ot,ka=function(e,t,r){var a=this||Ra;return Ta.forEach(r,(function(r){e=r.call(a,e,t)})),e},Ia=Ca(),La=xa,qa=fa();function Ua(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new qa}var Da,Na,ja=ot,Ba=function(e,t){t=t||{};var r={};function a(e,t){return ja.isPlainObject(e)&&ja.isPlainObject(t)?ja.merge(e,t):ja.isPlainObject(t)?ja.merge({},t):ja.isArray(t)?t.slice():t}function n(r){return ja.isUndefined(t[r])?ja.isUndefined(e[r])?void 0:a(void 0,e[r]):a(e[r],t[r])}function i(e){if(!ja.isUndefined(t[e]))return a(void 0,t[e])}function s(r){return ja.isUndefined(t[r])?ja.isUndefined(e[r])?void 0:a(void 0,e[r]):a(void 0,t[r])}function o(r){return r in t?a(e[r],t[r]):r in e?a(void 0,e[r]):void 0}var l={url:i,method:i,data:i,baseURL:s,transformRequest:s,transformResponse:s,paramsSerializer:s,timeout:s,timeoutMessage:s,withCredentials:s,adapter:s,responseType:s,xsrfCookieName:s,xsrfHeaderName:s,onUploadProgress:s,onDownloadProgress:s,decompress:s,maxContentLength:s,maxBodyLength:s,beforeRedirect:s,transport:s,httpAgent:s,httpsAgent:s,cancelToken:s,socketPath:s,responseEncoding:s,validateStatus:o};return ja.forEach(Object.keys(e).concat(Object.keys(t)),(function(e){var t=l[e]||n,a=t(e);ja.isUndefined(a)&&t!==o||(r[e]=a)})),r};function Ma(){return Na?Da:(Na=1,Da={version:"0.27.2"})}var Ha=Ma().version,$a=Ht(),za={};["object","boolean","number","function","string","symbol"].forEach((function(e,t){za[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}}));var Ya={};za.transitional=function(e,t,r){function a(e,t){return"[Axios v"+Ha+"] Transitional option '"+e+"'"+t+(r?". "+r:"")}return function(r,n,i){if(!1===e)throw new $a(a(n," has been removed"+(t?" in "+t:"")),$a.ERR_DEPRECATED);return t&&!Ya[n]&&(Ya[n]=!0,console.warn(a(n," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(r,n,i)}};var Wa,Va,Ga,Qa,Ka,Ja,Xa={assertOptions:function(e,t,r){if("object"!=typeof e)throw new $a("options must be an object",$a.ERR_BAD_OPTION_VALUE);for(var a=Object.keys(e),n=a.length;n-- >0;){var i=a[n],s=t[i];if(s){var o=e[i],l=void 0===o||s(o,i,e);if(!0!==l)throw new $a("option "+i+" must be "+l,$a.ERR_BAD_OPTION_VALUE)}else if(!0!==r)throw new $a("Unknown option "+i,$a.ERR_BAD_OPTION)}},validators:za},Za=ot,en=ut,tn=ft,rn=function(e){return Ua(e),e.headers=e.headers||{},e.data=ka.call(e,e.data,e.headers,e.transformRequest),e.headers=Oa.merge(e.headers.common||{},e.headers[e.method]||{},e.headers),Oa.forEach(["delete","get","head","post","put","patch","common"],(function(t){delete e.headers[t]})),(e.adapter||La.adapter)(e).then((function(t){return Ua(e),t.data=ka.call(e,t.data,t.headers,e.transformResponse),t}),(function(t){return Ia(t)||(Ua(e),t&&t.response&&(t.response.data=ka.call(e,t.response.data,t.response.headers,e.transformResponse))),Promise.reject(t)}))},an=Ba,nn=ua,sn=Xa,on=sn.validators;function ln(e){this.defaults=e,this.interceptors={request:new tn,response:new tn}}ln.prototype.request=function(e,t){"string"==typeof e?(t=t||{}).url=e:t=e||{},(t=an(this.defaults,t)).method?t.method=t.method.toLowerCase():this.defaults.method?t.method=this.defaults.method.toLowerCase():t.method="get";var r=t.transitional;void 0!==r&&sn.assertOptions(r,{silentJSONParsing:on.transitional(on.boolean),forcedJSONParsing:on.transitional(on.boolean),clarifyTimeoutError:on.transitional(on.boolean)},!1);var a=[],n=!0;this.interceptors.request.forEach((function(e){"function"==typeof e.runWhen&&!1===e.runWhen(t)||(n=n&&e.synchronous,a.unshift(e.fulfilled,e.rejected))}));var i,s=[];if(this.interceptors.response.forEach((function(e){s.push(e.fulfilled,e.rejected)})),!n){var o=[rn,void 0];for(Array.prototype.unshift.apply(o,a),o=o.concat(s),i=Promise.resolve(t);o.length;)i=i.then(o.shift(),o.shift());return i}for(var l=t;a.length;){var c=a.shift(),u=a.shift();try{l=c(l)}catch(e){u(e);break}}try{i=rn(l)}catch(e){return Promise.reject(e)}for(;s.length;)i=i.then(s.shift(),s.shift());return i},ln.prototype.getUri=function(e){e=an(this.defaults,e);var t=nn(e.baseURL,e.url);return en(t,e.params,e.paramsSerializer)},Za.forEach(["delete","get","head","options"],(function(e){ln.prototype[e]=function(t,r){return this.request(an(r||{},{method:e,url:t,data:(r||{}).data}))}})),Za.forEach(["post","put","patch"],(function(e){function t(t){return function(r,a,n){return this.request(an(n||{},{method:e,headers:t?{"Content-Type":"multipart/form-data"}:{},url:r,data:a}))}}ln.prototype[e]=t(),ln.prototype[e+"Form"]=t(!0)}));var cn=ot,un=He,dn=ln,hn=Ba;var fn=function e(t){var r=new dn(t),a=un(dn.prototype.request,r);return cn.extend(a,dn.prototype,r),cn.extend(a,r),a.create=function(r){return e(hn(t,r))},a}(xa);fn.Axios=dn,fn.CanceledError=fa(),fn.CancelToken=function(){if(Va)return Wa;Va=1;var e=fa();function t(t){if("function"!=typeof t)throw new TypeError("executor must be a function.");var r;this.promise=new Promise((function(e){r=e}));var a=this;this.promise.then((function(e){if(a._listeners){var t,r=a._listeners.length;for(t=0;t<r;t++)a._listeners[t](e);a._listeners=null}})),this.promise.then=function(e){var t,r=new Promise((function(e){a.subscribe(e),t=e})).then(e);return r.cancel=function(){a.unsubscribe(t)},r},t((function(t){a.reason||(a.reason=new e(t),r(a.reason))}))}return t.prototype.throwIfRequested=function(){if(this.reason)throw this.reason},t.prototype.subscribe=function(e){this.reason?e(this.reason):this._listeners?this._listeners.push(e):this._listeners=[e]},t.prototype.unsubscribe=function(e){if(this._listeners){var t=this._listeners.indexOf(e);-1!==t&&this._listeners.splice(t,1)}},t.source=function(){var e,r=new t((function(t){e=t}));return{token:r,cancel:e}},Wa=t}(),fn.isCancel=Ca(),fn.VERSION=Ma().version,fn.toFormData=Vr(),fn.AxiosError=Ht(),fn.Cancel=fn.CanceledError,fn.all=function(e){return Promise.all(e)},fn.spread=Qa?Ga:(Qa=1,Ga=function(e){return function(t){return e.apply(null,t)}}),fn.isAxiosError=function(){if(Ja)return Ka;Ja=1;var e=ot;return Ka=function(t){return e.isObject(t)&&!0===t.isAxiosError}}(),Me.exports=fn,Me.exports.default=fn;var pn=Me.exports;function gn(e){this.message=e}gn.prototype=new Error,gn.prototype.name="InvalidCharacterError";var mn="undefined"!=typeof window&&window.atob&&window.atob.bind(window)||function(e){var t=String(e).replace(/=+$/,"");if(t.length%4==1)throw new gn("'atob' failed: The string to be decoded is not correctly encoded.");for(var r,a,n=0,i=0,s="";a=t.charAt(i++);~a&&(r=n%4?64*r+a:a,n++%4)?s+=String.fromCharCode(255&r>>(-2*n&6)):0)a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(a);return s};function vn(e){var t=e.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw"Illegal base64url string!"}try{return function(e){return decodeURIComponent(mn(e).replace(/(.)/g,(function(e,t){var r=t.charCodeAt(0).toString(16).toUpperCase();return r.length<2&&(r="0"+r),"%"+r})))}(t)}catch(e){return mn(t)}}function yn(e){this.message=e}yn.prototype=new Error,yn.prototype.name="InvalidTokenError";class wn{constructor(){this.inIframe=salla.helpers.isIframe(),salla.event.on("twilight::before.ready",(e=>this.initiateRequest(e))),salla.event.on("profile::info.fetched",(e=>this.setCurrencyAndLanguage(e))),salla.event.on("auth::token.fetched",(e=>{salla.storage.set("token",e),this.inIframe&&salla.log("token fetched iframe"),this.inIframe&&salla.cookie.set("s-token",e),this.setToken(e)})),salla.event.on("auth::token.invalid",(()=>{salla.storage.remove("user"),salla.storage.remove("token")})),this.notifier_handler_disabled=!1,this.axios=pn.create({headers:{common:{"X-Requested-With":"XMLHttpRequest","S-SOURCE":"twilight","S-APP-VERSION":"v2.0.0","S-APP-OS":"browser","cache-control":"no-cache"}}})}getHeaders(){return this.axios.defaults.headers.common}setHeaders(e){return Object.entries(e).forEach((e=>this.setHeader(e[0],e[1]))),this}setHeader(e,t){return salla.infiniteScroll.fetchOptions.headers[e]=this.axios.defaults.headers.common[e]=t,this}async withoutNotifier(e){return this.notifier_handler_disabled=!0,await e().finally((()=>{this.notifier_handler_disabled=!1}))}async initiateRequest(e){this.axios.defaults.baseURL=Salla.config.get("store.api",Salla.config.get("store.url")),this.setHeaders({"Store-Identifier":Salla.config.get("store.id"),currency:e.user?.currency_code||"SAR","accept-language":salla.lang.getLocale(),"s-user-id":e.user?.id,...e.headers||{}});const t=salla.storage.get("scope");t&&this.setHeaders({"s-scope-type":t.type,"s-scope-id":t.id});const r=salla.storage.session.get("s-utms");r&&this.setHeaders(r),await this.injectTokenToTheRequests(e),salla.storage.get("affiliate_code")&&this.setHeader("s-affiliate-code",salla.storage.get("affiliate_code"))}async injectTokenToTheRequests(e){let t=salla.storage.get("token"),r="guest"===e.user.type,a=e.user?.id,n=salla.storage.get("user.id"),i=e=>{this.setToken(e),salla.event.emit("api::initiated")},s=async()=>{!r&&a?(salla.log("Api:: case 1 => current is is guest & web session available"),await salla.auth.api.refresh().then((async()=>{await salla.profile.info()})).catch((()=>salla.auth.event.tokenInvalid()))):salla.auth.event.tokenInvalid()};if(!t)return salla.log("Api:: case 1 => current is is guest"),void await s();let o=function(e,t){if("string"!=typeof e)throw new yn("Invalid token specified");var r=!0===(t=t||{}).header?0:1;try{return JSON.parse(vn(e.split(".")[r]))}catch(e){throw new yn("Invalid token specified: "+e.message)}}(t);return Date.now()/1e3>o.exp?(salla.log("Api:: case 2 => current user is logged-in and there is a token, but it's expired"),void await s()):o.sub===a&&n===a&&n&&a?(salla.log("Api:: case 4 => current user is logged-in and there is a token, and it's not expired"),void i(t)):(salla.log("Api:: case 3 => there is a token and user in session/local missing or mismatch"),salla.log(`sub:${o.sub} userIdInWeb:${a} userIdInStorage:${n}`),this.setHeader("Authorization","Bearer "+t),void await salla.profile.info().then((async e=>{!this.inIframe&&await salla.auth.api.request("auth/jwt",{callerName:"salla.auth.request.injectTokenToTheRequests"}),i(t)})).catch((()=>{salla.log("Api:: case 3 => failed get fresh profile"),this.setHeader("Authorization",null),salla.auth.event.tokenInvalid()})))}setToken(e){return this.setHeader("Authorization","Bearer "+e),salla.event.emit("api::token.injected",e),this.token=e,this}setCurrencyAndLanguage(e){return this.setHeaders({currency:e.data.currency,"accept-language":e.data.language})}request(e,t=void 0,r="get",a={}){let n={endPoint:e,payload:t,method:r,options:a},i="undefined"!=typeof event?event.currentTarget:null,s=!1;return"SALLA-BUTTON"===i?.tagName&&(s=!0),s&&i?.load(),this.axios[n.method](n.endPoint,n.payload,n.options).then((e=>(s&&i?.stop(),e.data&&e.request&&(e=e.data),this.handleAfterResponseActions(e),e))).catch((e=>{throw s&&i?.stop(),salla.event.document.requestFailed(n,e),this.handleErrorResponse(e),e}))}handleAfterResponseActions(e){if(!e)return;let{data:t,googleTags:r=null}=e,a=t&&t.googleTags?t.googleTags:r;try{dataLayer&&a&&dataLayer.push(a)}catch(e){salla.logger.error(e.message)}this.fireEventsForResponse(e),this.showAlert(e)}fireEventsForResponse(e){let t=e?.events||e.data?.events||e.error?.events;"string"==typeof t&&(t=JSON.parse(t)),t&&Object.keys(t).forEach((e=>salla.event.dispatch(e,t[e])))}handleErrorResponse(e){if(e.response&&e.response.data)return e.response.data.error&&e.response.data.error.fields&&!this.notifier_handler_disabled?this.handleInvalidFields(e):this.handleAfterResponseActions(e.response.data)}showAlert(e){if(e&&!this.notifier_handler_disabled)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 t=e.response.data.error.fields,r=[];Object.keys(t).forEach((e=>{let a=t[e];Array.isArray(a)?a.forEach((e=>r.push(e))):r.push(a)}));let a=(r.length>1?"* ":"")+r.join("\n* ");salla.error(a,e)}isFastRequestsAllowed(){return Salla.config.get("fastRequests")}promise(e,t=!0){return new Promise(((r,a)=>t?r(e):a(e)))}errorPromise(e){return this.promise(e,!1)}successPromise(e){return this.promise(e,!0)}}class bn extends Ae{constructor(){super(),this.namespace="component",this.endpoints={getMenus:"menus/{headOrFoot}",reviews:"reviews"},this.endpointsMethods={getMenus:"get",reviews:"get"}}async getMenus(e="header"){return this.request(["getMenus",e]).then((function(e){return salla.event.component.menuFetched(e),e})).catch((function(e){throw salla.event.component.menuFetchFailed(e),e}))}async getReviews({per_page:e=5,type:t="all",items:r}){if(!t){const e="Review type cannot be empty. Please provide one.";return salla.event.component.reviewsFetchFailed(e),salla.api.errorPromise(e)}const a=!r||"string"==typeof r&&"[]"===r||Array.isArray(r)&&!r.length;if(!new Set(["all","store","categories","products","json"]).has(t)){const e="Invalid review type. Please provide a valid type.";return salla.event.component.reviewsFetchFailed(e),salla.api.errorPromise(e)}if("all"!==t&&"store"!==t&&a){const e="Items cannot be empty. Please provide one.";return salla.event.component.reviewsFetchFailed(e),salla.api.errorPromise(e)}if(new Set(["products","categories"]).has(t)&&!Array.isArray(r)){const e=`Items value must be an array of ${t} id for review type of ${t}.`;return salla.event.component.reviewsFetchFailed(e),salla.api.errorPromise(e)}return this.request(["reviews"],{params:{per_page:e,type:t,items:r}},"get").then((function(e){return salla.event.component.reviewsFetched(e),e})).catch((function(e){throw salla.event.component.reviewsFetchFailed(e),e}))}}class Sn extends Ae{constructor(){super(),this.namespace="booking",this.endpoints={fetch:"advertisements"},this.endpointsMethods={fetch:"get"}}async fetch(e=null){const t=e?{page:e}:{};return this.request(["fetch"],{params:t}).then((function(e){return salla.event.advertisement.fetched(e),e})).catch((function(e){throw salla.event.advertisement.fetchFailed(e),e}))}}class En extends Ae{constructor(){super(),this.namespace="navigation",this.endpoints={breadcrumbs:"breadcrumbs"},this.endpointsMethods={breadcrumbs:"get"},this.after_init()}fetchBreadcrumbs(e){if(!e.page){let e="The 'page' parameter is required for the Breadcrumb API. Please provide a valid 'page' parameter.";return salla.event.navigation.breadcrumbFetchFailed(e),salla.api.errorPromise(e)}if(["product.single","product.index","customer.orders.single","product.index.tag","page-single","landing-page","brands.single","blog.single","blog.index.author","blog.index.category","blog.index.tag"].includes(e.page)&&!e.id){let t=`The 'id' parameter is required when the 'page' parameter is set to ${e.page}. Please provide valid value for the 'ID' parameter.`;return salla.event.navigation.breadcrumbFetchFailed(t),salla.api.errorPromise(t)}return this.request("breadcrumbs",{params:e}).then((function(e){return salla.event.navigation.breadcrumbFetched(e),e})).catch((function(e){throw salla.event.navigation.breadcrumbFetchFailed(e),e}))}}class _n{constructor(e){"ready"!==Y.status?e?(Y.config.merge(e),e?.events&&Y.event.dispatchEvents(e?.events),e._token&&salla.api.setHeader("X-CSRF-TOKEN",e._token),this.injectMaintenanceAlert(),this.injectTemplateStoreAlert(),this.injectThemePreviewAlert(),this.injectAppInstallAlert(),this.injectEditAlert(),e?.user?.language_code&&salla.lang.setLocale(e?.user?.language_code),salla.lang.loadStoreTranslations(),this.setSallaReady(e)):this.setSallaReady(e):salla.log("Trying to re-initiate Salla, while its status === 'ready'!")}injectMaintenanceAlert(){salla.config.get("maintenance")&&(document.body.classList.add("has-maintenance-bar"),document.querySelector("salla-maintenance-alert")?salla.logger.warn("salla-maintenance-alert element Existed before!"):salla.lang.onLoaded((()=>document.body.prepend(document.createElement("salla-maintenance-alert")))))}injectTemplateStoreAlert(){salla.config.get("store.template")&&(document.body.classList.add("has-bottom-alert"),document.querySelector("salla-bottom-alert")?salla.logger.warn("salla-bottom-alert element Existed before!"):salla.lang.onLoaded((()=>document.body.append(document.createElement("salla-bottom-alert")))))}injectAppInstallAlert(){salla.config.get("store.app_install_prompt")&&salla.config.get("store.apps")&&!salla.storage.get("app_install_prompt_disabled")&&(document.body.classList.add("has-app-install-alert"),document.querySelector("salla-app-install-alert")?salla.logger.warn("salla-app-install-alert element Existed before!"):salla.lang.onLoaded((()=>document.body.append(document.createElement("salla-app-install-alert")))))}injectThemePreviewAlert(){"preview"===salla.config.get("theme.mode")&&(document.body.classList.add("has-preview-bar"),document.querySelector("#s-theme_preview_bar")?salla.logger.warn("#s-theme_preview_bar element 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=`\n <div style="display:flex; align-items:center;">\n <img width="32" src="https://cdn.salla.network/images/logo/logo-light.svg">\n <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>\n </div>\n <a href="${salla.url.get("preview_theme/cancel/preview")}" style="line-height:32px; width:32px;"><i class="sicon-cancel"></i></a>\n `,document.body.prepend(e)})))}injectEditAlert(){let e=salla.config.get("edit");e&&(document.querySelector("#s-edit-alert")?salla.logger.warn("#s-edit-alert element Existed before!"):salla.lang.onLoaded((()=>{let t=document.createElement("div");t.id="s-edit-alert",t.innerHTML=`\n <a href="${e}" style="display:block; background-color:${salla.config.get("theme.color.primary","#5cd5c4")}; color:${salla.config.get("theme.color.reverse","#fff")}; padding: 10px; text-align:center; font-size: 0.875rem; line-height: 1.25rem;">\n <i class="sicon-edit"></i> \n ${salla.lang.get("pages.products.quick_edit")}\n </a>\n `,document.body.prepend(t)})))}handleElementAjaxRequest(e,t){if(!(t instanceof HTMLFormElement||t instanceof HTMLAnchorElement))return salla.logger.warn("trying to call ajax from non Element!!"),!1;e.preventDefault();let r=t.getAjaxFormData(e),a=r.method?r.method.toLowerCase():void 0;salla.api.request(r.url,r.formData,a).then((e=>(e.data&&e.request&&(e=e.data),salla.api.handleAfterResponseActions(e),this.callAjaxEvent(r.events.success,e,r.formData),e))).catch((e=>{throw salla.api.handleErrorResponse(e),this.callAjaxEvent(r.events.fail,e,r.formData),e}))}callAjaxEvent(e,t,r){if(e){if(r instanceof FormData){const e={};Array.from(r.entries()).forEach((function(t){e[t[0]]=t[1]})),r=e}window[e]?window[e](t,r):salla.event.dispatch(e,t,r)}}setSallaReady(e){this.storeUTMs(),Y.event.dispatch("twilight::before.ready",e),Y.status="ready",Y.event.dispatch("twilight::initiated",e),window.dispatchEvent(new CustomEvent("twilight::initiated",{detail:e}))}storeUTMs(){const e={fbclid:"facebook",gad_source:"google",ttclid:"tiktok",twclid:"twitter",scid:"snapchat"},t=["fbclid","gad_source","ttclid","twclid","scid"],r=["utm_source","utm_medium","utm_campaign","utm_term","utm_content",...t],a={},n={};window.location.search.replace("?","").split("&").map((e=>e.split("="))).filter((([e])=>r.includes(e.toLowerCase()))).forEach((([e,t])=>a[e.toLowerCase()]=t));const i=t.some((e=>a[e]));!a.utm_source&&i&&(a.utm_source=e[i],a.utm_campaign=a.utm_campaign||`Using the CLICKID ${i} provided by ${a.utm_source}`,a.utm_term=a.utm_term||`${i}: ${a[i]}`),a.utm_source&&(Object.entries(a).filter((([e])=>!t.includes(e))).forEach((([e,t])=>n[`s-${e.replace("_","-")}`]=t)),salla.storage.session.set("s-utms",n))}}return Y.status="loading",Y.notify=Q,Y.lang=new class extends _e{constructor(e){(e=e||{}).messages=e.messages||window.translations,e.locale=e.locale||(window.locale||navigator.language||navigator.userLanguage||"ar").split("-")[0],e.fallback=e.fallback||e.locale,super(e),this.translationsLoaded=!1}onLoaded(e){return new Promise((t=>{if(this.translationsLoaded)return t(e?e():null);Salla.event.once("languages::translations.loaded",(()=>t(e?e():null)))}))}loadStoreTranslations(){if(this.hash=salla.config.get("theme.translations_hash",salla.config.get("store.id","twilight")),this.message||(salla.log("try to load translations from localstorage"),this.messages=salla.storage.get(`s_translations.${this.hash}`),this.messages&&(this.translationsLoaded=!0)&&super.setMessages(this.messages)),this.messages)return salla.event.dispatch("languages::translations.loaded"),void salla.logger.info("The messages of transactions is already loaded");salla.url.get("")?this.loadScript(salla.url.get(`languages/assets/${this.hash}.js`)):this.loadScript("https://cdn.salla.network/js/translations.js",!1)}setMessages(e){super.setMessages(e),salla.event.dispatch("languages::translations.loaded"),this.translationsLoaded=!0}loadScript(e,t=!0){let r=document.createElement("script");r.src=e,r.onload=()=>{if(window.translations)return salla.storage.remove("s_translations"),salla.storage.set("s_translations",{[this.hash]:window.translations}),this.setMessages(window.translations);r.onerror()},r.onerror=()=>{if(t)return salla.logger.warn("Failed to load Translations for store, lets try load it from CDN"),this.loadScript("https://cdn.salla.network/js/translations.js",!1);salla.logger.error("Failed to load Translations, check your network logs for more details\nor: salla.lang.setMessages({....}), see https://docs.salla.dev for more information's.")},document.head.appendChild(r)}getWithDefault(e,t,r,a){let n=this.get(e,r,a);return n!==e?n:t}get(e,t,r){let a=e;(window.translations||this.translationsLoaded)&&(a="trans."+e);let n=super.get(a,t,r);return n!==a?n:super.get(a,t,"en").replace(a,e)}set(e,t){return salla.helpers.setNested(this.messages[`${this.getLocale()}.trans`],e,t),this}add(e,t){return Object.entries(t).forEach((t=>salla.helpers.setNested(this.messages[t[0]+".trans"],e,t[1]))),this}addBulk(e){return Object.entries(e).forEach((([e,t])=>{this.add(e,t)})),this}},Y.form=new class{async submit(e,t=null){let r=t;if("SubmitEvent"===t?.constructor?.name||"submit"===t?.type){if(t.preventDefault(),"FORM"!==t.target?.tagName)return Salla.logger.warn("Failed find the target element for submit action. make sure you submit a form element"),new Promise((()=>{throw"Failed find the target element for submit action. make sure you submit a form element"}));"SALLA-BUTTON"===t?.submitter?.parentElement?.tagName&&t.submitter.parentElement.load(),r=t.target.getElementSallaData(),salla.log("Data from element",r)}if(/^https?:\/\/(?:www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)$/gm.test(e))return salla.api.request(e,r,"post").finally((()=>{loaderSupported&&t?.submitter?.parentElement.stop()}));let a=e.split("."),n=a.splice(-1);return await salla.call(a.join("."))[n](r).finally((()=>t?.submitter?.parentElement?.stop())).catch((e=>{throw salla.logger.warn(e),e}))}onSubmit(e,t){return salla.form.submit(e,t),!1}onChange(e,t){return t?.currentTarget?"FORM"!==t?.currentTarget?.tagName||t.currentTarget.checkValidity()?(salla.form.submit(e,t.currentTarget.getElementSallaData()),!0):(salla.logger.warn(`Trying to trigger '${e}' without filling required fields!`),!1):(salla.logger.warn(`Trying to trigger '${e}' without event!`),!1)}getPossibleValue(e,t,r=!1){if(!e)return;if("object"!=typeof e)return e;let a;for(let r=0;r<t.length&&!(a=e[t[r]])&&!("undefined"!=typeof FormData&&e instanceof FormData&&(a=e.get(t[r])));r++);return a=a||e,"object"!=typeof a||r?a:void 0}},Y.infiniteScroll=new class extends K{constructor(e,t){super(e,t),this.options={path:".infinite-scroll-btn",history:"push",status:".infinite-scroll-status",append:".list-block"},this.fetchOptions={headers:{"S-INFINITE-SCROLL":!0,"S-Source":"twilight","cache-control":"no-cache",pragma:"no-cache"}},this.instances=[]}initiate(e,t,r,a=!1){a?((r=r||{}).fetchOptions={...this.fetchOptions,...r.fetchOptions||{}},r.responseBody="json"):r=this.getCustomOptions(t,r);let n="string"!=typeof e?e:document.querySelector(e),i=r.path;if(!n||!i||"string"==typeof i&&!document.querySelector(i))return void Salla.logger.warn(n?"Path Option (a link that has next page link) Not Existed!":"Container For InfiniteScroll not Existed!");let s=new Se(n,r);return s.on("scrollThreshold",Salla.infiniteScroll.event.scrollThreshold),s.on("request",Salla.infiniteScroll.event.request),s.on("load",Salla.infiniteScroll.event.load),s.on("append",Salla.infiniteScroll.event.append),s.on("error",Salla.infiniteScroll.event.error),s.on("last",Salla.infiniteScroll.event.last),s.on("history",Salla.infiniteScroll.event.history),this.instances.push(s),s}getCustomOptions(e,t){return(t="object"==typeof e&&e||t||this.options).fetchOptions=this.fetchOptions,t.path=t.path||this.options.path,t.button=t.button||t.path,t.status=t.status||this.options.status,t.hasOwnProperty("history")||(t.history=this.options.history),t.nextPage=t.nextPage||t.next_page,t.append="string"==typeof e&&e||t.append||this.options.append,t}loadNextPage(e){("string"!=typeof e?e:document.querySelector(e)).loadNextPage()}destroy(e){("string"!=typeof e?e:document.querySelector(e)).destroy()}}(void 0,salla.event.infiniteScroll),Y.api=new class extends wn{constructor(){super(),this.auth=new xe,this.cart=new Fe,this.loyalty=new Pe,this.order=new Te,this.rating=new Le,this.product=new Re,this.profile=new Ce,this.comment=new Oe,this.currency=new ke,this.document=new Ie,this.wishlist=new qe,this.scope=new Ue,this.booking=new De,this.landing=new Ne,this.notifications=new je,this.component=new bn,this.advertisement=new Sn,this.navigation=new En}},["cart","auth","order","scope","rating","comment","loyalty","product","profile","currency","document","wishlist","booking","landing"].forEach((e=>Y[e]=new K(Y.api[e],Y.event[e]))),Y.call=e=>{let t=Y,r=e.split(".");for(;r.length&&(t=t[r.shift()]););return t},Y.init=e=>new _n(e),salla.event.once("twilight::init",salla.init),salla.event.once("twilight::api",(e=>{let t=e?.events;t&&salla.event.dispatchEvents(t)})),Y.success=Y.notify.success,Y.error=Y.notify.error,Y.versions.twilight="2.13.118",Y.onInitiated=e=>salla.event.once("twilight::initiated",e),Y.onReady=Y.onReady||function(e){return new Promise((function(t){return"ready"===salla.status?t(e?e(salla.config.all()):salla.config.all()):Y.onInitiated((r=>t(e?e(r):r)))}))},window.dispatchEvent(new CustomEvent("salla::created")),Y}));
|
|
19
|
+
*/!function(e,t){e.exports=function(){function e(){if("undefined"!=typeof document&&document.documentElement)return document.documentElement.lang}function t(e){return"-Inf"===e?-1/0:"+Inf"===e||"Inf"===e||"*"===e?1/0:parseInt(e,10)}var r=/^({\s*(\-?\d+(\.\d+)?[\s*,\s*\-?\d+(\.\d+)?]*)\s*})|([\[\]])\s*(-Inf|\*|\-?\d+(\.\d+)?)\s*,\s*(\+?Inf|\*|\-?\d+(\.\d+)?)\s*([\[\]])$/,a=/({\s*(\-?\d+(\.\d+)?[\s*,\s*\-?\d+(\.\d+)?]*)\s*})|([\[\]])\s*(-Inf|\*|\-?\d+(\.\d+)?)\s*,\s*(\+?Inf|\*|\-?\d+(\.\d+)?)\s*([\[\]])/,n={locale:"en"},i=function(t){t=t||{},this.locale=t.locale||e()||n.locale,this.fallback=t.fallback,this.messages=t.messages};return i.prototype.setMessages=function(e){this.messages=e},i.prototype.getLocale=function(){return this.locale||this.fallback},i.prototype.setLocale=function(e){this.locale=e},i.prototype.getFallback=function(){return this.fallback},i.prototype.setFallback=function(e){this.fallback=e},i.prototype.has=function(e,t){return!("string"!=typeof e||!this.messages)&&null!==this._getMessage(e,t)},i.prototype.get=function(e,t,r){if(!this.has(e,r))return e;var a=this._getMessage(e,r);return null===a?e:(t&&(a=this._applyReplacements(a,t)),a)},i.prototype.trans=function(e,t){return this.get(e,t)},i.prototype.choice=function(e,t,r,n){(r=void 0!==r?r:{}).count=t;var i=this.get(e,r,n);if(null==i)return i;for(var s=i.split("|"),o=[],l=0;l<s.length;l++)if(s[l]=s[l].trim(),a.test(s[l])){var c=s[l].split(/\s/);o.push(c.shift()),s[l]=c.join(" ")}if(1===s.length)return i;for(var u=0;u<o.length;u++)if(this._testInterval(t,o[u]))return s[u];return n=n||this._getLocale(e),s[this._getPluralForm(t,n)]},i.prototype.transChoice=function(e,t,r){return this.choice(e,t,r)},i.prototype._parseKey=function(e,t){if("string"!=typeof e||"string"!=typeof t)return null;var r=e.split("."),a=r[0].replace(/\//g,".");return{source:t+"."+a,sourceFallback:this.getFallback()+"."+a,entries:r.slice(1)}},i.prototype._getMessage=function(e,t){if(t=t||this.getLocale(),e=this._parseKey(e,t),void 0===this.messages[e.source]&&void 0===this.messages[e.sourceFallback])return null;var r=this.messages[e.source],a=e.entries.slice(),n=a.join(".");if("string"!=typeof(r=void 0!==r?this._getValueInKey(r,n):void 0)&&this.messages[e.sourceFallback])for(r=this.messages[e.sourceFallback],a=e.entries.slice(),n="";a.length&&void 0!==r;)r[n=n?n.concat(".",a.shift()):a.shift()]&&(r=r[n],n="");return"string"!=typeof r?null:r},i.prototype._getValueInKey=function(e,t){if("string"==typeof e[t])return e[t];for(var r=(t=(t=t.replace(/\[(\w+)\]/g,".$1")).replace(/^\./,"")).split("."),a=0,n=r.length;a<n;++a){var i=r.slice(0,a+1).join("."),s=r.slice(a+1,r.length).join(".");if(e[i])return this._getValueInKey(e[i],s)}return e},i.prototype._getLocale=function(e){return e=this._parseKey(e,this.locale),this.messages[e.source]?this.locale:this.messages[e.sourceFallback]?this.fallback:null},i.prototype._findMessageInTree=function(e,t){for(;e.length&&void 0!==t;){var r=e.join(".");if(t[r]){t=t[r];break}t=t[e.shift()]}return t},i.prototype._sortReplacementKeys=function(e,t){return t.length-e.length},i.prototype._applyReplacements=function(e,t){return Object.keys(t).sort(this._sortReplacementKeys).forEach((function(r){e=e.replace(new RegExp(":"+r,"gi"),(function(e){var a=t[r];return e===e.toUpperCase()?a.toUpperCase():e===e.replace(/\w/i,(function(e){return e.toUpperCase()}))?a.charAt(0).toUpperCase()+a.slice(1):a}))})),e},i.prototype._testInterval=function(e,a){if("string"!=typeof a)throw"Invalid interval: should be a string.";var n=(a=a.trim()).match(r);if(!n)throw"Invalid interval: "+a;if(!n[2]){var i=(n=n.filter((function(e){return!!e})))[1],s=t(n[2]);s===1/0&&(s=-1/0);var o=t(n[3]),l=n[4];return("["===i?e>=s:e>s)&&("]"===l?e<=o:e<o)}for(var c=n[2].split(","),u=0;u<c.length;u++)if(parseInt(c[u],10)===e)return!0;return!1},i.prototype._getPluralForm=function(e,t){switch(t){case"az":case"bo":case"dz":case"id":case"ja":case"jv":case"ka":case"km":case"kn":case"ko":case"ms":case"th":case"tr":case"vi":case"zh":default:return 0;case"af":case"bn":case"bg":case"ca":case"da":case"de":case"el":case"en":case"eo":case"es":case"et":case"eu":case"fa":case"fi":case"fo":case"fur":case"fy":case"gl":case"gu":case"ha":case"he":case"hu":case"is":case"it":case"ku":case"lb":case"ml":case"mn":case"mr":case"nah":case"nb":case"ne":case"nl":case"nn":case"no":case"om":case"or":case"pa":case"pap":case"ps":case"pt":case"so":case"sq":case"sv":case"sw":case"ta":case"te":case"tk":case"ur":case"zu":return 1==e?0:1;case"am":case"bh":case"fil":case"fr":case"gun":case"hi":case"hy":case"ln":case"mg":case"nso":case"xbr":case"ti":case"wa":return 0===e||1===e?0:1;case"be":case"bs":case"hr":case"ru":case"sr":case"uk":return e%10==1&&e%100!=11?0:e%10>=2&&e%10<=4&&(e%100<10||e%100>=20)?1:2;case"cs":case"sk":return 1==e?0:e>=2&&e<=4?1:2;case"ga":return 1==e?0:2==e?1:2;case"lt":return e%10==1&&e%100!=11?0:e%10>=2&&(e%100<10||e%100>=20)?1:2;case"sl":return e%100==1?0:e%100==2?1:e%100==3||e%100==4?2:3;case"mk":return e%10==1?0:1;case"mt":return 1==e?0:0===e||e%100>1&&e%100<11?1:e%100>10&&e%100<20?2:3;case"lv":return 0===e?0:e%10==1&&e%100!=11?1:2;case"pl":return 1==e?0:e%10>=2&&e%10<=4&&(e%100<12||e%100>14)?1:2;case"cy":return 1==e?0:2==e?1:8==e||11==e?2:3;case"ro":return 1==e?0:0===e||e%100>0&&e%100<20?1:2;case"ar":return 0===e?0:1==e?1:2==e?2:e%100>=3&&e%100<=10?3:e%100>=11&&e%100<=99?4:5}},i}()}(Ee);var _e=Ee.exports;class Ae{constructor(){this.endpoints={},this.webEndpoints=[],this.namespace="BaseApi",this.endpointsMethods={},this.endpointsHeaders={};let e=/function (.{1,})\(/.exec(this.constructor.toString());this.className=(e&&e.length>1?e[1]:"").toLowerCase(),this.debounce={request:void 0,time:300,enabled:!0,exclude:[]}}after_init(){}normalRequest(e,t=void 0,r=null){let a=Array.isArray(e),n=a?this.getUrl(...e):this.getUrl(e);e=a?e[0]:e,r=r||this.endpointsMethods[e]||"post";let i=this.endpointsHeaders[e];if("get"===r&&t instanceof FormData){let e={};Array.from(t.entries()).forEach((function(t){e[t[0]]=t[1]})),t={params:e}}return i&&"get"===r&&(t=t?Object.assign(t,i):i),this.webEndpoints.includes(e)?n=salla.url.get(n):"http"!==n.substring(0,4)&&(n=salla.url.api(n)),Salla.api.request(n,t,r,{headers:i})}request(e,t=void 0,r=null){return!salla.api.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,r)):this.normalRequest(e,t,r)}getUrl(e){let t=this.endpoints[e]||e;const r=/{[^{}]+}/i;for(let e=1;e<arguments.length;e++)t=t.replace(r,arguments[e]);return t}event(){return salla.event[this.className]}}class Fe extends Ae{constructor(){super(),this.addToCartTries=0,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}",uploadImage:"cart/{cart}/image",status:"cart/{cart}/status",addCoupon:"cart/{id}/coupon",deleteCoupon:"cart/{id}/coupon",getQuickOrderSettings:"checkout/quick-order",createQuickOrder:"checkout/quick-order",priceQuote:"cart/{cartId}/price-quote",offers:"offers/cart/{cartId}"},this.endpointsMethods={latest:"get",details:"get",status:"get",updateItem:"post",deleteItem:"delete",deleteImage:"delete",deleteCoupon:"put",getQuickOrderSettings:"get",offers:"get"},this.webEndpoints=["latest"],this.latestCart=null,this.after_init(),salla.event.on("api::initiated",(()=>salla.api.cart.getCurrentCartId(!1,"api::initiated"))),salla.event.on("auth::token.fetched",this._checkCurrentCart),salla.event.on("auth::token.invalid",this._checkCurrentCart),salla.event.on("auth::verified",(()=>salla.api.cart.getCurrentCartId(!0,"auth::verified")),{async:!0}),salla.event.on("profile::info.fetched",this._checkCurrentCart),salla.event.on("twilight::error",(e=>(e.includes("Cart not available")||e.includes("السلة غير متاحة"))&&salla.cart.api.reset()))}_checkCurrentCart(){let e=salla.storage.get("cart"),t=salla.config.get("user")?.id,r=salla.config.get("store")?.id;e&&e.id&&(e.user_id!==t||e.store_id!==r)&&(salla.log("cart",{user_id:e.user_id,store_id:e.store_id}),salla.log("current",{user_id:t,store_id:r}),salla.log("Api:: case2 => The cart is not belong to current "+(e.user_id!==t?"user":"store")+"!"),salla.cart.api.reset())}async getCurrentCartId(e=!1,t="getCurrentCartId"){if(!e){if(salla.cart.api.latestCart)return salla.cart.api.latestCart.cart.id;let e=salla.storage.get("cart.id");if(e)return e}let r=await salla.cart.api.latest(t);return salla.cart.api.latestCart=r.data,salla.cart.api.latestCart.cart.id}getUploadImageEndpoint(e){return salla.url.api(this.getUrl("uploadImage",e||salla.storage.get("cart.id")))}latest(e="direct"){return this.request("latest",{params:{source:"",callerName:e}}).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(e,t=[]){return e=e||await salla.api.cart.getCurrentCartId(!1,"salla.api.cart.details"),this.request(["details",e],{params:{with:t}}).then((function(e){return salla.cart.event.detailsFetched(e),e})).catch((function(e){throw salla.cart.event.detailsNotFetched(e),e}))}async quickAdd(e,t){return this.addItem({id:e,quantity:t,endpoint:"quickAdd"})}async addItem(e){let t=this.getCartPayload(e);if(!t.id){let e='There is no product "id"!';return salla.cart.event.itemAddedFailed(e),salla.api.errorPromise(e)}let r=salla.form.getPossibleValue(t.payload,["endpoint"]);r&&["addItem","quickAdd"].includes(r)||(r=salla.form.getPossibleValue(t.payload,["quantity","donating_amount"])?"addItem":"quickAdd");let a=await salla.api.cart.getCurrentCartId(!1,"salla.api.cart.addItem");return this.request([r,a,t.id],t.payload).then((function(e){return salla.cart.api.addToCartTries=0,salla.cart.event.itemAdded(e,t.id),e})).catch((function(r){if(!salla.cart.api.addToCartTries)return salla.cart.api.addToCartTries++,salla.cart.reset(),salla.cart.api.addItem(e);throw salla.cart.event.itemAddedFailed(r,t.id),r}))}async deleteItem(e){let t=this.getCartPayload(e);if(!t.id){let e='There is no "id"!';return salla.cart.event.itemDeletedFailed(e),salla.api.errorPromise(e)}let r=await salla.api.cart.getCurrentCartId(!1,"salla.api.cart.deleteItem");return this.request(["deleteItem",r,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.getCartPayload(e);if(!t.id){let e='There is no "id"!';return salla.cart.event.itemUpdatedFailed(e),salla.api.errorPromise(e)}let r=await salla.api.cart.getCurrentCartId(!1,"salla.api.cart.updateItem");return"Object"===t.payload.constructor?.name?t.payload._method="PUT":t.payload.append("_method","PUT"),this.request(["updateItem",r,t.id],t.payload).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(e){if(!(e=salla.form.getPossibleValue(e,["id","image_id","photo_id"]))){let e='There is no "id"!';return salla.cart.event.imageNotDeleted(e),salla.api.errorPromise(e)}let t=await salla.api.cart.getCurrentCartId(!1,"salla.api.cart.deleteImage");return this.request(["deleteImage",t,e]).then((function(t){return salla.cart.event.imageDeleted(t,e),t})).catch((function(t){throw salla.cart.event.imageNotDeleted(t,e),t}))}async status(e){const t=(new Date).getTime(),r=Math.random().toString(36).substring(2,15);return this.request(["status",e||await salla.api.cart.getCurrentCartId(!1,"salla.api.cart.status")],{params:{has_apple_pay:salla.helpers.hasApplePay(),"s-hash":`${r}_${t}`}})}async submit(){if(salla.config.isGuest())return salla.log("it looks that the current user is not logged-in, lets login then submit"),salla.cart.loginOnCartPage();this.status(await salla.api.cart.getCurrentCartId(!1,"salla.api.cart.submit")).then((e=>{let t=e.data.next_step?.to;if(t||(window.history.pushState({},"",salla.url.addParamToUrl("reload","empty_next_step")),window.history.pushState({},"",salla.url.addParamToUrl("acitve",!1===e.data.active?"false":"true_or_undfined")),salla.cart.reset(),window.location.reload()),!["checkout","refresh","login"].includes(t)){let e="Can't find next_step );";throw salla.cart.reset(),salla.cart.event.submitFailed(e),e}return salla.cart.event.submitted(e),"login"===t?salla.cart.loginOnCartPage():"checkout"===t?window.location.href=e.data.next_step.url+(salla.helpers.hasApplePay()?"?has_apple_pay=true":""):(window.history.pushState({},"",salla.url.addParamToUrl("reload","refresh")),void window.location.reload())})).catch((function(e){salla.cart.api.tries=salla.cart.api.tries||0,salla.cart.reset();let t=404===e?.response?.data?.status;if(t&&0===salla.cart.api.tries)return salla.cart.api.tries++,salla.log("we recived that the current cart is not found, we will try to re-submit one more time"),salla.cart.submit();throw t&&salla.error(salla.lang.get("pages.checkout.try_again")),salla.cart.event.submitFailed(e),e}))}getCartPayload(e){let t=e?.data||("object"==typeof e?e:void 0);return e=t?salla.form.getPossibleValue(t,["prod_id","product_id","item_id","id"]):e,t="object"==typeof t?t:void 0,{id:e,payload:t}}normalRequest(e,t=void 0,r=null){return super.normalRequest(e,t,r).catch((async e=>{throw 403===e?.response?.status&&(this.reset(),salla.error(salla.lang.get("pages.checkout.try_again"))),e}))}reset(){salla.api.cart.latestCart=null,salla.storage.remove("cart"),salla.cart.event.successReset()}async addCoupon(e){if(e=e.data||e,!(e=salla.form.getPossibleValue(e,["coupon"]))){let e=new Error('There is no "Coupon Code"!');return e.name="EmptyCoupon",salla.event.cart.couponAdditionFailed(e),salla.api.errorPromise(e)}let t=await salla.cart.api.getCurrentCartId(!1,"salla.api.cart.addCoupon");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 e=await salla.cart.api.getCurrentCartId(!1,"salla.api.cart.deleteCoupon");return this.request(["deleteCoupon",e],{}).then((function(t){return salla.event.cart.couponDeleted(t,e),t})).catch((function(t){throw salla.event.cart.couponDeletionFailed(t,e),t}))}getQuickOrderSettings(){return this.request("getQuickOrderSettings").then((e=>(salla.event.cart.quickOrderSettingFetched(e),e))).catch((e=>{throw salla.event.cart.quickOrderSettingFailed(e),e}))}createQuickOrder(e){return this.request("createQuickOrder",e).then((e=>(salla.event.cart.quickOrderSucceeded(e),e))).catch((e=>{throw salla.event.cart.quickOrderFailed(e),e}))}async priceQuote(e){return salla.config.isGuest()?(salla.auth.api.setAfterLoginEvent("cart::priceQuote",e),void salla.event.dispatch("login::open")):this.request(["priceQuote",e||await salla.api.cart.getCurrentCartId(!1,"salla.api.cart.priceQuote")]).then((e=>(salla.cart.api.reset(),salla.event.cart.priceQuoteSucceeded(e).then((()=>(setTimeout((()=>window.location.href=salla.url.get("/")),1e3),e)))))).catch((e=>salla.event.cart.priceQuoteFailed(e).then((()=>{throw 404===e.error?.code&&window.location.reload(),e}))))}loginOnCartPage(){salla.auth.setCanRedirect(!1),salla.event.dispatch("login::open"),salla.auth.event.onLoggedIn((e=>{salla.event.dispatch("login::close"),salla.cart.submit()}))}async offers(){const e=await salla.cart.api.getCurrentCartId(!1,"salla.api.cart.offers");return this.request(["offers",e]).then((e=>(salla.event.cart.offersFetched(e),e))).catch((e=>{throw salla.event.cart.offersFailed(e),e}))}}class Pe extends Ae{constructor(){super(),this.namespace="loyalty",this.endpoints={getProgram:"loyalty",exchange:"loyalty/exchange",reset:"loyalty/exchange"},this.endpointsMethods={getProgram:"get",reset:"put"},this.after_init()}getProgram(){return this.request("getProgram").then((e=>(salla.loyalty.event.programFetched(e),e))).catch((e=>{throw salla.loyalty.event.programNotFetched(e),e}))}async exchange(e,t=null){if(!(e=salla.form.getPossibleValue(e,["id","loyalty_prize_id","prize_id"]))){let e="Unable to find cart id. Please provide one.";return salla.loyalty.event.exchangeFailed(e),salla.api.errorPromise(e)}if(!(t=t||await salla.cart.getCurrentCartId(!1,"salla.api.loyalty.exchange"))){let e="Unable to find cart id. Please provide one.";return salla.loyalty.event.exchangeFailed(e),salla.api.errorPromise(e)}return this.request("exchange",{loyalty_prize_id:e,cart_id:t}).then((function(t){return salla.loyalty.event.exchangeSucceeded(t,e),t})).catch((function(t){throw salla.loyalty.event.exchangeFailed(t,e),t}))}async reset(e=null){if(!(e=e||await salla.cart.getCurrentCartId(!1,"salla.api.loyalty.reset"))){let e="Unable to find cart id. Please provide one.";return salla.loyalty.event.resetFailed(e),salla.api.errorPromise(e)}return this.request("reset",{cart_id:e}).then((e=>(salla.loyalty.event.resetSucceeded(e),e))).catch((e=>{throw salla.loyalty.event.resetFailed(e),e}))}}class xe extends Ae{constructor(){super(),this.namespace="auth",this.canRedirect_=!0,this.afterLoginEvent={event:null,payload:null},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.inIframe=salla.helpers.isIframe(),this.after_init()}setAfterLoginEvent(e,t){salla.api.auth.afterLoginEvent={event:e,payload:t}}setCanRedirect(e){salla.api.auth.canRedirect_=e}canRedirect(){return salla.api.auth.canRedirect_&&!salla.api.auth.afterLoginEvent.event}login(e){e?.data&&(e=e.data);let t=salla.form.getPossibleValue(e,["type"]);if(!["email","mobile"].includes(t)){let e="Login type should be in: [email, mobile]";return salla.auth.event.codeNotSent(e),salla.api.errorPromise(e)}return this.request(["login",t],e).then((function(e){return salla.auth.event.codeSent(e,t),e})).catch((function(e){throw salla.auth.event.codeNotSent(e,t),e}))}async verify(e,t=!0){let r=salla.form.getPossibleValue(e,["type"]);if(!r){let e="Failed to know what's login type!";return salla.auth.event.verificationFailed(e),salla.api.errorPromise(e)}t=!1!==salla.form.getPossibleValue(e,["supportWebAuth"])&&t,salla.auth.event.next_event&&(e.next_event=salla.auth.event.next_event);let a=await salla.auth.api.request(["verify",r],e);return 200!==a?.status?(salla.auth.event.verificationFailed(a,r),salla.api.errorPromise(a)):salla.auth.api.handlAfterAuthenticatedResponse(a,t)}async handlAfterAuthenticatedResponse(e,t){e.data||(e={data:e});let r="authenticated"===e.data?.case;return r&&salla.auth.event.tokenFetched(e.data.token),t&&!this.inIframe&&await salla.auth.api.request("auth/jwt",{callerName:"salla.auth.api.handlAfterAuthenticatedResponse"}),r&&await salla.auth.event.loggedIn(e).then((()=>salla.auth.api.afterUserLogin())),await salla.auth.event.verified(e,e.data.verification.type),salla.api.successPromise(e)}resend(e){let t;return(e=e.data||e).type=e.type||"mobile","mobile"!==e.type||e.phone&&e.country_code?"email"!==e.type||e.email?this.request("resend",e).then((function(t){return salla.auth.event.codeSent(t,e),t})).catch((function(t){throw salla.auth.event.codeNotSent(t,e),t})):(salla.auth.event.codeNotSent(t="There is no email!",e),salla.api.errorPromise(t)):(salla.auth.event.codeNotSent(t="There is no phone or country_code!",e),salla.api.errorPromise(t))}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((async e=>(salla.auth.event.registered.call(t,e),"authenticated"===e.data?.case&&(salla.auth.event.tokenFetched(e.data.token),!this.inIframe&&await salla.auth.request("auth/jwt",{callerName:"salla.auth.api.register"}),salla.auth.event.loggedIn(e),salla.auth.api.afterUserLogin()),e))).catch((function(e){throw salla.auth.event.registrationFailed.call(t,e),e}))}handleIframeReadyAction(e,t){e.contentWindow?.postMessage({source:"logout",type:"init",data:{id:salla.config.get("store.id"),lang:"ar",appUrl:t,apiUrl:salla.config.get("store.api").replace(/\/+$/,""),settings:salla.config.all(),storage:{}}},"*")}appendIframeAndLogout(){return new Promise((e=>{let t=salla.config.get("login.url","https://accounts.salla.com");const r=document.createElement("iframe");r.style.display="none",r.src=`${t}/logout`;const a=n=>{if("login"!==n.data.source)return;let i=n.data.type.replace("iframe::","");if(salla.log("iframe::logout-iframe message received",n.data),["logged-out","ready"].includes(i)){if("ready"===i)return this.handleIframeReadyAction(r,t);window.removeEventListener("message",a),r.remove(),e()}};window.addEventListener("message",a),document.body.appendChild(r)}))}logout(e="twilight"){return salla.storage.clearAll(),salla.cookie.clearAll(),e=encodeURI(e),salla.auth.event.loggedOut().then((()=>this.appendIframeAndLogout())).then((()=>{let t=salla.url.get(`logout?from=${e}`);console.log(`Going to ${t}, to do any thing before this action use: salla.auth.even.onLoggedOut(()=>{...})`);try{location.href=t}catch(e){salla.log(e)}})).catch((e=>console.error("Error during logout:",e)))}refresh(){return this.request("refresh").then((function(e){return salla.auth.event.tokenFetched(e.data.token),e})).catch((function(e){throw salla.auth.event.refreshFailed(e),e}))}afterUserLogin(){this.afterLoginEvent.event&&salla.event.emit(this.afterLoginEvent.event,this.afterLoginEvent.payload)}}class Te extends Ae{constructor(){super(),this.namespace="order",this.endpoints={cancel:"orders/cancel/{id}",createCartFromOrder:"reorder/{id}",sendInvoice:"orders/send/{id}",fetch:"orders"},this.endpointsMethods={createCartFromOrder:"get",fetch:"get"},this.after_init()}show(e){let t=salla.form.getPossibleValue(e?.data||e,["id","order_id"]);salla.event.dispatch("mobile::order.placed",{order_id:t}),location.href=salla.form.getPossibleValue(e?.data||e,["url"])}cancel(e){return e=e||Salla.config.get("page.id"),this.request(["cancel",e],{params:{has_apple_pay:salla.helpers.hasApplePay()}}).then((function(t){return salla.event.order.canceled(t,e),t})).catch((function(t){throw salla.event.order.notCanceled(t,e),t}))}createCartFromOrder(e){return e=e||salla.config.get("page.id"),this.request(["createCartFromOrder",e]).then((function(t){return salla.cart.reset(),salla.event.order.orderCreated(t,e),window.location.href=t.data.url,t})).catch((function(t){throw salla.event.order.orderCreationFailed(t,e),t}))}sendInvoice(e){let t=salla.form.getPossibleValue(e,["id"])||salla.config.get("page.id");if(!t||isNaN(t)){let e="There is no id!";return salla.order.event.invoiceNotSent(e),salla.api.errorPromise(e)}return this.request(["sendInvoice",t],e).then((e=>(salla.event.order.invoiceSent(e,t),e))).catch((e=>{throw salla.event.order.invoiceNotSent(e,t),e}))}fetch(e){return this.request(["fetch"],{params:e}).then((function(e){return salla.event.order.ordersFetched(e),e})).catch((function(e){throw salla.event.order.ordersNotFetched(e),e}))}}class Re extends Ae{constructor(){super(),this.namespace="product",this.previousQuery="",this.endpoints={getPrice:"products/{id}/price",availabilitySubscribe:"products/{id}/availability-notify",search:"products/search",details:"products/{product_id}/details",categories:"products/categories/{?id}",offers:"products/{product_id}/specialoffer",getSizeGuides:"products/{prod_id}/size-guides",giftDetail:"products/{product_id}/buy-as-gift",giftToCart:"products/{product_id}/buy-as-gift",giftImage:"products/buy-as-gift/image",buyNow:"products/{product_id}/buy-now",fetch:"products",fetchOptions:"products/options"},this.endpointsMethods={details:"get",giftDetail:"get",fetch:"get",offers:"get",fetchOptions:"get"},this.after_init()}getPrice(e){let t=e.data||e,r=salla.form.getPossibleValue(t,["id","prod_id","product_id"]);return this.request(["getPrice",r],"object"==typeof t?t:void 0).then((function(e){return salla.product.event.priceUpdated(e,r),e})).catch((function(e){throw salla.product.event.priceUpdateFailed(e,r),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(e){let t=e.data||e;return e=salla.form.getPossibleValue(t,["id","prod_id"]),this.request(["availabilitySubscribe",e],"object"==typeof t?t:void 0).then((function(t){return salla.product.event.availabilitySubscribed(t,e),t})).catch((function(t){throw salla.product.event.availabilitySubscribeFailed(t,e),t}))}search(e){let t=e.data;if(t||(t={params:"string"==typeof e?{query:e}:e}),!(e=t instanceof FormData?t.get("query"):t.query||t.params?.query)){let e='There is no "query"!';return salla.product.event.searchFailed(e),salla.api.errorPromise(e)}if(e===salla.api.product.previousQuery){let e="Query is same as previous one!";return salla.product.event.searchFailed(e),salla.api.product.previousQuery=null,salla.api.errorPromise(e)}return salla.api.product.previousQuery=e,this.request("search",t,"get").then((function(t){return salla.product.event.searchResults(t,e),t})).catch((function(t){throw salla.product.event.searchFailed(t,e),t}))}offers(e){if(!(e=salla.form.getPossibleValue(e?.data|e,["product_id","id"]))){let e='There is no "product_id"!';return salla.product.event.fetchOffersFailed(e),salla.api.errorPromise(e)}return this.request(["offers",e]).then((function(t){return salla.product.event.offersFetched(t,e),t})).catch((function(t){throw salla.product.event.fetchOffersFailed(t,e),t}))}getSizeGuides(e){return this.request(`products/${e}/size-guides`,null,"get").then((t=>(salla.product.event.sizeGuideFetched(t,e),t))).catch((t=>{throw salla.product.event.sizeGuideFetchFailed(t,e),t}))}getGiftDetails(e){return this.request(["giftDetail",e]).then((t=>(salla.product.event.giftFetched(t,e),t))).catch((t=>{throw salla.product.event.giftFetchFailed(t,e),t}))}getDetails(e,t=[]){if(!Array.isArray(t)){let e="withItems should be array.";return salla.product.event.detailFetchFailed(e),salla.api.errorPromise(e)}if(!e){let e="productId is not passed.";return salla.product.event.detailFetchFailed(e),salla.api.errorPromise(e)}return this.request(["details",e],{params:{with:t}}).then((function(t){return salla.product.event.detailFetched(t,e),t})).catch((function(t){throw salla.product.event.availabilitySubscribeFailed(t,e),t}))}addGiftToCart(e,t,r=!1){return this.request(["giftToCart",e],t).then((t=>(salla.product.event.addGiftToCartSucceeded(t,e),r&&(window.location.href=t.redirect),t))).catch((t=>{throw salla.product.event.addGiftToCartFailed(t,e),t}))}uploadGiftImage(e){return this.request("giftImage",e).then((e=>(salla.product.event.giftImageUploadSucceeded(e),e))).catch((e=>{throw salla.product.event.giftImageUploadFailed(e),e}))}fetch(e){if(!e.source){const e="Source cannot be empty. Please provide one.";return salla.product.event.productListFetchFailed(e),salla.api.errorPromise(e)}const t=!e.source_value,r="string"==typeof e.source_value&&"[]"===e.source_value,a=Array.isArray(e.source_value)&&!e.source_value.length;if((t||r||a)&&!["offers","latest","sales","wishlist","top-rated"].includes(e.source)){const e="Source value cannot be empty. Please provide one.";return salla.product.event.productListFetchFailed(e),salla.api.errorPromise(e)}if(["categories","brands","tags","selected"].includes(e.source)&&!Array.isArray(e.source_value)){const e="SourceValue type error. Expected an array.";return salla.product.event.productListFetchFailed(e),salla.api.errorPromise(e)}if("search"===e.source&&"string"!=typeof e.source_value){const e="SourceValue type error. Expected a string.";return salla.product.event.productListFetchFailed(e),salla.api.errorPromise(e)}if("related"===e.source&&isNaN(e.source_value)){const e="SourceValue type error. Expected a number.";return salla.product.event.productListFetchFailed(e),salla.api.errorPromise(e)}return this.request(this.endpoints.fetch,{params:e},"get").then((async t=>{if(salla.product.event.productListFetchSucceeded(t),e.includes&&e.includes.includes("options")&&t.data){const e=t.data.map((e=>e.id)),r=await this.fetchOptions(e);this.updateProductOptions(t.data,r.data)}return t})).catch((e=>{throw salla.product.event.productListFetchFailed(e),e}))}updateProductOptions(e,t){const r=new Map(t.map((e=>[e.id,e.options])));for(const t of e)t.options=r.get(t.id)}fetchOptions(e){if(!e||0===e.length){const e="At least one product ID is required. Please provide a valid list of product IDs.";return salla.product.event.productOptionsNotFetched(e),salla.api.errorPromise(e)}const t={selected:e};return this.request(this.endpoints.fetchOptions,{params:t},"get").then((e=>(salla.product.event.productOptionsFetched(e),e))).catch((e=>{throw salla.product.event.productOptionsNotFetched(e),e}))}}class Ce extends Ae{constructor(){super(),this.namespace="profile",this.endpoints={info:"auth/user",update:"profile/update",updateContacts:"profile/contacts/update",updateSettings:"profile/settings",verify:"profile/verify",delete:"profile"},this.endpointsMethods={delete:"delete"},this.after_init()}info(){return this.request("info",null,"get").then((e=>{let t={id:e.data.id,type:"user",email:e.data.email,mobile:e.data.phone.code+e.data.phone.number,country_code:e.data.phone.country,language_code:e.data.language,currency_code:e.data.currency,notifications:e.data.notifications,pending_orders:e.data.pending_orders,avatar:e.data.avatar,first_name:e.data.first_name,last_name:e.data.last_name,fetched_at:Date.now()};return salla.config.set("user",t),salla.storage.set("user",t),salla.profile.event.infoFetched(e),e})).catch((e=>{throw salla.profile.event.infoNotFetched(e),e}))}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.verificationCodeSent(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}))}updateSettings(e){return this.request("updateSettings",e).then((e=>(salla.event.profile.settingsUpdated(e),e))).catch((e=>{throw salla.event.profile.updateSettingsFailed(e),e}))}delete(){return this.request("delete").then((e=>(salla.storage.clearAll(),salla.cookie.clearAll(),salla.event.profile.deleted(e),window.location.href=salla.url.get("logout"),e))).catch((e=>{throw salla.event.profile.notDeleted(e),e}))}}class Oe extends Ae{constructor(){super(),this.namespace="comment",this.endpoints={addComment:"{type}/{id}/comments",comments:"/comments"},this.after_init()}add(e){if(e?.data&&(e=e.data),"string"==typeof(e=this.getCommentPayload(e,!0)))return salla.event.comment.additionFailed(e),salla.api.errorPromise(e);if(!e.comment){let e="can't find comment content!";return salla.event.comment.additionFailed(e),salla.api.errorPromise(e)}return this.request(["addComment",e.type,e.id],{comment:e.comment}).then((function(t){return salla.event.comment.added(t,e.id),t})).catch((function(t){throw salla.event.comment.additionFailed(t,e.id),t}))}getCommentPayload(e,t=!1){let r={};if(["id","type","comment","per_page","page","sort"].forEach((t=>{let a=salla.form.getPossibleValue(e,[t]);a&&(r[t]=a)})),!t){let t=e.ids;if(t&&(r.ids=Array.isArray(t)?t:[t]),!r.ids||!r.ids.length)return"Failed to get ids!"}return r.type&&["products","pages","product","page"].includes(r.type)?(r.type+=["product","page"].includes(r.type)?"s":"",r):"Failed to get type one of:(products, product, page, pages)!"}fetchComments(e){if("string"==typeof(e=this.getCommentPayload(e)))return salla.event.comment.fetchFailed(e),salla.api.errorPromise(e);const t={per_page:e.per_page||5,page:e.page||1,type:e.type,ids:e.ids};return e.sort&&(t.sort=e.sort),this.request(["comments"],{params:t},"get").then((function(t){return salla.event.comment.fetched(t,e),t})).catch((function(t){throw salla.event.comment.fetchFailed(t,e),t}))}getPageComments(e,t=1,r=5,a){return this.fetchComments({ids:[e],type:"pages",page:t,per_page:r,sort:a})}getProductComments(e,t=1,r=5,a){return this.fetchComments({ids:[e],type:"products",page:t,per_page:r,sort:a})}}class ke extends Ae{constructor(){super(),this.namespace="currency",this.endpoints={change:"/",list:"currencies"},this.endpointsMethods={change:"get",list:"get"},this.webEndpoints=["change"],this.after_init()}change(e){if(!(e=salla.form.getPossibleValue(e.data||e,["currency","code"]))){let e="Can't find currency code!";return salla.currency.event.failed(e),salla.api.errorPromise(e)}return this.request("change",{params:{change_currency:"",currency:e}}).then((function(t){return salla.cookie.set("fresh_summary",1),salla.storage.set("cart",""),salla.currency.event.changed(t,e),t})).catch((function(t){throw salla.currency.event.failed(t,e),t}))}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 Ie extends Ae{constructor(){super(),this.namespace="document"}}class Le extends Ae{constructor(){super(),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(e){let t="object"==typeof e?e:{},r=salla.form.getPossibleValue(e?.data||e,["order_id","id"]);if(!r){let e='There is no "order_id"!';return salla.event.rating.orderNotFetched(e),salla.api.errorPromise(e)}return this.request(["order",r],t).then((function(e){return salla.event.rating.orderFetched(e,r),e})).catch((function(e){throw salla.event.rating.orderNotFetched(e,r),e}))}store(e){if(!(e=e?.data||e)){let e='There is no "data"!';return salla.event.rating.storeFailed(e),salla.api.errorPromise(e)}return this.request("store",e).then((function(t){return salla.event.rating.storeRated(t,e),t})).catch((function(t){throw salla.event.rating.storeFailed(t,e),t}))}products(e){if(!(e=e?.data||e)){let e='There is no "data"!';return salla.event.rating.productsFailed(e),salla.api.errorPromise(e)}return this.request("products",e).then((function(t){return salla.event.rating.productsRated(t,e),t})).catch((function(t){throw salla.event.rating.productsFailed(t,e),t}))}shipping(e){if(!(e=e?.data||e)){let e='There is no "data"!';return salla.event.rating.shippingFailed(e),salla.api.errorPromise(e)}return this.request("shipping",e).then((function(t){return salla.event.rating.shippingRated(t,e),t})).catch((function(t){throw salla.event.rating.shippingFailed(t,e),t}))}}class qe extends Ae{constructor(){super(),this.namespace="wishlist",this.endpoints={add:"products/favorites/{id}",remove:"products/favorites/{id}"},this.endpointsMethods={remove:"delete"},this.after_init()}toggle(e){return salla.storage.get("salla::wishlist",[]).includes(e)?this.remove(e):this.add(e)}add(e){let t;return salla.config.isGuest()?(salla.wishlist.event.additionFailed(t=salla.lang.get("common.messages.must_login")),salla.error(t),salla.api.errorPromise(t)):(e=salla.form.getPossibleValue(e?.data||e,["product_id","id"]))?this.request(["add",e]).then((t=>(this.updateWishlistStorage(e),salla.wishlist.event.added(t,e),t))).catch((function(t){throw salla.wishlist.event.additionFailed(t,e),t})):(salla.wishlist.event.additionFailed(t="Failed to get product id!"),salla.api.errorPromise(t))}remove(e){let t;return salla.config.isGuest()?(salla.wishlist.event.additionFailed(t=salla.lang.get("common.messages.must_login")),salla.error(t),salla.api.errorPromise(t)):(e=salla.form.getPossibleValue(e?.data||e,["product_id","id"]))?this.request(["remove",e]).then((t=>(this.updateWishlistStorage(e,!1),salla.wishlist.event.removed(t,e),t))).catch((function(t){throw salla.wishlist.event.removingFailed(t,e),t})):(salla.wishlist.event.removingFailed(t="Failed to get id!"),salla.api.errorPromise(t))}updateWishlistStorage(e,t=!0){let r=salla.storage.get("salla::wishlist",[]);t?r.push(e):r.splice(r.indexOf(e),1),salla.storage.set("salla::wishlist",r)}}class De extends Ae{constructor(){super(),this.namespace="scopes",this.endpoints={get:"scopes",change:"scopes",getProductAvailability:"scopes/availability?product_id={id}"},this.after_init()}get(){return this.request("scopes",null,"get").then((e=>(salla.scope.event.fetched(e),e))).catch((e=>{throw salla.scope.event.notFetched(e),e}))}change(e){return this.request("scopes",e).then((e=>(salla.scope.event.changeSucceeded(e),e))).catch((e=>{throw salla.scope.event.changeFailed(e),e}))}getProductAvailability(e=null){return this.request(`scopes/availability?product_id=${e}`,null,"get").then((t=>(salla.scope.event.productAvailabilityFetched(t,e),t))).catch((e=>{throw salla.scope.event.productAvailabilityNotFetched(e),e}))}}class Ue extends Ae{constructor(){super(),this.namespace="booking",this.endpoints={add:"cart/booking/product/{id}"},this.endpointsMethods={add:"get"}}async add(e,t=!0){if(!e){let e="Please provide product id.";return salla.booking.event.additionFailed(e),salla.api.errorPromise(e)}return this.request(["add",e]).then((function(e){return salla.booking.event.added(e),t&&"booking"===e.data.redirect.to&&(window.location.href=e.data.redirect.url),e})).catch((function(e){throw salla.booking.event.additionFailed(e),e}))}}class Ne extends Ae{constructor(){super(),this.namespace="landing",this.endpoints={getDetails:"landing/{landing_page_id}",createCartFromPage:"landing/{landing_page_id}",breadcrumbs:"breadcrumbs"},this.endpointsMethods={getDetails:"get",breadcrumbs:"get"},this.after_init()}getDetails(e){if(!e){let e="page landing id not passed";return salla.event.landing.getDetailsFailed(e),salla.api.errorPromise(e)}return this.request(["getDetails",e]).then((function(t){return salla.event.landing.detailsFetched(t,e),t})).catch((function(t){throw salla.event.landing.getDetailsFailed(t,e),t}))}createCartFromPage(e){if(!e){let e="page landing id not passed";return salla.event.landing.orderCreationFailed(e),salla.api.errorPromise(e)}return salla.config.isGuest()?(salla.auth.api.setAfterLoginEvent("landing::createCartFromPage",e),salla.event.dispatch("login::open"),salla.api.successPromise("")):this.request(["createCartFromPage",e]).then((function(t){return salla.event.landing.orderCreated(t,e).then((()=>location.href=t.data.url)),t})).catch((function(t){throw salla.event.landing.orderCreationFailed(t,e),t}))}fetchBreadcrumbs(e){if(!e.page){let e="The 'page' parameter is required for the Breadcrumb API. Please provide a valid 'page' parameter.";return salla.event.landing.breadcrumbFetchFailed(e),salla.api.errorPromise(e)}if("product.single"===e.page&&!e.id&&!e.parent_id){let e="The 'id' and 'parent_id' parameters are required when the 'page' parameter is set to 'product.single'. Please provide valid values for both parameters.";return salla.event.landing.breadcrumbFetchFailed(e),salla.api.errorPromise(e)}if(["product.index","customer.orders.single","product.index.tag","page-single","landing-page","brands.single","blog.single","blog.index.author","blog.index.category","blog.index.tag"].includes(e.page)&&!e.id){let t=`The 'id' parameter is required when the 'page' parameter is set to ${e.page}. Please provide valid value for the 'ID' parameter.`;return salla.event.landing.breadcrumbFetchFailed(t),salla.api.errorPromise(t)}return this.request("breadcrumbs",{params:e}).then((function(e){return salla.event.landing.breadcrumbFetched(e),e})).catch((function(e){throw salla.event.landing.breadcrumbFetchFailed(e),e}))}}class je extends Ae{constructor(){super(),this.namespace="notifications",this.endpoints={fetch:"notifications"},this.endpointsMethods={fetch:"get"},this.after_init()}fetch(e){return this.request(["fetch"],{params:e}).then((function(e){return salla.event.notifications.fetched(e),e})).catch((function(e){throw salla.event.notifications.fetchFailed(e),e}))}}var Be,Me={exports:{}},He=function(e,t){return function(){for(var r=new Array(arguments.length),a=0;a<r.length;a++)r[a]=arguments[a];return e.apply(t,r)}},$e=He,ze=Object.prototype.toString,Ye=(Be=Object.create(null),function(e){var t=ze.call(e);return Be[t]||(Be[t]=t.slice(8,-1).toLowerCase())});function We(e){return e=e.toLowerCase(),function(t){return Ye(t)===e}}function Ve(e){return Array.isArray(e)}function Ge(e){return void 0===e}var Qe=We("ArrayBuffer");function Ke(e){return null!==e&&"object"==typeof e}function Je(e){if("object"!==Ye(e))return!1;var t=Object.getPrototypeOf(e);return null===t||t===Object.prototype}var Xe=We("Date"),Ze=We("File"),et=We("Blob"),tt=We("FileList");function rt(e){return"[object Function]"===ze.call(e)}var at=We("URLSearchParams");function nt(e,t){if(null!=e)if("object"!=typeof e&&(e=[e]),Ve(e))for(var r=0,a=e.length;r<a;r++)t.call(null,e[r],r,e);else for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.call(null,e[n],n,e)}var it,st=(it="undefined"!=typeof Uint8Array&&Object.getPrototypeOf(Uint8Array),function(e){return it&&e instanceof it}),ot={isArray:Ve,isArrayBuffer:Qe,isBuffer:function(e){return null!==e&&!Ge(e)&&null!==e.constructor&&!Ge(e.constructor)&&"function"==typeof e.constructor.isBuffer&&e.constructor.isBuffer(e)},isFormData:function(e){var t="[object FormData]";return e&&("function"==typeof FormData&&e instanceof FormData||ze.call(e)===t||rt(e.toString)&&e.toString()===t)},isArrayBufferView:function(e){return"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&Qe(e.buffer)},isString:function(e){return"string"==typeof e},isNumber:function(e){return"number"==typeof e},isObject:Ke,isPlainObject:Je,isUndefined:Ge,isDate:Xe,isFile:Ze,isBlob:et,isFunction:rt,isStream:function(e){return Ke(e)&&rt(e.pipe)},isURLSearchParams:at,isStandardBrowserEnv:function(){return("undefined"==typeof navigator||"ReactNative"!==navigator.product&&"NativeScript"!==navigator.product&&"NS"!==navigator.product)&&("undefined"!=typeof window&&"undefined"!=typeof document)},forEach:nt,merge:function e(){var t={};function r(r,a){Je(t[a])&&Je(r)?t[a]=e(t[a],r):Je(r)?t[a]=e({},r):Ve(r)?t[a]=r.slice():t[a]=r}for(var a=0,n=arguments.length;a<n;a++)nt(arguments[a],r);return t},extend:function(e,t,r){return nt(t,(function(t,a){e[a]=r&&"function"==typeof t?$e(t,r):t})),e},trim:function(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")},stripBOM:function(e){return 65279===e.charCodeAt(0)&&(e=e.slice(1)),e},inherits:function(e,t,r,a){e.prototype=Object.create(t.prototype,a),e.prototype.constructor=e,r&&Object.assign(e.prototype,r)},toFlatObject:function(e,t,r){var a,n,i,s={};t=t||{};do{for(n=(a=Object.getOwnPropertyNames(e)).length;n-- >0;)s[i=a[n]]||(t[i]=e[i],s[i]=!0);e=Object.getPrototypeOf(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},kindOf:Ye,kindOfTest:We,endsWith:function(e,t,r){e=String(e),(void 0===r||r>e.length)&&(r=e.length),r-=t.length;var a=e.indexOf(t,r);return-1!==a&&a===r},toArray:function(e){if(!e)return null;var t=e.length;if(Ge(t))return null;for(var r=new Array(t);t-- >0;)r[t]=e[t];return r},isTypedArray:st,isFileList:tt},lt=ot;function ct(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}var ut=function(e,t,r){if(!t)return e;var a;if(r)a=r(t);else if(lt.isURLSearchParams(t))a=t.toString();else{var n=[];lt.forEach(t,(function(e,t){null!=e&&(lt.isArray(e)?t+="[]":e=[e],lt.forEach(e,(function(e){lt.isDate(e)?e=e.toISOString():lt.isObject(e)&&(e=JSON.stringify(e)),n.push(ct(t)+"="+ct(e))})))})),a=n.join("&")}if(a){var i=e.indexOf("#");-1!==i&&(e=e.slice(0,i)),e+=(-1===e.indexOf("?")?"?":"&")+a}return e},dt=ot;function ht(){this.handlers=[]}ht.prototype.use=function(e,t,r){return this.handlers.push({fulfilled:e,rejected:t,synchronous:!!r&&r.synchronous,runWhen:r?r.runWhen:null}),this.handlers.length-1},ht.prototype.eject=function(e){this.handlers[e]&&(this.handlers[e]=null)},ht.prototype.forEach=function(e){dt.forEach(this.handlers,(function(t){null!==t&&e(t)}))};var ft=ht;function pt(){throw new Error("setTimeout has not been defined")}function gt(){throw new Error("clearTimeout has not been defined")}var mt=pt,vt=gt;function yt(e){if(mt===setTimeout)return setTimeout(e,0);if((mt===pt||!mt)&&setTimeout)return mt=setTimeout,setTimeout(e,0);try{return mt(e,0)}catch(t){try{return mt.call(null,e,0)}catch(t){return mt.call(this,e,0)}}}"function"==typeof global.setTimeout&&(mt=setTimeout),"function"==typeof global.clearTimeout&&(vt=clearTimeout);var wt,bt=[],St=!1,Et=-1;function _t(){St&&wt&&(St=!1,wt.length?bt=wt.concat(bt):Et=-1,bt.length&&At())}function At(){if(!St){var e=yt(_t);St=!0;for(var t=bt.length;t;){for(wt=bt,bt=[];++Et<t;)wt&&wt[Et].run();Et=-1,t=bt.length}wt=null,St=!1,function(e){if(vt===clearTimeout)return clearTimeout(e);if((vt===gt||!vt)&&clearTimeout)return vt=clearTimeout,clearTimeout(e);try{return vt(e)}catch(t){try{return vt.call(null,e)}catch(t){return vt.call(this,e)}}}(e)}}function Ft(e,t){this.fun=e,this.array=t}Ft.prototype.run=function(){this.fun.apply(null,this.array)};function Pt(){}var xt=Pt,Tt=Pt,Rt=Pt,Ct=Pt,Ot=Pt,kt=Pt,It=Pt;var Lt=global.performance||{},qt=Lt.now||Lt.mozNow||Lt.msNow||Lt.oNow||Lt.webkitNow||function(){return(new Date).getTime()};var Dt=new Date;var Ut,Nt,jt={nextTick:function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var r=1;r<arguments.length;r++)t[r-1]=arguments[r];bt.push(new Ft(e,t)),1!==bt.length||St||yt(At)},title:"browser",browser:!0,env:{},argv:[],version:"",versions:{},on:xt,addListener:Tt,once:Rt,off:Ct,removeListener:Ot,removeAllListeners:kt,emit:It,binding:function(e){throw new Error("process.binding is not supported")},cwd:function(){return"/"},chdir:function(e){throw new Error("process.chdir is not supported")},umask:function(){return 0},hrtime:function(e){var t=.001*qt.call(Lt),r=Math.floor(t),a=Math.floor(t%1*1e9);return e&&(r-=e[0],(a-=e[1])<0&&(r--,a+=1e9)),[r,a]},platform:"browser",release:{},config:{},uptime:function(){return(new Date-Dt)/1e3}},Bt=jt,Mt=ot;function Ht(){if(Nt)return Ut;Nt=1;var e=ot;function t(e,t,r,a,n){Error.call(this),this.message=e,this.name="AxiosError",t&&(this.code=t),r&&(this.config=r),a&&(this.request=a),n&&(this.response=n)}e.inherits(t,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:this.config,code:this.code,status:this.response&&this.response.status?this.response.status:null}}});var r=t.prototype,a={};return["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED"].forEach((function(e){a[e]={value:e}})),Object.defineProperties(t,a),Object.defineProperty(r,"isAxiosError",{value:!0}),t.from=function(a,n,i,s,o,l){var c=Object.create(r);return e.toFlatObject(a,c,(function(e){return e!==Error.prototype})),t.call(c,a.message,n,i,s,o),c.name=a.name,l&&Object.assign(c,l),c},Ut=t}var $t={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},zt=[],Yt=[],Wt="undefined"!=typeof Uint8Array?Uint8Array:Array,Vt=!1;function Gt(){Vt=!0;for(var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",t=0;t<64;++t)zt[t]=e[t],Yt[e.charCodeAt(t)]=t;Yt["-".charCodeAt(0)]=62,Yt["_".charCodeAt(0)]=63}function Qt(e,t,r){for(var a,n,i=[],s=t;s<r;s+=3)a=(e[s]<<16)+(e[s+1]<<8)+e[s+2],i.push(zt[(n=a)>>18&63]+zt[n>>12&63]+zt[n>>6&63]+zt[63&n]);return i.join("")}function Kt(e){var t;Vt||Gt();for(var r=e.length,a=r%3,n="",i=[],s=16383,o=0,l=r-a;o<l;o+=s)i.push(Qt(e,o,o+s>l?l:o+s));return 1===a?(t=e[r-1],n+=zt[t>>2],n+=zt[t<<4&63],n+="=="):2===a&&(t=(e[r-2]<<8)+e[r-1],n+=zt[t>>10],n+=zt[t>>4&63],n+=zt[t<<2&63],n+="="),i.push(n),i.join("")}function Jt(e,t,r,a,n){var i,s,o=8*n-a-1,l=(1<<o)-1,c=l>>1,u=-7,d=r?n-1:0,h=r?-1:1,f=e[t+d];for(d+=h,i=f&(1<<-u)-1,f>>=-u,u+=o;u>0;i=256*i+e[t+d],d+=h,u-=8);for(s=i&(1<<-u)-1,i>>=-u,u+=a;u>0;s=256*s+e[t+d],d+=h,u-=8);if(0===i)i=1-c;else{if(i===l)return s?NaN:1/0*(f?-1:1);s+=Math.pow(2,a),i-=c}return(f?-1:1)*s*Math.pow(2,i-a)}function Xt(e,t,r,a,n,i){var s,o,l,c=8*i-n-1,u=(1<<c)-1,d=u>>1,h=23===n?Math.pow(2,-24)-Math.pow(2,-77):0,f=a?0:i-1,p=a?1:-1,g=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(o=isNaN(t)?1:0,s=u):(s=Math.floor(Math.log(t)/Math.LN2),t*(l=Math.pow(2,-s))<1&&(s--,l*=2),(t+=s+d>=1?h/l:h*Math.pow(2,1-d))*l>=2&&(s++,l/=2),s+d>=u?(o=0,s=u):s+d>=1?(o=(t*l-1)*Math.pow(2,n),s+=d):(o=t*Math.pow(2,d-1)*Math.pow(2,n),s=0));n>=8;e[r+f]=255&o,f+=p,o/=256,n-=8);for(s=s<<n|o,c+=n;c>0;e[r+f]=255&s,f+=p,s/=256,c-=8);e[r+f-p]|=128*g}var Zt={}.toString,er=Array.isArray||function(e){return"[object Array]"==Zt.call(e)};function tr(){return ar.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function rr(e,t){if(tr()<t)throw new RangeError("Invalid typed array length");return ar.TYPED_ARRAY_SUPPORT?(e=new Uint8Array(t)).__proto__=ar.prototype:(null===e&&(e=new ar(t)),e.length=t),e}function ar(e,t,r){if(!(ar.TYPED_ARRAY_SUPPORT||this instanceof ar))return new ar(e,t,r);if("number"==typeof e){if("string"==typeof t)throw new Error("If encoding is specified then the first argument must be a string");return sr(this,e)}return nr(this,e,t,r)}function nr(e,t,r,a){if("number"==typeof t)throw new TypeError('"value" argument must not be a number');return"undefined"!=typeof ArrayBuffer&&t instanceof ArrayBuffer?function(e,t,r,a){if(t.byteLength,r<0||t.byteLength<r)throw new RangeError("'offset' is out of bounds");if(t.byteLength<r+(a||0))throw new RangeError("'length' is out of bounds");t=void 0===r&&void 0===a?new Uint8Array(t):void 0===a?new Uint8Array(t,r):new Uint8Array(t,r,a);ar.TYPED_ARRAY_SUPPORT?(e=t).__proto__=ar.prototype:e=or(e,t);return e}(e,t,r,a):"string"==typeof t?function(e,t,r){"string"==typeof r&&""!==r||(r="utf8");if(!ar.isEncoding(r))throw new TypeError('"encoding" must be a valid string encoding');var a=0|ur(t,r);e=rr(e,a);var n=e.write(t,r);n!==a&&(e=e.slice(0,n));return e}(e,t,r):function(e,t){if(cr(t)){var r=0|lr(t.length);return 0===(e=rr(e,r)).length||t.copy(e,0,0,r),e}if(t){if("undefined"!=typeof ArrayBuffer&&t.buffer instanceof ArrayBuffer||"length"in t)return"number"!=typeof t.length||(a=t.length)!=a?rr(e,0):or(e,t);if("Buffer"===t.type&&er(t.data))return or(e,t.data)}var a;throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")}(e,t)}function ir(e){if("number"!=typeof e)throw new TypeError('"size" argument must be a number');if(e<0)throw new RangeError('"size" argument must not be negative')}function sr(e,t){if(ir(t),e=rr(e,t<0?0:0|lr(t)),!ar.TYPED_ARRAY_SUPPORT)for(var r=0;r<t;++r)e[r]=0;return e}function or(e,t){var r=t.length<0?0:0|lr(t.length);e=rr(e,r);for(var a=0;a<r;a+=1)e[a]=255&t[a];return e}function lr(e){if(e>=tr())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+tr().toString(16)+" bytes");return 0|e}function cr(e){return!(null==e||!e._isBuffer)}function ur(e,t){if(cr(e))return e.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e.byteLength;"string"!=typeof e&&(e=""+e);var r=e.length;if(0===r)return 0;for(var a=!1;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":case void 0:return $r(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return zr(e).length;default:if(a)return $r(e).length;t=(""+t).toLowerCase(),a=!0}}function dr(e,t,r){var a=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return Pr(this,t,r);case"utf8":case"utf-8":return Er(this,t,r);case"ascii":return Ar(this,t,r);case"latin1":case"binary":return Fr(this,t,r);case"base64":return Sr(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return xr(this,t,r);default:if(a)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),a=!0}}function hr(e,t,r){var a=e[t];e[t]=e[r],e[r]=a}function fr(e,t,r,a,n){if(0===e.length)return-1;if("string"==typeof r?(a=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,isNaN(r)&&(r=n?0:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(n)return-1;r=e.length-1}else if(r<0){if(!n)return-1;r=0}if("string"==typeof t&&(t=ar.from(t,a)),cr(t))return 0===t.length?-1:pr(e,t,r,a,n);if("number"==typeof t)return t&=255,ar.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?n?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):pr(e,[t],r,a,n);throw new TypeError("val must be string, number or Buffer")}function pr(e,t,r,a,n){var i,s=1,o=e.length,l=t.length;if(void 0!==a&&("ucs2"===(a=String(a).toLowerCase())||"ucs-2"===a||"utf16le"===a||"utf-16le"===a)){if(e.length<2||t.length<2)return-1;s=2,o/=2,l/=2,r/=2}function c(e,t){return 1===s?e[t]:e.readUInt16BE(t*s)}if(n){var u=-1;for(i=r;i<o;i++)if(c(e,i)===c(t,-1===u?0:i-u)){if(-1===u&&(u=i),i-u+1===l)return u*s}else-1!==u&&(i-=i-u),u=-1}else for(r+l>o&&(r=o-l),i=r;i>=0;i--){for(var d=!0,h=0;h<l;h++)if(c(e,i+h)!==c(t,h)){d=!1;break}if(d)return i}return-1}function gr(e,t,r,a){r=Number(r)||0;var n=e.length-r;a?(a=Number(a))>n&&(a=n):a=n;var i=t.length;if(i%2!=0)throw new TypeError("Invalid hex string");a>i/2&&(a=i/2);for(var s=0;s<a;++s){var o=parseInt(t.substr(2*s,2),16);if(isNaN(o))return s;e[r+s]=o}return s}function mr(e,t,r,a){return Yr($r(t,e.length-r),e,r,a)}function vr(e,t,r,a){return Yr(function(e){for(var t=[],r=0;r<e.length;++r)t.push(255&e.charCodeAt(r));return t}(t),e,r,a)}function yr(e,t,r,a){return vr(e,t,r,a)}function wr(e,t,r,a){return Yr(zr(t),e,r,a)}function br(e,t,r,a){return Yr(function(e,t){for(var r,a,n,i=[],s=0;s<e.length&&!((t-=2)<0);++s)a=(r=e.charCodeAt(s))>>8,n=r%256,i.push(n),i.push(a);return i}(t,e.length-r),e,r,a)}function Sr(e,t,r){return 0===t&&r===e.length?Kt(e):Kt(e.slice(t,r))}function Er(e,t,r){r=Math.min(e.length,r);for(var a=[],n=t;n<r;){var i,s,o,l,c=e[n],u=null,d=c>239?4:c>223?3:c>191?2:1;if(n+d<=r)switch(d){case 1:c<128&&(u=c);break;case 2:128==(192&(i=e[n+1]))&&(l=(31&c)<<6|63&i)>127&&(u=l);break;case 3:i=e[n+1],s=e[n+2],128==(192&i)&&128==(192&s)&&(l=(15&c)<<12|(63&i)<<6|63&s)>2047&&(l<55296||l>57343)&&(u=l);break;case 4:i=e[n+1],s=e[n+2],o=e[n+3],128==(192&i)&&128==(192&s)&&128==(192&o)&&(l=(15&c)<<18|(63&i)<<12|(63&s)<<6|63&o)>65535&&l<1114112&&(u=l)}null===u?(u=65533,d=1):u>65535&&(u-=65536,a.push(u>>>10&1023|55296),u=56320|1023&u),a.push(u),n+=d}return function(e){var t=e.length;if(t<=_r)return String.fromCharCode.apply(String,e);var r="",a=0;for(;a<t;)r+=String.fromCharCode.apply(String,e.slice(a,a+=_r));return r}(a)}ar.TYPED_ARRAY_SUPPORT=void 0===global.TYPED_ARRAY_SUPPORT||global.TYPED_ARRAY_SUPPORT,tr(),ar.poolSize=8192,ar._augment=function(e){return e.__proto__=ar.prototype,e},ar.from=function(e,t,r){return nr(null,e,t,r)},ar.TYPED_ARRAY_SUPPORT&&(ar.prototype.__proto__=Uint8Array.prototype,ar.__proto__=Uint8Array),ar.alloc=function(e,t,r){return function(e,t,r,a){return ir(t),t<=0?rr(e,t):void 0!==r?"string"==typeof a?rr(e,t).fill(r,a):rr(e,t).fill(r):rr(e,t)}(null,e,t,r)},ar.allocUnsafe=function(e){return sr(null,e)},ar.allocUnsafeSlow=function(e){return sr(null,e)},ar.isBuffer=function(e){return null!=e&&(!!e._isBuffer||Wr(e)||function(e){return"function"==typeof e.readFloatLE&&"function"==typeof e.slice&&Wr(e.slice(0,0))}(e))},ar.compare=function(e,t){if(!cr(e)||!cr(t))throw new TypeError("Arguments must be Buffers");if(e===t)return 0;for(var r=e.length,a=t.length,n=0,i=Math.min(r,a);n<i;++n)if(e[n]!==t[n]){r=e[n],a=t[n];break}return r<a?-1:a<r?1:0},ar.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},ar.concat=function(e,t){if(!er(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return ar.alloc(0);var r;if(void 0===t)for(t=0,r=0;r<e.length;++r)t+=e[r].length;var a=ar.allocUnsafe(t),n=0;for(r=0;r<e.length;++r){var i=e[r];if(!cr(i))throw new TypeError('"list" argument must be an Array of Buffers');i.copy(a,n),n+=i.length}return a},ar.byteLength=ur,ar.prototype._isBuffer=!0,ar.prototype.swap16=function(){var e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var t=0;t<e;t+=2)hr(this,t,t+1);return this},ar.prototype.swap32=function(){var e=this.length;if(e%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var t=0;t<e;t+=4)hr(this,t,t+3),hr(this,t+1,t+2);return this},ar.prototype.swap64=function(){var e=this.length;if(e%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var t=0;t<e;t+=8)hr(this,t,t+7),hr(this,t+1,t+6),hr(this,t+2,t+5),hr(this,t+3,t+4);return this},ar.prototype.toString=function(){var e=0|this.length;return 0===e?"":0===arguments.length?Er(this,0,e):dr.apply(this,arguments)},ar.prototype.equals=function(e){if(!cr(e))throw new TypeError("Argument must be a Buffer");return this===e||0===ar.compare(this,e)},ar.prototype.inspect=function(){var e="";return this.length>0&&(e=this.toString("hex",0,50).match(/.{2}/g).join(" "),this.length>50&&(e+=" ... ")),"<Buffer "+e+">"},ar.prototype.compare=function(e,t,r,a,n){if(!cr(e))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===r&&(r=e?e.length:0),void 0===a&&(a=0),void 0===n&&(n=this.length),t<0||r>e.length||a<0||n>this.length)throw new RangeError("out of range index");if(a>=n&&t>=r)return 0;if(a>=n)return-1;if(t>=r)return 1;if(this===e)return 0;for(var i=(n>>>=0)-(a>>>=0),s=(r>>>=0)-(t>>>=0),o=Math.min(i,s),l=this.slice(a,n),c=e.slice(t,r),u=0;u<o;++u)if(l[u]!==c[u]){i=l[u],s=c[u];break}return i<s?-1:s<i?1:0},ar.prototype.includes=function(e,t,r){return-1!==this.indexOf(e,t,r)},ar.prototype.indexOf=function(e,t,r){return fr(this,e,t,r,!0)},ar.prototype.lastIndexOf=function(e,t,r){return fr(this,e,t,r,!1)},ar.prototype.write=function(e,t,r,a){if(void 0===t)a="utf8",r=this.length,t=0;else if(void 0===r&&"string"==typeof t)a=t,r=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t|=0,isFinite(r)?(r|=0,void 0===a&&(a="utf8")):(a=r,r=void 0)}var n=this.length-t;if((void 0===r||r>n)&&(r=n),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");a||(a="utf8");for(var i=!1;;)switch(a){case"hex":return gr(this,e,t,r);case"utf8":case"utf-8":return mr(this,e,t,r);case"ascii":return vr(this,e,t,r);case"latin1":case"binary":return yr(this,e,t,r);case"base64":return wr(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return br(this,e,t,r);default:if(i)throw new TypeError("Unknown encoding: "+a);a=(""+a).toLowerCase(),i=!0}},ar.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var _r=4096;function Ar(e,t,r){var a="";r=Math.min(e.length,r);for(var n=t;n<r;++n)a+=String.fromCharCode(127&e[n]);return a}function Fr(e,t,r){var a="";r=Math.min(e.length,r);for(var n=t;n<r;++n)a+=String.fromCharCode(e[n]);return a}function Pr(e,t,r){var a=e.length;(!t||t<0)&&(t=0),(!r||r<0||r>a)&&(r=a);for(var n="",i=t;i<r;++i)n+=Hr(e[i]);return n}function xr(e,t,r){for(var a=e.slice(t,r),n="",i=0;i<a.length;i+=2)n+=String.fromCharCode(a[i]+256*a[i+1]);return n}function Tr(e,t,r){if(e%1!=0||e<0)throw new RangeError("offset is not uint");if(e+t>r)throw new RangeError("Trying to access beyond buffer length")}function Rr(e,t,r,a,n,i){if(!cr(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>n||t<i)throw new RangeError('"value" argument is out of bounds');if(r+a>e.length)throw new RangeError("Index out of range")}function Cr(e,t,r,a){t<0&&(t=65535+t+1);for(var n=0,i=Math.min(e.length-r,2);n<i;++n)e[r+n]=(t&255<<8*(a?n:1-n))>>>8*(a?n:1-n)}function Or(e,t,r,a){t<0&&(t=4294967295+t+1);for(var n=0,i=Math.min(e.length-r,4);n<i;++n)e[r+n]=t>>>8*(a?n:3-n)&255}function kr(e,t,r,a,n,i){if(r+a>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function Ir(e,t,r,a,n){return n||kr(e,0,r,4),Xt(e,t,r,a,23,4),r+4}function Lr(e,t,r,a,n){return n||kr(e,0,r,8),Xt(e,t,r,a,52,8),r+8}ar.prototype.slice=function(e,t){var r,a=this.length;if((e=~~e)<0?(e+=a)<0&&(e=0):e>a&&(e=a),(t=void 0===t?a:~~t)<0?(t+=a)<0&&(t=0):t>a&&(t=a),t<e&&(t=e),ar.TYPED_ARRAY_SUPPORT)(r=this.subarray(e,t)).__proto__=ar.prototype;else{var n=t-e;r=new ar(n,void 0);for(var i=0;i<n;++i)r[i]=this[i+e]}return r},ar.prototype.readUIntLE=function(e,t,r){e|=0,t|=0,r||Tr(e,t,this.length);for(var a=this[e],n=1,i=0;++i<t&&(n*=256);)a+=this[e+i]*n;return a},ar.prototype.readUIntBE=function(e,t,r){e|=0,t|=0,r||Tr(e,t,this.length);for(var a=this[e+--t],n=1;t>0&&(n*=256);)a+=this[e+--t]*n;return a},ar.prototype.readUInt8=function(e,t){return t||Tr(e,1,this.length),this[e]},ar.prototype.readUInt16LE=function(e,t){return t||Tr(e,2,this.length),this[e]|this[e+1]<<8},ar.prototype.readUInt16BE=function(e,t){return t||Tr(e,2,this.length),this[e]<<8|this[e+1]},ar.prototype.readUInt32LE=function(e,t){return t||Tr(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},ar.prototype.readUInt32BE=function(e,t){return t||Tr(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},ar.prototype.readIntLE=function(e,t,r){e|=0,t|=0,r||Tr(e,t,this.length);for(var a=this[e],n=1,i=0;++i<t&&(n*=256);)a+=this[e+i]*n;return a>=(n*=128)&&(a-=Math.pow(2,8*t)),a},ar.prototype.readIntBE=function(e,t,r){e|=0,t|=0,r||Tr(e,t,this.length);for(var a=t,n=1,i=this[e+--a];a>0&&(n*=256);)i+=this[e+--a]*n;return i>=(n*=128)&&(i-=Math.pow(2,8*t)),i},ar.prototype.readInt8=function(e,t){return t||Tr(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},ar.prototype.readInt16LE=function(e,t){t||Tr(e,2,this.length);var r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},ar.prototype.readInt16BE=function(e,t){t||Tr(e,2,this.length);var r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},ar.prototype.readInt32LE=function(e,t){return t||Tr(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},ar.prototype.readInt32BE=function(e,t){return t||Tr(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},ar.prototype.readFloatLE=function(e,t){return t||Tr(e,4,this.length),Jt(this,e,!0,23,4)},ar.prototype.readFloatBE=function(e,t){return t||Tr(e,4,this.length),Jt(this,e,!1,23,4)},ar.prototype.readDoubleLE=function(e,t){return t||Tr(e,8,this.length),Jt(this,e,!0,52,8)},ar.prototype.readDoubleBE=function(e,t){return t||Tr(e,8,this.length),Jt(this,e,!1,52,8)},ar.prototype.writeUIntLE=function(e,t,r,a){(e=+e,t|=0,r|=0,a)||Rr(this,e,t,r,Math.pow(2,8*r)-1,0);var n=1,i=0;for(this[t]=255&e;++i<r&&(n*=256);)this[t+i]=e/n&255;return t+r},ar.prototype.writeUIntBE=function(e,t,r,a){(e=+e,t|=0,r|=0,a)||Rr(this,e,t,r,Math.pow(2,8*r)-1,0);var n=r-1,i=1;for(this[t+n]=255&e;--n>=0&&(i*=256);)this[t+n]=e/i&255;return t+r},ar.prototype.writeUInt8=function(e,t,r){return e=+e,t|=0,r||Rr(this,e,t,1,255,0),ar.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&e,t+1},ar.prototype.writeUInt16LE=function(e,t,r){return e=+e,t|=0,r||Rr(this,e,t,2,65535,0),ar.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):Cr(this,e,t,!0),t+2},ar.prototype.writeUInt16BE=function(e,t,r){return e=+e,t|=0,r||Rr(this,e,t,2,65535,0),ar.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):Cr(this,e,t,!1),t+2},ar.prototype.writeUInt32LE=function(e,t,r){return e=+e,t|=0,r||Rr(this,e,t,4,4294967295,0),ar.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e):Or(this,e,t,!0),t+4},ar.prototype.writeUInt32BE=function(e,t,r){return e=+e,t|=0,r||Rr(this,e,t,4,4294967295,0),ar.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):Or(this,e,t,!1),t+4},ar.prototype.writeIntLE=function(e,t,r,a){if(e=+e,t|=0,!a){var n=Math.pow(2,8*r-1);Rr(this,e,t,r,n-1,-n)}var i=0,s=1,o=0;for(this[t]=255&e;++i<r&&(s*=256);)e<0&&0===o&&0!==this[t+i-1]&&(o=1),this[t+i]=(e/s>>0)-o&255;return t+r},ar.prototype.writeIntBE=function(e,t,r,a){if(e=+e,t|=0,!a){var n=Math.pow(2,8*r-1);Rr(this,e,t,r,n-1,-n)}var i=r-1,s=1,o=0;for(this[t+i]=255&e;--i>=0&&(s*=256);)e<0&&0===o&&0!==this[t+i+1]&&(o=1),this[t+i]=(e/s>>0)-o&255;return t+r},ar.prototype.writeInt8=function(e,t,r){return e=+e,t|=0,r||Rr(this,e,t,1,127,-128),ar.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=255&e,t+1},ar.prototype.writeInt16LE=function(e,t,r){return e=+e,t|=0,r||Rr(this,e,t,2,32767,-32768),ar.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):Cr(this,e,t,!0),t+2},ar.prototype.writeInt16BE=function(e,t,r){return e=+e,t|=0,r||Rr(this,e,t,2,32767,-32768),ar.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):Cr(this,e,t,!1),t+2},ar.prototype.writeInt32LE=function(e,t,r){return e=+e,t|=0,r||Rr(this,e,t,4,2147483647,-2147483648),ar.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):Or(this,e,t,!0),t+4},ar.prototype.writeInt32BE=function(e,t,r){return e=+e,t|=0,r||Rr(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),ar.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):Or(this,e,t,!1),t+4},ar.prototype.writeFloatLE=function(e,t,r){return Ir(this,e,t,!0,r)},ar.prototype.writeFloatBE=function(e,t,r){return Ir(this,e,t,!1,r)},ar.prototype.writeDoubleLE=function(e,t,r){return Lr(this,e,t,!0,r)},ar.prototype.writeDoubleBE=function(e,t,r){return Lr(this,e,t,!1,r)},ar.prototype.copy=function(e,t,r,a){if(r||(r=0),a||0===a||(a=this.length),t>=e.length&&(t=e.length),t||(t=0),a>0&&a<r&&(a=r),a===r)return 0;if(0===e.length||0===this.length)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(r<0||r>=this.length)throw new RangeError("sourceStart out of bounds");if(a<0)throw new RangeError("sourceEnd out of bounds");a>this.length&&(a=this.length),e.length-t<a-r&&(a=e.length-t+r);var n,i=a-r;if(this===e&&r<t&&t<a)for(n=i-1;n>=0;--n)e[n+t]=this[n+r];else if(i<1e3||!ar.TYPED_ARRAY_SUPPORT)for(n=0;n<i;++n)e[n+t]=this[n+r];else Uint8Array.prototype.set.call(e,this.subarray(r,r+i),t);return i},ar.prototype.fill=function(e,t,r,a){if("string"==typeof e){if("string"==typeof t?(a=t,t=0,r=this.length):"string"==typeof r&&(a=r,r=this.length),1===e.length){var n=e.charCodeAt(0);n<256&&(e=n)}if(void 0!==a&&"string"!=typeof a)throw new TypeError("encoding must be a string");if("string"==typeof a&&!ar.isEncoding(a))throw new TypeError("Unknown encoding: "+a)}else"number"==typeof e&&(e&=255);if(t<0||this.length<t||this.length<r)throw new RangeError("Out of range index");if(r<=t)return this;var i;if(t>>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(i=t;i<r;++i)this[i]=e;else{var s=cr(e)?e:$r(new ar(e,a).toString()),o=s.length;for(i=0;i<r-t;++i)this[i+t]=s[i%o]}return this};var qr,Dr,Ur,Nr,jr,Br,Mr=/[^+\/0-9A-Za-z-_]/g;function Hr(e){return e<16?"0"+e.toString(16):e.toString(16)}function $r(e,t){var r;t=t||1/0;for(var a=e.length,n=null,i=[],s=0;s<a;++s){if((r=e.charCodeAt(s))>55295&&r<57344){if(!n){if(r>56319){(t-=3)>-1&&i.push(239,191,189);continue}if(s+1===a){(t-=3)>-1&&i.push(239,191,189);continue}n=r;continue}if(r<56320){(t-=3)>-1&&i.push(239,191,189),n=r;continue}r=65536+(n-55296<<10|r-56320)}else n&&(t-=3)>-1&&i.push(239,191,189);if(n=null,r<128){if((t-=1)<0)break;i.push(r)}else if(r<2048){if((t-=2)<0)break;i.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;i.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;i.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return i}function zr(e){return function(e){var t,r,a,n,i,s;Vt||Gt();var o=e.length;if(o%4>0)throw new Error("Invalid string. Length must be a multiple of 4");i="="===e[o-2]?2:"="===e[o-1]?1:0,s=new Wt(3*o/4-i),a=i>0?o-4:o;var l=0;for(t=0,r=0;t<a;t+=4,r+=3)n=Yt[e.charCodeAt(t)]<<18|Yt[e.charCodeAt(t+1)]<<12|Yt[e.charCodeAt(t+2)]<<6|Yt[e.charCodeAt(t+3)],s[l++]=n>>16&255,s[l++]=n>>8&255,s[l++]=255&n;return 2===i?(n=Yt[e.charCodeAt(t)]<<2|Yt[e.charCodeAt(t+1)]>>4,s[l++]=255&n):1===i&&(n=Yt[e.charCodeAt(t)]<<10|Yt[e.charCodeAt(t+1)]<<4|Yt[e.charCodeAt(t+2)]>>2,s[l++]=n>>8&255,s[l++]=255&n),s}(function(e){if((e=function(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")}(e).replace(Mr,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function Yr(e,t,r,a){for(var n=0;n<a&&!(n+r>=t.length||n>=e.length);++n)t[n+r]=e[n];return n}function Wr(e){return!!e.constructor&&"function"==typeof e.constructor.isBuffer&&e.constructor.isBuffer(e)}function Vr(){if(Dr)return qr;Dr=1;var e=ot;return qr=function(t,r){r=r||new FormData;var a=[];function n(t){return null===t?"":e.isDate(t)?t.toISOString():e.isArrayBuffer(t)||e.isTypedArray(t)?"function"==typeof Blob?new Blob([t]):ar.from(t):t}return function t(i,s){if(e.isPlainObject(i)||e.isArray(i)){if(-1!==a.indexOf(i))throw Error("Circular reference detected in "+s);a.push(i),e.forEach(i,(function(a,i){if(!e.isUndefined(a)){var o,l=s?s+"."+i:i;if(a&&!s&&"object"==typeof a)if(e.endsWith(i,"{}"))a=JSON.stringify(a);else if(e.endsWith(i,"[]")&&(o=e.toArray(a)))return void o.forEach((function(t){!e.isUndefined(t)&&r.append(l,n(t))}));t(a,l)}})),a.pop()}else r.append(s,n(i))}(t),r},qr}function Gr(){if(Nr)return Ur;Nr=1;var e=Ht();return Ur=function(t,r,a){var n=a.config.validateStatus;a.status&&n&&!n(a.status)?r(new e("Request failed with status code "+a.status,[e.ERR_BAD_REQUEST,e.ERR_BAD_RESPONSE][Math.floor(a.status/100)-4],a.config,a.request,a)):t(a)}}function Qr(){if(Br)return jr;Br=1;var e=ot;return jr=e.isStandardBrowserEnv()?{write:function(t,r,a,n,i,s){var o=[];o.push(t+"="+encodeURIComponent(r)),e.isNumber(a)&&o.push("expires="+new Date(a).toGMTString()),e.isString(n)&&o.push("path="+n),e.isString(i)&&o.push("domain="+i),!0===s&&o.push("secure"),document.cookie=o.join("; ")},read:function(e){var t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove:function(e){this.write(e,"",Date.now()-864e5)}}:{write:function(){},read:function(){return null},remove:function(){}}}var Kr,Jr,Xr,Zr,ea,ta,ra,aa,na,ia,sa,oa,la=function(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)},ca=function(e,t){return t?e.replace(/\/+$/,"")+"/"+t.replace(/^\/+/,""):e},ua=function(e,t){return e&&!la(t)?ca(e,t):t};function da(){if(Jr)return Kr;Jr=1;var e=ot,t=["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"];return Kr=function(r){var a,n,i,s={};return r?(e.forEach(r.split("\n"),(function(r){if(i=r.indexOf(":"),a=e.trim(r.substr(0,i)).toLowerCase(),n=e.trim(r.substr(i+1)),a){if(s[a]&&t.indexOf(a)>=0)return;s[a]="set-cookie"===a?(s[a]?s[a]:[]).concat([n]):s[a]?s[a]+", "+n:n}})),s):s},Kr}function ha(){if(Zr)return Xr;Zr=1;var e=ot;return Xr=e.isStandardBrowserEnv()?function(){var t,r=/(msie|trident)/i.test(navigator.userAgent),a=document.createElement("a");function n(e){var t=e;return r&&(a.setAttribute("href",t),t=a.href),a.setAttribute("href",t),{href:a.href,protocol:a.protocol?a.protocol.replace(/:$/,""):"",host:a.host,search:a.search?a.search.replace(/^\?/,""):"",hash:a.hash?a.hash.replace(/^#/,""):"",hostname:a.hostname,port:a.port,pathname:"/"===a.pathname.charAt(0)?a.pathname:"/"+a.pathname}}return t=n(window.location.href),function(r){var a=e.isString(r)?n(r):r;return a.protocol===t.protocol&&a.host===t.host}}():function(){return!0}}function fa(){if(ta)return ea;ta=1;var e=Ht();function t(t){e.call(this,null==t?"canceled":t,e.ERR_CANCELED),this.name="CanceledError"}return ot.inherits(t,e,{__CANCEL__:!0}),ea=t}function pa(){return aa?ra:(aa=1,ra=function(e){var t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""})}function ga(){if(ia)return na;ia=1;var e=ot,t=Gr(),r=Qr(),a=ut,n=ua,i=da(),s=ha(),o=$t,l=Ht(),c=fa(),u=pa();return na=function(d){return new Promise((function(h,f){var p,g=d.data,m=d.headers,v=d.responseType;function y(){d.cancelToken&&d.cancelToken.unsubscribe(p),d.signal&&d.signal.removeEventListener("abort",p)}e.isFormData(g)&&e.isStandardBrowserEnv()&&delete m["Content-Type"];var w=new XMLHttpRequest;if(d.auth){var b=d.auth.username||"",S=d.auth.password?unescape(encodeURIComponent(d.auth.password)):"";m.Authorization="Basic "+btoa(b+":"+S)}var E=n(d.baseURL,d.url);function _(){if(w){var e="getAllResponseHeaders"in w?i(w.getAllResponseHeaders()):null,r={data:v&&"text"!==v&&"json"!==v?w.response:w.responseText,status:w.status,statusText:w.statusText,headers:e,config:d,request:w};t((function(e){h(e),y()}),(function(e){f(e),y()}),r),w=null}}if(w.open(d.method.toUpperCase(),a(E,d.params,d.paramsSerializer),!0),w.timeout=d.timeout,"onloadend"in w?w.onloadend=_:w.onreadystatechange=function(){w&&4===w.readyState&&(0!==w.status||w.responseURL&&0===w.responseURL.indexOf("file:"))&&setTimeout(_)},w.onabort=function(){w&&(f(new l("Request aborted",l.ECONNABORTED,d,w)),w=null)},w.onerror=function(){f(new l("Network Error",l.ERR_NETWORK,d,w,w)),w=null},w.ontimeout=function(){var e=d.timeout?"timeout of "+d.timeout+"ms exceeded":"timeout exceeded",t=d.transitional||o;d.timeoutErrorMessage&&(e=d.timeoutErrorMessage),f(new l(e,t.clarifyTimeoutError?l.ETIMEDOUT:l.ECONNABORTED,d,w)),w=null},e.isStandardBrowserEnv()){var A=(d.withCredentials||s(E))&&d.xsrfCookieName?r.read(d.xsrfCookieName):void 0;A&&(m[d.xsrfHeaderName]=A)}"setRequestHeader"in w&&e.forEach(m,(function(e,t){void 0===g&&"content-type"===t.toLowerCase()?delete m[t]:w.setRequestHeader(t,e)})),e.isUndefined(d.withCredentials)||(w.withCredentials=!!d.withCredentials),v&&"json"!==v&&(w.responseType=d.responseType),"function"==typeof d.onDownloadProgress&&w.addEventListener("progress",d.onDownloadProgress),"function"==typeof d.onUploadProgress&&w.upload&&w.upload.addEventListener("progress",d.onUploadProgress),(d.cancelToken||d.signal)&&(p=function(e){w&&(f(!e||e&&e.type?new c:e),w.abort(),w=null)},d.cancelToken&&d.cancelToken.subscribe(p),d.signal&&(d.signal.aborted?p():d.signal.addEventListener("abort",p))),g||(g=null);var F=u(E);F&&-1===["http","https","file"].indexOf(F)?f(new l("Unsupported protocol "+F+":",l.ERR_BAD_REQUEST,d)):w.send(g)}))},na}var ma=ot,va=function(e,t){Mt.forEach(e,(function(r,a){a!==t&&a.toUpperCase()===t.toUpperCase()&&(e[t]=r,delete e[a])}))},ya=Ht(),wa=$t,ba=Vr(),Sa={"Content-Type":"application/x-www-form-urlencoded"};function Ea(e,t){!ma.isUndefined(e)&&ma.isUndefined(e["Content-Type"])&&(e["Content-Type"]=t)}var _a,Aa={transitional:wa,adapter:(("undefined"!=typeof XMLHttpRequest||void 0!==Bt&&"[object process]"===Object.prototype.toString.call(Bt))&&(_a=ga()),_a),transformRequest:[function(e,t){if(va(t,"Accept"),va(t,"Content-Type"),ma.isFormData(e)||ma.isArrayBuffer(e)||ma.isBuffer(e)||ma.isStream(e)||ma.isFile(e)||ma.isBlob(e))return e;if(ma.isArrayBufferView(e))return e.buffer;if(ma.isURLSearchParams(e))return Ea(t,"application/x-www-form-urlencoded;charset=utf-8"),e.toString();var r,a=ma.isObject(e),n=t&&t["Content-Type"];if((r=ma.isFileList(e))||a&&"multipart/form-data"===n){var i=this.env&&this.env.FormData;return ba(r?{"files[]":e}:e,i&&new i)}return a||"application/json"===n?(Ea(t,"application/json"),function(e,t,r){if(ma.isString(e))try{return(t||JSON.parse)(e),ma.trim(e)}catch(e){if("SyntaxError"!==e.name)throw e}return(r||JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){var t=this.transitional||Aa.transitional,r=t&&t.silentJSONParsing,a=t&&t.forcedJSONParsing,n=!r&&"json"===this.responseType;if(n||a&&ma.isString(e)&&e.length)try{return JSON.parse(e)}catch(e){if(n){if("SyntaxError"===e.name)throw ya.from(e,ya.ERR_BAD_RESPONSE,this,null,this.response);throw e}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:oa?sa:(oa=1,sa=null)},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*"}}};ma.forEach(["delete","get","head"],(function(e){Aa.headers[e]={}})),ma.forEach(["post","put","patch"],(function(e){Aa.headers[e]=ma.merge(Sa)}));var Fa,Pa,xa=Aa,Ta=ot,Ra=xa;function Ca(){return Pa?Fa:(Pa=1,Fa=function(e){return!(!e||!e.__CANCEL__)})}var Oa=ot,ka=function(e,t,r){var a=this||Ra;return Ta.forEach(r,(function(r){e=r.call(a,e,t)})),e},Ia=Ca(),La=xa,qa=fa();function Da(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new qa}var Ua,Na,ja=ot,Ba=function(e,t){t=t||{};var r={};function a(e,t){return ja.isPlainObject(e)&&ja.isPlainObject(t)?ja.merge(e,t):ja.isPlainObject(t)?ja.merge({},t):ja.isArray(t)?t.slice():t}function n(r){return ja.isUndefined(t[r])?ja.isUndefined(e[r])?void 0:a(void 0,e[r]):a(e[r],t[r])}function i(e){if(!ja.isUndefined(t[e]))return a(void 0,t[e])}function s(r){return ja.isUndefined(t[r])?ja.isUndefined(e[r])?void 0:a(void 0,e[r]):a(void 0,t[r])}function o(r){return r in t?a(e[r],t[r]):r in e?a(void 0,e[r]):void 0}var l={url:i,method:i,data:i,baseURL:s,transformRequest:s,transformResponse:s,paramsSerializer:s,timeout:s,timeoutMessage:s,withCredentials:s,adapter:s,responseType:s,xsrfCookieName:s,xsrfHeaderName:s,onUploadProgress:s,onDownloadProgress:s,decompress:s,maxContentLength:s,maxBodyLength:s,beforeRedirect:s,transport:s,httpAgent:s,httpsAgent:s,cancelToken:s,socketPath:s,responseEncoding:s,validateStatus:o};return ja.forEach(Object.keys(e).concat(Object.keys(t)),(function(e){var t=l[e]||n,a=t(e);ja.isUndefined(a)&&t!==o||(r[e]=a)})),r};function Ma(){return Na?Ua:(Na=1,Ua={version:"0.27.2"})}var Ha=Ma().version,$a=Ht(),za={};["object","boolean","number","function","string","symbol"].forEach((function(e,t){za[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}}));var Ya={};za.transitional=function(e,t,r){function a(e,t){return"[Axios v"+Ha+"] Transitional option '"+e+"'"+t+(r?". "+r:"")}return function(r,n,i){if(!1===e)throw new $a(a(n," has been removed"+(t?" in "+t:"")),$a.ERR_DEPRECATED);return t&&!Ya[n]&&(Ya[n]=!0,console.warn(a(n," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(r,n,i)}};var Wa,Va,Ga,Qa,Ka,Ja,Xa={assertOptions:function(e,t,r){if("object"!=typeof e)throw new $a("options must be an object",$a.ERR_BAD_OPTION_VALUE);for(var a=Object.keys(e),n=a.length;n-- >0;){var i=a[n],s=t[i];if(s){var o=e[i],l=void 0===o||s(o,i,e);if(!0!==l)throw new $a("option "+i+" must be "+l,$a.ERR_BAD_OPTION_VALUE)}else if(!0!==r)throw new $a("Unknown option "+i,$a.ERR_BAD_OPTION)}},validators:za},Za=ot,en=ut,tn=ft,rn=function(e){return Da(e),e.headers=e.headers||{},e.data=ka.call(e,e.data,e.headers,e.transformRequest),e.headers=Oa.merge(e.headers.common||{},e.headers[e.method]||{},e.headers),Oa.forEach(["delete","get","head","post","put","patch","common"],(function(t){delete e.headers[t]})),(e.adapter||La.adapter)(e).then((function(t){return Da(e),t.data=ka.call(e,t.data,t.headers,e.transformResponse),t}),(function(t){return Ia(t)||(Da(e),t&&t.response&&(t.response.data=ka.call(e,t.response.data,t.response.headers,e.transformResponse))),Promise.reject(t)}))},an=Ba,nn=ua,sn=Xa,on=sn.validators;function ln(e){this.defaults=e,this.interceptors={request:new tn,response:new tn}}ln.prototype.request=function(e,t){"string"==typeof e?(t=t||{}).url=e:t=e||{},(t=an(this.defaults,t)).method?t.method=t.method.toLowerCase():this.defaults.method?t.method=this.defaults.method.toLowerCase():t.method="get";var r=t.transitional;void 0!==r&&sn.assertOptions(r,{silentJSONParsing:on.transitional(on.boolean),forcedJSONParsing:on.transitional(on.boolean),clarifyTimeoutError:on.transitional(on.boolean)},!1);var a=[],n=!0;this.interceptors.request.forEach((function(e){"function"==typeof e.runWhen&&!1===e.runWhen(t)||(n=n&&e.synchronous,a.unshift(e.fulfilled,e.rejected))}));var i,s=[];if(this.interceptors.response.forEach((function(e){s.push(e.fulfilled,e.rejected)})),!n){var o=[rn,void 0];for(Array.prototype.unshift.apply(o,a),o=o.concat(s),i=Promise.resolve(t);o.length;)i=i.then(o.shift(),o.shift());return i}for(var l=t;a.length;){var c=a.shift(),u=a.shift();try{l=c(l)}catch(e){u(e);break}}try{i=rn(l)}catch(e){return Promise.reject(e)}for(;s.length;)i=i.then(s.shift(),s.shift());return i},ln.prototype.getUri=function(e){e=an(this.defaults,e);var t=nn(e.baseURL,e.url);return en(t,e.params,e.paramsSerializer)},Za.forEach(["delete","get","head","options"],(function(e){ln.prototype[e]=function(t,r){return this.request(an(r||{},{method:e,url:t,data:(r||{}).data}))}})),Za.forEach(["post","put","patch"],(function(e){function t(t){return function(r,a,n){return this.request(an(n||{},{method:e,headers:t?{"Content-Type":"multipart/form-data"}:{},url:r,data:a}))}}ln.prototype[e]=t(),ln.prototype[e+"Form"]=t(!0)}));var cn=ot,un=He,dn=ln,hn=Ba;var fn=function e(t){var r=new dn(t),a=un(dn.prototype.request,r);return cn.extend(a,dn.prototype,r),cn.extend(a,r),a.create=function(r){return e(hn(t,r))},a}(xa);fn.Axios=dn,fn.CanceledError=fa(),fn.CancelToken=function(){if(Va)return Wa;Va=1;var e=fa();function t(t){if("function"!=typeof t)throw new TypeError("executor must be a function.");var r;this.promise=new Promise((function(e){r=e}));var a=this;this.promise.then((function(e){if(a._listeners){var t,r=a._listeners.length;for(t=0;t<r;t++)a._listeners[t](e);a._listeners=null}})),this.promise.then=function(e){var t,r=new Promise((function(e){a.subscribe(e),t=e})).then(e);return r.cancel=function(){a.unsubscribe(t)},r},t((function(t){a.reason||(a.reason=new e(t),r(a.reason))}))}return t.prototype.throwIfRequested=function(){if(this.reason)throw this.reason},t.prototype.subscribe=function(e){this.reason?e(this.reason):this._listeners?this._listeners.push(e):this._listeners=[e]},t.prototype.unsubscribe=function(e){if(this._listeners){var t=this._listeners.indexOf(e);-1!==t&&this._listeners.splice(t,1)}},t.source=function(){var e,r=new t((function(t){e=t}));return{token:r,cancel:e}},Wa=t}(),fn.isCancel=Ca(),fn.VERSION=Ma().version,fn.toFormData=Vr(),fn.AxiosError=Ht(),fn.Cancel=fn.CanceledError,fn.all=function(e){return Promise.all(e)},fn.spread=Qa?Ga:(Qa=1,Ga=function(e){return function(t){return e.apply(null,t)}}),fn.isAxiosError=function(){if(Ja)return Ka;Ja=1;var e=ot;return Ka=function(t){return e.isObject(t)&&!0===t.isAxiosError}}(),Me.exports=fn,Me.exports.default=fn;var pn=Me.exports;function gn(e){this.message=e}gn.prototype=new Error,gn.prototype.name="InvalidCharacterError";var mn="undefined"!=typeof window&&window.atob&&window.atob.bind(window)||function(e){var t=String(e).replace(/=+$/,"");if(t.length%4==1)throw new gn("'atob' failed: The string to be decoded is not correctly encoded.");for(var r,a,n=0,i=0,s="";a=t.charAt(i++);~a&&(r=n%4?64*r+a:a,n++%4)?s+=String.fromCharCode(255&r>>(-2*n&6)):0)a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(a);return s};function vn(e){var t=e.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw"Illegal base64url string!"}try{return function(e){return decodeURIComponent(mn(e).replace(/(.)/g,(function(e,t){var r=t.charCodeAt(0).toString(16).toUpperCase();return r.length<2&&(r="0"+r),"%"+r})))}(t)}catch(e){return mn(t)}}function yn(e){this.message=e}yn.prototype=new Error,yn.prototype.name="InvalidTokenError";class wn{constructor(){this.inIframe=salla.helpers.isIframe(),salla.event.on("twilight::before.ready",(e=>this.initiateRequest(e))),salla.event.on("profile::info.fetched",(e=>this.setCurrencyAndLanguage(e))),salla.event.on("auth::token.fetched",(e=>{salla.storage.set("token",e),this.inIframe&&salla.log("token fetched iframe"),this.inIframe&&salla.cookie.set("s-token",e,60),this.setToken(e)})),salla.event.on("auth::token.invalid",(()=>{salla.storage.remove("user"),salla.storage.remove("token")})),this.notifier_handler_disabled=!1,this.axios=pn.create({headers:{common:{"X-Requested-With":"XMLHttpRequest","S-SOURCE":"twilight","S-APP-VERSION":"v2.0.0","S-APP-OS":"browser","cache-control":"no-cache"}}})}getHeaders(){return this.axios.defaults.headers.common}setHeaders(e){return Object.entries(e).forEach((e=>this.setHeader(e[0],e[1]))),this}setHeader(e,t){return salla.infiniteScroll.fetchOptions.headers[e]=this.axios.defaults.headers.common[e]=t,this}async withoutNotifier(e){return this.notifier_handler_disabled=!0,await e().finally((()=>{this.notifier_handler_disabled=!1}))}async initiateRequest(e){this.axios.defaults.baseURL=Salla.config.get("store.api",Salla.config.get("store.url")),this.setHeaders({"Store-Identifier":Salla.config.get("store.id"),currency:e.user?.currency_code||"SAR","accept-language":salla.lang.getLocale(),"s-user-id":e.user?.id,...e.headers||{}});const t=salla.storage.get("scope");t&&this.setHeaders({"s-scope-type":t.type,"s-scope-id":t.id});const r=salla.storage.session.get("s-utms");r&&this.setHeaders(r),await this.injectTokenToTheRequests(e),salla.storage.get("affiliate_code")&&this.setHeader("s-affiliate-code",salla.storage.get("affiliate_code"))}async injectTokenToTheRequests(e){let t=salla.storage.get("token"),r="guest"===e.user.type,a=e.user?.id,n=salla.storage.get("user.id"),i=e=>{this.setToken(e),salla.event.emit("api::initiated")},s=async()=>{!r&&a?(salla.log("Api:: case 1 => current is is guest & web session available"),await salla.auth.api.refresh().then((async()=>{await salla.profile.info()})).catch((()=>salla.auth.event.tokenInvalid()))):salla.auth.event.tokenInvalid()};if(!t)return salla.log("Api:: case 1 => current is is guest"),void await s();let o=function(e,t){if("string"!=typeof e)throw new yn("Invalid token specified");var r=!0===(t=t||{}).header?0:1;try{return JSON.parse(vn(e.split(".")[r]))}catch(e){throw new yn("Invalid token specified: "+e.message)}}(t);return Date.now()/1e3>o.exp?(salla.log("Api:: case 2 => current user is logged-in and there is a token, but it's expired"),void await s()):o.sub===a&&n===a&&n&&a?(salla.log("Api:: case 4 => current user is logged-in and there is a token, and it's not expired"),void i(t)):(salla.log("Api:: case 3 => there is a token and user in session/local missing or mismatch"),salla.log(`sub:${o.sub} userIdInWeb:${a} userIdInStorage:${n}`),this.setHeader("Authorization","Bearer "+t),void await salla.profile.info().then((async e=>{!this.inIframe&&await salla.auth.api.request("auth/jwt",{callerName:"salla.auth.request.injectTokenToTheRequests"}),i(t)})).catch((()=>{salla.log("Api:: case 3 => failed get fresh profile"),this.setHeader("Authorization",null),salla.auth.event.tokenInvalid()})))}setToken(e){return this.setHeader("Authorization","Bearer "+e),salla.event.emit("api::token.injected",e),this.token=e,this}setCurrencyAndLanguage(e){return this.setHeaders({currency:e.data.currency,"accept-language":e.data.language})}request(e,t=void 0,r="get",a={}){let n={endPoint:e,payload:t,method:r,options:a},i="undefined"!=typeof event?event.currentTarget:null,s=!1;return"SALLA-BUTTON"===i?.tagName&&(s=!0),s&&i?.load(),this.axios[n.method](n.endPoint,n.payload,n.options).then((e=>(s&&i?.stop(),e.data&&e.request&&(e=e.data),this.handleAfterResponseActions(e),e))).catch((e=>{throw s&&i?.stop(),salla.event.document.requestFailed(n,e),this.handleErrorResponse(e),e}))}handleAfterResponseActions(e){if(!e)return;let{data:t,googleTags:r=null}=e,a=t&&t.googleTags?t.googleTags:r;try{dataLayer&&a&&dataLayer.push(a)}catch(e){salla.logger.error(e.message)}this.fireEventsForResponse(e),this.showAlert(e)}fireEventsForResponse(e){let t=e?.events||e.data?.events||e.error?.events;"string"==typeof t&&(t=JSON.parse(t)),t&&Object.keys(t).forEach((e=>salla.event.dispatch(e,t[e])))}handleErrorResponse(e){if(e.response&&e.response.data)return e.response.data.error&&e.response.data.error.fields&&!this.notifier_handler_disabled?this.handleInvalidFields(e):this.handleAfterResponseActions(e.response.data)}showAlert(e){if(e&&!this.notifier_handler_disabled)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 t=e.response.data.error.fields,r=[];Object.keys(t).forEach((e=>{let a=t[e];Array.isArray(a)?a.forEach((e=>r.push(e))):r.push(a)}));let a=(r.length>1?"* ":"")+r.join("\n* ");salla.error(a,e)}isFastRequestsAllowed(){return Salla.config.get("fastRequests")}promise(e,t=!0){return new Promise(((r,a)=>t?r(e):a(e)))}errorPromise(e){return this.promise(e,!1)}successPromise(e){return this.promise(e,!0)}}class bn extends Ae{constructor(){super(),this.namespace="component",this.endpoints={getMenus:"menus/{headOrFoot}",reviews:"reviews"},this.endpointsMethods={getMenus:"get",reviews:"get"}}async getMenus(e="header"){return this.request(["getMenus",e]).then((function(e){return salla.event.component.menuFetched(e),e})).catch((function(e){throw salla.event.component.menuFetchFailed(e),e}))}async getReviews({per_page:e=5,type:t="all",items:r}){if(!t){const e="Review type cannot be empty. Please provide one.";return salla.event.component.reviewsFetchFailed(e),salla.api.errorPromise(e)}const a=!r||"string"==typeof r&&"[]"===r||Array.isArray(r)&&!r.length;if(!new Set(["all","store","categories","products","json"]).has(t)){const e="Invalid review type. Please provide a valid type.";return salla.event.component.reviewsFetchFailed(e),salla.api.errorPromise(e)}if("all"!==t&&"store"!==t&&a){const e="Items cannot be empty. Please provide one.";return salla.event.component.reviewsFetchFailed(e),salla.api.errorPromise(e)}if(new Set(["products","categories"]).has(t)&&!Array.isArray(r)){const e=`Items value must be an array of ${t} id for review type of ${t}.`;return salla.event.component.reviewsFetchFailed(e),salla.api.errorPromise(e)}return this.request(["reviews"],{params:{per_page:e,type:t,items:r}},"get").then((function(e){return salla.event.component.reviewsFetched(e),e})).catch((function(e){throw salla.event.component.reviewsFetchFailed(e),e}))}}class Sn extends Ae{constructor(){super(),this.namespace="booking",this.endpoints={fetch:"advertisements"},this.endpointsMethods={fetch:"get"}}async fetch(e=null){const t=e?{page:e}:{};return this.request(["fetch"],{params:t}).then((function(e){return salla.event.advertisement.fetched(e),e})).catch((function(e){throw salla.event.advertisement.fetchFailed(e),e}))}}class En extends Ae{constructor(){super(),this.namespace="navigation",this.endpoints={breadcrumbs:"breadcrumbs"},this.endpointsMethods={breadcrumbs:"get"},this.after_init()}fetchBreadcrumbs(e){if(!e.page){let e="The 'page' parameter is required for the Breadcrumb API. Please provide a valid 'page' parameter.";return salla.event.navigation.breadcrumbFetchFailed(e),salla.api.errorPromise(e)}if(["product.single","product.index","customer.orders.single","product.index.tag","page-single","landing-page","brands.single","blog.single","blog.index.author","blog.index.category","blog.index.tag"].includes(e.page)&&!e.id){let t=`The 'id' parameter is required when the 'page' parameter is set to ${e.page}. Please provide valid value for the 'ID' parameter.`;return salla.event.navigation.breadcrumbFetchFailed(t),salla.api.errorPromise(t)}return this.request("breadcrumbs",{params:e}).then((function(e){return salla.event.navigation.breadcrumbFetched(e),e})).catch((function(e){throw salla.event.navigation.breadcrumbFetchFailed(e),e}))}}class _n{constructor(e){"ready"!==Y.status?e?(Y.config.merge(e),e?.events&&Y.event.dispatchEvents(e?.events),e._token&&salla.api.setHeader("X-CSRF-TOKEN",e._token),this.injectMaintenanceAlert(),this.injectTemplateStoreAlert(),this.injectThemePreviewAlert(),this.injectAppInstallAlert(),this.injectEditAlert(),e?.user?.language_code&&salla.lang.setLocale(e?.user?.language_code),salla.lang.loadStoreTranslations(),this.setSallaReady(e)):this.setSallaReady(e):salla.log("Trying to re-initiate Salla, while its status === 'ready'!")}injectMaintenanceAlert(){salla.config.get("maintenance")&&(document.body.classList.add("has-maintenance-bar"),document.querySelector("salla-maintenance-alert")?salla.logger.warn("salla-maintenance-alert element Existed before!"):salla.lang.onLoaded((()=>document.body.prepend(document.createElement("salla-maintenance-alert")))))}injectTemplateStoreAlert(){salla.config.get("store.template")&&(document.body.classList.add("has-bottom-alert"),document.querySelector("salla-bottom-alert")?salla.logger.warn("salla-bottom-alert element Existed before!"):salla.lang.onLoaded((()=>document.body.append(document.createElement("salla-bottom-alert")))))}injectAppInstallAlert(){salla.config.get("store.app_install_prompt")&&salla.config.get("store.apps")&&!salla.storage.get("app_install_prompt_disabled")&&(document.body.classList.add("has-app-install-alert"),document.querySelector("salla-app-install-alert")?salla.logger.warn("salla-app-install-alert element Existed before!"):salla.lang.onLoaded((()=>document.body.append(document.createElement("salla-app-install-alert")))))}injectThemePreviewAlert(){"preview"===salla.config.get("theme.mode")&&(document.body.classList.add("has-preview-bar"),document.querySelector("#s-theme_preview_bar")?salla.logger.warn("#s-theme_preview_bar element 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=`\n <div style="display:flex; align-items:center;">\n <img width="32" src="https://cdn.salla.network/images/logo/logo-light.svg">\n <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>\n </div>\n <a href="${salla.url.get("preview_theme/cancel/preview")}" style="line-height:32px; width:32px;"><i class="sicon-cancel"></i></a>\n `,document.body.prepend(e)})))}injectEditAlert(){let e=salla.config.get("edit");e&&(document.querySelector("#s-edit-alert")?salla.logger.warn("#s-edit-alert element Existed before!"):salla.lang.onLoaded((()=>{let t=document.createElement("div");t.id="s-edit-alert",t.innerHTML=`\n <a href="${e}" style="display:block; background-color:${salla.config.get("theme.color.primary","#5cd5c4")}; color:${salla.config.get("theme.color.reverse","#fff")}; padding: 10px; text-align:center; font-size: 0.875rem; line-height: 1.25rem;">\n <i class="sicon-edit"></i> \n ${salla.lang.get("pages.products.quick_edit")}\n </a>\n `,document.body.prepend(t)})))}handleElementAjaxRequest(e,t){if(!(t instanceof HTMLFormElement||t instanceof HTMLAnchorElement))return salla.logger.warn("trying to call ajax from non Element!!"),!1;e.preventDefault();let r=t.getAjaxFormData(e),a=r.method?r.method.toLowerCase():void 0;salla.api.request(r.url,r.formData,a).then((e=>(e.data&&e.request&&(e=e.data),salla.api.handleAfterResponseActions(e),this.callAjaxEvent(r.events.success,e,r.formData),e))).catch((e=>{throw salla.api.handleErrorResponse(e),this.callAjaxEvent(r.events.fail,e,r.formData),e}))}callAjaxEvent(e,t,r){if(e){if(r instanceof FormData){const e={};Array.from(r.entries()).forEach((function(t){e[t[0]]=t[1]})),r=e}window[e]?window[e](t,r):salla.event.dispatch(e,t,r)}}setSallaReady(e){Y.event.dispatch("twilight::before.ready",e),Y.status="ready",Y.event.dispatch("twilight::initiated",e),window.dispatchEvent(new CustomEvent("twilight::initiated",{detail:e}))}storeUTMs(){const e={fbclid:"facebook",gad_source:"google",ttclid:"tiktok",twclid:"twitter",scid:"snapchat"},t=["fbclid","gad_source","ttclid","twclid","scid"],r=["utm_source","utm_medium","utm_campaign","utm_term","utm_content",...t],a={},n={};window.location.search.replace("?","").split("&").map((e=>e.split("="))).filter((([e])=>r.includes(e.toLowerCase()))).forEach((([e,t])=>a[e.toLowerCase()]=t));const i=t.some((e=>a[e]));!a.utm_source&&i&&(a.utm_source=e[i],a.utm_campaign=a.utm_campaign||`Using the CLICKID ${i} provided by ${a.utm_source}`,a.utm_term=a.utm_term||`${i}: ${a[i]}`),a.utm_source&&(Object.entries(a).filter((([e])=>!t.includes(e))).forEach((([e,t])=>n[`s-${e.replace("_","-")}`]=t)),salla.storage.session.set("s-utms",n))}}return Y.status="loading",Y.notify=Q,Y.lang=new class extends _e{constructor(e){(e=e||{}).messages=e.messages||window.translations,e.locale=e.locale||(window.locale||navigator.language||navigator.userLanguage||"ar").split("-")[0],e.fallback=e.fallback||e.locale,super(e),this.translationsLoaded=!1}onLoaded(e){return new Promise((t=>{if(this.translationsLoaded)return t(e?e():null);Salla.event.once("languages::translations.loaded",(()=>t(e?e():null)))}))}loadStoreTranslations(){if(this.hash=salla.config.get("theme.translations_hash",salla.config.get("store.id","twilight")),this.message||(salla.log("try to load translations from localstorage"),this.messages=salla.storage.get(`s_translations.${this.hash}`),this.messages&&(this.translationsLoaded=!0)&&super.setMessages(this.messages)),this.messages)return salla.event.dispatch("languages::translations.loaded"),void salla.logger.info("The messages of transactions is already loaded");salla.url.get("")?this.loadScript(salla.url.get(`languages/assets/${this.hash}.js`)):this.loadScript("https://cdn.salla.network/js/translations.js",!1)}setMessages(e){super.setMessages(e),salla.event.dispatch("languages::translations.loaded"),this.translationsLoaded=!0}loadScript(e,t=!0){let r=document.createElement("script");r.src=e,r.onload=()=>{if(window.translations)return salla.storage.remove("s_translations"),salla.storage.set("s_translations",{[this.hash]:window.translations}),this.setMessages(window.translations);r.onerror()},r.onerror=()=>{if(t)return salla.logger.warn("Failed to load Translations for store, lets try load it from CDN"),this.loadScript("https://cdn.salla.network/js/translations.js",!1);salla.logger.error("Failed to load Translations, check your network logs for more details\nor: salla.lang.setMessages({....}), see https://docs.salla.dev for more information's.")},document.head.appendChild(r)}getWithDefault(e,t,r,a){let n=this.get(e,r,a);return n!==e?n:t}get(e,t,r){let a=e;(window.translations||this.translationsLoaded)&&(a="trans."+e);let n=super.get(a,t,r);return n!==a?n:super.get(a,t,"en").replace(a,e)}set(e,t){return salla.helpers.setNested(this.messages[`${this.getLocale()}.trans`],e,t),this}add(e,t){return Object.entries(t).forEach((t=>salla.helpers.setNested(this.messages[t[0]+".trans"],e,t[1]))),this}addBulk(e){return Object.entries(e).forEach((([e,t])=>{this.add(e,t)})),this}},Y.form=new class{async submit(e,t=null){let r=t;if("SubmitEvent"===t?.constructor?.name||"submit"===t?.type){if(t.preventDefault(),"FORM"!==t.target?.tagName)return Salla.logger.warn("Failed find the target element for submit action. make sure you submit a form element"),new Promise((()=>{throw"Failed find the target element for submit action. make sure you submit a form element"}));"SALLA-BUTTON"===t?.submitter?.parentElement?.tagName&&t.submitter.parentElement.load(),r=t.target.getElementSallaData(),salla.log("Data from element",r)}if(/^https?:\/\/(?:www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)$/gm.test(e))return salla.api.request(e,r,"post").finally((()=>{loaderSupported&&t?.submitter?.parentElement.stop()}));let a=e.split("."),n=a.splice(-1);return await salla.call(a.join("."))[n](r).finally((()=>t?.submitter?.parentElement?.stop())).catch((e=>{throw salla.logger.warn(e),e}))}onSubmit(e,t){return salla.form.submit(e,t),!1}onChange(e,t){return t?.currentTarget?"FORM"!==t?.currentTarget?.tagName||t.currentTarget.checkValidity()?(salla.form.submit(e,t.currentTarget.getElementSallaData()),!0):(salla.logger.warn(`Trying to trigger '${e}' without filling required fields!`),!1):(salla.logger.warn(`Trying to trigger '${e}' without event!`),!1)}getPossibleValue(e,t,r=!1){if(!e)return;if("object"!=typeof e)return e;let a;for(let r=0;r<t.length&&!(a=e[t[r]])&&!("undefined"!=typeof FormData&&e instanceof FormData&&(a=e.get(t[r])));r++);return a=a||e,"object"!=typeof a||r?a:void 0}},Y.infiniteScroll=new class extends K{constructor(e,t){super(e,t),this.options={path:".infinite-scroll-btn",history:"push",status:".infinite-scroll-status",append:".list-block"},this.fetchOptions={headers:{"S-INFINITE-SCROLL":!0,"S-Source":"twilight","cache-control":"no-cache",pragma:"no-cache"}},this.instances=[]}initiate(e,t,r,a=!1){a?((r=r||{}).fetchOptions={...this.fetchOptions,...r.fetchOptions||{}},r.responseBody="json"):r=this.getCustomOptions(t,r);let n="string"!=typeof e?e:document.querySelector(e),i=r.path;if(!n||!i||"string"==typeof i&&!document.querySelector(i))return void Salla.logger.warn(n?"Path Option (a link that has next page link) Not Existed!":"Container For InfiniteScroll not Existed!");let s=new Se(n,r);return s.on("scrollThreshold",Salla.infiniteScroll.event.scrollThreshold),s.on("request",Salla.infiniteScroll.event.request),s.on("load",Salla.infiniteScroll.event.load),s.on("append",Salla.infiniteScroll.event.append),s.on("error",Salla.infiniteScroll.event.error),s.on("last",Salla.infiniteScroll.event.last),s.on("history",Salla.infiniteScroll.event.history),this.instances.push(s),s}getCustomOptions(e,t){return(t="object"==typeof e&&e||t||this.options).fetchOptions=this.fetchOptions,t.path=t.path||this.options.path,t.button=t.button||t.path,t.status=t.status||this.options.status,t.hasOwnProperty("history")||(t.history=this.options.history),t.nextPage=t.nextPage||t.next_page,t.append="string"==typeof e&&e||t.append||this.options.append,t}loadNextPage(e){("string"!=typeof e?e:document.querySelector(e)).loadNextPage()}destroy(e){("string"!=typeof e?e:document.querySelector(e)).destroy()}}(void 0,salla.event.infiniteScroll),Y.api=new class extends wn{constructor(){super(),this.auth=new xe,this.cart=new Fe,this.loyalty=new Pe,this.order=new Te,this.rating=new Le,this.product=new Re,this.profile=new Ce,this.comment=new Oe,this.currency=new ke,this.document=new Ie,this.wishlist=new qe,this.scope=new De,this.booking=new Ue,this.landing=new Ne,this.notifications=new je,this.component=new bn,this.advertisement=new Sn,this.navigation=new En}},["cart","auth","order","scope","rating","comment","loyalty","product","profile","currency","document","wishlist","booking","landing"].forEach((e=>Y[e]=new K(Y.api[e],Y.event[e]))),Y.call=e=>{let t=Y,r=e.split(".");for(;r.length&&(t=t[r.shift()]););return t},Y.init=e=>new _n(e),salla.event.once("twilight::init",salla.init),salla.event.once("twilight::api",(e=>{let t=e?.events;t&&salla.event.dispatchEvents(t)})),Y.success=Y.notify.success,Y.error=Y.notify.error,Y.versions.twilight="2.15.0-alpha.0",Y.onInitiated=e=>salla.event.once("twilight::initiated",e),Y.onReady=Y.onReady||function(e){return new Promise((function(t){return"ready"===salla.status?t(e?e(salla.config.all()):salla.config.all()):Y.onInitiated((r=>t(e?e(r):r)))}))},window.dispatchEvent(new CustomEvent("salla::created")),Y}));
|
|
20
20
|
//# sourceMappingURL=twilight.min.js.map
|