@salla.sa/twilight 2.14.306 → 2.14.308
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.
- package/dist/@salla.sa/twilight.min.js +1 -1
- package/dist/cjs/index.js +1 -1
- package/dist/esm/index.js +1 -1
- package/package.json +3 -3
package/dist/cjs/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var e=require("@salla.sa/base"),t=require("infinite-scroll"),a=require("lang.js"),n=require("axios"),r=require("jwt-decode"),i=require("@jitsu/js"),o=function(e,t,a){return alert(e)},s=function(e,t){return o(e,l.error,t)},l={error:"error",success:"success",info:"info"},c={fire:function(e,t,a){return o(e,t,a)},setNotifier:function(e){o=e,salla.event.emit("twilight::notifier.changed")},error:s,success:function(e,t){return o(e,l.success,t)},info:function(e,t){return o(e,l.info,t)},sallaInitiated:function(){var e=window.location.href.match(/([\?\&]danger=)[^&]+/g);e&&(window.history.replaceState(null,document.title,window.location.pathname),salla.event.once("twilight::notifier.changed",(function(){e.forEach((function(e){e=decodeURI(e.replace("?danger=","").replace("&danger=",""));var t=document.createElement("div");t.innerText=e,s(t.innerHTML),salla.event.emit("twilight::error",e)}))})))},types:l},u=function(e,t){return this.api=e,this.event=t,new Proxy(this,{get:function(a,n){return"event"===n?t:"api"===n?e:e&&e[n]||a[n]}})};function d(e,t){(null==t||t>e.length)&&(t=e.length);for(var a=0,n=Array(t);a<t;a++)n[a]=e[a];return n}function p(e,t,a){if(v())return Reflect.construct.apply(null,arguments);var n=[null];return n.push.apply(n,t),new(e.bind.apply(e,n))}function h(e,t){var a="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(a)return(a=a.call(e)).next.bind(a);if(Array.isArray(e)||(a=function(e,t){if(e){if("string"==typeof e)return d(e,t);var a={}.toString.call(e).slice(8,-1);return"Object"===a&&e.constructor&&(a=e.constructor.name),"Map"===a||"Set"===a?Array.from(e):"Arguments"===a||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(a)?d(e,t):void 0}}(e))||t){a&&(e=a);var n=0;return function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function f(){return f=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var a=arguments[t];for(var n in a)({}).hasOwnProperty.call(a,n)&&(e[n]=a[n])}return e},f.apply(null,arguments)}function g(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,m(e,t)}function v(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(v=function(){return!!e})()}function m(e,t){return m=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},m(e,t)}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){if(this.getAttribute){if(this.hasAttribute("data-json"))try{return JSON.parse(this.getAttribute("data-json"))}catch(e){}var t=this.getAttribute("data-function");if(t&&window[t]){if("function"==typeof window[t]){for(var a,n=arguments.length,r=new Array(n>1?n-1:0),i=1;i<n;i++)r[i-1]=arguments[i];return this.getFilteredData((a=window[t]).call.apply(a,[this].concat(r)))}return this.getFilteredData(window[t])}var o=this.hasAttribute("data-form-selector")?document.querySelector(this.dataset.formSelector):void 0;if((o="FORM"===this.tagName?this:o||this.closest("form")||this.closest("[salla-form-data]")||this)&&"FORM"===o.tagName)return this.getFilteredData(new FormData(o),null,o);var s=o.querySelectorAll("[name]");if(!s.length)return this.getFilteredData();var l=Object.assign({},this.dataset);return s.forEach((function(e){if(!["checkbox","radio"].includes(e.type)||e.checked)try{var t=Salla.helpers.inputData(e.name,e.value,l);l[t.name]=t.value}catch(t){Salla.log(e.name+" can't be send")}})),this.getFilteredData(l)}},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 a=0;a<this.attributes.length;a++){var n=this.attributes[a].name.toLowerCase();if(0===n.indexOf(e))return!t||n}return!1},HTMLFormElement.prototype.getAjaxFormData=function(e){var t=this.querySelectorAll('input[type="file"]');t.forEach((function(e){e.files.length||e.setAttribute("disabled","")}));var a=new FormData(this);return t.forEach((function(e){e.files.length||e.removeAttribute("disabled")})),{formData:this.getFilteredData(a,e),url:this.getAttribute("action"),method:this.getAttribute("method")||"post",events:{success:this.dataset.onSuccess,fail:this.dataset.onFail}}},Element.prototype.getFilteredData=function(e,t,a){var n,r=this;return void 0===e&&(e=null),void 0===t&&(t=null),void 0===a&&(a=null),e=e||(null==(n=a)?void 0:n.dataset)||this.dataset,a&&this.name&&void 0!==this.value&&(e=function(e,t,a){e instanceof FormData?e.append(t,a):e[t]=a;return e}(e,this.name,this.value)),["filterBeforeSubmit","filterBeforeSend"].forEach((function(n){var i,o=(null==(i=a)?void 0:i.dataset[n])||r.dataset[n];if(o){var s=window[o];if("function"==typeof s){if(!s(e,a||r,t)&&e)throw"Data failed to be pass verify function window."+o+"(formData, element, event)!";return s(e,a||r,t)}Salla.log("window."+o+"() 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}}};var y=function(){function e(){this.events={},this.namespace="";var e=/function (.{1,})\(/.exec(this.constructor.toString());this.className=(e&&e.length>1?e[1]:"").toLowerCase()}var t=e.prototype;return t.after_init=function(){this.createDynamicFunctions()},t.createDynamicFunctions=function(){var e=this;Object.keys(this.events).forEach((function(t){e.createDynamicEventFuns(t),e.createDynamicListenerFuns(t)}))},t.createDynamicEventFuns=function(e){if(!this[e]){var t=this;this[e]=function(){for(var a=arguments.length,n=new Array(a),r=0;r<a;r++)n[r]=arguments[r];return t.dispatch.apply(t,[e].concat(n))}}},t.createDynamicListenerFuns=function(e){var t="on"+e.charAt(0).toUpperCase()+e.slice(1);if(!this[t]){var a=this;this[t]=function(t){return a.on(e,(async function(){return t.apply(void 0,arguments)}))}}},t.getEventName=function(e){return e=this.events[e]||e||"unknown-event",!this.namespace||e.includes("::")?e:this.namespace+Salla.event.delimiter+e},t.dispatch=function(e){for(var t,a=arguments.length,n=new Array(a>1?a-1:0),r=1;r<a;r++)n[r-1]=arguments[r];return(t=Salla.event).emitAsync.apply(t,[this.getEventName(e)].concat(n))},t.on=function(e,t,a){return void 0===a&&(a={}),Salla.event.addListener(this.getEventName(e),t,a)},t.once=function(e,t){return Salla.event.once(this.getEventName(e),t)},e}(),w=function(e){function t(){var t;return(t=e.call(this)||this).namespace="auth",t.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"},t.after_init(),t}g(t,e);var a=t.prototype;return a.login=function(e){return e?(e.type&&this.setTypeActionOnVerified(e.type),this.next_event=e.next_event||null,this.dispatch.apply(this,["login"].concat(Array.prototype.slice.call(arguments)))):(this.next_event=null,this.dispatch.apply(this,["login"].concat(Array.prototype.slice.call(arguments))))},a.loggedIn=async function(e){var t=this;return Salla.profile.info().finally((function(){return t.dispatch("loggedIn",e)}))},a.setTypeActionOnVerified=function(e){this.type_action_on_verified=e},a.getTypeActionOnVerified=function(){return this.type_action_on_verified||"redirect"},t}(y),S=function(e){function t(){var t;return(t=e.call(this)||this).namespace="cart",t.events={latestFetched:"latest.fetched",latestFailed:"latest.failed",updated:"updated",itemUpdated:"item.updated",itemUpdatedFailed:"item.updated.failed",itemAdded:"item.added",beforeAddItem:"before.add.item",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",beforeStartFastCheckout:"before.start.fast-checkout",submitting:"submitting"},t.after_init(),t}g(t,e);var a=t.prototype;return a.updated=function(e){var t;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,tax_amount:e.cart.tax_amount,total_discount:e.cart.total_discount,real_shipping_cost:e.cart.real_shipping_cost,count:e.cart.count,shipping_cost:null!=(t=e.cart.free_shipping_bar)&&t.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"))},a.latestFetched=function(e){return this.updated(e.data),this.dispatch("latestFetched",e)},a.itemAdded=function(e,t){return this.updated(e.data),this.dispatch("itemAdded",e,t)},a.itemDeleted=function(e,t){return this.updated(e.data),this.dispatch("itemDeleted",e,t)},a.itemUpdated=function(e,t){return this.updated(e.data),this.dispatch("itemUpdated",e,t)},a.couponAdded=function(e,t){return this.updated(e.data),this.dispatch("couponAdded",e,t)},a.couponDeleted=function(e,t){return this.updated(e.data),this.dispatch("couponDeleted",e,t)},t}(y),b=function(e){function t(){var t;return(t=e.call(this)||this).namespace="order",t.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"},t.after_init(),t}return g(t,e),t}(y),_=function(e){function t(){var t;return(t=e.call(this)||this).namespace="scope",t.events={fetched:"fetched",notFetched:"not.fetched",productAvailabilityFetched:"product-availability.fetched",productAvailabilityNotFetched:"product-availability.not.fetched",changeSucceeded:"changed",changeFailed:"not.changed"},t.after_init(),t}return g(t,e),t}(y),F=function(e){function t(){var t;return(t=e.call(this)||this).namespace="rating",t.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"},t.after_init(),t}return g(t,e),t}(y),C=function(e){function t(){var t;return(t=e.call(this)||this).namespace="comment",t.events={added:"added",additionFailed:"addition.failed",fetched:"fetched",fetchFailed:"fetch.failed"},t.after_init(),t}return g(t,e),t}(y),k=function(e){function t(){var t;return(t=e.call(this)||this).namespace="loyalty",t.events={exchangeSucceeded:"exchange.succeeded",exchangeFailed:"exchange.failed",programFetched:"program.fetched",programNotFetched:"program.not.fetched",resetSucceeded:"exchange-reset.succeeded",resetFailed:"exchange-reset.failed"},t.after_init(),t}g(t,e);var a=t.prototype;return a.exchangeSucceeded=function(e,t){return salla.cart.event.updated(e.data),this.dispatch("exchangeSucceeded",e,t)},a.resetSucceeded=function(e){return salla.cart.event.updated(e.data),this.dispatch("resetSucceeded",e)},t}(y),P=function(e){function t(){var t;return(t=e.call(this)||this).namespace="profile",t.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"},t.after_init(),t}return g(t,e),t}(y),A=function(e){function t(){var t;return(t=e.call(this)||this).namespace="product",t.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"},t.after_init(),t}return g(t,e),t}(y),q=function(e){function t(){var t;return(t=e.call(this)||this).namespace="document",t.events={click:"click",change:"change",submit:"submit",keyup:"keyup",leaving:"leaving",request:"request",requestFailed:"request.failed"},t.after_init(),t}g(t,e);var a=t.prototype;return a.onClick=function(e,t){this.fireCallableFuns("click",e,t)},a.onChange=function(e,t){this.fireCallableFuns("change",e,t)},a.onSubmit=function(e,t){this.fireCallableFuns("submit",e,t)},a.onKeyup=function(e,t){this.fireCallableFuns("keyup",e,t)},a.fireCallableFuns=function(e,t,a){this.on(e,(function(e){"function"!=typeof t?"function"==typeof a&&e.target.matches(t)&&a(e):t(e)}))},a.fireEvent=function(e,t){for(var a=arguments.length,n=new Array(a>2?a-2:0),r=2;r<a;r++)n[r-2]=arguments[r];return this.fireEventForElements.apply(this,[e,t,!1].concat(n))},a.fireEventForAll=function(e,t){for(var a=arguments.length,n=new Array(a>2?a-2:0),r=2;r<a;r++)n[r-2]=arguments[r];return this.fireEventForElements.apply(this,[e,t,!0].concat(n))},a.fireEventForElements=function(e,t,a){for(var n=this,r=arguments.length,i=new Array(r>3?r-3:0),o=3;o<r;o++)i[o-3]=arguments[o];if("string"==typeof e){if(a)return document.querySelectorAll(e).forEach((function(e){return n.fireEventForElements.apply(n,[e,t,!1].concat(i))}));e=document.querySelector(e)}if(e){var s=p(CustomEvent,[t].concat(i));return e.dispatchEvent(s)}salla.log("Failed To get element to fire event: "+t)},t}(y),E=function(e){function t(){var t;return(t=e.call(this)||this).namespace="wishlist",t.events={added:"added",removed:"removed",additionFailed:"addition.failed",removingFailed:"removing.failed"},t.after_init(),t}return g(t,e),t}(y),I=function(e){function t(){var t;return(t=e.call(this)||this).namespace="currency",t.events={changed:"changed",failed:"failed",fetched:"fetched",failedToFetch:"failed.to.fetch"},t.after_init(),t}return g(t,e),t}(y),x=function(e){function t(){var t;return(t=e.call(this)||this).namespace="infiniteScroll",t.events={scrollThreshold:"scroll.threshold",request:"request",load:"load",append:"append",error:"error",last:"last",history:"history"},t.after_init(),t}return g(t,e),t}(y),T=function(e){function t(){var t;return(t=e.call(this)||this).namespace="booking",t.events={added:"added",additionFailed:"addition.failed"},t.after_init(),t}return g(t,e),t}(y),L=function(e){function t(){var t;return(t=e.call(this)||this).namespace="landing",t.events={detailsFetched:"order.fetched",getDetailsFailed:"get.details.failed",orderCreated:"order.created",orderCreationFailed:"order.creation.failed",breadcrumbFetched:"breadcrumb.fetched",breadcrumbFetchFailed:"breadcrumb.fetch.failed"},t.after_init(),t}return g(t,e),t}(y),R=function(e){function t(){var t;return(t=e.call(this)||this).namespace="notifications",t.events={fetched:"fetched",fetchFailed:"fetch.failed"},t.after_init(),t}return g(t,e),t}(y),O=function(e){function t(){var t;return(t=e.call(this)||this).namespace="component",t.events={menuFetched:"menus.fetched",menuFetchFailed:"menus.fetch.failed",reviewsFetched:"reviews.fetched",reviewsFetchFailed:"reviews.fetch.failed"},t.after_init(),t}return g(t,e),t}(y),j=function(e){function t(){var t;return(t=e.call(this)||this).namespace="advertisement",t.events={fetched:"advertisement.fetched",fetchFailed:"advertisement.not.fetched"},t.after_init(),t}return g(t,e),t}(y),D=function(e){function t(){var t;return(t=e.call(this)||this).namespace="navigation",t.events={breadcrumbFetched:"breadcrumb.fetched",breadcrumbFetchFailed:"breadcrumb.fetch.failed"},t.after_init(),t}return g(t,e),t}(y),U=function(e){function t(){var t;return(t=e.call(this)||this).namespace="metadata",t.events={valueFetched:"value.fetched",valueNotFetch:"value.not.fetched"},t.after_init(),t}return g(t,e),t}(y);function N(e){e&&e.sallaInitiated&&!e.initiated&&(e.sallaInitiated(),e.initiated=!0)}Salla.event.auth=new w,Salla.event.cart=new S,Salla.event.order=new b,Salla.event.scope=new _,Salla.event.rating=new F,Salla.event.booking=new T,Salla.event.comment=new C,Salla.event.landing=new L,Salla.event.loyalty=new k,Salla.event.product=new A,Salla.event.profile=new P,Salla.event.currency=new I,Salla.event.document=new q,Salla.event.wishlist=new E,Salla.event.infiniteScroll=new x,Salla.event.notifications=new R,Salla.event.component=new O,Salla.event.advertisement=new j,Salla.event.navigation=new D,Salla.event.metadata=new U,Salla.event.on("twilight::initiated",(function(){Object.keys(Salla).forEach((function(e){"object"==typeof(e=Salla[e])&&(N(e),Object.keys(e).forEach((function(t){N(e[t])})))}))})),Salla.config.default_properties={debug:"undefined"!=typeof process&&"development"===process.env.NODE_ENV,token:null,fastRequests:!0,canLeave:!0,store:{api:["group","test"].includes(window.location.hostname.split(".").pop())?window.location.origin+"/api/v1/":"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=function(){return"user"===Salla.config.get("user.type")},Salla.config.isGuest=function(){return!Salla.config.isUser()},Salla.config.languages=async function(){var e;if(Salla.config.triedToGetLanguages_)return Salla.config.get("languages");Salla.config.triedToGetLanguages_=!0;var t=!0,a=[];return null==(e=await salla.document.api.request("languages",null,"get"))||null==(e=e.data)||e.map((function(e){t&&(a=[],t=!1),e.code=e.code||e.iso_code,e.url=salla.url.get(e.code),e.is_rtl=e.is_rtl||e.rtl,a.push(e)})),Salla.config.set("languages",a),a},Salla.config.currencies=async function(){var e;if(Salla.config.triedToGetCurrencies_)return Salla.config.get("currencies");Salla.config.triedToGetCurrencies_=!0;var t=!0,a={};return null==(e=await salla.currency.api.list())||null==(e=e.data)||e.map((function(e){t&&(a={},t=!1),e.country_code=e.code.substr(0,2).toLowerCase(),a[e.code]=e})),Salla.config.set("currencies",a),a},Salla.config.isMobileApp=function(){var e;return["ios","android"].includes(null==(e=Salla.analytics)||null==(e=e.jitsuAnalytics)||null==(e=e.getContextProperty("app"))||null==(e=e.platform)?void 0:e.toLowerCase())};var M=function(e){function a(t,a){var n;return(n=e.call(this,t,a)||this).options={path:".infinite-scroll-btn",history:"push",status:".infinite-scroll-status",append:".list-block"},n.fetchOptions={headers:{"S-INFINITE-SCROLL":!0,"S-Source":"twilight","cache-control":"no-cache",pragma:"no-cache"}},n.instances=[],n}g(a,e);var n=a.prototype;return n.initiate=function(e,a,n,r){void 0===r&&(r=!1),r?((n=n||{}).fetchOptions=f({},this.fetchOptions,n.fetchOptions||{}),n.responseBody="json"):n=this.getCustomOptions(a,n);var i="string"!=typeof e?e:document.querySelector(e),o=n.path;if(i&&o&&("string"!=typeof o||document.querySelector(o))){var s=new t(i,n);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}Salla.logger.warn(i?"Path Option (a link that has next page link) Not Existed!":"Container For InfiniteScroll not Existed!")},n.getCustomOptions=function(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},n.loadNextPage=function(e){("string"!=typeof e?e:document.querySelector(e)).loadNextPage()},n.destroy=function(e){("string"!=typeof e?e:document.querySelector(e)).destroy()},a}(u),H=function(){function e(){}var t=e.prototype;return t.submit=async function(e,t){var a,n;void 0===t&&(t=null);var r=t;if("SubmitEvent"===(null==(a=t)||null==(a=a.constructor)?void 0:a.name)||"submit"===(null==(n=t)?void 0:n.type)){var i,o;if(t.preventDefault(),"FORM"!==(null==(i=t.target)?void 0:i.tagName))return Salla.logger.warn("Failed find the target element for submit action. make sure you submit a form element"),new Promise((function(){throw"Failed find the target element for submit action. make sure you submit a form element"}));"SALLA-BUTTON"===(null==(o=t)||null==(o=o.submitter)||null==(o=o.parentElement)?void 0:o.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((function(){var e;loaderSupported&&(null==(e=t)||null==(e=e.submitter)||e.parentElement.stop())}));var s=e.split("."),l=s.splice(-1);return await salla.call(s.join("."))[l](r).finally((function(){var e;return null==(e=t)||null==(e=e.submitter)||null==(e=e.parentElement)?void 0:e.stop()})).catch((function(e){throw salla.logger.warn(e),e}))},t.onSubmit=function(e,t){return salla.form.submit(e,t),!1},t.onChange=function(e,t){var a;return null!=t&&t.currentTarget?"FORM"!==(null==t||null==(a=t.currentTarget)?void 0:a.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)},t.getPossibleValue=function(e,t,a){if(void 0===a&&(a=!1),e){if("object"!=typeof e)return e;for(var n,r=0;r<t.length&&!(n=e[t[r]])&&!("undefined"!=typeof FormData&&e instanceof FormData&&(n=e.get(t[r])));r++);return"object"!=typeof(n=n||e)||a?n:void 0}},e}(),V=function(e){function t(t){var a;return(t=t||{}).messages=t.messages||window.translations,t.locale=t.locale||(window.locale||navigator.language||navigator.userLanguage||"ar").split("-")[0],t.fallback=t.fallback||t.locale,(a=e.call(this,t)||this).translationsLoaded=!1,a}g(t,e);var a=t.prototype;return a.onLoaded=function(e){var t=this;return new Promise((function(a){if(t.translationsLoaded)return a(e?e():null);Salla.event.once("languages::translations.loaded",(function(){return a(e?e():null)}))}))},a.loadStoreTranslations=function(){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)&&e.prototype.setMessages.call(this,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)},a.setMessages=function(t){e.prototype.setMessages.call(this,t),salla.event.dispatch("languages::translations.loaded"),this.translationsLoaded=!0},a.loadScript=function(e,t){var a=this;void 0===t&&(t=!0);var n=document.createElement("script");n.src=e,n.onload=function(){var e;if(window.translations)return salla.storage.remove("s_translations"),salla.storage.set("s_translations",((e={})[a.hash]=window.translations,e)),a.setMessages(window.translations);n.onerror()},n.onerror=function(){if(t)return salla.logger.warn("Failed to load Translations for store, lets try load it from CDN"),a.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(n)},a.getWithDefault=function(e,t,a,n){var r=this.get(e,a,n);return r!==e?r:t},a.get=function(t,a,n){var r=t;(window.translations||this.translationsLoaded)&&(r="trans."+t);var i=e.prototype.get.call(this,r,a,n);return i!==r?i:e.prototype.get.call(this,r,a,"en").replace(r,t)},a.set=function(e,t){return salla.helpers.setNested(this.messages[this.getLocale()+".trans"],e,t),this},a.add=function(e,t){var a=this;return Object.entries(t).forEach((function(t){return salla.helpers.setNested(a.messages[t[0]+".trans"],e,t[1])})),this},a.addBulk=function(e){var t=this;return Object.entries(e).forEach((function(e){var a=e[0],n=e[1];t.add(a,n)})),this},t}(a),G=function(){function e(){this.endpoints={},this.webEndpoints=[],this.namespace="BaseApi",this.endpointsMethods={},this.endpointsHeaders={};var 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:[]}}var t=e.prototype;return t.after_init=function(){},t.normalRequest=function(e,t,a){void 0===t&&(t=void 0),void 0===a&&(a=null);var n=Array.isArray(e),r=n?this.getUrl.apply(this,e):this.getUrl(e);e=n?e[0]:e,a=a||this.endpointsMethods[e]||"post";var i=this.endpointsHeaders[e];if("get"===a&&t instanceof FormData){var o={};Array.from(t.entries()).forEach((function(e){o[e[0]]=e[1]})),t={params:o}}return i&&"get"===a&&(t=t?Object.assign(t,i):i),this.webEndpoints.includes(e)?r=salla.url.get(r):"http"!==r.substring(0,4)&&(r=salla.url.api(r)),Salla.api.request(r,t,a,{headers:i})},t.request=function(e,t,a){return void 0===t&&(t=void 0),void 0===a&&(a=null),!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,a)):this.normalRequest(e,t,a)},t.getUrl=function(e){for(var t=this.endpoints[e]||e,a=/{[^{}]+}/i,n=1;n<arguments.length;n++)t=t.replace(a,arguments[n]);return t},t.event=function(){return salla.event[this.className]},e}(),z=function(e){function t(){var t;return(t=e.call(this)||this).addToCartTries=0,t.guestCartAssigned=!1,t.namespace="cart",t._pendingCartIdRequest=null,t._pendingAssignRequest=null,t.endpoints={latest:"cart/latest",latestApi:"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}",giftCartDetails:"cart/{cartId}/buy-as-gift",cartGiftToCart:"cart/{cart_id}/buy-as-gift",assign:"cart/{cartId}/assign?merge=1"},t.endpointsMethods={latest:"get",details:"get",status:"get",updateItem:"post",deleteItem:"delete",deleteImage:"delete",deleteCoupon:"put",getQuickOrderSettings:"get",offers:"get",giftCartDetails:"get"},t.webEndpoints=["latest"],t.latestCart=null,t.after_init(),salla.event.on("api::initiated",(function(){return salla.api.cart.getCurrentCartId(!1,"api::initiated")})),salla.event.on("auth::token.fetched",t._checkCurrentCart),salla.event.on("auth::token.invalid",t._checkCurrentCart),salla.event.on("auth::verified",(async function(){try{await Salla.api.cart.assign()}catch(e){Salla.log("Error on assign after verified",e)}return Salla.api.cart.getCurrentCartId(!0,"auth::verified")}),{async:!0}),salla.event.on("twilight::initiated",(function(){return salla.api.cart.syncGuestCart()})),salla.event.on("profile::info.fetched",(function(){return t._checkCurrentCart(!0)})),salla.event.on("twilight::error",(function(e){return(e.includes("Cart not available")||e.includes("السلة غير متاحة"))&&salla.cart.api.reset()})),t}g(t,e);var a=t.prototype;return a._checkCurrentCart=function(e){var t,a;void 0===e&&(e=!1);var n=salla.storage.get("cart"),r=null==(t=salla.config.get("user"))?void 0:t.id,i=null==(a=salla.config.get("store"))?void 0:a.id;n&&n.id&&!e&&(n.user_id===r&&n.store_id===i||(salla.log("cart",{user_id:n.user_id,store_id:n.store_id}),salla.log("current",{user_id:r,store_id:i}),salla.log("Api:: case2 => The cart is not belong to current "+(n.user_id!==r?"user":"store")+"!"),salla.cart.api.reset()),salla.url.is_page("cart")&&n.id!==salla.config.get("page.id")&&(salla.log("cart",{user_id:n.user_id,store_id:n.store_id}),salla.log("current",{user_id:r,store_id:i}),salla.log("Api:: case2 => The cart is different between storage:"+n.id+" & session:"+salla.config.get("page.id")+" !"),salla.cart.api.reset()))},a.getCurrentCartId=async function(e,t){if(void 0===e&&(e=!1),void 0===t&&(t="getCurrentCartId"),Salla.cart.api._pendingCartIdRequest)return Salla.cart.api._pendingCartIdRequest;Salla.cart.api._pendingCartIdRequest=async function(){try{if(!e){if(Salla.cart.api.latestCart)return Salla.cart.api.latestCart.cart.id;var a=Salla.storage.get("cart.id");if(a)return a}var n=await Salla.cart.api.latest(t);return Salla.cart.api.latestCart=n.data,Salla.cart.api.latestCart.cart.id}finally{Salla.cart.api._pendingCartIdRequest=null}}();var a=Salla.cart.api._pendingCartIdRequest;return Salla.cart.api._pendingCartIdRequest=null,a},a.getUploadImageEndpoint=function(e){return salla.url.api(this.getUrl("uploadImage",e||salla.storage.get("cart.id")))},a.latest=function(e){return void 0===e&&(e="direct"),this.request(salla.auth.api.isSessionless()?"latestApi":"latest",{params:{source:"",callerName:e}}).then((function(e){return salla.api.cart.set(e.data.cart),salla.event.cart.latestFetched(e),e})).catch((function(e){throw salla.api.cart.reset(),salla.event.cart.latestFailed(e),e}))},a.details=async function(e,t){return void 0===t&&(t=[]),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}))},a.quickAdd=async function(e,t,a){return this.addItem({id:e,quantity:t,offerType:a,endpoint:"quickAdd"})},a.addItem=async function(e){var t=this.getCartPayload(e);if(!t.id){var a='There is no product "id"!';return salla.cart.event.itemAddedFailed(a),salla.api.errorPromise(a)}var n=salla.form.getPossibleValue(t.payload,["endpoint"]);n&&["addItem","quickAdd"].includes(n)||(n=salla.form.getPossibleValue(t.payload,["quantity","donating_amount"])?"addItem":"quickAdd");var r=await Salla.api.cart.getCurrentCartId(!1,"salla.api.cart.addItem");try{t.payload=Salla.helpers.createFormDataWrapper(t.payload||{}),await Salla.cart.event.beforeAddItem(t)}catch(e){}return this.request([n,r,t.id],t.payload.getRawData()).then((function(e){Salla.cart.api.addToCartTries=0;try{Salla.cart.event.itemAdded(e,t.id)}catch(e){Salla.log(e)}return e})).catch((function(a){if(!Salla.cart.api.addToCartTries)return Salla.cart.api.addToCartTries++,Salla.cart.reset(),Salla.cart.api.addItem(e);throw Salla.cart.event.itemAddedFailed(a,t.id),a}))},a.deleteItem=async function(e){var t=this.getCartPayload(e);if(!t.id){var a='There is no "id"!';return salla.cart.event.itemDeletedFailed(a),salla.api.errorPromise(a)}var n=await salla.api.cart.getCurrentCartId(!1,"salla.api.cart.deleteItem");return this.request(["deleteItem",n,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}))},a.updateItem=async function(e){var t,a=this.getCartPayload(e);if(!a.id){var n='There is no "id"!';return salla.cart.event.itemUpdatedFailed(n),salla.api.errorPromise(n)}var r=await salla.api.cart.getCurrentCartId(!1,"salla.api.cart.updateItem");return"Object"===(null==(t=a.payload.constructor)?void 0:t.name)?a.payload._method="PUT":a.payload.append("_method","PUT"),this.request(["updateItem",r,a.id],a.payload).then((function(e){return salla.cart.event.itemUpdated(e,a.id),e})).catch((function(e){throw salla.cart.event.itemUpdatedFailed(e,a.id),e}))},a.deleteImage=async function(e){if(!(e=salla.form.getPossibleValue(e,["id","image_id","photo_id"]))){var t='There is no "id"!';return salla.cart.event.imageNotDeleted(t),salla.api.errorPromise(t)}var a=await salla.api.cart.getCurrentCartId(!1,"salla.api.cart.deleteImage");return this.request(["deleteImage",a,e]).then((function(t){return salla.cart.event.imageDeleted(t,e),t})).catch((function(t){throw salla.cart.event.imageNotDeleted(t,e),t}))},a.status=async function(e,t){void 0===t&&(t=!1),e=e||await salla.api.cart.getCurrentCartId(!1,"salla.api.cart.status");var a={has_apple_pay:salla.helpers.hasApplePay()};t&&(a.guest_checkout=1);try{await salla.cart.event.submitting()}catch(e){salla.log("Error on: salla.cart.event.submitting()")}return this.request(["status",e],{params:a})},a.submit=async function(e,t){if(void 0===e&&(e=!1),void 0===t&&(t=!1),console.log("salla.cart.api.submit",{isGuestCheckout:e}),salla.config.isGuest()&&!e)return salla.log("it looks that the current user is not logged-in, lets login then submit"),salla.cart.loginOnCartPage();var a;if(t)try{var n,r=await Salla.api.cart.assign();a=null==r||null==(n=r.data)?void 0:n.cart_id}catch(e){Salla.log("Error on assign after login from submit",e)}this.status(null!=a?a:await salla.api.cart.getCurrentCartId(!1,"salla.api.cart.submit"),e).then((function(e){var t,a=null==(t=e.data.next_step)?void 0:t.to;if(a||(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(a)){var n="Can't find next_step );";throw salla.cart.reset(),salla.cart.event.submitFailed(n),n}return salla.cart.event.submitted(e),"login"===a?salla.cart.loginOnCartPage():"checkout"===a?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){var t;salla.cart.api.tries=salla.cart.api.tries||0,salla.cart.reset();var a=404===(null==e||null==(t=e.response)||null==(t=t.data)?void 0:t.status);if(a&&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 a&&salla.error(salla.lang.get("pages.checkout.try_again")),salla.cart.event.submitFailed(e),e}))},a.getCartPayload=function(e){var t,a=(null==(t=e)?void 0:t.data)||("object"==typeof e?e:void 0);return{id:e=a?salla.form.getPossibleValue(a,["prod_id","product_id","item_id","id"]):e,payload:a="object"==typeof a?a:void 0}},a.normalRequest=function(t,a,n){var r=this;return void 0===a&&(a=void 0),void 0===n&&(n=null),e.prototype.normalRequest.call(this,t,a,n).catch((async function(e){var t;throw 403===(null==e||null==(t=e.response)?void 0:t.status)&&(r.reset(),salla.error(salla.lang.get("pages.checkout.try_again"))),e}))},a.reset=function(){salla.api.cart.latestCart=null,salla.storage.remove("cart"),salla.cookie.clearCookieByPrefix(salla.api.cart.getCartCookiePrefix()),salla.cart.event.successReset()},a.addCoupon=async function(e){if(e=e.data||e,!(e=salla.form.getPossibleValue(e,["coupon"]))){var t=new Error('There is no "Coupon Code"!');return t.name="EmptyCoupon",salla.event.cart.couponAdditionFailed(t),salla.api.errorPromise(t)}var a=await salla.cart.api.getCurrentCartId(!1,"salla.api.cart.addCoupon");return this.request(["addCoupon",a],{coupon:e}).then((function(e){var t,n=salla.storage.get("cart");return n&&null!=(t=e.data)&&null!=(t=t.cart)&&t.coupon&&(n.coupon=e.data.cart.coupon,salla.storage.set("cart",n)),salla.event.cart.couponAdded(e,a),e})).catch((function(e){throw salla.event.cart.couponAdditionFailed(e,a),e}))},a.deleteCoupon=async function(){var e=await salla.cart.api.getCurrentCartId(!1,"salla.api.cart.deleteCoupon");return this.request(["deleteCoupon",e],{}).then((function(t){var a=salla.storage.get("cart");return a&&a.coupon&&(delete a.coupon,salla.storage.set("cart",a)),salla.event.cart.couponDeleted(t,e),t})).catch((function(t){throw salla.event.cart.couponDeletionFailed(t,e),t}))},a.getQuickOrderSettings=function(){return this.request("getQuickOrderSettings").then((function(e){return salla.event.cart.quickOrderSettingFetched(e),e})).catch((function(e){throw salla.event.cart.quickOrderSettingFailed(e),e}))},a.createQuickOrder=function(e){return this.request("createQuickOrder",e).then((function(e){return salla.event.cart.quickOrderSucceeded(e),e})).catch((function(e){throw salla.event.cart.quickOrderFailed(e),e}))},a.priceQuote=async function(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((function(e){return salla.cart.api.reset(),salla.event.cart.priceQuoteSucceeded(e).then((function(){return setTimeout((function(){return window.location.href=salla.url.get("/")}),1e3),e}))})).catch((function(e){return salla.event.cart.priceQuoteFailed(e).then((function(){var t;throw 404===(null==(t=e.error)?void 0:t.code)&&window.location.reload(),e}))}))},a.loginOnCartPage=function(){salla.auth.setCanRedirect(!1),salla.event.dispatch("login::open",{withoutReload:!0,source:"cart-submit"}),salla.auth.event.onLoggedIn((function(){salla.event.dispatch("login::close"),salla.cart.submit(!1,!0)}))},a.set=function(e){salla.storage.set("cart",e),salla.api.cart.syncGuestCart()},a.offers=async function(){var e=await salla.cart.api.getCurrentCartId(!1,"salla.api.cart.offers");return this.request(["offers",e]).then((function(e){return salla.event.cart.offersFetched(e),e})).catch((function(e){throw salla.event.cart.offersFailed(e),e}))},a.getGiftCartDetails=async function(){var e=await salla.api.cart.getCurrentCartId(!1,"salla.api.cart.getGiftCartDetails");return this.request(["giftCartDetails",e]).then((function(t){return salla.product.event.giftFetched(t,e),t})).catch((function(t){throw salla.product.event.giftFetchFailed(t,e),t}))},a.addCartGiftToCart=async function(e,t){void 0===t&&(t=!1);var a=await salla.api.cart.getCurrentCartId(!1,"salla.api.cart.addCartGiftToCart");return this.request(["cartGiftToCart",a],e).then((function(e){return salla.product.event.addGiftToCartSucceeded(e,a),t&&(window.location.href=e.redirect),e})).catch((function(e){throw salla.product.event.addGiftToCartFailed(e,a),e}))},a.syncGuestCart=async function(){if(salla.config.isGuest()){var e=salla.api.cart.getCartCookiePrefix(),t=salla.cookie.getCookieByPrefix(e),a=salla.storage.get("cart.id");if(!a&&t.length)try{var n,r=null==(n=(await salla.api.cart.latest()).data)||null==(n=n.cart)?void 0:n.id;r&&salla.api.cart.setCartCookie(e,r)}catch(e){salla.log("Failed to fetch latest cart:",e)}salla.cookie.clearCookieByPrefix(e),a&&(salla.config.set("headers.s-cart-id",a),salla.api.cart.setCartCookie(e,a))}},a.assign=async function(){var e=this;if(Salla.api.cart._pendingAssignRequest)return Salla.api.cart._pendingAssignRequest;var t=Salla.storage.get("cart.id");return!(!t||Salla.api.cart.guestCartAssigned)&&(Salla.api.cart._pendingAssignRequest=async function(){try{var a=await e.request(["assign",t]);return Salla.api.cart.guestCartAssigned=!0,a}catch(e){throw e}finally{Salla.api.cart._pendingAssignRequest=null}}(),Salla.api.cart._pendingAssignRequest)},a.setCartCookie=function(e,t){salla.cookie.set(e+"-"+t,t,1)},a.getCartCookiePrefix=function(){return"cart-id-"+salla.config.get("store.id")},t}(G),W=function(e){function t(){var t;return(t=e.call(this)||this).namespace="loyalty",t.endpoints={getProgram:"loyalty",exchange:"loyalty/exchange",reset:"loyalty/exchange"},t.endpointsMethods={getProgram:"get",reset:"put"},t.after_init(),t}g(t,e);var a=t.prototype;return a.getProgram=function(){return this.request("getProgram").then((function(e){return salla.loyalty.event.programFetched(e),e})).catch((function(e){throw salla.loyalty.event.programNotFetched(e),e}))},a.exchange=async function(e,t){if(void 0===t&&(t=null),!(e=salla.form.getPossibleValue(e,["id","loyalty_prize_id","prize_id"]))){var a="Unable to find cart id. Please provide one.";return salla.loyalty.event.exchangeFailed(a),salla.api.errorPromise(a)}if(!(t=t||await salla.cart.getCurrentCartId(!1,"salla.api.loyalty.exchange"))){var n="Unable to find cart id. Please provide one.";return salla.loyalty.event.exchangeFailed(n),salla.api.errorPromise(n)}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}))},a.reset=async function(e){if(void 0===e&&(e=null),!(e=e||await salla.cart.getCurrentCartId(!1,"salla.api.loyalty.reset"))){var t="Unable to find cart id. Please provide one.";return salla.loyalty.event.resetFailed(t),salla.api.errorPromise(t)}return this.request("reset",{cart_id:e}).then((function(e){return salla.loyalty.event.resetSucceeded(e),e})).catch((function(e){throw salla.loyalty.event.resetFailed(e),e}))},t}(G),B=function(e){function t(){var t;return(t=e.call(this)||this).namespace="auth",t.canRedirect_=!0,t.afterLoginEvent={event:null,payload:null},t.endpoints={login:"auth/{type}/send_verification",resend:"auth/resend_verification",verify:"auth/{type}/verify",register:"auth/register",logout:"logout",refresh:"auth/refresh"},t.webEndpoints=["logout","auth/jwt","refresh"],t.endpointsMethods={logout:"get"},t.inIframe=salla.helpers.isIframe(),Salla.event.on("twilight::init",(function(){if(Salla.config.isGuest()&&location.href.includes("force_logout"))return delete Salla.api.axios.defaults.headers.common.Authorization,Salla.api.auth.logout("twilight",!1)})),t.after_init(),t}g(t,e);var a=t.prototype;return a.setAfterLoginEvent=function(e,t){salla.api.auth.afterLoginEvent={event:e,payload:t}},a.setCanRedirect=function(e){salla.api.auth.canRedirect_=e},a.canRedirect=function(){return salla.api.auth.canRedirect_&&!salla.api.auth.afterLoginEvent.event},a.login=function(e){var t;null!=(t=e)&&t.data&&(e=e.data);var a=salla.form.getPossibleValue(e,["type"]);if(!["email","mobile"].includes(a)){var n="Login type should be in: [email, mobile]";return salla.auth.event.codeNotSent(n),salla.api.errorPromise(n)}return this.request(["login",a],e).then((function(e){return salla.auth.event.codeSent(e,a),e})).catch((function(e){throw salla.auth.event.codeNotSent(e,a),salla.auth.api.trackBlockedError(e,"login"),e}))},a.verify=async function(e,t){void 0===t&&(t=!0);var a=salla.form.getPossibleValue(e,["type"]);if(!a){var n="Failed to know what's login type!";return salla.auth.event.verificationFailed(n),salla.api.errorPromise(n)}t=!1!==salla.form.getPossibleValue(e,["supportWebAuth"])&&t,salla.auth.event.next_event&&(e.next_event=salla.auth.event.next_event);var r=await salla.auth.api.request(["verify",a],e);return 200!==(null==r?void 0:r.status)?(salla.auth.event.verificationFailed(r,a),salla.api.errorPromise(r)):salla.auth.api.handlAfterAuthenticatedResponse(r,t)},a.handlAfterAuthenticatedResponse=async function(e,t){var a;e.data||(e={data:e});var n="authenticated"===(null==(a=e.data)?void 0:a.case);return n&&salla.auth.event.tokenFetched(e.data.token),t&&!this.inIframe&&!this.isSessionless()&&await salla.auth.api.request("auth/jwt",{callerName:"salla.auth.api.handlAfterAuthenticatedResponse"}),n&&await salla.auth.event.loggedIn(e).then((function(){return salla.auth.api.afterUserLogin()})),await salla.auth.event.verified(e,e.data.verification.type),salla.api.successPromise(e)},a.resend=function(e){var 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),salla.auth.api.trackBlockedError(t,"resend"),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))},a.register=function(e){var t,a=this;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 function(e){var n;return salla.auth.event.registered.call(t,e),"authenticated"===(null==(n=e.data)?void 0:n.case)&&(salla.auth.event.tokenFetched(e.data.token),!a.inIframe&&!a.isSessionless()&&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),salla.auth.api.trackBlockedError(e,"register"),e}))},a.handleIframeReadyAction=function(e,t){var a;null==(a=e.contentWindow)||a.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:{}}},"*")},a.appendIframeAndLogout=function(){var e=this;return new Promise((function(t){var a=salla.config.get("login.url","https://accounts.salla.com"),n=document.createElement("iframe");n.style.display="none",n.src=a+"/logout";var r=function(i){if("login"===i.data.source){var o=i.data.type.replace("iframe::","");if(salla.log("iframe::logout-iframe message received",i.data),["logged-out","ready"].includes(o)){if("ready"===o)return e.handleIframeReadyAction(n,a);window.removeEventListener("message",r),n.remove(),t()}}};window.addEventListener("message",r),document.body.appendChild(n)}))},a.logout=function(e,t){var a=this;return void 0===e&&(e="twilight"),void 0===t&&(t=!0),salla.storage.clearAll(),salla.cookie.clearAll(),e=encodeURI(e),salla.auth.event.loggedOut().then((function(){return a.appendIframeAndLogout()})).then((function(){if(t){var a=salla.url.get("logout?from="+e);console.log("Going to "+a+", to do any thing before this action use: salla.auth.even.onLoggedOut(()=>{...})");try{location.href=a}catch(e){salla.log(e)}}})).catch((function(e){return console.error("Error during logout:",e)}))},a.refresh=function(){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}))},a.afterUserLogin=function(){this.afterLoginEvent.event&&salla.event.emit(this.afterLoginEvent.event,this.afterLoginEvent.payload)},a.isSessionless=function(){return"sessionless"===salla.config.get("auth.mode")},a.trackBlockedError=function(e,t){var a;blockedByProxy=void 0===(null==e||null==(a=e.response)||null==(a=a.headers)?void 0:a["s-ray"]),blockedByProxy&&salla.analytics.track("BlockedByProxy",{class:"auth",function:t,reason:"non-server-request",message:e.message})},t}(G),Q=function(e){function t(){var t;return(t=e.call(this)||this).namespace="order",t.endpoints={cancel:"orders/cancel/{id}",createCartFromOrder:"reorder/{id}",reorderProduct:"reorder/product/{id}",sendInvoice:"orders/send/{id}",fetch:"orders"},t.endpointsMethods={createCartFromOrder:"get",fetch:"get"},t.after_init(),t}g(t,e);var a=t.prototype;return a.show=function(e){var t=salla.form.getPossibleValue((null==e?void 0:e.data)||e,["id","order_id"]);salla.event.dispatch("mobile::order.placed",{order_id:t}),location.href=salla.form.getPossibleValue((null==e?void 0:e.data)||e,["url"])},a.cancel=function(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}))},a.createCartFromOrder=function(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}))},a.reorderProduct=function(e){return e=e||salla.config.get("page.id"),this.request(["reorderProduct",e]).then((function(e){return salla.event.order.orderCreated(e,e.data.order_id),window.location.href=e.data.url,e})).catch((function(e){throw e}))},a.sendInvoice=function(e){var t=salla.form.getPossibleValue(e,["id"])||salla.config.get("page.id");if(!t||isNaN(t)){var a="There is no id!";return salla.order.event.invoiceNotSent(a),salla.api.errorPromise(a)}return this.request(["sendInvoice",t],e).then((function(e){return salla.event.order.invoiceSent(e,t),e})).catch((function(e){throw salla.event.order.invoiceNotSent(e,t),e}))},a.fetch=function(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}))},t}(G),K=function(e){function t(){var t;return(t=e.call(this)||this).namespace="product",t.previousQuery="",t.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",giftProductDetails:"products/{product_id}/buy-as-gift",productGiftToCart:"products/{product_id}/buy-as-gift",giftImage:"products/buy-as-gift/image",buyNow:"products/{product_id}/buy-now",fetch:"products",fetchOptions:"products/options"},t.endpointsMethods={details:"get",giftProductDetails:"get",fetch:"get",offers:"get",fetchOptions:"get"},t.after_init(),t}g(t,e);var a=t.prototype;return a.getPrice=function(e){var t=e.data||e,a=salla.form.getPossibleValue(t,["id","prod_id","product_id"]);return this.request(["getPrice",a],"object"==typeof t?t:void 0).then((function(e){return salla.product.event.priceUpdated(e,a),e})).catch((function(e){throw salla.product.event.priceUpdateFailed(e,a),e}))},a.categories=function(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}))},a.availabilitySubscribe=function(e){var 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}))},a.search=function(e){var t,a=e.data;if(a||(a={params:"string"==typeof e?{query:e}:e}),!(e=a instanceof FormData?a.get("query"):a.query||(null==(t=a.params)?void 0:t.query))){var n='There is no "query"!';return salla.product.event.searchFailed(n),salla.api.errorPromise(n)}if(e===salla.api.product.previousQuery){var r="Query is same as previous one!";return salla.product.event.searchFailed(r),salla.api.product.previousQuery=null,salla.api.errorPromise(r)}return salla.api.product.previousQuery=e,this.request("search",a,"get").then((function(t){return salla.product.event.searchResults(t,e),t})).catch((function(t){throw salla.product.event.searchFailed(t,e),t}))},a.offers=function(e){var t;if(!(e=salla.form.getPossibleValue((null==(t=e)?void 0:t.data)|e,["product_id","id"]))){var a='There is no "product_id"!';return salla.product.event.fetchOffersFailed(a),salla.api.errorPromise(a)}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}))},a.getSizeGuides=function(e){return this.request("products/"+e+"/size-guides",null,"get").then((function(t){return salla.product.event.sizeGuideFetched(t,e),t})).catch((function(t){throw salla.product.event.sizeGuideFetchFailed(t,e),t}))},a.getGiftProductDetails=function(e){return this.request(["giftProductDetails",e]).then((function(t){return salla.product.event.giftFetched(t,e),t})).catch((function(t){throw salla.product.event.giftFetchFailed(t,e),t}))},a.getDetails=function(e,t){if(void 0===t&&(t=[]),!Array.isArray(t)){var a="withItems should be array.";return salla.product.event.detailFetchFailed(a),salla.api.errorPromise(a)}if(!e){var n="productId is not passed.";return salla.product.event.detailFetchFailed(n),salla.api.errorPromise(n)}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}))},a.addProductGiftToCart=function(e,t,a){return void 0===a&&(a=!1),this.request(["productGiftToCart",e],t).then((function(t){return salla.product.event.addGiftToCartSucceeded(t,e),a&&(window.location.href=t.redirect),t})).catch((function(t){throw salla.product.event.addGiftToCartFailed(t,e),t}))},a.uploadGiftImage=function(e){return this.request("giftImage",e).then((function(e){return salla.product.event.giftImageUploadSucceeded(e),e})).catch((function(e){throw salla.product.event.giftImageUploadFailed(e),e}))},a.fetch=function(e){if(!e.source){var t="Source cannot be empty. Please provide one.";return salla.product.event.productListFetchFailed(t),salla.api.errorPromise(t)}var a=!e.source_value,n="string"==typeof e.source_value&&"[]"===e.source_value,r=Array.isArray(e.source_value)&&!e.source_value.length;if((a||n||r)&&!["offers","latest","sales","wishlist","top-rated","reorder"].includes(e.source)){var i="Source value cannot be empty. Please provide one.";return salla.product.event.productListFetchFailed(i),salla.api.errorPromise(i)}if(["categories","brands","tags","selected"].includes(e.source)&&!Array.isArray(e.source_value)){var o="SourceValue type error. Expected an array.";return salla.product.event.productListFetchFailed(o),salla.api.errorPromise(o)}if("search"===e.source&&"string"!=typeof e.source_value){var s="SourceValue type error. Expected a string.";return salla.product.event.productListFetchFailed(s),salla.api.errorPromise(s)}if("related"===e.source&&isNaN(e.source_value)){var l="SourceValue type error. Expected a number.";return salla.product.event.productListFetchFailed(l),salla.api.errorPromise(l)}return this.request(this.endpoints.fetch,{params:e},"get").then((async function(e){return salla.product.event.productListFetchSucceeded(e),e})).catch((function(e){throw salla.product.event.productListFetchFailed(e),e}))},a.fetchOptions=function(e,t){if(void 0===t&&(t={}),!e||0===e.length){var a="At least one product ID is required. Please provide a valid list of product IDs.";return salla.product.event.productOptionsNotFetched(a),salla.api.errorPromise(a)}var n=t.with,r=void 0===n?[]:n,i={selected:e};return r.length>0&&(i.with=r),this.request(this.endpoints.fetchOptions,{params:i},"get").then((function(e){return salla.product.event.productOptionsFetched(e),e})).catch((function(e){throw salla.product.event.productOptionsNotFetched(e),e}))},t}(G),J=function(e){function t(){var t;return(t=e.call(this)||this).namespace="profile",t.endpoints={info:"auth/user",update:"profile/update",updateContacts:"profile/contacts/update",updateCustomFields:"profile/fields",updateSettings:"profile/settings",verify:"profile/verify",delete:"profile"},t.endpointsMethods={delete:"delete"},t.after_init(),t}g(t,e);var a=t.prototype;return a.syncUserData=function(e){var t={id:e.id,type:"user",email:e.email,mobile:e.phone.code+e.phone.number,country_code:e.phone.country,language_code:e.language,currency_code:e.currency,notifications:e.notifications,pending_orders:e.pending_orders,avatar:e.avatar,first_name:e.first_name,last_name:e.last_name,is_hidden_name:e.is_hidden_name,is_notifiable:e.is_notifiable,can_comment:salla.config.get("user.can_comment"),fetched_at:Date.now()};salla.config.set("user",t),salla.storage.set("user",t)},a.info=function(){var e=this;return this.request("info",null,"get").then((function(t){return e.syncUserData(t.data),salla.profile.event.infoFetched(t),t})).catch((function(e){throw salla.profile.event.infoNotFetched(e),e}))},a.update=function(e){var t=this;if(Salla.config.get("store.features",[]).includes("sso-login")){var a="SSO login is enabled. You cannot update your profile.";return Salla.error(a),Promise.reject(new Error(a))}return this.request("update",e).then((function(e){return t.syncUserData(e.data),salla.profile.event.updated(e),e})).catch((function(e){throw salla.event.profile.updateFailed(e),e}))},a.updateCustomFields=function(e){var t=this;if(Salla.config.get("store.features",[]).includes("sso-login")){var a="SSO login is enabled. You cannot update your profile.";return Salla.error(a),Promise.reject(new Error(a))}return this.request("updateCustomFields",e).then((function(e){return t.syncUserData(e.data),salla.profile.event.updated(e),e})).catch((function(e){throw salla.event.profile.updateFailed(e),e}))},a.updateContacts=function(e){return this.request("updateContacts",e).then((function(e){return salla.profile.event.verificationCodeSent(e),e})).catch((function(e){throw salla.event.profile.updateContactsFailed(e),e}))},a.verify=function(e){return this.request("verify",e).then((function(e){return salla.profile.event.verified(e),e})).catch((function(e){throw salla.event.profile.unverified(e),e}))},a.updateSettings=function(e){return this.request("updateSettings",e).then((function(e){return salla.event.profile.settingsUpdated(e),e})).catch((function(e){throw salla.event.profile.updateSettingsFailed(e),e}))},a.delete=function(){return this.request("delete").then((function(e){return salla.storage.clearAll(),salla.cookie.clearAll(),salla.auth.api.appendIframeAndLogout().then((function(){salla.event.profile.deleted(e),window.location.href=salla.url.get("logout")})),e})).catch((function(e){throw salla.event.profile.notDeleted(e),e}))},t}(G),X=function(e){function t(){var t;return(t=e.call(this)||this).namespace="comment",t.endpoints={addComment:"{type}/{id}/comments",comments:"/comments"},t.after_init(),t}g(t,e);var a=t.prototype;return a.add=function(e){var t;if(null!=(t=e)&&t.data&&(e=e.data),"string"==typeof(e=this.getCommentPayload(e,!0)))return salla.event.comment.additionFailed(e),salla.api.errorPromise(e);if(!e.comment){var a="can't find comment content!";return salla.event.comment.additionFailed(a),salla.api.errorPromise(a)}return this.request(["addComment","blog"==e.type?"blogs":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}))},a.getCommentPayload=function(e,t){void 0===t&&(t=!1);var a={};if(["id","type","comment","per_page","page","sort"].forEach((function(t){var n=salla.form.getPossibleValue(e,[t]);n&&(a[t]=n)})),!t){var n=e.ids;if(n&&(a.ids=Array.isArray(n)?n:[n]),!a.ids||!a.ids.length)return"Failed to get ids!"}return a.type&&["products","pages","product","page","blogs","blog"].includes(a.type)?(a.type+=["product","page"].includes(a.type)?"s":"",a):"Failed to get type one of:(products, product, page, pages, blog, blogs)!"},a.fetchComments=function(e){if("string"==typeof(e=this.getCommentPayload(e)))return salla.event.comment.fetchFailed(e),salla.api.errorPromise(e);var 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}))},a.getComments=function(e,t,a,n,r){void 0===a&&(a=1),void 0===n&&(n=5);var i=Array.isArray(t)?t:[t];return this.fetchComments({ids:i,type:e+"s",page:a,per_page:n,sort:r})},t}(G),Z=function(e){function t(){var t;return(t=e.call(this)||this).namespace="currency",t.endpoints={change:"/",list:"currencies"},t.endpointsMethods={change:"get",list:"get"},t.webEndpoints=["change"],t.after_init(),t}g(t,e);var a=t.prototype;return a.change=function(e){if(!(e=salla.form.getPossibleValue(e.data||e,["currency","code"]))){var t="Can't find currency code!";return salla.currency.event.failed(t),salla.api.errorPromise(t)}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}))},a.list=function(){return this.request("list").then((function(e){return salla.currency.event.fetched(e),e})).catch((function(e){throw salla.currency.event.failedToFetch(e),e}))},t}(G),$=function(e){function t(){var t;return(t=e.call(this)||this).namespace="document",t}return g(t,e),t.prototype.reload=function(){window.location.reload()},t}(G),Y=function(e){function t(){var t;return(t=e.call(this)||this).namespace="rating",t.endpoints={store:"rating/store",products:"rating/products",shipping:"rating/shipping",order:"rating/{order_id}"},t.endpointsMethods={order:"get"},t.after_init(),t}g(t,e);var a=t.prototype;return a.order=function(e){var t="object"==typeof e?e:{},a=salla.form.getPossibleValue((null==e?void 0:e.data)||e,["order_id","id"]);if(!a){var n='There is no "order_id"!';return salla.event.rating.orderNotFetched(n),salla.api.errorPromise(n)}return this.request(["order",a],t).then((function(e){return salla.event.rating.orderFetched(e,a),e})).catch((function(e){throw salla.event.rating.orderNotFetched(e,a),e}))},a.store=function(e){var t;if(!(e=(null==(t=e)?void 0:t.data)||e)){var a='There is no "data"!';return salla.event.rating.storeFailed(a),salla.api.errorPromise(a)}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}))},a.products=function(e){var t;if(!(e=(null==(t=e)?void 0:t.data)||e)){var a='There is no "data"!';return salla.event.rating.productsFailed(a),salla.api.errorPromise(a)}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}))},a.shipping=function(e){var t;if(!(e=(null==(t=e)?void 0:t.data)||e)){var a='There is no "data"!';return salla.event.rating.shippingFailed(a),salla.api.errorPromise(a)}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}))},t}(G),ee=function(e){function t(){var t;return(t=e.call(this)||this).namespace="wishlist",t.endpoints={add:"products/favorites/{id}",remove:"products/favorites/{id}"},t.endpointsMethods={remove:"delete"},Salla.onReady((function(){var e;"customer.wishlist"===Salla.config.get("page.slug")&&(null!=(e=Salla.storage.getWithTTL("s-utms"))&&e["s-utm-source"]||t.injectSourceIntoRequest())})),t}g(t,e);var a=t.prototype;return a.injectSourceIntoRequest=function(){Salla.api.axios.interceptors.request.use((function(e){return e.headers=f({},e.headers,{"s-utm-source":"wishlist"}),e}),(function(e){return Promise.reject(e)}))},a.toggle=function(e){return salla.storage.get("salla::wishlist",[]).includes(e)?this.remove(e):this.add(e)},a.add=function(e){var t,a,n=this;return salla.config.isGuest()?(salla.wishlist.event.additionFailed(a=salla.lang.get("common.messages.must_login")),salla.error(a),salla.api.errorPromise(a)):(e=salla.form.getPossibleValue((null==(t=e)?void 0:t.data)||e,["product_id","id"]))?this.request(["add",e]).then((function(t){return n.updateWishlistStorage(e),salla.wishlist.event.added(t,e),t})).catch((function(t){throw salla.wishlist.event.additionFailed(t,e),t})):(salla.wishlist.event.additionFailed(a="Failed to get product id!"),salla.api.errorPromise(a))},a.remove=function(e){var t,a,n=this;return salla.config.isGuest()?(salla.wishlist.event.additionFailed(a=salla.lang.get("common.messages.must_login")),salla.error(a),salla.api.errorPromise(a)):(e=salla.form.getPossibleValue((null==(t=e)?void 0:t.data)||e,["product_id","id"]))?this.request(["remove",e]).then((function(t){return n.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(a="Failed to get id!"),salla.api.errorPromise(a))},a.updateWishlistStorage=function(e,t){void 0===t&&(t=!0);var a=salla.storage.get("salla::wishlist",[]);t?a.push(e):a.splice(a.indexOf(e),1),salla.storage.set("salla::wishlist",a)},t}(G),te=function(e){function t(){var t;return(t=e.call(this)||this).namespace="scopes",t.endpoints={get:"scopes",change:"scopes",getProductAvailability:"scopes/availability?product_id={id}"},t.after_init(),t}g(t,e);var a=t.prototype;return a.get=function(){return this.request("scopes",null,"get").then((function(e){return salla.scope.event.fetched(e),e})).catch((function(e){throw salla.scope.event.notFetched(e),e}))},a.change=function(e){return this.request("scopes",e).then((function(e){return salla.scope.event.changeSucceeded(e),e})).catch((function(e){throw salla.scope.event.changeFailed(e),e}))},a.getProductAvailability=function(e){return void 0===e&&(e=null),this.request("scopes/availability?product_id="+e,null,"get").then((function(t){return salla.scope.event.productAvailabilityFetched(t,e),t})).catch((function(e){throw salla.scope.event.productAvailabilityNotFetched(e),e}))},t}(G),ae=function(e){function t(){var t;return(t=e.call(this)||this).namespace="booking",t.endpoints={add:"cart/booking/product/{id}"},t.endpointsMethods={add:"get"},t}return g(t,e),t.prototype.add=async function(e,t){if(void 0===t&&(t=!0),!e){var a="Please provide product id.";return salla.booking.event.additionFailed(a),salla.api.errorPromise(a)}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}))},t}(G),ne=function(e){function t(){var t;return(t=e.call(this)||this).namespace="landing",t.endpoints={getDetails:"landing/{landing_page_id}",createCartFromPage:"landing/{landing_page_id}",breadcrumbs:"breadcrumbs"},t.endpointsMethods={getDetails:"get",breadcrumbs:"get"},t.after_init(),t}g(t,e);var a=t.prototype;return a.getDetails=function(e){if(!e){var t="page landing id not passed";return salla.event.landing.getDetailsFailed(t),salla.api.errorPromise(t)}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}))},a.createCartFromPage=function(e){if(!e){var t="page landing id not passed";return salla.event.landing.orderCreationFailed(t),salla.api.errorPromise(t)}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((function(){return location.href=t.data.url})),t})).catch((function(t){throw salla.event.landing.orderCreationFailed(t,e),t}))},a.fetchBreadcrumbs=function(e){if(!e.page){var t="The 'page' parameter is required for the Breadcrumb API. Please provide a valid 'page' parameter.";return salla.event.landing.breadcrumbFetchFailed(t),salla.api.errorPromise(t)}if("product.single"===e.page&&!e.id&&!e.parent_id){var a="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(a),salla.api.errorPromise(a)}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){var n="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(n),salla.api.errorPromise(n)}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}))},t}(G),re=function(e){function t(){var t;return(t=e.call(this)||this).namespace="notifications",t.endpoints={fetch:"notifications"},t.endpointsMethods={fetch:"get"},t.after_init(),t}return g(t,e),t.prototype.fetch=function(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}))},t}(G),ie=function(){function e(){var e,t=this;this.inIframe=salla.helpers.isIframe(),salla.event.on("twilight::before.ready",(async function(e){return await t.initiateRequest(e)})),salla.event.on("profile::info.fetched",(function(e){return t.setCurrencyAndLanguage(e)})),salla.event.on("auth::token.fetched",(function(e){salla.storage.set("token",e),t.inIframe&&salla.log("token fetched iframe"),t.inIframe&&salla.cookie.set("s-token",e,60),t.setToken(e)})),salla.event.on("auth::token.invalid",(function(){salla.storage.remove("user"),salla.storage.remove("token")})),this.notifier_handler_disabled=!1,this.axios=n.create({baseURL:Salla.config.get("store.api",Salla.config.get("store.url")),headers:{common:{"X-Requested-With":"XMLHttpRequest","S-SOURCE":"twilight","S-APP-VERSION":(null==(e=Salla)||null==(e=e.versions)?void 0:e.twilight)||"2.0.0","S-APP-OS":"browser","cache-control":"no-cache"}}}),this.axios.interceptors.request.use((function(e){"preview"===Salla.config.get("theme.mode")&&(e.url=Salla.url.addParamToUrl("use_username_url",1,e.url));try{var t=Salla.config.get("swoole",[]),a=new RegExp(t.join("|"),"i");t.length>0&&a.test(e.url)&&(e.headers["s-store-api-version"]="swoole")}catch(e){console.log(e)}return e}),(function(e){return Promise.reject(e)}))}var t=e.prototype;return t.getHeaders=function(){var e=f({},this.axios.defaults.headers.common);return delete e["Content-Type"],e},t.getHeader=function(e){var t;return null==(t=Object.entries(this.getHeaders()).filter((function(t){return t[0].toLowerCase()===e.toLowerCase()}))[0])?void 0:t[1]},t.setHeaders=function(e){var t=this;return Object.entries(e).forEach((function(e){return t.setHeader(e[0],e[1])})),this},t.setHeader=function(e,t){return salla.infiniteScroll.fetchOptions.headers[e]=this.axios.defaults.headers.common[e]=t,this},t.withoutNotifier=async function(e){var t=this;return this.notifier_handler_disabled=!0,await e().finally((function(){t.notifier_handler_disabled=!1}))},t.initiateRequest=async function(e){var t,a,n;this.axios.defaults.baseURL=Salla.config.get("store.api",Salla.config.get("store.url")),this.setHeaders(f({"Store-Identifier":Salla.config.get("store.id"),currency:(null==(t=e.user)?void 0:t.currency_code)||"SAR","accept-language":salla.lang.getLocale(),"s-user-id":null==(a=e.user)?void 0:a.id,"s-country":null==(n=e.user)?void 0:n.country_code},e.headers||{}));var r=Salla.config.get("store.scope",Salla.storage.get("scope")),i=new URLSearchParams(window.location.search).get("scope");i&&r&&!Salla.url.is_page("cart")&&(r.id=i,Salla.storage.set("scope",r),Salla.cart.reset()),r&&this.setHeaders({"s-scope-type":r.type,"s-scope-id":r.id});var o=Salla.storage.getWithTTL("s-utms");if(o){var s={};Object.entries(o).forEach((function(e){var t=e[0],a=e[1];s[t]="string"==typeof a&&/[^\x00-\x7F]/.test(a)?encodeURIComponent(a):a})),this.setHeaders(s)}await this.injectTokenToTheRequests(e),salla.storage.get("affiliate_code")&&this.setHeader("s-affiliate-code",salla.storage.get("affiliate_code"))},t.injectTokenToTheRequests=async function(e){var t,a,n=this,i=salla.storage.get("token"),o="guest"===(null==(t=e.user)?void 0:t.type),s=parseInt((null==(a=e.user)?void 0:a.id)||0),l=parseInt(salla.storage.get("user.id")||0),c=salla.auth.api.isSessionless(),u=function(e){n.setToken(e),salla.event.emit("api::initiated")},d=async function(){o||c||!s?salla.auth.event.tokenInvalid():(salla.log("Api:: case 1 => current is is guest & web session available"),await salla.auth.api.refresh().then((async function(){await salla.profile.info()})).catch((function(){return salla.auth.event.tokenInvalid()})))};if(!i)return salla.log("Api:: case 1 => current is is guest"),void await d();var p=r.jwtDecode(i);return Date.now()/1e3>p.exp?(salla.log("Api:: case 2 => current user is logged-in and there is a token, but it's expired"),void await d()):(c?parseInt(p.sub)!==l:!l||!s||l!==s||parseInt(p.sub)!==s)?(salla.log("Api:: case 3 => there is a token and user in session/local missing or mismatch"),salla.log("sub:"+p.sub+" userIdInWeb:"+s+" userIdInStorage:"+l+", isSessionless:"+c,p.sub,s,l),this.setHeader("Authorization","Bearer "+i),void await salla.profile.info().then((async function(e){!n.inIframe&&!c&&await salla.auth.api.request("auth/jwt",{callerName:"salla.auth.request.injectTokenToTheRequests"}),u(i)})).catch((function(){salla.log("Api:: case 3 => failed get fresh profile"),n.setHeader("Authorization",null),salla.auth.event.tokenInvalid()}))):(salla.log("Api:: case 4 => current user is logged-in and there is a token, and it's not expired"),void u(i))},t.setToken=function(e){return this.setHeader("Authorization","Bearer "+e),salla.event.emit("api::token.injected",e),this.token=e,this},t.setCurrencyAndLanguage=function(e){return this.setHeaders({currency:e.data.currency,"accept-language":e.data.language})},t.request=function(e,t,a,n){var r=this;void 0===t&&(t=void 0),void 0===a&&(a="get"),void 0===n&&(n={});var i={endPoint:e,payload:t,method:a,options:n},o="undefined"!=typeof event?event.currentTarget:null,s=!1;return"SALLA-BUTTON"===(null==o?void 0:o.tagName)&&(s=!0),s&&(null==o||o.load()),this.axios[i.method](i.endPoint,i.payload,i.options).then((function(e){return s&&(null==o||o.stop()),e.data&&e.request&&(e=e.data),r.handleAfterResponseActions(e),e})).catch((function(e){throw s&&(null==o||o.stop()),salla.event.document.requestFailed(i,e),r.handleErrorResponse(e),e}))},t.handleAfterResponseActions=function(e){if(e){var t=e.data,a=e.googleTags,n=void 0===a?null:a,r=t&&t.googleTags?t.googleTags:n;try{dataLayer&&r&&dataLayer.push(r)}catch(e){salla.logger.error(e.message)}this.fireEventsForResponse(e),this.showAlert(e)}},t.fireEventsForResponse=function(e){var t,a,n=(null==e?void 0:e.events)||(null==(t=e.data)?void 0:t.events)||(null==(a=e.error)?void 0:a.events);"string"==typeof n&&(n=JSON.parse(n)),n&&Object.keys(n).forEach((function(e){return salla.event.dispatch(e,n[e])}))},t.handleErrorResponse=function(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)},t.showAlert=function(e){var t,a;if(e&&!this.notifier_handler_disabled)return e.case&&e.msg?salla.notify.fire(e.msg,e.case,e):e.hasOwnProperty("success")&&null!=(t=e.data)&&t.message?salla.notify.fire(null==(a=e.data)?void 0:a.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},t.handleInvalidFields=function(e){var t=e.response.data.error.fields,a=[];Object.keys(t).forEach((function(e){var n=t[e];Array.isArray(n)?n.forEach((function(e){return a.push(e)})):a.push(n)}));var n=(a.length>1?"* ":"")+a.join("\n* ");salla.error(n,e)},t.isFastRequestsAllowed=function(){return Salla.config.get("fastRequests")},t.promise=function(e,t){return void 0===t&&(t=!0),new Promise((function(a,n){return t?a(e):n(e)}))},t.errorPromise=function(e){return this.promise(e,!1)},t.successPromise=function(e){return this.promise(e,!0)},e}(),oe=function(e){function t(){var t;return(t=e.call(this)||this).namespace="component",t.endpoints={getMenus:"menus/{headOrFoot}?store_id={store}&lang={lang}",reviews:"reviews"},t.endpointsMethods={getMenus:"get",reviews:"get"},t}g(t,e);var a=t.prototype;return a.getMenus=async function(e){return void 0===e&&(e="header"),this.request(["getMenus",e,salla.config.get("store.id"),salla.lang.getLocale()]).then((function(e){return salla.event.component.menuFetched(e),e})).catch((function(e){throw salla.event.component.menuFetchFailed(e),e}))},a.getReviews=async function(e){var t=e.per_page,a=void 0===t?5:t,n=e.type,r=void 0===n?"all":n,i=e.items,o=void 0===i?void 0:i;if(!r){var s="Review type cannot be empty. Please provide one.";return salla.event.component.reviewsFetchFailed(s),salla.api.errorPromise(s)}var l=!o||"string"==typeof o&&"[]"===o||Array.isArray(o)&&!o.length;if(!new Set(["all","store","categories","products","json"]).has(r)){var c="Invalid review type. Please provide a valid type.";return salla.event.component.reviewsFetchFailed(c),salla.api.errorPromise(c)}if("all"!==r&&"store"!==r&&l){var u="Items cannot be empty. Please provide one.";return salla.event.component.reviewsFetchFailed(u),salla.api.errorPromise(u)}if(new Set(["products","categories"]).has(r)&&!Array.isArray(o)){var d="Items value must be an array of "+r+" id for review type of "+r+".";return salla.event.component.reviewsFetchFailed(d),salla.api.errorPromise(d)}return this.request(["reviews"],{params:{per_page:a,type:r,items:o}},"get").then((function(e){return salla.event.component.reviewsFetched(e),e})).catch((function(e){throw salla.event.component.reviewsFetchFailed(e),e}))},t}(G),se=function(e){function t(){var t;return(t=e.call(this)||this).namespace="booking",t.endpoints={fetch:"advertisements"},t.endpointsMethods={fetch:"get"},t}return g(t,e),t.prototype.fetch=async function(e){void 0===e&&(e=null);var 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}))},t}(G),le=function(e){function t(){var t;return(t=e.call(this)||this).namespace="navigation",t.endpoints={breadcrumbs:"breadcrumbs"},t.endpointsMethods={breadcrumbs:"get"},t.after_init(),t}return g(t,e),t.prototype.fetchBreadcrumbs=function(e){if(!e.page){var t="The 'page' parameter is required for the Breadcrumb API. Please provide a valid 'page' parameter.";return salla.event.navigation.breadcrumbFetchFailed(t),salla.api.errorPromise(t)}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){var a="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(a),salla.api.errorPromise(a)}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}))},t}(G),ce=function(e){function t(){var t;return(t=e.call(this)||this).namespace="metadata",t.endpoints={fetchValues:"https://api.salla.dev/store/v1/metadata/values"},t.endpointsMethods={fetchValues:"get"},t}return g(t,e),t.prototype.fetchValues=async function(e,t){if(!e||!t){var a="Please provide entity type and entity ids.";return salla.metadata.event.valueNotFetch(a),salla.api.errorPromise(a)}var n={type:e,entities:Array.isArray(t)?t:[t]};return this.request(this.endpoints.fetchValues,{params:n},"get").then((function(e){return salla.metadata.event.valueFetched(e),e})).catch((function(e){throw salla.metadata.event.valueNotFetch(e),e}))},t}(G),ue=function(e){function t(){var t;return(t=e.call(this)||this).auth=new B,t.cart=new z,t.loyalty=new W,t.order=new Q,t.rating=new Y,t.product=new K,t.profile=new J,t.comment=new X,t.currency=new Z,t.document=new $,t.wishlist=new ee,t.scope=new te,t.booking=new ae,t.landing=new ne,t.notifications=new re,t.component=new oe,t.advertisement=new se,t.navigation=new le,t.metadata=new ce,t}return g(t,e),t.prototype.beaconRequest=function(e,t){var a,n,r,i;if(void 0===t&&(t={}),null==(a=window.navigator)||!a.sendBeacon)return fetch(e,t);var o="string"==typeof(null==(n=t)?void 0:n.body)?null==(r=t)?void 0:r.body:JSON.stringify((null==(i=t)?void 0:i.body)||{}),s=new Blob([o],{type:"application/json"});return Salla.log("Beacon payload size: "+s.size+" bytes (~"+(s.size/1024).toFixed(2)+" KB)"),navigator.sendBeacon(e,s),Promise.resolve(new Response('{"status":"sent_via_beacon"}',{status:200,headers:{"Content-Type":"application/json"}}))},t}(ie),de=function(){function t(t){var a,n;if("ready"!==e.status)if(t){var r;if(e.config.merge(t),!["salla.sa","salla.group"].includes(location.hostname)||null!=(a=e.config.get("store.url"))&&a.includes(location.hostname)||!e.config.get("store.username")||e.config.set("store.url",window.location.origin+"/"+e.config.get("store.username")),(null==t?void 0:t.events)&&e.event.dispatchEvents(null==t?void 0:t.events),t._token&&salla.api.setHeader("X-CSRF-TOKEN",t._token),window.self===window.top&&(this.injectMaintenanceAlert(),this.injectThemePreviewAlert()),this.injectTemplateStoreAlert(),this.injectAppInstallAlert(),this.applyContentCopyright(),this.injectEditAlert(),null!=t&&null!=(n=t.user)&&n.language_code)salla.lang.setLocale(null==t||null==(r=t.user)?void 0:r.language_code);salla.lang.loadStoreTranslations(),this.setSallaReady(t),this.afterInit()}else this.setSallaReady(t);else salla.log("Trying to re-initiate Salla, while its status === 'ready'!")}var a=t.prototype;return a.afterInit=function(){e.url.is_page("product.single")&&e.config.isGuest()&&window.addEventListener("mini-checkout::before-init",(function(t){t.preventDefault(),e.event.emit("login::open")}))},a.applyContentCopyright=function(){if(e.config.get("store.settings.content_copyright")){["contextmenu","selectstart","copy"].forEach((function(e){document.addEventListener(e,(function(e){(function(e){var t;if(!e)return!1;var a=null==(t=e.tagName)?void 0:t.toLowerCase();return"input"===a||"textarea"===a})(e.target)||e.preventDefault()}))})),document.addEventListener("keydown",(function(e){var t=e.key.toLowerCase();("f12"===t||e.ctrlKey&&e.shiftKey&&["i","j","c"].includes(t)||e.ctrlKey&&"u"===t)&&(e.preventDefault(),e.stopPropagation())}));var t=document.createElement("style");t.textContent="\n body {\n -webkit-touch-callout: none;\n -webkit-user-select: none;\n -moz-user-select: none;\n -ms-user-select: none;\n user-select: none;\n }\n input, textarea {\n -webkit-touch-callout: auto;\n -webkit-user-select: auto;\n -moz-user-select: auto;\n -ms-user-select: auto;\n user-select: auto;\n }\n img {\n pointer-events: none;\n -webkit-user-drag: none;\n }\n ",document.head.appendChild(t)}},a.injectMaintenanceAlert=function(){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((function(){return document.body.prepend(document.createElement("salla-maintenance-alert"))})))},a.injectTemplateStoreAlert=function(){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((function(){return document.body.append(document.createElement("salla-bottom-alert"))})))},a.injectAppInstallAlert=function(){salla.config.get("store.app_install_prompt")&&salla.config.get("store.apps")&&!salla.storage.get("app_install_prompt_disabled")&&!salla.config.isMobileApp()&&(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((function(){return document.body.append(document.createElement("salla-app-install-alert"))})))},a.injectThemePreviewAlert=function(){"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((function(){var 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)})))},a.injectEditAlert=function(){var e=salla.config.get("edit");e&&(document.querySelector("#s-edit-alert")?salla.logger.warn("#s-edit-alert element Existed before!"):salla.lang.onLoaded((function(){var 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)})))},a.handleElementAjaxRequest=function(e,t){var a=this;if(!(t instanceof HTMLFormElement||t instanceof HTMLAnchorElement))return salla.logger.warn("trying to call ajax from non Element!!"),!1;e.preventDefault();var n=t.getAjaxFormData(e),r=n.method?n.method.toLowerCase():void 0;salla.api.request(n.url,n.formData,r).then((function(e){return e.data&&e.request&&(e=e.data),salla.api.handleAfterResponseActions(e),a.callAjaxEvent(n.events.success,e,n.formData),e})).catch((function(e){throw salla.api.handleErrorResponse(e),a.callAjaxEvent(n.events.fail,e,n.formData),e}))},a.callAjaxEvent=function(e,t,a){if(e){if(a instanceof FormData){var n={};Array.from(a.entries()).forEach((function(e){n[e[0]]=e[1]})),a=n}window[e]?window[e](t,a):salla.event.dispatch(e,t,a)}},a.setSallaReady=function(t){this.storeUTMs(),e.event.emitAsync("twilight::before.ready",t),e.status="ready",e.event.dispatch("twilight::initiated",t),window.dispatchEvent(new CustomEvent("twilight::initiated",{detail:t}))},a.storeUTMs=function(){var e=["fbclid","gad_source","ttclid","twclid","scid"],t=["utm_source","utm_medium","utm_campaign","utm_term","utm_content"].concat(e),a={},n={};window.location.search.replace("?","").split("&").map((function(e){return e.split("=")})).filter((function(e){var a=e[0];return t.includes(a.toLowerCase())})).forEach((function(e){var t=e[0],n=e[1],r=n||"";try{r=decodeURIComponent(n)}catch(e){console.warn("Failed to decode UTM param:",t,n,e)}a[t.toLowerCase()]=r}));var r=e.find((function(e){return a[e]}));!a.utm_source&&r&&(a.utm_source={fbclid:"facebook",gad_source:"google",ttclid:"tiktok",twclid:"twitter",scid:"snapchat"}[r],a.utm_campaign=a.utm_campaign||"Using the CLICKID "+r+" provided by "+a.utm_source,a.utm_term=a.utm_term||r+": "+a[r]),a.utm_source&&(Object.entries(a).filter((function(t){var a=t[0];return!e.includes(a)})).forEach((function(e){var t=e[0],a=e[1];n["s-"+t.replace("_","-")]=a})),n["s-utm-referrer"]=document.referrer,salla.storage.setWithTTL("s-utms",n,129600),this.logUTMVisitData(n))},a.logUTMVisitData=async function(e){var t=e["s-utm-source"],a=e["s-utm-medium"],n=e["s-utm-campaign"];e&&"affiliate"===t&&a&&n&&fetch(salla.config.get("affiliate.utm_url"),{method:"POST",mode:"cors",headers:{"Content-Type":"application/json","s-utm-source":t,"s-utm-medium":a,"s-utm-campaign":n}}).then((function(e){if(e.ok){var t=new URL(window.location.href),a=window.history.state;t.searchParams.delete("utm_source"),t.searchParams.delete("utm_medium"),t.searchParams.delete("utm_campaign"),window.history.replaceState(a,"",t)}}))},t}(),pe=function(){function e(){var e=this;Salla.onReady((function(){return e.init()}))}var t=e.prototype;return t.init=function(){var e,t=this;if(salla.config.get("store.features",[]).includes("sso-login")){if(window.location.hostname.includes("salla"))return salla.log("SSO is not supported yet for stores without custom domain.");salla.auth.event.onLoggedOut((function(){return new Promise((function(e){var t=document.createElement("iframe");t.style.display="none",t.src=salla.url.get("sso/logout"),document.body.appendChild(t),t.onload=function(){document.body.removeChild(t),e()}}))})),null==(e=document.querySelector("salla-login-modal"))||e.remove(),Salla.event.removeAllListeners("login::open"),Salla.event.prependListener("login::open",(function(){return t.redirect()})),window.addEventListener("mini-checkout::before-init",(function(e){Salla.config.isUser()||(e.preventDefault(),t.redirect())}))}},t.redirect=function(){var e=window.location.pathname+window.location.search,t=window.location.origin+"/sso/login?intended_to="+encodeURIComponent(e);return console.log("Redirecting to:",t),window.location.href=t,!0},e}(),he=function(){function e(e){this.item=e[0]}return e.prototype.toSegment=function(){var e,t,a,n;return{event:"Product Added",properties:{cart_id:null==(e=this.item.cart_id)?void 0:e.toString(),product_id:null==(t=this.item.id)?void 0:t.toString(),category:this.item.category,currency:null==(a=Salla.config.currency())?void 0:a.code,name:this.item.name,brand:this.item.brand,variant:null==(n=this.item.variant)?void 0:n.toString(),price:this.item.price,quantity:this.item.quantity,sku:this.item.sku,coupon:this.item.coupon,position:this.item.position,url:this.item.url,image_url:this.item.image_url}}},e.shouldSend=function(){return"customer.wishlist"!==salla.config.get("page.slug")},e}(),fe=function(){function e(e){this.product=e[0]}return e.prototype.toSegment=function(){var e;return{event:"Product Viewed",properties:{product_id:null==(e=this.product.id)?void 0:e.toString(),category:this.product.category,name:this.product.name,brand:this.product.brand,variant:this.product.variant,price:this.product.price,quantity:this.product.quantity,currency:this.product.currency,coupon:this.product.coupon,position:this.product.position,value:this.product.value,sku:this.product.sku,url:this.product.url,image_url:this.product.image_url}}},e}(),ge=function(){function e(e){this.cart=e[0]}return e.prototype.toSegment=function(){var e;return{event:"Cart Viewed",properties:{cart_id:null==(e=this.cart.cart_id)?void 0:e.toString(),products:this.cart.products.map((function(e){var t,a;return{product_id:null==(t=e.id)?void 0:t.toString(),name:e.name,price:e.price,category:e.category,sku:e.sku,position:e.position,url:e.url,image_url:e.image_url,brand:e.brand,currency:null==(a=Salla.config.currency())?void 0:a.code,variant:e.variant,coupon:e.coupon,quantity:e.quantity}}))}}},e}(),ve=function(){function e(e){var t=null==e?void 0:e.nextPage;this.listId=salla.config.get("page.slug"),Salla.config.get("page.id")&&(this.listId+="_"+salla.config.get("page.id")),this.sorts=null;try{if(t){var a=new URL(t).searchParams.get("sort");a&&(this.sorts=[{type:"sort",value:a}])}e.source&&(this.listId=this.listId+"_"+e.source),e.sourceValue&&(this.listId=this.listId+"_"+(Array.isArray(e.sourceValue)?e.sourceValue.join("_"):e.sourceValue))}catch(e){salla.logger.error(e)}this.products=null==e?void 0:e.data}return e.prototype.toSegment=function(){return{event:"Product List Viewed",properties:{list_id:this.listId,category:salla.config.get("page.title"),sorts:this.sorts,products:this.products.map((function(e){var t,a,n,r,i,o;return{product_id:e.id,category:null==(t=e.category)?void 0:t.name,currency:null==(a=Salla.config.currency())?void 0:a.code,name:e.name,brand:null==(n=e.brand)?void 0:n.name,variant:null==(r=e.variant)?void 0:r.toString(),coupon:null==(i=e.coupon)?void 0:i.toString(),price:e.price,quantity:Number(e.quantity),sku:e.sku,position:0,url:e.url,image_url:null==(o=e.image)?void 0:o.url}}))}}},e.shouldSend=function(e){return!((null==e?void 0:e.nextPage)||"").includes("filters")&&!["index","customer.wishlist"].includes(salla.config.get("page.slug"))},e}(),me=function(){function e(e){this.query=e}return e.prototype.toSegment=function(){return{event:"Products Searched",properties:{query:this.query}}},e}(),ye=function(){function e(){this.user=JSON.parse(localStorage.getItem("user"))}return e.prototype.toSegment=function(){var e,t,a,n,r;return{event:"Signed In",properties:{first_name:null==(e=this.user)?void 0:e.first_name,last_name:null==(t=this.user)?void 0:t.last_name,type:null==(a=this.user)?void 0:a.type,mobile:null==(n=this.user)?void 0:n.mobile,email:null==(r=this.user)?void 0:r.email}}},e.shouldSend=function(){return"user"===Salla.config.get("user.type")?!Salla.analytics.history.find((function(e){return"Signed In"===e.eventName})):(Salla.profile.event.onInfoFetched((function(){return Salla.event.emit("Signed In")})),!1)},e}(),we=function(e){function t(){return e.apply(this,arguments)||this}return g(t,e),t.prototype.toSegment=function(){var t=e.prototype.toSegment.call(this);return{event:"Signed Up",properties:null==t?void 0:t.properties}},t.shouldSend=function(){return"user"===Salla.config.get("user.type")||(Salla.profile.event.onInfoFetched((function(){return Salla.event.emit("Signed Up")})),!1)},t}(ye),Se=function(){function e(){}return e.prototype.toSegment=function(){return{event:"Signed Out",properties:{}}},e}(),be=function(){function e(e){this.item=e[0]}return e.prototype.toSegment=function(){var e,t,a,n,r,i,o,s,l,c,u,d,p,h;return{event:"Product Removed",properties:{cart_id:null==(e=this.item)||null==(e=e.cart_id)?void 0:e.toString(),product_id:null==(t=this.item)||null==(t=t.id)?void 0:t.toString(),category:null==(a=this.item)?void 0:a.category,currency:null==(n=Salla.config.currency())?void 0:n.code,name:null==(r=this.item)?void 0:r.name,brand:null==(i=this.item)?void 0:i.brand,variant:null==(o=this.item)?void 0:o.variant,price:null==(s=this.item)?void 0:s.price,quantity:null==(l=this.item)?void 0:l.quantity,sku:null==(c=this.item)?void 0:c.sku,coupon:null==(u=this.item)?void 0:u.coupon,position:null==(d=this.item)?void 0:d.position,url:null==(p=this.item)?void 0:p.url,image_url:null==(h=this.item)?void 0:h.image_url}}},e}(),_e=function(){function e(e){this.product=e.data.product}return e.prototype.toSegment=function(){var e,t,a,n;return{event:"Product Added to Wishlist",properties:(n={wishlist_id:salla.config.get("store.id")+"_"+salla.config.get("user.id"),wishlist_name:salla.config.get("store.name"),product_id:null==(e=this.product.id)?void 0:e.toString(),name:this.product.name,brand:this.product.brand,variant:this.product.variant,price:this.product.price,quantity:Math.max(1,Number(this.product.quantity)),sku:this.product.sku||null,position:Number(this.product.position||0),url:this.product.url,image_url:(null==(t=this.product)?void 0:t.image)||null,category:this.product.category,currency:null==(a=Salla.config.currency())?void 0:a.code},n.brand=this.product.brand,n)}},e}(),Fe=function(){function e(e){this.product=e.data.product}return e.prototype.toSegment=function(){var e,t,a,n;return{event:"Product Removed from Wishlist",properties:(n={wishlist_id:salla.config.get("store.id")+"_"+salla.config.get("user.id"),wishlist_name:salla.config.get("store.name"),product_id:null==(e=this.product.id)?void 0:e.toString(),name:this.product.name,brand:this.product.brand,variant:this.product.variant,price:this.product.price,quantity:Math.max(1,Number(this.product.quantity)),sku:this.product.sku||null,coupon:this.product.coupon||null,position:Number(this.product.position||0),currency:null==(t=Salla.config.currency())?void 0:t.code,url:this.product.url,image_url:(null==(a=this.product)?void 0:a.image)||null,category:this.product.category},n.brand=this.product.brand,n)}},e}(),Ce=function(){function e(e){this.details=e[0]}return e.prototype.toSegment=function(){return{event:"Order Completed",properties:this.details}},e}(),ke=function(){function e(e){this.item=e[0]}return e.prototype.toSegment=function(){var e,t;return{event:"Wishlist Product Added to Cart",properties:{wishlist_id:salla.config.get("store.id")+"_"+salla.config.get("user.id"),wishlist_name:salla.config.get("store.name"),cart_id:null==(e=this.item.cart_id)?void 0:e.toString(),product_id:null==(t=this.item.id)?void 0:t.toString(),category:this.item.category,name:this.item.name,brand:this.item.brand,variant:this.item.variant,price:this.item.price,quantity:this.item.quantity,sku:this.item.sku,coupon:this.item.coupon,position:this.item.position,url:this.item.url,image_url:this.item.image_url}}},e.shouldSend=function(){return"customer.wishlist"===salla.config.get("page.slug")},e}(),Pe=function(){function e(e){this.data=e}return e.prototype.toSegment=function(){var e,t=(null==(e=Salla.analytics.history.find((function(e){return"Product Viewed"===e.eventName})))?void 0:e.payload)||{};return t.share_via=this.data.share_via,{event:"Product Shared",properties:t}},e.shouldSend=function(){return"product.single"===salla.config.get("page.slug")},e}(),Ae=function(){function e(e){this.details=e}return e.prototype.toSegment=function(){return{event:"Product Reviewed",properties:this.details}},e.registerEvent=function(){salla.event.rating.onProductsRated((function(e,t){var a=t.products,n=t.order_id;Object.values(a).forEach((function(e){var t;Salla.event.emit("Product Reviewed",{product_id:null==(t=e.product_id)?void 0:t.toString(),review_id:null==n?void 0:n.toString(),review_body:e.comment,rating:e.rating})}))}))},e}(),qe=function(){function e(e){this.promotion=e[0]}return e.prototype.toSegment=function(){var e;return{event:"Promotion Viewed",properties:{promotion_id:null==(e=this.promotion.id)?void 0:e.toString(),creative:this.promotion.creative,name:this.promotion.name,position:this.promotion.position}}},e}(),Ee=function(){function e(e){this.promotion=e[0]}return e.prototype.toSegment=function(){var e;return{event:"Promotion Clicked",properties:{promotion_id:null==(e=this.promotion.id)?void 0:e.toString(),creative:this.promotion.creative,name:this.promotion.name,position:this.promotion.position}}},e}(),Ie=function(){function e(e){this.transaction=e}var t=e.prototype;return t.getCartId=function(){var e,t;return"cart"===salla.config.get("page.slug")?null==(t=salla.config.get("page.id"))?void 0:t.toString():(null==(e=this.transaction)||null==(e=e.data)||null==(e=e.cart)||null==(e=e.id)?void 0:e.toString())||""},t.toSegment=function(){var e,t;return{event:"Coupon Applied",properties:{cart_id:this.getCartId(),coupon_name:(null==(e=this.transaction)||null==(e=e.data)||null==(e=e.cart)?void 0:e.coupon)||"",discount:(null==(t=this.transaction)||null==(t=t.data)||null==(t=t.cart)?void 0:t.discount)||0,currency:salla.config.get("user.currency")||""}}},e}(),xe=function(){function e(e){this.transaction=e}var t=e.prototype;return t.getCartId=function(){var e;return"cart"===salla.config.get("page.slug")?null==(e=salla.config.get("page.id"))?void 0:e.toString():""},t.getCouponCode=function(){try{var e,t,a=null==(e=this.transaction.response)||null==(e=e.config)?void 0:e.data;return a?null==(t=JSON.parse(a))?void 0:t.coupon:""}catch(e){return""}},t.toSegment=function(){var e;return{event:"Coupon Denied",properties:{cart_id:this.getCartId(),coupon_name:this.getCouponCode(),reason:(null==(e=this.transaction.response)||null==(e=e.data)||null==(e=e.error)?void 0:e.message)||"Unknown error"}}},e}(),Te=function(){function e(e){this.transaction=e}var t=e.prototype;return t.getCartId=function(){var e,t;return"cart"===salla.config.get("page.slug")?null==(t=salla.config.get("page.id"))?void 0:t.toString():(null==(e=this.transaction)||null==(e=e.data)||null==(e=e.cart)||null==(e=e.id)?void 0:e.toString())||""},t.toSegment=function(){var e,t;return{event:"Coupon Removed",properties:{cart_id:this.getCartId(),coupon_name:(null==(e=this.transaction)?void 0:e.coupon)||"",discount:(null==(t=this.transaction)||null==(t=t.data)||null==(t=t.cart)?void 0:t.discount)||0,currency:salla.config.get("user.currency")||""}}},e}(),Le=function(){function e(e){this.details=null==e?void 0:e.data}return e.prototype.toSegment=function(){var t=this,a=["first_name","last_name","birthday","gender"].filter((function(a){var n,r;return e.user[a]!==(null==(n=t.details)?void 0:n[a])&&(void 0!==e.user[a]||void 0!==(null==(r=t.details)?void 0:r[a]))}));return e.setUser(this.details),{event:"User Profile Updated",properties:{updated_fields:a}}},e.registerEvent=function(){Salla.onReady((function(){salla.url.is_page("customer.profile")&&e.setUser(Salla.config.get("user"))}))},e.setUser=function(t){e.user={first_name:null==t?void 0:t.first_name,last_name:null==t?void 0:t.last_name,gender:null==t?void 0:t.gender,birthday:null==t?void 0:t.birthday,avatar:null==t?void 0:t.avatar}},e.shouldSend=function(){return"user"===Salla.config.get("user.type")},e}();Le.user={};var Re=function(e){function t(t){var a;a=e.call(this,t)||this;var n=(null==t?void 0:t.nextPage)||"";return a.filters=a.extractFilters(n),a}g(t,e);var a=t.prototype;return a.extractFilters=function(e){if(!e)return null;try{var t=new URL(e),a=[];return Array.from(t.searchParams.entries()).forEach((function(e){var t=e[0],n=e[1];if(t.startsWith("filters[")){var r=t.match(/^filters\[(.*?)\]/),i=r?r[1]:t;a.push({type:i,value:n})}})),a.length>0?a:null}catch(e){return console.warn("Error extracting filters from URL:",e),null}},a.toSegment=function(){var t=e.prototype.toSegment.call(this);return{event:"Product List Filtered",properties:f({},null==t?void 0:t.properties,{filters:this.filters})}},t.shouldSend=function(e){return((null==e?void 0:e.nextPage)||"").includes("filters")},t}(ve),Oe=function(){function e(e){this.cart=e}return e.prototype.toSegment=function(){var e,t,a,n,r=this;return{event:"Cart Updated",properties:{cart_id:null==(e=this.cart.id)?void 0:e.toString(),value:this.cart.total,revenue:this.cart.sub_total,tax:this.cart.tax_amount,discount:this.cart.total_discount,shipping:this.cart.real_shipping_cost,currency:null==(t=Salla.config.currency())?void 0:t.code,affiliation:null==(a=Salla.storage.getWithTTL("s-utms"))?void 0:a["s-utm-source"],products:null==(n=this.cart.items)?void 0:n.map((function(e){var t,a,n,i,o,s;return{product_id:null==(t=e.product_id)?void 0:t.toString(),name:e.product_name,price:e.product_price,category:null==(a=e.category)?void 0:a.toString(),sku:null==(n=e.product_sku)?void 0:n.toString(),position:e.position,url:e.url,image_url:e.product_image,brand:null==(i=e.brand)?void 0:i.toString(),currency:null==(o=Salla.config.currency())?void 0:o.code,variant:null==(s=e.variant)?void 0:s.toString(),coupon:r.cart.coupon,quantity:e.quantity}}))}}},e.shouldSend=function(){return"cart"===salla.config.get("page.slug")},e}(),je=function(){function e(e){this.scope=e.data}var t=e.prototype;return t.toSegment=function(){return{event:"Market Selected",properties:f({},this.getScope(this.scope),{prev:this.getScope(Salla.config.get("store.scope"))})}},t.getScope=function(e){var t;return{id:null==(t=(e=e||{}).id)?void 0:t.toString(),country:this.getScopeAttribute(e,"countries"),currency:this.getScopeAttribute(e,"currencies"),locale:this.getScopeAttribute(e,"languages")}},t.getScopeAttribute=function(e,t){return e=e[t],Array.isArray(e)?e[0]:e},e}(),De=function(){function e(){}return e.registerEvents=function(){Object.values(this.events).forEach((function(e){e.forEach((function(e){"function"==typeof e.registerEvent&&e.registerEvent()}))}))},e.transform=function(e,t){try{for(var a,n=h(this.events[e]||[]);!(a=n()).done;){var r=a.value;if(r&&("function"!=typeof r.shouldSend||r.shouldSend(t))){var i=new r(t).toSegment();return{event:i.event,properties:i.properties}}}return null}catch(e){return console.error("Failed to transform event:",e),null}},e}();De.events={"Order Completed":[Ce],"Product Added":[he,ke],"Product Removed":[be],"Product Viewed":[fe],"Product Added to Wishlist":[_e],"Product Removed from Wishlist":[Fe],"Cart Viewed":[ge],"Products Searched":[me],"Product List Viewed":[ve],"Product List Filtered":[Re],"Signed Up":[we],"Signed In":[ye],"Signed Out":[Se],"Product Reviewed":[Ae],"Product Shared":[Pe],"Promotion Viewed":[qe],"Promotion Clicked":[Ee],"Coupon Applied":[Ie],"Coupon Removed":[Te],"Coupon Denied":[xe],"User Profile Updated":[Le],"Cart Updated":[Oe],"Market Selected":[je]};var Ue=function(){function e(){var e=this;this.history=[],this.customTrackers=[],this.mappedEvents={"wishlist::added":"Product Added to Wishlist","wishlist::removed":"Product Removed from Wishlist","salla-products-list::products.fetched":["Product List Viewed","Product List Filtered"],"auth::registered":"Signed Up","auth::logged.in":"Signed In","auth::logged.out":"Signed Out","share-element":"Product Shared","promotion::viewed":"Promotion Viewed","promotion::clicked":"Promotion Clicked","cart::coupon.added":"Coupon Applied","cart::coupon.deleted":"Coupon Removed","cart::coupon.addition.failed":"Coupon Denied","profile::updated":"User Profile Updated","cart::updated":"Cart Updated","scope::changed":"Market Selected"},Salla.event.onAny((function(t,a){try{if(Object.keys(e.mappedEvents).includes(t)){var n=e.mappedEvents[t];return void(Array.isArray(n)?n:[n]).forEach((function(e){return Salla.event.emit(e,a)}))}if(!Salla.config.get("jitsu.events",[]).includes(t))return;var r=De.transform(t,a);r&&e.track(r.event,r.properties)}catch(e){Salla.log("Error in analytics event handling:",e)}})),Salla.event.on("twilight::before.ready",(function(t){var a,n,r,o,s;e.debugAnalytics=i.jitsuAnalytics({host:e.getAnalyticsHost(t),writeKey:"bbLD6Xqr1OKsDJfxZBCy7SJN1RIsrkBp:WEa99iY220v9qX7KiuAlML9ldSFJKW2p",fetch:e.customFetch}),e.debugAnalytics.setContextProperty("library",{twilight:Salla.versions});var l=(null==t?void 0:t.jitsu)||{},c=l.host,u=l.key;if(e.jitsuAnalytics=null,c&&u){var d;if(De.registerEvents(),e.initVisitorData(),e.jitsuAnalytics=i.jitsuAnalytics({host:e.getAnalyticsHost(t),writeKey:u,cookieCapture:{vsc:"vsc"}}),e.setContext("store_id",null==(a=t.store)?void 0:a.id),e.setContext("version",null==(n=t.jitsu)?void 0:n.version),e.setContext("library",{twilight:Salla.versions}),null!=(r=t.jitsu)&&null!=(r=r.context)&&r.extra&&e.setExtraContext(t.jitsu.context.extra),null!=(o=t.store)&&null!=(o=o.scope)&&o.id)e.setContext("scope",null==(d=t.store)?void 0:d.scope);"user"===(null==t||null==(s=t.user)?void 0:s.type)&&e.setContext("traits",e.getFormattedUser(t.user)),e.registerTracker({name:"DefaultSallaTracker",track:function(t,a){return e.jitsuAnalytics.track(t,a)},page:function(t){return e.jitsuAnalytics.page(t)}})}else salla.log("Jitsu configuration is missing. Analytics will not be tracked.")})),Salla.onReady((function(){var t,a={name:Salla.config.get("page.slug",""),id:null==(t=Salla.config.get("page.id",""))?void 0:t.toString()};e.setContext("page",a),e.page(a)}))}var t=e.prototype;return t.setExtraContext=function(e){var t;null!=e&&null!=(t=e.headers)&&t["s-app-os"]&&(this.setContext("app",{version:e.headers["s-app-os-version"],app_release_tag:e.headers["s-app-version"],platform:e.headers["s-app-os"].toLowerCase()}),delete e.headers["s-app-os"],delete e.headers["s-app-os-version"],delete e.headers["s-app-version"],delete e.headers["s-source"]),this.setContext("system",e)},t.getAnalyticsHost=function(e){var t,a="https://salla.cloud/_app/e";if(null==e||null==(t=e.store)||!t.url)return Salla.log("Error getting store url - no config or store URL provided"),a;var n=e.store.url;try{var r="",i=n;if(/https:\/\/demostore\.salla\.sa/.test(i))return Salla.log("demostore.salla.sa detected, using fallback URL"),a;var o=i.match(/(salla\.sa)\/(?:(ar|en)\/)?((?!ar$|en$)[a-zA-Z0-9.-]+)/);if(o){var s=o[3];if(!s||0===s.trim().length||"ar"===s||"en"===s)return Salla.log("Error: invalid or empty store name in salla.sa URL"),a;r=new URL(i).origin+"/"+s}else{r=new URL(i).origin}return r+"/_app/e"}catch(e){return Salla.log("Error getting store url, forwarding to salla.cloud:",e),a}},t.setContext=function(e,t){var a,n;null==(a=this.jitsuAnalytics)||a.setContextProperty(e,t),null==(n=this.debugAnalytics)||n.setContextProperty(e,t)},t.customFetch=function(e,t){var a;return Salla.api.beaconRequest(e+"?writekey="+(null==t||null==(a=t.headers)?void 0:a["X-Write-Key"]),t)},t.track=function(e,t){void 0===t&&(t={}),t=this.finalPayload(t),this.history.push({action:"track",eventName:e,payload:t}),this.pushEventToCustomTrackers("track",e,t)},t.log=function(e,t){var a;return void 0===t&&(t={}),null==(a=this.debugAnalytics)?void 0:a.track(e,t).catch((function(e){return salla.log("Error tracking event:",e),Promise.reject(e)}))},t.page=function(e){var t,a;void 0===e&&(e={}),(e=this.finalPayload(e)).id=null==(t=e.id||Salla.config.get("page.id",""))?void 0:t.toString(),e.name=e.name||Salla.config.get("page.slug"),e.keywords=e.keywords||(null==(a=document.querySelector("meta[name=keywords]"))?void 0:a.content),e.referrer=e.referrer||document.referrer,this.history.push({action:"page",payload:e}),this.pushEventToCustomTrackers("page",e)},t.finalPayload=function(e){void 0===e&&(e={});var t=Salla.storage.getWithTTL("s-utms");if(t){var a,n=t["s-utm-campaign"],r=t["s-utm-source"],i=t["s-utm-medium"],o=t["s-utm-term"],s=t["s-utm-content"],l=t["s-utm-referrer"];null==(a=Salla.analytics)||a.setContext("campaign",{name:n,source:r,medium:i,term:o,content:s,referrer:l})}return f({},{},e)},t.registerTracker=function(e){"object"==typeof e?"string"==typeof e.name&&e.name?"function"==typeof e.track?"function"==typeof e.page?this.customTrackers.find((function(t){return t.name===e.name}))?Salla.log("tracker with the same name already exists!"):(this.customTrackers.push(e),this.history.forEach((function(t){return"track"===t.action?e.track(t.eventName,t.payload):"page"===t.action?e.page(t.payload):void 0}))):Salla.log("tracker.page most be a function!"):Salla.log("tracker.track most be a function!"):Salla.log("tracker.name most be a string!"):Salla.log('tracker most be an object {name:"tracker name", track: callback, page: callback}!')},t.pushEventToCustomTrackers=function(e,t,a){var n=this;void 0===a&&(a={});var r="page"===e?[t]:[t,a];return Promise.allSettled(this.customTrackers.map((function(t){return n.pushEventToCustomTracker(t[e],r)}))).then((function(t){return t.filter((function(e){return"rejected"===e.status})).map((function(t){return Salla.log("Error on customTracker to send "+e,t)}))}))},t.pushEventToCustomTracker=function(e,t){try{var a=e.apply(void 0,t);return Promise.resolve(a).catch((function(e){return Promise.reject(e)}))}catch(e){return Promise.reject(e)}},t.getFormattedUser=function(e){return e.phone=e.mobile,e.country=e.country_code,e.language=e.language_code,e.currency=e.currency_code,e},t.initVisitorData=function(){null!=Salla.cookie.get("vsc")||Salla.cookie.set("vsc",""+Date.now(),1)},e}(),Ne=function(){function e(){var e=this;Salla.onReady((function(){return e.init()}))}var t=e.prototype;return t.init=function(){if(!Salla.config.isUser()){var e=new URLSearchParams(window.location.search);if(e.has("intended_to"))try{var t=new URL(e.get("intended_to"));if(t.hostname!==window.location.hostname)return;return this.handleAfterLoginEvent(t)}catch(e){return void console.warn("Invalid URL provided in intended_to parameter")}}},t.handleAfterLoginEvent=function(e){var t="intend::user.logged.in";Salla.event.on(t,(function(){return window.location=e})),Salla.api.auth.setAfterLoginEvent(t),Salla.api.auth.setCanRedirect(!1),Salla.event.on("salla-login::ready",(function(){return Salla.event.emit("login::open",{withoutReload:!0})}))},e}(),Me=function(){function e(e){var t=this;void 0===e&&(e={}),this.config=f({WHITELIST:[location.hostname,"salla.com","salla.sa","salla.dev","salla.network","salla.group","mtjr.at"],POLL_INTERVAL_MS:500,WHITELIST_PAGES:["customer.orders.single","page-single","blog.single","blog.index"]},e),this.originalMethods={},this.isInitialized=!1,Salla.onReady((function(){return t.init()}))}var t=e.prototype;return t.normalizeUrl=function(e){try{return new URL(e,location.href)}catch(e){return null}},t.shouldIgnoreUrl=function(e){if(!e)return!1;var t="string"==typeof e?e:e.href||String(e),a=t.toLowerCase();if(["tel:","mailto:","javascript:"].some((function(e){return a.startsWith(e)})))return!0;try{var n=new URL(t,location.href).hostname.toLowerCase();return["facebook.com","fb.com","twitter.com","x.com","instagram.com","linkedin.com","youtube.com","youtu.be","tiktok.com","snapchat.com","pinterest.com","whatsapp.com","wa.me","iwtsp.com","telegram.org","t.me","discord.com","discord.gg","reddit.com","tumblr.com","google.com","forms.gle","maps.app.goo.gl","goo.gl","apple.com","smsaexpress.com","aramex.com","aj-ex.com","redboxsa.com","fastcoo-tech.com","express.dhl","najizxpress.net","jtexpress.me","jtexpress-sa.com","tamex.com.sa","aymakan.com.sa","fastlo.com","sls-express.com","logestechs.com","massuul.com","tamara.co","gov.sa","org.sa","stc.com.sa","sa","addtoany.com","wchat.freshchat.com","getbutton.io","heyzine.com","linktr.ee"].some((function(e){return n===e||n.endsWith("."+e)}))}catch(e){return!1}},t.isWhitelisted=function(e){if(!e)return!1;for(var t,a=e.hostname.toLowerCase(),n=h(this.config.WHITELIST);!(t=n()).done;){var r=t.value,i=String(r||"").toLowerCase().trim();if(i&&(a===i||a.endsWith("."+i)))return!0}return!1},t.emit=function(e){try{window.__redirectLogs||(window.__redirectLogs=[]),window.__redirectLogs.push(e);try{Salla.analytics.log("redirect",e)}catch(e){}}catch(e){}},t.logRedirect=function(e,t,a){if(!this.shouldIgnoreUrl(t)){var n=this.normalizeUrl(t),r=this.normalizeUrl(location.href),i=this.isWhitelisted(n),o={redirect_source:e,redirect_from:r?r.href:String(location.href),redirect_to:n?n.href:String(t),redirect_host:n?n.hostname:null,redirect_referrer:document.referrer||null,page_slug:Salla.config.get("page.slug"),whitelisted:i,stack:a&&a.stack?String(a.stack):void 0,meta:a||void 0};i||this.emit(o)}},t.hookHistoryAPIs=function(){var e=this;["pushState","replaceState"].forEach((function(t){try{var a=history[t];"function"==typeof a&&(e.originalMethods["history."+t]=a,history[t]=function(){for(var n=arguments.length,r=new Array(n),i=0;i<n;i++)r[i]=arguments[i];try{var o;e.logRedirect(t,null!=(o=r[2])?o:location.href)}catch(e){}return a.apply(history,r)})}catch(e){}})),window.addEventListener("popstate",(function(){e.logRedirect("popstate",location.href)})),window.addEventListener("hashchange",(function(){e.logRedirect("hashchange",location.href)}))},t.hookLocationMethods=function(){var e=this;try{var t=location.assign.bind(location);this.originalMethods["location.assign"]=t,location.assign=function(a){return e.logRedirect("location.assign",a,{stack:(new Error).stack}),t(a)}}catch(e){}try{var a=location.replace.bind(location);this.originalMethods["location.replace"]=a,location.replace=function(t){return e.logRedirect("location.replace",t,{stack:(new Error).stack}),a(t)}}catch(e){}},t.hookWindowOpen=function(){var e=this;try{var t=window.open;this.originalMethods["window.open"]=t,window.open=function(a){a&&e.logRedirect("window.open",a,{stack:(new Error).stack});for(var n=arguments.length,r=new Array(n>1?n-1:0),i=1;i<n;i++)r[i-1]=arguments[i];return t.apply(window,[a].concat(r))}}catch(e){}},t.setupEventListeners=function(){var e=this;this.handleLinkClick=function(t){var a=t.target&&t.target.closest?t.target.closest("a[href]"):null;if(a){var n=a.getAttribute("href");if(n&&!n.startsWith("#")&&!e.shouldIgnoreUrl(n)){var r=a.getAttribute("target")||"_self";setTimeout((function(){e.logRedirect("link-click",n,{target:r})}),0)}}},document.addEventListener("click",this.handleLinkClick,!0),this.handleFormSubmit=function(t){var a=t.target,n=a&&a.getAttribute&&a.getAttribute("action")||location.href,r=(a&&a.method?String(a.method):"GET").toUpperCase();e.logRedirect("form-submit",n,{method:r})},document.addEventListener("submit",this.handleFormSubmit,!0)},t.setupPerformanceObserver=function(){var e=this;try{this.performanceObserver=new PerformanceObserver((function(t){for(var a,n=h(t.getEntries());!(a=n()).done;){var r=a.value;"navigation"===r.entryType&&e.logRedirect("performance-navigation",location.href,{type:r.type,redirectCount:r.redirectCount})}})),this.performanceObserver.observe({type:"navigation",buffered:!0})}catch(e){}},t.init=function(){if(!this.config.WHITELIST_PAGES.includes(Salla.config.get("page.slug"))&&!this.isInitialized){var e=new URL(Salla.config.get("store.url")).hostname.split(".").slice(-2).join(".");this.config.WHITELIST.includes(e)||this.config.WHITELIST.push(e),this.hookHistoryAPIs(),this.hookLocationMethods(),this.hookWindowOpen(),this.setupEventListeners(),this.setupPerformanceObserver(),this.isInitialized=!0}},t.destroy=function(){var e=this;this.isInitialized&&(Object.keys(this.originalMethods).forEach((function(t){var a=t.split("."),n=a[0],r=a[1];"history"===n&&e.originalMethods[t]?history[r]=e.originalMethods[t]:"location"===n&&e.originalMethods[t]?location[r]=e.originalMethods[t]:"window"===n&&"open"===r&&e.originalMethods[t]&&(window.open=e.originalMethods[t])})),this.handleLinkClick&&document.removeEventListener("click",this.handleLinkClick,!0),this.handleFormSubmit&&document.removeEventListener("submit",this.handleFormSubmit,!0),this.performanceObserver&&this.performanceObserver.disconnect(),this.isInitialized=!1)},e}(),He=function(){function e(){this._store=new Map,this._whitelist=new Map([["salla-add-product-button",new Set(["validate","componentDidLoad"])],["salla-products-list",new Set(["componentDidLoad"])]]),this._componentHistory=new Map}var t=e.prototype;return t.registerHook=function(e,t,a,n){var r=this;if(void 0===n&&(n={}),!this._isAllowed(e,t))return console.warn('[Hooks] Hook "'+e+":"+t+'" is not allowed'),function(){};var i=0|n.priority,o=!!n.once,s=this._ensureTag(e),l=s.get(t)||[];return l.push({cb:a,p:i,once:o}),l.sort((function(e,t){return t.p-e.p})),s.set(t,l),"componentDidLoad"===t&&this._callForLoadedComponents(e,a),function(){return r.removeHook(e,t,a)}},t.registerHookOnce=function(e,t,a,n){return void 0===n&&(n={}),this.registerHook(e,t,a,f({},n,{once:!0}))},t.call=async function(e,t,a){var n=this._store.get(e);if(n){var r=n.get(t);if(r&&0!==r.length)for(var i=0,o=[].concat(r);i<o.length;i++){var s=o[i];try{await s.cb(a)}catch(a){console.warn('[Hooks] "'+e+":"+t+'" callback failed:',a)}s.once&&this.removeHook(e,t,s.cb)}}},t.removeHook=function(e,t,a){var n=this._store.get(e);if(!n)return!1;if(!n.has(t))return!1;if(!a)return n.delete(t),0===n.size&&this._store.delete(e),!0;var r=n.get(t),i=r.findIndex((function(e){return e.cb===a}));return i>-1&&(r.splice(i,1),0===r.length&&n.delete(t),0===n.size&&this._store.delete(e),!0)},t.clear=function(e){e?this._store.delete(e):this._store.clear()},t.get=function(e,t){var a,n=this._store.get(e);return n&&(null==(a=n.get(t))?void 0:a.map((function(e){return e.cb})))||[]},t._ensureTag=function(e){var t=this._store.get(e);return t||(t=new Map,this._store.set(e,t)),t},t._isAllowed=function(e,t){var a=this._whitelist.get(e);return a?!!a.has(t)||(console.warn('[Hooks] Hook "'+t+'" is not allowed for tag "'+e+'"'),!1):(console.warn('[Hooks] Tag "'+e+'" is not in the whitelist'),!1)},t.registerComponent=function(e,t){this._componentHistory.has(e)||this._componentHistory.set(e,new Set);var a=this._componentHistory.get(e);if(!a.has(t))return a.add(t),this.call(e,"componentDidLoad",t)},t._callForLoadedComponents=async function(e,t){var a=this._componentHistory.get(e);if(a&&0!==a.size)for(var n,r=h(a);!(n=r()).done;){var i=n.value;try{await t(i)}catch(t){console.warn('[Hooks] "'+e.replace(/[^a-zA-Z0-9-_]/g,"")+':componentDidLoad" callback failed:',t)}}},e}();e.onInitiated=function(e){return salla.event.once("twilight::initiated",e)},e.onReady=e.onReady||function(t){return new Promise((function(a){return"ready"===salla.status?a(t?t(salla.config.all()):salla.config.all()):e.onInitiated((function(e){return a(t?t(e):e)}))}))},e.status="loading",e.notify=c,e.lang=new V,e.form=new H,e.infiniteScroll=new M(void 0,salla.event.infiniteScroll),e.api=new ue,e.sso=new pe,e.intend=new Ne,e.hooks=new He,["cart","auth","order","scope","rating","comment","loyalty","product","profile","currency","document","wishlist","booking","landing","metadata"].forEach((function(t){return e[t]=new u(e.api[t],e.event[t])})),e.call=function(t){for(var a=e,n=t.split(".");n.length&&(a=a[n.shift()]););return a},e.analytics=new Ue,e.init=function(e){return new de(e)},new Me,salla.event.once("twilight::init",salla.init),salla.event.on("twilight::api",(function(e){var t=null==e?void 0:e.events;t&&salla.event.dispatchEvents(t)})),e.success=e.notify.success,e.error=e.notify.error,e.versions.twilight="2.14.305",window.dispatchEvent(new CustomEvent("salla::created")),module.exports=e;
|
|
1
|
+
"use strict";var e=require("@salla.sa/base"),t=require("infinite-scroll"),a=require("lang.js"),n=require("axios"),r=require("jwt-decode"),i=require("@jitsu/js"),o=function(e,t,a){return alert(e)},s=function(e,t){return o(e,l.error,t)},l={error:"error",success:"success",info:"info"},c={fire:function(e,t,a){return o(e,t,a)},setNotifier:function(e){o=e,salla.event.emit("twilight::notifier.changed")},error:s,success:function(e,t){return o(e,l.success,t)},info:function(e,t){return o(e,l.info,t)},sallaInitiated:function(){var e=window.location.href.match(/([\?\&]danger=)[^&]+/g);e&&(window.history.replaceState(null,document.title,window.location.pathname),salla.event.once("twilight::notifier.changed",(function(){e.forEach((function(e){e=decodeURI(e.replace("?danger=","").replace("&danger=",""));var t=document.createElement("div");t.innerText=e,s(t.innerHTML),salla.event.emit("twilight::error",e)}))})))},types:l},u=function(e,t){return this.api=e,this.event=t,new Proxy(this,{get:function(a,n){return"event"===n?t:"api"===n?e:e&&e[n]||a[n]}})};function d(e,t){(null==t||t>e.length)&&(t=e.length);for(var a=0,n=Array(t);a<t;a++)n[a]=e[a];return n}function h(e,t,a){if(v())return Reflect.construct.apply(null,arguments);var n=[null];return n.push.apply(n,t),new(e.bind.apply(e,n))}function p(e,t){var a="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(a)return(a=a.call(e)).next.bind(a);if(Array.isArray(e)||(a=function(e,t){if(e){if("string"==typeof e)return d(e,t);var a={}.toString.call(e).slice(8,-1);return"Object"===a&&e.constructor&&(a=e.constructor.name),"Map"===a||"Set"===a?Array.from(e):"Arguments"===a||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(a)?d(e,t):void 0}}(e))||t){a&&(e=a);var n=0;return function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function f(){return f=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var a=arguments[t];for(var n in a)({}).hasOwnProperty.call(a,n)&&(e[n]=a[n])}return e},f.apply(null,arguments)}function g(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,m(e,t)}function v(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(v=function(){return!!e})()}function m(e,t){return m=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},m(e,t)}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){if(this.getAttribute){if(this.hasAttribute("data-json"))try{return JSON.parse(this.getAttribute("data-json"))}catch(e){}var t=this.getAttribute("data-function");if(t&&window[t]){if("function"==typeof window[t]){for(var a,n=arguments.length,r=new Array(n>1?n-1:0),i=1;i<n;i++)r[i-1]=arguments[i];return this.getFilteredData((a=window[t]).call.apply(a,[this].concat(r)))}return this.getFilteredData(window[t])}var o=this.hasAttribute("data-form-selector")?document.querySelector(this.dataset.formSelector):void 0;if((o="FORM"===this.tagName?this:o||this.closest("form")||this.closest("[salla-form-data]")||this)&&"FORM"===o.tagName)return this.getFilteredData(new FormData(o),null,o);var s=o.querySelectorAll("[name]");if(!s.length)return this.getFilteredData();var l=Object.assign({},this.dataset);return s.forEach((function(e){if(!["checkbox","radio"].includes(e.type)||e.checked)try{var t=Salla.helpers.inputData(e.name,e.value,l);l[t.name]=t.value}catch(t){Salla.log(e.name+" can't be send")}})),this.getFilteredData(l)}},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 a=0;a<this.attributes.length;a++){var n=this.attributes[a].name.toLowerCase();if(0===n.indexOf(e))return!t||n}return!1},HTMLFormElement.prototype.getAjaxFormData=function(e){var t=this.querySelectorAll('input[type="file"]');t.forEach((function(e){e.files.length||e.setAttribute("disabled","")}));var a=new FormData(this);return t.forEach((function(e){e.files.length||e.removeAttribute("disabled")})),{formData:this.getFilteredData(a,e),url:this.getAttribute("action"),method:this.getAttribute("method")||"post",events:{success:this.dataset.onSuccess,fail:this.dataset.onFail}}},Element.prototype.getFilteredData=function(e,t,a){var n,r=this;return void 0===e&&(e=null),void 0===t&&(t=null),void 0===a&&(a=null),e=e||(null==(n=a)?void 0:n.dataset)||this.dataset,a&&this.name&&void 0!==this.value&&(e=function(e,t,a){e instanceof FormData?e.append(t,a):e[t]=a;return e}(e,this.name,this.value)),["filterBeforeSubmit","filterBeforeSend"].forEach((function(n){var i,o=(null==(i=a)?void 0:i.dataset[n])||r.dataset[n];if(o){var s=window[o];if("function"==typeof s){if(!s(e,a||r,t)&&e)throw"Data failed to be pass verify function window."+o+"(formData, element, event)!";return s(e,a||r,t)}Salla.log("window."+o+"() 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}}};var y=function(){function e(){this.events={},this.namespace="";var e=/function (.{1,})\(/.exec(this.constructor.toString());this.className=(e&&e.length>1?e[1]:"").toLowerCase()}var t=e.prototype;return t.after_init=function(){this.createDynamicFunctions()},t.createDynamicFunctions=function(){var e=this;Object.keys(this.events).forEach((function(t){e.createDynamicEventFuns(t),e.createDynamicListenerFuns(t)}))},t.createDynamicEventFuns=function(e){if(!this[e]){var t=this;this[e]=function(){for(var a=arguments.length,n=new Array(a),r=0;r<a;r++)n[r]=arguments[r];return t.dispatch.apply(t,[e].concat(n))}}},t.createDynamicListenerFuns=function(e){var t="on"+e.charAt(0).toUpperCase()+e.slice(1);if(!this[t]){var a=this;this[t]=function(t){return a.on(e,(async function(){return t.apply(void 0,arguments)}))}}},t.getEventName=function(e){return e=this.events[e]||e||"unknown-event",!this.namespace||e.includes("::")?e:this.namespace+Salla.event.delimiter+e},t.dispatch=function(e){for(var t,a=arguments.length,n=new Array(a>1?a-1:0),r=1;r<a;r++)n[r-1]=arguments[r];return(t=Salla.event).emitAsync.apply(t,[this.getEventName(e)].concat(n))},t.on=function(e,t,a){return void 0===a&&(a={}),Salla.event.addListener(this.getEventName(e),t,a)},t.once=function(e,t){return Salla.event.once(this.getEventName(e),t)},e}(),w=function(e){function t(){var t;return(t=e.call(this)||this).namespace="auth",t.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"},t.after_init(),t}g(t,e);var a=t.prototype;return a.login=function(e){return e?(e.type&&this.setTypeActionOnVerified(e.type),this.next_event=e.next_event||null,this.dispatch.apply(this,["login"].concat(Array.prototype.slice.call(arguments)))):(this.next_event=null,this.dispatch.apply(this,["login"].concat(Array.prototype.slice.call(arguments))))},a.loggedIn=async function(e){var t=this;return Salla.profile.info().finally((function(){return t.dispatch("loggedIn",e)}))},a.setTypeActionOnVerified=function(e){this.type_action_on_verified=e},a.getTypeActionOnVerified=function(){return this.type_action_on_verified||"redirect"},t}(y),S=function(e){function t(){var t;return(t=e.call(this)||this).namespace="cart",t.events={latestFetched:"latest.fetched",latestFailed:"latest.failed",updated:"updated",itemUpdated:"item.updated",itemUpdatedFailed:"item.updated.failed",itemAdded:"item.added",beforeAddItem:"before.add.item",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",beforeStartFastCheckout:"before.start.fast-checkout",submitting:"submitting"},t.after_init(),t}g(t,e);var a=t.prototype;return a.updated=function(e){var t;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,tax_amount:e.cart.tax_amount,total_discount:e.cart.total_discount,real_shipping_cost:e.cart.real_shipping_cost,count:e.cart.count,shipping_cost:null!=(t=e.cart.free_shipping_bar)&&t.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"))},a.latestFetched=function(e){return this.updated(e.data),this.dispatch("latestFetched",e)},a.itemAdded=function(e,t){return this.updated(e.data),this.dispatch("itemAdded",e,t)},a.itemDeleted=function(e,t){return this.updated(e.data),this.dispatch("itemDeleted",e,t)},a.itemUpdated=function(e,t){return this.updated(e.data),this.dispatch("itemUpdated",e,t)},a.couponAdded=function(e,t){return this.updated(e.data),this.dispatch("couponAdded",e,t)},a.couponDeleted=function(e,t){return this.updated(e.data),this.dispatch("couponDeleted",e,t)},t}(y),b=function(e){function t(){var t;return(t=e.call(this)||this).namespace="order",t.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"},t.after_init(),t}return g(t,e),t}(y),_=function(e){function t(){var t;return(t=e.call(this)||this).namespace="scope",t.events={fetched:"fetched",notFetched:"not.fetched",productAvailabilityFetched:"product-availability.fetched",productAvailabilityNotFetched:"product-availability.not.fetched",changeSucceeded:"changed",changeFailed:"not.changed"},t.after_init(),t}return g(t,e),t}(y),F=function(e){function t(){var t;return(t=e.call(this)||this).namespace="rating",t.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"},t.after_init(),t}return g(t,e),t}(y),k=function(e){function t(){var t;return(t=e.call(this)||this).namespace="comment",t.events={added:"added",additionFailed:"addition.failed",fetched:"fetched",fetchFailed:"fetch.failed"},t.after_init(),t}return g(t,e),t}(y),C=function(e){function t(){var t;return(t=e.call(this)||this).namespace="loyalty",t.events={exchangeSucceeded:"exchange.succeeded",exchangeFailed:"exchange.failed",programFetched:"program.fetched",programNotFetched:"program.not.fetched",resetSucceeded:"exchange-reset.succeeded",resetFailed:"exchange-reset.failed"},t.after_init(),t}g(t,e);var a=t.prototype;return a.exchangeSucceeded=function(e,t){return salla.cart.event.updated(e.data),this.dispatch("exchangeSucceeded",e,t)},a.resetSucceeded=function(e){return salla.cart.event.updated(e.data),this.dispatch("resetSucceeded",e)},t}(y),P=function(e){function t(){var t;return(t=e.call(this)||this).namespace="profile",t.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"},t.after_init(),t}return g(t,e),t}(y),A=function(e){function t(){var t;return(t=e.call(this)||this).namespace="product",t.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"},t.after_init(),t}return g(t,e),t}(y),q=function(e){function t(){var t;return(t=e.call(this)||this).namespace="document",t.events={click:"click",change:"change",submit:"submit",keyup:"keyup",leaving:"leaving",request:"request",requestFailed:"request.failed"},t.after_init(),t}g(t,e);var a=t.prototype;return a.onClick=function(e,t){this.fireCallableFuns("click",e,t)},a.onChange=function(e,t){this.fireCallableFuns("change",e,t)},a.onSubmit=function(e,t){this.fireCallableFuns("submit",e,t)},a.onKeyup=function(e,t){this.fireCallableFuns("keyup",e,t)},a.fireCallableFuns=function(e,t,a){this.on(e,(function(e){"function"!=typeof t?"function"==typeof a&&e.target.matches(t)&&a(e):t(e)}))},a.fireEvent=function(e,t){for(var a=arguments.length,n=new Array(a>2?a-2:0),r=2;r<a;r++)n[r-2]=arguments[r];return this.fireEventForElements.apply(this,[e,t,!1].concat(n))},a.fireEventForAll=function(e,t){for(var a=arguments.length,n=new Array(a>2?a-2:0),r=2;r<a;r++)n[r-2]=arguments[r];return this.fireEventForElements.apply(this,[e,t,!0].concat(n))},a.fireEventForElements=function(e,t,a){for(var n=this,r=arguments.length,i=new Array(r>3?r-3:0),o=3;o<r;o++)i[o-3]=arguments[o];if("string"==typeof e){if(a)return document.querySelectorAll(e).forEach((function(e){return n.fireEventForElements.apply(n,[e,t,!1].concat(i))}));e=document.querySelector(e)}if(e){var s=h(CustomEvent,[t].concat(i));return e.dispatchEvent(s)}salla.log("Failed To get element to fire event: "+t)},t}(y),E=function(e){function t(){var t;return(t=e.call(this)||this).namespace="wishlist",t.events={added:"added",removed:"removed",additionFailed:"addition.failed",removingFailed:"removing.failed"},t.after_init(),t}return g(t,e),t}(y),I=function(e){function t(){var t;return(t=e.call(this)||this).namespace="currency",t.events={changed:"changed",failed:"failed",fetched:"fetched",failedToFetch:"failed.to.fetch"},t.after_init(),t}return g(t,e),t}(y),T=function(e){function t(){var t;return(t=e.call(this)||this).namespace="infiniteScroll",t.events={scrollThreshold:"scroll.threshold",request:"request",load:"load",append:"append",error:"error",last:"last",history:"history"},t.after_init(),t}return g(t,e),t}(y),x=function(e){function t(){var t;return(t=e.call(this)||this).namespace="booking",t.events={added:"added",additionFailed:"addition.failed"},t.after_init(),t}return g(t,e),t}(y),L=function(e){function t(){var t;return(t=e.call(this)||this).namespace="landing",t.events={detailsFetched:"order.fetched",getDetailsFailed:"get.details.failed",orderCreated:"order.created",orderCreationFailed:"order.creation.failed",breadcrumbFetched:"breadcrumb.fetched",breadcrumbFetchFailed:"breadcrumb.fetch.failed"},t.after_init(),t}return g(t,e),t}(y),R=function(e){function t(){var t;return(t=e.call(this)||this).namespace="notifications",t.events={fetched:"fetched",fetchFailed:"fetch.failed"},t.after_init(),t}return g(t,e),t}(y),O=function(e){function t(){var t;return(t=e.call(this)||this).namespace="component",t.events={menuFetched:"menus.fetched",menuFetchFailed:"menus.fetch.failed",reviewsFetched:"reviews.fetched",reviewsFetchFailed:"reviews.fetch.failed"},t.after_init(),t}return g(t,e),t}(y),j=function(e){function t(){var t;return(t=e.call(this)||this).namespace="advertisement",t.events={fetched:"advertisement.fetched",fetchFailed:"advertisement.not.fetched"},t.after_init(),t}return g(t,e),t}(y),D=function(e){function t(){var t;return(t=e.call(this)||this).namespace="navigation",t.events={breadcrumbFetched:"breadcrumb.fetched",breadcrumbFetchFailed:"breadcrumb.fetch.failed"},t.after_init(),t}return g(t,e),t}(y),U=function(e){function t(){var t;return(t=e.call(this)||this).namespace="metadata",t.events={valueFetched:"value.fetched",valueNotFetch:"value.not.fetched"},t.after_init(),t}return g(t,e),t}(y);function N(e){e&&e.sallaInitiated&&!e.initiated&&(e.sallaInitiated(),e.initiated=!0)}Salla.event.auth=new w,Salla.event.cart=new S,Salla.event.order=new b,Salla.event.scope=new _,Salla.event.rating=new F,Salla.event.booking=new x,Salla.event.comment=new k,Salla.event.landing=new L,Salla.event.loyalty=new C,Salla.event.product=new A,Salla.event.profile=new P,Salla.event.currency=new I,Salla.event.document=new q,Salla.event.wishlist=new E,Salla.event.infiniteScroll=new T,Salla.event.notifications=new R,Salla.event.component=new O,Salla.event.advertisement=new j,Salla.event.navigation=new D,Salla.event.metadata=new U,Salla.event.on("twilight::initiated",(function(){Object.keys(Salla).forEach((function(e){"object"==typeof(e=Salla[e])&&(N(e),Object.keys(e).forEach((function(t){N(e[t])})))}))})),Salla.config.default_properties={debug:"undefined"!=typeof process&&"development"===process.env.NODE_ENV,token:null,fastRequests:!0,canLeave:!0,store:{api:["group","test"].includes(window.location.hostname.split(".").pop())?window.location.origin+"/api/v1/":"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=function(){return"user"===Salla.config.get("user.type")},Salla.config.isGuest=function(){return!Salla.config.isUser()},Salla.config.languages=async function(){var e;if(Salla.config.triedToGetLanguages_)return Salla.config.get("languages");Salla.config.triedToGetLanguages_=!0;var t=!0,a=[];return null==(e=await salla.document.api.request("languages",null,"get"))||null==(e=e.data)||e.map((function(e){t&&(a=[],t=!1),e.code=e.code||e.iso_code,e.url=salla.url.get(e.code),e.is_rtl=e.is_rtl||e.rtl,a.push(e)})),Salla.config.set("languages",a),a},Salla.config.currencies=async function(){var e;if(Salla.config.triedToGetCurrencies_)return Salla.config.get("currencies");Salla.config.triedToGetCurrencies_=!0;var t=!0,a={};return null==(e=await salla.currency.api.list())||null==(e=e.data)||e.map((function(e){t&&(a={},t=!1),e.country_code=e.code.substr(0,2).toLowerCase(),a[e.code]=e})),Salla.config.set("currencies",a),a},Salla.config.isMobileApp=function(){var e;return["ios","android"].includes(null==(e=Salla.analytics)||null==(e=e.jitsuAnalytics)||null==(e=e.getContextProperty("app"))||null==(e=e.platform)?void 0:e.toLowerCase())};var M=function(e){function a(t,a){var n;return(n=e.call(this,t,a)||this).options={path:".infinite-scroll-btn",history:"push",status:".infinite-scroll-status",append:".list-block"},n.fetchOptions={headers:{"S-INFINITE-SCROLL":!0,"S-Source":"twilight","cache-control":"no-cache",pragma:"no-cache"}},n.instances=[],n}g(a,e);var n=a.prototype;return n.initiate=function(e,a,n,r){void 0===r&&(r=!1),r?((n=n||{}).fetchOptions=f({},this.fetchOptions,n.fetchOptions||{}),n.responseBody="json"):n=this.getCustomOptions(a,n);var i="string"!=typeof e?e:document.querySelector(e),o=n.path;if(i&&o&&("string"!=typeof o||document.querySelector(o))){var s=new t(i,n);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}Salla.logger.warn(i?"Path Option (a link that has next page link) Not Existed!":"Container For InfiniteScroll not Existed!")},n.getCustomOptions=function(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},n.loadNextPage=function(e){("string"!=typeof e?e:document.querySelector(e)).loadNextPage()},n.destroy=function(e){("string"!=typeof e?e:document.querySelector(e)).destroy()},a}(u),H=function(){function e(){}var t=e.prototype;return t.submit=async function(e,t){var a,n;void 0===t&&(t=null);var r=t;if("SubmitEvent"===(null==(a=t)||null==(a=a.constructor)?void 0:a.name)||"submit"===(null==(n=t)?void 0:n.type)){var i,o;if(t.preventDefault(),"FORM"!==(null==(i=t.target)?void 0:i.tagName))return Salla.logger.warn("Failed find the target element for submit action. make sure you submit a form element"),new Promise((function(){throw"Failed find the target element for submit action. make sure you submit a form element"}));"SALLA-BUTTON"===(null==(o=t)||null==(o=o.submitter)||null==(o=o.parentElement)?void 0:o.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((function(){var e;loaderSupported&&(null==(e=t)||null==(e=e.submitter)||e.parentElement.stop())}));var s=e.split("."),l=s.splice(-1);return await salla.call(s.join("."))[l](r).finally((function(){var e;return null==(e=t)||null==(e=e.submitter)||null==(e=e.parentElement)?void 0:e.stop()})).catch((function(e){throw salla.logger.warn(e),e}))},t.onSubmit=function(e,t){return salla.form.submit(e,t),!1},t.onChange=function(e,t){var a;return null!=t&&t.currentTarget?"FORM"!==(null==t||null==(a=t.currentTarget)?void 0:a.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)},t.getPossibleValue=function(e,t,a){if(void 0===a&&(a=!1),e){if("object"!=typeof e)return e;for(var n,r=0;r<t.length&&!(n=e[t[r]])&&!("undefined"!=typeof FormData&&e instanceof FormData&&(n=e.get(t[r])));r++);return"object"!=typeof(n=n||e)||a?n:void 0}},e}(),V=function(e){function t(t){var a;return(t=t||{}).messages=t.messages||window.translations,t.locale=t.locale||(window.locale||navigator.language||navigator.userLanguage||"ar").split("-")[0],t.fallback=t.fallback||t.locale,(a=e.call(this,t)||this).translationsLoaded=!1,a}g(t,e);var a=t.prototype;return a.onLoaded=function(e){var t=this;return new Promise((function(a){if(t.translationsLoaded)return a(e?e():null);Salla.event.once("languages::translations.loaded",(function(){return a(e?e():null)}))}))},a.loadStoreTranslations=function(){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)&&e.prototype.setMessages.call(this,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)},a.setMessages=function(t){e.prototype.setMessages.call(this,t),salla.event.dispatch("languages::translations.loaded"),this.translationsLoaded=!0},a.loadScript=function(e,t){var a=this;void 0===t&&(t=!0);var n=document.createElement("script");n.src=e,n.onload=function(){var e;if(window.translations)return salla.storage.remove("s_translations"),salla.storage.set("s_translations",((e={})[a.hash]=window.translations,e)),a.setMessages(window.translations);n.onerror()},n.onerror=function(){if(t)return salla.logger.warn("Failed to load Translations for store, lets try load it from CDN"),a.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(n)},a.getWithDefault=function(e,t,a,n){var r=this.get(e,a,n);return r!==e?r:t},a.get=function(t,a,n){var r=t;(window.translations||this.translationsLoaded)&&(r="trans."+t);var i=e.prototype.get.call(this,r,a,n);return i!==r?i:e.prototype.get.call(this,r,a,"en").replace(r,t)},a.set=function(e,t){return salla.helpers.setNested(this.messages[this.getLocale()+".trans"],e,t),this},a.add=function(e,t){var a=this;return Object.entries(t).forEach((function(t){return salla.helpers.setNested(a.messages[t[0]+".trans"],e,t[1])})),this},a.addBulk=function(e){var t=this;return Object.entries(e).forEach((function(e){var a=e[0],n=e[1];t.add(a,n)})),this},t}(a),G=function(){function e(){this.endpoints={},this.webEndpoints=[],this.namespace="BaseApi",this.endpointsMethods={},this.endpointsHeaders={};var 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:[]}}var t=e.prototype;return t.after_init=function(){},t.normalRequest=function(e,t,a){void 0===t&&(t=void 0),void 0===a&&(a=null);var n=Array.isArray(e),r=n?this.getUrl.apply(this,e):this.getUrl(e);e=n?e[0]:e,a=a||this.endpointsMethods[e]||"post";var i=this.endpointsHeaders[e];if("get"===a&&t instanceof FormData){var o={};Array.from(t.entries()).forEach((function(e){o[e[0]]=e[1]})),t={params:o}}return i&&"get"===a&&(t=t?Object.assign(t,i):i),this.webEndpoints.includes(e)?r=salla.url.get(r):"http"!==r.substring(0,4)&&(r=salla.url.api(r)),Salla.api.request(r,t,a,{headers:i})},t.request=function(e,t,a){return void 0===t&&(t=void 0),void 0===a&&(a=null),!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,a)):this.normalRequest(e,t,a)},t.getUrl=function(e){for(var t=this.endpoints[e]||e,a=/{[^{}]+}/i,n=1;n<arguments.length;n++)t=t.replace(a,arguments[n]);return t},t.event=function(){return salla.event[this.className]},e}(),z=function(e){function t(){var t;return(t=e.call(this)||this).addToCartTries=0,t.guestCartAssigned=!1,t.namespace="cart",t._pendingCartIdRequest=null,t._pendingAssignRequest=null,t.endpoints={latest:"cart/latest",latestApi:"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}",giftCartDetails:"cart/{cartId}/buy-as-gift",cartGiftToCart:"cart/{cart_id}/buy-as-gift",assign:"cart/{cartId}/assign?merge=1"},t.endpointsMethods={latest:"get",details:"get",status:"get",updateItem:"post",deleteItem:"delete",deleteImage:"delete",deleteCoupon:"put",getQuickOrderSettings:"get",offers:"get",giftCartDetails:"get"},t.webEndpoints=["latest"],t.latestCart=null,t.after_init(),salla.event.on("api::initiated",(function(){return salla.api.cart.getCurrentCartId(!1,"api::initiated")})),salla.event.on("auth::token.fetched",t._checkCurrentCart),salla.event.on("auth::token.invalid",t._checkCurrentCart),salla.event.on("auth::verified",(async function(){try{await Salla.api.cart.assign()}catch(e){Salla.log("Error on assign after verified",e)}return Salla.api.cart.getCurrentCartId(!0,"auth::verified")}),{async:!0}),salla.event.on("twilight::initiated",(function(){return salla.api.cart.syncGuestCart()})),salla.event.on("profile::info.fetched",(function(){return t._checkCurrentCart(!0)})),salla.event.on("twilight::error",(function(e){return(e.includes("Cart not available")||e.includes("السلة غير متاحة"))&&salla.cart.api.reset()})),t}g(t,e);var a=t.prototype;return a._checkCurrentCart=function(e){var t,a;void 0===e&&(e=!1);var n=salla.storage.get("cart"),r=null==(t=salla.config.get("user"))?void 0:t.id,i=null==(a=salla.config.get("store"))?void 0:a.id;n&&n.id&&!e&&(n.user_id===r&&n.store_id===i||(salla.log("cart",{user_id:n.user_id,store_id:n.store_id}),salla.log("current",{user_id:r,store_id:i}),salla.log("Api:: case2 => The cart is not belong to current "+(n.user_id!==r?"user":"store")+"!"),salla.cart.api.reset()),salla.url.is_page("cart")&&n.id!==salla.config.get("page.id")&&(salla.log("cart",{user_id:n.user_id,store_id:n.store_id}),salla.log("current",{user_id:r,store_id:i}),salla.log("Api:: case2 => The cart is different between storage:"+n.id+" & session:"+salla.config.get("page.id")+" !"),salla.cart.api.reset()))},a.getCurrentCartId=async function(e,t){if(void 0===e&&(e=!1),void 0===t&&(t="getCurrentCartId"),Salla.cart.api._pendingCartIdRequest)return Salla.cart.api._pendingCartIdRequest;Salla.cart.api._pendingCartIdRequest=async function(){try{if(!e){if(Salla.cart.api.latestCart)return Salla.cart.api.latestCart.cart.id;var a=Salla.storage.get("cart.id");if(a)return a}var n=await Salla.cart.api.latest(t);return Salla.cart.api.latestCart=n.data,Salla.cart.api.latestCart.cart.id}finally{Salla.cart.api._pendingCartIdRequest=null}}();var a=Salla.cart.api._pendingCartIdRequest;return Salla.cart.api._pendingCartIdRequest=null,a},a.getUploadImageEndpoint=function(e){return salla.url.api(this.getUrl("uploadImage",e||salla.storage.get("cart.id")))},a.latest=function(e){return void 0===e&&(e="direct"),this.request(salla.auth.api.isSessionless()?"latestApi":"latest",{params:{source:"",callerName:e}}).then((function(e){return salla.api.cart.set(e.data.cart),salla.event.cart.latestFetched(e),e})).catch((function(e){throw salla.api.cart.reset(),salla.event.cart.latestFailed(e),e}))},a.details=async function(e,t){return void 0===t&&(t=[]),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}))},a.quickAdd=async function(e,t,a){return this.addItem({id:e,quantity:t,offerType:a,endpoint:"quickAdd"})},a.addItem=async function(e){var t=this.getCartPayload(e);if(!t.id){var a='There is no product "id"!';return salla.cart.event.itemAddedFailed(a),salla.api.errorPromise(a)}var n=salla.form.getPossibleValue(t.payload,["endpoint"]);n&&["addItem","quickAdd"].includes(n)||(n=salla.form.getPossibleValue(t.payload,["quantity","donating_amount"])?"addItem":"quickAdd");var r=await Salla.api.cart.getCurrentCartId(!1,"salla.api.cart.addItem");try{t.payload=Salla.helpers.createFormDataWrapper(t.payload||{}),await Salla.cart.event.beforeAddItem(t)}catch(e){}return this.request([n,r,t.id],t.payload.getRawData()).then((function(e){Salla.cart.api.addToCartTries=0;try{Salla.cart.event.itemAdded(e,t.id)}catch(e){Salla.log(e)}return e})).catch((function(a){if(!Salla.cart.api.addToCartTries)return Salla.cart.api.addToCartTries++,Salla.cart.reset(),Salla.cart.api.addItem(e);throw Salla.cart.event.itemAddedFailed(a,t.id),a}))},a.deleteItem=async function(e){var t=this.getCartPayload(e);if(!t.id){var a='There is no "id"!';return salla.cart.event.itemDeletedFailed(a),salla.api.errorPromise(a)}var n=await salla.api.cart.getCurrentCartId(!1,"salla.api.cart.deleteItem");return this.request(["deleteItem",n,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}))},a.updateItem=async function(e){var t,a=this.getCartPayload(e);if(!a.id){var n='There is no "id"!';return salla.cart.event.itemUpdatedFailed(n),salla.api.errorPromise(n)}var r=await salla.api.cart.getCurrentCartId(!1,"salla.api.cart.updateItem");return"Object"===(null==(t=a.payload.constructor)?void 0:t.name)?a.payload._method="PUT":a.payload.append("_method","PUT"),this.request(["updateItem",r,a.id],a.payload).then((function(e){return salla.cart.event.itemUpdated(e,a.id),e})).catch((function(e){throw salla.cart.event.itemUpdatedFailed(e,a.id),e}))},a.deleteImage=async function(e){if(!(e=salla.form.getPossibleValue(e,["id","image_id","photo_id"]))){var t='There is no "id"!';return salla.cart.event.imageNotDeleted(t),salla.api.errorPromise(t)}var a=await salla.api.cart.getCurrentCartId(!1,"salla.api.cart.deleteImage");return this.request(["deleteImage",a,e]).then((function(t){return salla.cart.event.imageDeleted(t,e),t})).catch((function(t){throw salla.cart.event.imageNotDeleted(t,e),t}))},a.status=async function(e,t){void 0===t&&(t=!1),e=e||await salla.api.cart.getCurrentCartId(!1,"salla.api.cart.status");var a={has_apple_pay:salla.helpers.hasApplePay()};t&&(a.guest_checkout=1);try{await salla.cart.event.submitting()}catch(e){salla.log("Error on: salla.cart.event.submitting()")}return this.request(["status",e],{params:a})},a.submit=async function(e,t){if(void 0===e&&(e=!1),void 0===t&&(t=!1),console.log("salla.cart.api.submit",{isGuestCheckout:e}),salla.config.isGuest()&&!e)return salla.log("it looks that the current user is not logged-in, lets login then submit"),salla.cart.loginOnCartPage();var a;if(t)try{var n,r=await Salla.api.cart.assign();a=null==r||null==(n=r.data)?void 0:n.cart_id}catch(e){Salla.log("Error on assign after login from submit",e)}this.status(null!=a?a:await salla.api.cart.getCurrentCartId(!1,"salla.api.cart.submit"),e).then((function(e){var t,a=null==(t=e.data.next_step)?void 0:t.to;if(a||(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(a)){var n="Can't find next_step );";throw salla.cart.reset(),salla.cart.event.submitFailed(n),n}return salla.cart.event.submitted(e),"login"===a?salla.cart.loginOnCartPage():"checkout"===a?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){var t;salla.cart.api.tries=salla.cart.api.tries||0,salla.cart.reset();var a=404===(null==e||null==(t=e.response)||null==(t=t.data)?void 0:t.status);if(a&&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 a&&salla.error(salla.lang.get("pages.checkout.try_again")),salla.cart.event.submitFailed(e),e}))},a.getCartPayload=function(e){var t,a=(null==(t=e)?void 0:t.data)||("object"==typeof e?e:void 0);return{id:e=a?salla.form.getPossibleValue(a,["prod_id","product_id","item_id","id"]):e,payload:a="object"==typeof a?a:void 0}},a.normalRequest=function(t,a,n){var r=this;return void 0===a&&(a=void 0),void 0===n&&(n=null),e.prototype.normalRequest.call(this,t,a,n).catch((async function(e){var t;throw 403===(null==e||null==(t=e.response)?void 0:t.status)&&(r.reset(),salla.error(salla.lang.get("pages.checkout.try_again"))),e}))},a.reset=function(){salla.api.cart.latestCart=null,salla.storage.remove("cart"),salla.cookie.clearCookieByPrefix(salla.api.cart.getCartCookiePrefix()),salla.cart.event.successReset()},a.addCoupon=async function(e){if(e=e.data||e,!(e=salla.form.getPossibleValue(e,["coupon"]))){var t=new Error('There is no "Coupon Code"!');return t.name="EmptyCoupon",salla.event.cart.couponAdditionFailed(t),salla.api.errorPromise(t)}var a=await salla.cart.api.getCurrentCartId(!1,"salla.api.cart.addCoupon");return this.request(["addCoupon",a],{coupon:e}).then((function(e){var t,n=salla.storage.get("cart");return n&&null!=(t=e.data)&&null!=(t=t.cart)&&t.coupon&&(n.coupon=e.data.cart.coupon,salla.storage.set("cart",n)),salla.event.cart.couponAdded(e,a),e})).catch((function(e){throw salla.event.cart.couponAdditionFailed(e,a),e}))},a.deleteCoupon=async function(){var e=await salla.cart.api.getCurrentCartId(!1,"salla.api.cart.deleteCoupon");return this.request(["deleteCoupon",e],{}).then((function(t){var a=salla.storage.get("cart");return a&&a.coupon&&(delete a.coupon,salla.storage.set("cart",a)),salla.event.cart.couponDeleted(t,e),t})).catch((function(t){throw salla.event.cart.couponDeletionFailed(t,e),t}))},a.getQuickOrderSettings=function(){return this.request("getQuickOrderSettings").then((function(e){return salla.event.cart.quickOrderSettingFetched(e),e})).catch((function(e){throw salla.event.cart.quickOrderSettingFailed(e),e}))},a.createQuickOrder=function(e){return this.request("createQuickOrder",e).then((function(e){return salla.event.cart.quickOrderSucceeded(e),e})).catch((function(e){throw salla.event.cart.quickOrderFailed(e),e}))},a.priceQuote=async function(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((function(e){return salla.cart.api.reset(),salla.event.cart.priceQuoteSucceeded(e).then((function(){return setTimeout((function(){return window.location.href=salla.url.get("/")}),1e3),e}))})).catch((function(e){return salla.event.cart.priceQuoteFailed(e).then((function(){var t;throw 404===(null==(t=e.error)?void 0:t.code)&&window.location.reload(),e}))}))},a.loginOnCartPage=function(){salla.auth.setCanRedirect(!1),salla.event.dispatch("login::open",{withoutReload:!0,source:"cart-submit"}),salla.auth.event.onLoggedIn((function(){salla.event.dispatch("login::close"),salla.cart.submit(!1,!0)}))},a.set=function(e){salla.storage.set("cart",e),salla.api.cart.syncGuestCart()},a.offers=async function(){var e=await salla.cart.api.getCurrentCartId(!1,"salla.api.cart.offers");return this.request(["offers",e]).then((function(e){return salla.event.cart.offersFetched(e),e})).catch((function(e){throw salla.event.cart.offersFailed(e),e}))},a.getGiftCartDetails=async function(){var e=await salla.api.cart.getCurrentCartId(!1,"salla.api.cart.getGiftCartDetails");return this.request(["giftCartDetails",e]).then((function(t){return salla.product.event.giftFetched(t,e),t})).catch((function(t){throw salla.product.event.giftFetchFailed(t,e),t}))},a.addCartGiftToCart=async function(e,t){void 0===t&&(t=!1);var a=await salla.api.cart.getCurrentCartId(!1,"salla.api.cart.addCartGiftToCart");return this.request(["cartGiftToCart",a],e).then((function(e){return salla.product.event.addGiftToCartSucceeded(e,a),t&&(window.location.href=e.redirect),e})).catch((function(e){throw salla.product.event.addGiftToCartFailed(e,a),e}))},a.syncGuestCart=async function(){if(salla.config.isGuest()){var e=salla.api.cart.getCartCookiePrefix(),t=salla.cookie.getCookieByPrefix(e),a=salla.storage.get("cart.id");if(!a&&t.length)try{var n,r=null==(n=(await salla.api.cart.latest()).data)||null==(n=n.cart)?void 0:n.id;r&&salla.api.cart.setCartCookie(e,r)}catch(e){salla.log("Failed to fetch latest cart:",e)}salla.cookie.clearCookieByPrefix(e),a&&(salla.config.set("headers.s-cart-id",a),salla.api.cart.setCartCookie(e,a))}},a.assign=async function(){var e=this;if(Salla.api.cart._pendingAssignRequest)return Salla.api.cart._pendingAssignRequest;var t=Salla.storage.get("cart.id");return!(!t||Salla.api.cart.guestCartAssigned)&&(Salla.api.cart._pendingAssignRequest=async function(){try{var a=await e.request(["assign",t]);return Salla.api.cart.guestCartAssigned=!0,a}catch(e){throw e}finally{Salla.api.cart._pendingAssignRequest=null}}(),Salla.api.cart._pendingAssignRequest)},a.setCartCookie=function(e,t){salla.cookie.set(e+"-"+t,t,1)},a.getCartCookiePrefix=function(){return"cart-id-"+salla.config.get("store.id")},t}(G),W=function(e){function t(){var t;return(t=e.call(this)||this).namespace="loyalty",t.endpoints={getProgram:"loyalty",exchange:"loyalty/exchange",reset:"loyalty/exchange"},t.endpointsMethods={getProgram:"get",reset:"put"},t.after_init(),t}g(t,e);var a=t.prototype;return a.getProgram=function(){return this.request("getProgram").then((function(e){return salla.loyalty.event.programFetched(e),e})).catch((function(e){throw salla.loyalty.event.programNotFetched(e),e}))},a.exchange=async function(e,t){if(void 0===t&&(t=null),!(e=salla.form.getPossibleValue(e,["id","loyalty_prize_id","prize_id"]))){var a="Unable to find cart id. Please provide one.";return salla.loyalty.event.exchangeFailed(a),salla.api.errorPromise(a)}if(!(t=t||await salla.cart.getCurrentCartId(!1,"salla.api.loyalty.exchange"))){var n="Unable to find cart id. Please provide one.";return salla.loyalty.event.exchangeFailed(n),salla.api.errorPromise(n)}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}))},a.reset=async function(e){if(void 0===e&&(e=null),!(e=e||await salla.cart.getCurrentCartId(!1,"salla.api.loyalty.reset"))){var t="Unable to find cart id. Please provide one.";return salla.loyalty.event.resetFailed(t),salla.api.errorPromise(t)}return this.request("reset",{cart_id:e}).then((function(e){return salla.loyalty.event.resetSucceeded(e),e})).catch((function(e){throw salla.loyalty.event.resetFailed(e),e}))},t}(G),B=function(e){function t(){var t;return(t=e.call(this)||this).namespace="auth",t.canRedirect_=!0,t.afterLoginEvent={event:null,payload:null},t.endpoints={login:"auth/{type}/send_verification",resend:"auth/resend_verification",verify:"auth/{type}/verify",register:"auth/register",logout:"logout",refresh:"auth/refresh"},t.webEndpoints=["logout","auth/jwt","refresh"],t.endpointsMethods={logout:"get"},t.inIframe=salla.helpers.isIframe(),Salla.event.on("twilight::init",(function(){if(Salla.config.isGuest()&&location.href.includes("force_logout"))return delete Salla.api.axios.defaults.headers.common.Authorization,Salla.api.auth.logout("twilight",!1)})),t.after_init(),t}g(t,e);var a=t.prototype;return a.setAfterLoginEvent=function(e,t){salla.api.auth.afterLoginEvent={event:e,payload:t}},a.setCanRedirect=function(e){salla.api.auth.canRedirect_=e},a.canRedirect=function(){return salla.api.auth.canRedirect_&&!salla.api.auth.afterLoginEvent.event},a.login=function(e){var t;null!=(t=e)&&t.data&&(e=e.data);var a=salla.form.getPossibleValue(e,["type"]);if(!["email","mobile"].includes(a)){var n="Login type should be in: [email, mobile]";return salla.auth.event.codeNotSent(n),salla.api.errorPromise(n)}return this.request(["login",a],e).then((function(e){return salla.auth.event.codeSent(e,a),e})).catch((function(e){throw salla.auth.event.codeNotSent(e,a),salla.auth.api.trackBlockedError(e,"login"),e}))},a.verify=async function(e,t){void 0===t&&(t=!0);var a=salla.form.getPossibleValue(e,["type"]);if(!a){var n="Failed to know what's login type!";return salla.auth.event.verificationFailed(n),salla.api.errorPromise(n)}t=!1!==salla.form.getPossibleValue(e,["supportWebAuth"])&&t,salla.auth.event.next_event&&(e.next_event=salla.auth.event.next_event);var r=await salla.auth.api.request(["verify",a],e);return 200!==(null==r?void 0:r.status)?(salla.auth.event.verificationFailed(r,a),salla.api.errorPromise(r)):salla.auth.api.handlAfterAuthenticatedResponse(r,t)},a.handlAfterAuthenticatedResponse=async function(e,t){var a;e.data||(e={data:e});var n="authenticated"===(null==(a=e.data)?void 0:a.case);return n&&salla.auth.event.tokenFetched(e.data.token),t&&!this.inIframe&&!this.isSessionless()&&await salla.auth.api.request("auth/jwt",{callerName:"salla.auth.api.handlAfterAuthenticatedResponse"}),n&&await salla.auth.event.loggedIn(e).then((function(){return salla.auth.api.afterUserLogin()})),await salla.auth.event.verified(e,e.data.verification.type),salla.api.successPromise(e)},a.resend=function(e){var 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),salla.auth.api.trackBlockedError(t,"resend"),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))},a.register=function(e){var t,a=this;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 function(e){var n;return salla.auth.event.registered.call(t,e),"authenticated"===(null==(n=e.data)?void 0:n.case)&&(salla.auth.event.tokenFetched(e.data.token),!a.inIframe&&!a.isSessionless()&&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),salla.auth.api.trackBlockedError(e,"register"),e}))},a.handleIframeReadyAction=function(e,t){var a;null==(a=e.contentWindow)||a.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:{}}},"*")},a.appendIframeAndLogout=function(){var e=this;return new Promise((function(t){var a=salla.config.get("login.url","https://accounts.salla.com"),n=document.createElement("iframe");n.style.display="none",n.src=a+"/logout";var r=function(i){if("login"===i.data.source){var o=i.data.type.replace("iframe::","");if(salla.log("iframe::logout-iframe message received",i.data),["logged-out","ready"].includes(o)){if("ready"===o)return e.handleIframeReadyAction(n,a);window.removeEventListener("message",r),n.remove(),t()}}};window.addEventListener("message",r),document.body.appendChild(n)}))},a.logout=function(e,t){var a=this;return void 0===e&&(e="twilight"),void 0===t&&(t=!0),salla.storage.clearAll(),salla.cookie.clearAll(),e=encodeURI(e),salla.auth.event.loggedOut().then((function(){return a.appendIframeAndLogout()})).then((function(){if(t){var a=salla.url.get("logout?from="+e);console.log("Going to "+a+", to do any thing before this action use: salla.auth.even.onLoggedOut(()=>{...})");try{location.href=a}catch(e){salla.log(e)}}})).catch((function(e){return console.error("Error during logout:",e)}))},a.refresh=function(){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}))},a.afterUserLogin=function(){this.afterLoginEvent.event&&salla.event.emit(this.afterLoginEvent.event,this.afterLoginEvent.payload)},a.isSessionless=function(){return"sessionless"===salla.config.get("auth.mode")},a.trackBlockedError=function(e,t){var a;blockedByProxy=void 0===(null==e||null==(a=e.response)||null==(a=a.headers)?void 0:a["s-ray"]),blockedByProxy&&salla.analytics.track("BlockedByProxy",{class:"auth",function:t,reason:"non-server-request",message:e.message})},t}(G),Q=function(e){function t(){var t;return(t=e.call(this)||this).namespace="order",t.endpoints={cancel:"orders/cancel/{id}",createCartFromOrder:"reorder/{id}",reorderProduct:"reorder/product/{id}",sendInvoice:"orders/send/{id}",fetch:"orders"},t.endpointsMethods={createCartFromOrder:"get",fetch:"get"},t.after_init(),t}g(t,e);var a=t.prototype;return a.show=function(e){var t=salla.form.getPossibleValue((null==e?void 0:e.data)||e,["id","order_id"]);salla.event.dispatch("mobile::order.placed",{order_id:t}),location.href=salla.form.getPossibleValue((null==e?void 0:e.data)||e,["url"])},a.cancel=function(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}))},a.createCartFromOrder=function(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}))},a.reorderProduct=function(e){return e=e||salla.config.get("page.id"),this.request(["reorderProduct",e]).then((function(e){return salla.event.order.orderCreated(e,e.data.order_id),window.location.href=e.data.url,e})).catch((function(e){throw e}))},a.sendInvoice=function(e){var t=salla.form.getPossibleValue(e,["id"])||salla.config.get("page.id");if(!t||isNaN(t)){var a="There is no id!";return salla.order.event.invoiceNotSent(a),salla.api.errorPromise(a)}return this.request(["sendInvoice",t],e).then((function(e){return salla.event.order.invoiceSent(e,t),e})).catch((function(e){throw salla.event.order.invoiceNotSent(e,t),e}))},a.fetch=function(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}))},t}(G),K=function(e){function t(){var t;return(t=e.call(this)||this).namespace="product",t.previousQuery="",t.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",giftProductDetails:"products/{product_id}/buy-as-gift",productGiftToCart:"products/{product_id}/buy-as-gift",giftImage:"products/buy-as-gift/image",buyNow:"products/{product_id}/buy-now",fetch:"products",fetchOptions:"products/options"},t.endpointsMethods={details:"get",giftProductDetails:"get",fetch:"get",offers:"get",fetchOptions:"get"},t.after_init(),t}g(t,e);var a=t.prototype;return a.getPrice=function(e){var t=e.data||e,a=salla.form.getPossibleValue(t,["id","prod_id","product_id"]);return this.request(["getPrice",a],"object"==typeof t?t:void 0).then((function(e){return salla.product.event.priceUpdated(e,a),e})).catch((function(e){throw salla.product.event.priceUpdateFailed(e,a),e}))},a.categories=function(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}))},a.availabilitySubscribe=function(e){var 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}))},a.search=function(e){var t,a=e.data;if(a||(a={params:"string"==typeof e?{query:e}:e}),!(e=a instanceof FormData?a.get("query"):a.query||(null==(t=a.params)?void 0:t.query))){var n='There is no "query"!';return salla.product.event.searchFailed(n),salla.api.errorPromise(n)}if(e===salla.api.product.previousQuery){var r="Query is same as previous one!";return salla.product.event.searchFailed(r),salla.api.product.previousQuery=null,salla.api.errorPromise(r)}return salla.api.product.previousQuery=e,this.request("search",a,"get").then((function(t){return salla.product.event.searchResults(t,e),t})).catch((function(t){throw salla.product.event.searchFailed(t,e),t}))},a.offers=function(e){var t;if(!(e=salla.form.getPossibleValue((null==(t=e)?void 0:t.data)|e,["product_id","id"]))){var a='There is no "product_id"!';return salla.product.event.fetchOffersFailed(a),salla.api.errorPromise(a)}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}))},a.getSizeGuides=function(e){return this.request("products/"+e+"/size-guides",null,"get").then((function(t){return salla.product.event.sizeGuideFetched(t,e),t})).catch((function(t){throw salla.product.event.sizeGuideFetchFailed(t,e),t}))},a.getGiftProductDetails=function(e){return this.request(["giftProductDetails",e]).then((function(t){return salla.product.event.giftFetched(t,e),t})).catch((function(t){throw salla.product.event.giftFetchFailed(t,e),t}))},a.getDetails=function(e,t){if(void 0===t&&(t=[]),!Array.isArray(t)){var a="withItems should be array.";return salla.product.event.detailFetchFailed(a),salla.api.errorPromise(a)}if(!e){var n="productId is not passed.";return salla.product.event.detailFetchFailed(n),salla.api.errorPromise(n)}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}))},a.addProductGiftToCart=function(e,t,a){return void 0===a&&(a=!1),this.request(["productGiftToCart",e],t).then((function(t){return salla.product.event.addGiftToCartSucceeded(t,e),a&&(window.location.href=t.redirect),t})).catch((function(t){throw salla.product.event.addGiftToCartFailed(t,e),t}))},a.uploadGiftImage=function(e){return this.request("giftImage",e).then((function(e){return salla.product.event.giftImageUploadSucceeded(e),e})).catch((function(e){throw salla.product.event.giftImageUploadFailed(e),e}))},a.fetch=function(e){if(!e.source){var t="Source cannot be empty. Please provide one.";return salla.product.event.productListFetchFailed(t),salla.api.errorPromise(t)}var a=!e.source_value,n="string"==typeof e.source_value&&"[]"===e.source_value,r=Array.isArray(e.source_value)&&!e.source_value.length;if((a||n||r)&&!["offers","latest","sales","wishlist","top-rated","reorder"].includes(e.source)){var i="Source value cannot be empty. Please provide one.";return salla.product.event.productListFetchFailed(i),salla.api.errorPromise(i)}if(["categories","brands","tags","selected"].includes(e.source)&&!Array.isArray(e.source_value)){var o="SourceValue type error. Expected an array.";return salla.product.event.productListFetchFailed(o),salla.api.errorPromise(o)}if("search"===e.source&&"string"!=typeof e.source_value){var s="SourceValue type error. Expected a string.";return salla.product.event.productListFetchFailed(s),salla.api.errorPromise(s)}if("related"===e.source&&isNaN(e.source_value)){var l="SourceValue type error. Expected a number.";return salla.product.event.productListFetchFailed(l),salla.api.errorPromise(l)}return this.request(this.endpoints.fetch,{params:e},"get").then((async function(e){return salla.product.event.productListFetchSucceeded(e),e})).catch((function(e){throw salla.product.event.productListFetchFailed(e),e}))},a.fetchOptions=function(e,t){if(void 0===t&&(t={}),!e||0===e.length){var a="At least one product ID is required. Please provide a valid list of product IDs.";return salla.product.event.productOptionsNotFetched(a),salla.api.errorPromise(a)}var n=t.with,r=void 0===n?[]:n,i={selected:e};return r.length>0&&(i.with=r),this.request(this.endpoints.fetchOptions,{params:i},"get").then((function(e){return salla.product.event.productOptionsFetched(e),e})).catch((function(e){throw salla.product.event.productOptionsNotFetched(e),e}))},t}(G),J=function(e){function t(){var t;return(t=e.call(this)||this).namespace="profile",t.endpoints={info:"auth/user",update:"profile/update",updateContacts:"profile/contacts/update",updateCustomFields:"profile/fields",updateSettings:"profile/settings",verify:"profile/verify",delete:"profile"},t.endpointsMethods={delete:"delete"},t.after_init(),t}g(t,e);var a=t.prototype;return a.syncUserData=function(e){var t={id:e.id,type:"user",email:e.email,mobile:e.phone.code+e.phone.number,country_code:e.phone.country,language_code:e.language,currency_code:e.currency,notifications:e.notifications,pending_orders:e.pending_orders,avatar:e.avatar,first_name:e.first_name,last_name:e.last_name,is_hidden_name:e.is_hidden_name,is_notifiable:e.is_notifiable,can_comment:salla.config.get("user.can_comment"),fetched_at:Date.now()};salla.config.set("user",t),salla.storage.set("user",t)},a.info=function(){var e=this;return this.request("info",null,"get").then((function(t){return e.syncUserData(t.data),salla.profile.event.infoFetched(t),t})).catch((function(e){throw salla.profile.event.infoNotFetched(e),e}))},a.update=function(e){var t=this;if(Salla.config.get("store.features",[]).includes("sso-login")){var a="SSO login is enabled. You cannot update your profile.";return Salla.error(a),Promise.reject(new Error(a))}return this.request("update",e).then((function(e){return t.syncUserData(e.data),salla.profile.event.updated(e),e})).catch((function(e){throw salla.event.profile.updateFailed(e),e}))},a.updateCustomFields=function(e){var t=this;if(Salla.config.get("store.features",[]).includes("sso-login")){var a="SSO login is enabled. You cannot update your profile.";return Salla.error(a),Promise.reject(new Error(a))}return this.request("updateCustomFields",e).then((function(e){return t.syncUserData(e.data),salla.profile.event.updated(e),e})).catch((function(e){throw salla.event.profile.updateFailed(e),e}))},a.updateContacts=function(e){return this.request("updateContacts",e).then((function(e){return salla.profile.event.verificationCodeSent(e),e})).catch((function(e){throw salla.event.profile.updateContactsFailed(e),e}))},a.verify=function(e){return this.request("verify",e).then((function(e){return salla.profile.event.verified(e),e})).catch((function(e){throw salla.event.profile.unverified(e),e}))},a.updateSettings=function(e){return this.request("updateSettings",e).then((function(e){return salla.event.profile.settingsUpdated(e),e})).catch((function(e){throw salla.event.profile.updateSettingsFailed(e),e}))},a.delete=function(){return this.request("delete").then((function(e){return salla.storage.clearAll(),salla.cookie.clearAll(),salla.auth.api.appendIframeAndLogout().then((function(){salla.event.profile.deleted(e),window.location.href=salla.url.get("logout")})),e})).catch((function(e){throw salla.event.profile.notDeleted(e),e}))},t}(G),X=function(e){function t(){var t;return(t=e.call(this)||this).namespace="comment",t.endpoints={addComment:"{type}/{id}/comments",comments:"/comments"},t.after_init(),t}g(t,e);var a=t.prototype;return a.add=function(e){var t;if(null!=(t=e)&&t.data&&(e=e.data),"string"==typeof(e=this.getCommentPayload(e,!0)))return salla.event.comment.additionFailed(e),salla.api.errorPromise(e);if(!e.comment){var a="can't find comment content!";return salla.event.comment.additionFailed(a),salla.api.errorPromise(a)}return this.request(["addComment","blog"==e.type?"blogs":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}))},a.getCommentPayload=function(e,t){void 0===t&&(t=!1);var a={};if(["id","type","comment","per_page","page","sort"].forEach((function(t){var n=salla.form.getPossibleValue(e,[t]);n&&(a[t]=n)})),!t){var n=e.ids;if(n&&(a.ids=Array.isArray(n)?n:[n]),!a.ids||!a.ids.length)return"Failed to get ids!"}return a.type&&["products","pages","product","page","blogs","blog"].includes(a.type)?(a.type+=["product","page"].includes(a.type)?"s":"",a):"Failed to get type one of:(products, product, page, pages, blog, blogs)!"},a.fetchComments=function(e){if("string"==typeof(e=this.getCommentPayload(e)))return salla.event.comment.fetchFailed(e),salla.api.errorPromise(e);var 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}))},a.getComments=function(e,t,a,n,r){void 0===a&&(a=1),void 0===n&&(n=5);var i=Array.isArray(t)?t:[t];return this.fetchComments({ids:i,type:e+"s",page:a,per_page:n,sort:r})},t}(G),Z=function(e){function t(){var t;return(t=e.call(this)||this).namespace="currency",t.endpoints={change:"/",list:"currencies"},t.endpointsMethods={change:"get",list:"get"},t.webEndpoints=["change"],t.after_init(),t}g(t,e);var a=t.prototype;return a.change=function(e){if(!(e=salla.form.getPossibleValue(e.data||e,["currency","code"]))){var t="Can't find currency code!";return salla.currency.event.failed(t),salla.api.errorPromise(t)}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}))},a.list=function(){return this.request("list").then((function(e){return salla.currency.event.fetched(e),e})).catch((function(e){throw salla.currency.event.failedToFetch(e),e}))},t}(G),$=function(e){function t(){var t;return(t=e.call(this)||this).namespace="document",t}return g(t,e),t.prototype.reload=function(){window.location.reload()},t}(G),Y=function(e){function t(){var t;return(t=e.call(this)||this).namespace="rating",t.endpoints={store:"rating/store",products:"rating/products",shipping:"rating/shipping",order:"rating/{order_id}"},t.endpointsMethods={order:"get"},t.after_init(),t}g(t,e);var a=t.prototype;return a.order=function(e){var t="object"==typeof e?e:{},a=salla.form.getPossibleValue((null==e?void 0:e.data)||e,["order_id","id"]);if(!a){var n='There is no "order_id"!';return salla.event.rating.orderNotFetched(n),salla.api.errorPromise(n)}return this.request(["order",a],t).then((function(e){return salla.event.rating.orderFetched(e,a),e})).catch((function(e){throw salla.event.rating.orderNotFetched(e,a),e}))},a.store=function(e){var t;if(!(e=(null==(t=e)?void 0:t.data)||e)){var a='There is no "data"!';return salla.event.rating.storeFailed(a),salla.api.errorPromise(a)}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}))},a.products=function(e){var t;if(!(e=(null==(t=e)?void 0:t.data)||e)){var a='There is no "data"!';return salla.event.rating.productsFailed(a),salla.api.errorPromise(a)}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}))},a.shipping=function(e){var t;if(!(e=(null==(t=e)?void 0:t.data)||e)){var a='There is no "data"!';return salla.event.rating.shippingFailed(a),salla.api.errorPromise(a)}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}))},t}(G),ee=function(e){function t(){var t;return(t=e.call(this)||this).namespace="wishlist",t.endpoints={add:"products/favorites/{id}",remove:"products/favorites/{id}"},t.endpointsMethods={remove:"delete"},Salla.onReady((function(){var e;"customer.wishlist"===Salla.config.get("page.slug")&&(null!=(e=Salla.storage.getWithTTL("s-utms"))&&e["s-utm-source"]||t.injectSourceIntoRequest())})),t}g(t,e);var a=t.prototype;return a.injectSourceIntoRequest=function(){Salla.api.axios.interceptors.request.use((function(e){return e.headers=f({},e.headers,{"s-utm-source":"wishlist"}),e}),(function(e){return Promise.reject(e)}))},a.toggle=function(e){return salla.storage.get("salla::wishlist",[]).includes(e)?this.remove(e):this.add(e)},a.add=function(e){var t,a,n=this;return salla.config.isGuest()?(salla.wishlist.event.additionFailed(a=salla.lang.get("common.messages.must_login")),salla.error(a),salla.api.errorPromise(a)):(e=salla.form.getPossibleValue((null==(t=e)?void 0:t.data)||e,["product_id","id"]))?this.request(["add",e]).then((function(t){return n.updateWishlistStorage(e),salla.wishlist.event.added(t,e),t})).catch((function(t){throw salla.wishlist.event.additionFailed(t,e),t})):(salla.wishlist.event.additionFailed(a="Failed to get product id!"),salla.api.errorPromise(a))},a.remove=function(e){var t,a,n=this;return salla.config.isGuest()?(salla.wishlist.event.additionFailed(a=salla.lang.get("common.messages.must_login")),salla.error(a),salla.api.errorPromise(a)):(e=salla.form.getPossibleValue((null==(t=e)?void 0:t.data)||e,["product_id","id"]))?this.request(["remove",e]).then((function(t){return n.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(a="Failed to get id!"),salla.api.errorPromise(a))},a.updateWishlistStorage=function(e,t){void 0===t&&(t=!0);var a=salla.storage.get("salla::wishlist",[]);t?a.push(e):a.splice(a.indexOf(e),1),salla.storage.set("salla::wishlist",a)},t}(G),te=function(e){function t(){var t;return(t=e.call(this)||this).namespace="scopes",t.endpoints={get:"scopes",change:"scopes",getProductAvailability:"scopes/availability?product_id={id}"},t.after_init(),t}g(t,e);var a=t.prototype;return a.get=function(){return this.request("scopes",null,"get").then((function(e){return salla.scope.event.fetched(e),e})).catch((function(e){throw salla.scope.event.notFetched(e),e}))},a.change=function(e){return this.request("scopes",e).then((function(e){return salla.scope.event.changeSucceeded(e),e})).catch((function(e){throw salla.scope.event.changeFailed(e),e}))},a.getProductAvailability=function(e){return void 0===e&&(e=null),this.request("scopes/availability?product_id="+e,null,"get").then((function(t){return salla.scope.event.productAvailabilityFetched(t,e),t})).catch((function(e){throw salla.scope.event.productAvailabilityNotFetched(e),e}))},t}(G),ae=function(e){function t(){var t;return(t=e.call(this)||this).namespace="booking",t.endpoints={add:"cart/booking/product/{id}"},t.endpointsMethods={add:"get"},t}return g(t,e),t.prototype.add=async function(e,t){if(void 0===t&&(t=!0),!e){var a="Please provide product id.";return salla.booking.event.additionFailed(a),salla.api.errorPromise(a)}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}))},t}(G),ne=function(e){function t(){var t;return(t=e.call(this)||this).namespace="landing",t.endpoints={getDetails:"landing/{landing_page_id}",createCartFromPage:"landing/{landing_page_id}",breadcrumbs:"breadcrumbs"},t.endpointsMethods={getDetails:"get",breadcrumbs:"get"},t.after_init(),t}g(t,e);var a=t.prototype;return a.getDetails=function(e){if(!e){var t="page landing id not passed";return salla.event.landing.getDetailsFailed(t),salla.api.errorPromise(t)}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}))},a.createCartFromPage=function(e){if(!e){var t="page landing id not passed";return salla.event.landing.orderCreationFailed(t),salla.api.errorPromise(t)}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((function(){return location.href=t.data.url})),t})).catch((function(t){throw salla.event.landing.orderCreationFailed(t,e),t}))},a.fetchBreadcrumbs=function(e){if(!e.page){var t="The 'page' parameter is required for the Breadcrumb API. Please provide a valid 'page' parameter.";return salla.event.landing.breadcrumbFetchFailed(t),salla.api.errorPromise(t)}if("product.single"===e.page&&!e.id&&!e.parent_id){var a="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(a),salla.api.errorPromise(a)}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){var n="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(n),salla.api.errorPromise(n)}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}))},t}(G),re=function(e){function t(){var t;return(t=e.call(this)||this).namespace="notifications",t.endpoints={fetch:"notifications"},t.endpointsMethods={fetch:"get"},t.after_init(),t}return g(t,e),t.prototype.fetch=function(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}))},t}(G),ie=function(){function e(){var e,t=this;this.inIframe=salla.helpers.isIframe(),salla.event.on("twilight::before.ready",(async function(e){return await t.initiateRequest(e)})),salla.event.on("profile::info.fetched",(function(e){return t.setCurrencyAndLanguage(e)})),salla.event.on("auth::token.fetched",(function(e){salla.storage.set("token",e),t.inIframe&&salla.log("token fetched iframe"),t.inIframe&&salla.cookie.set("s-token",e,60),t.setToken(e)})),salla.event.on("auth::token.invalid",(function(){salla.storage.remove("user"),salla.storage.remove("token")})),this.notifier_handler_disabled=!1,this.axios=n.create({baseURL:Salla.config.get("store.api",Salla.config.get("store.url")),headers:{common:{"X-Requested-With":"XMLHttpRequest","S-SOURCE":"twilight","S-APP-VERSION":(null==(e=Salla)||null==(e=e.versions)?void 0:e.twilight)||"2.0.0","S-APP-OS":"browser","cache-control":"no-cache"}}}),this.axios.interceptors.request.use((function(e){"preview"===Salla.config.get("theme.mode")&&(e.url=Salla.url.addParamToUrl("use_username_url",1,e.url));try{var t=Salla.config.get("swoole",[]),a=new RegExp(t.join("|"),"i");t.length>0&&a.test(e.url)&&(e.headers["s-store-api-version"]="swoole")}catch(e){console.log(e)}return e}),(function(e){return Promise.reject(e)}))}var t=e.prototype;return t.getHeaders=function(){var e=f({},this.axios.defaults.headers.common);return delete e["Content-Type"],e},t.getHeader=function(e){var t;return null==(t=Object.entries(this.getHeaders()).filter((function(t){return t[0].toLowerCase()===e.toLowerCase()}))[0])?void 0:t[1]},t.setHeaders=function(e){var t=this;return Object.entries(e).forEach((function(e){return t.setHeader(e[0],e[1])})),this},t.setHeader=function(e,t){return salla.infiniteScroll.fetchOptions.headers[e]=this.axios.defaults.headers.common[e]=t,this},t.withoutNotifier=async function(e){var t=this;return this.notifier_handler_disabled=!0,await e().finally((function(){t.notifier_handler_disabled=!1}))},t.initiateRequest=async function(e){var t,a,n;this.axios.defaults.baseURL=Salla.config.get("store.api",Salla.config.get("store.url")),this.setHeaders(f({"Store-Identifier":Salla.config.get("store.id"),currency:(null==(t=e.user)?void 0:t.currency_code)||"SAR","accept-language":salla.lang.getLocale(),"s-user-id":null==(a=e.user)?void 0:a.id,"s-country":null==(n=e.user)?void 0:n.country_code},e.headers||{}));var r=Salla.config.get("store.scope",Salla.storage.get("scope")),i=new URLSearchParams(window.location.search).get("scope");i&&r&&!Salla.url.is_page("cart")&&(r.id=i,Salla.storage.set("scope",r),Salla.cart.reset()),r&&this.setHeaders({"s-scope-type":r.type,"s-scope-id":r.id});var o=Salla.storage.getWithTTL("s-utms");if(o){var s={};Object.entries(o).forEach((function(e){var t=e[0],a=e[1];s[t]="string"==typeof a&&/[^\x00-\x7F]/.test(a)?encodeURIComponent(a):a})),this.setHeaders(s)}await this.injectTokenToTheRequests(e),salla.storage.get("affiliate_code")&&this.setHeader("s-affiliate-code",salla.storage.get("affiliate_code"))},t.injectTokenToTheRequests=async function(e){var t,a,n,i=this,o=this.getToken(),s="guest"===(null==(t=e.user)?void 0:t.type),l=parseInt((null==(a=e.user)?void 0:a.id)||0),c=parseInt(salla.storage.get("user.id")||0),u=salla.auth.api.isSessionless(),d=function(e){i.setToken(e),salla.event.emit("api::initiated")},h=async function(){s||u||!l?salla.auth.event.tokenInvalid():(salla.log("Api:: case 1 => current is is guest & web session available"),await salla.auth.api.refresh().then((async function(){await salla.profile.info()})).catch((function(){return salla.auth.event.tokenInvalid()})))};if(!o)return salla.log("Api:: case 1 => current is is guest"),void await h();try{n=r.jwtDecode(o)}catch(e){return Salla.logger.warn("Failed to decode JWT token",e),void Salla.auth.event.tokenInvalid()}return Date.now()/1e3>n.exp?(salla.log("Api:: case 2 => current user is logged-in and there is a token, but it's expired"),void await h()):(u?parseInt(n.sub)!==c:!c||!l||c!==l||parseInt(n.sub)!==l)?(salla.log("Api:: case 3 => there is a token and user in session/local missing or mismatch"),salla.log("sub:"+n.sub+" userIdInWeb:"+l+" userIdInStorage:"+c+", isSessionless:"+u,n.sub,l,c),this.setHeader("Authorization","Bearer "+o),void await salla.profile.info().then((async function(e){!i.inIframe&&!u&&await salla.auth.api.request("auth/jwt",{callerName:"salla.auth.request.injectTokenToTheRequests"}),d(o)})).catch((function(){salla.log("Api:: case 3 => failed get fresh profile"),i.setHeader("Authorization",null),salla.auth.event.tokenInvalid()}))):(salla.log("Api:: case 4 => current user is logged-in and there is a token, and it's not expired"),void d(o))},t.setToken=function(e){return this.setHeader("Authorization","Bearer "+e),salla.event.emit("api::token.injected",e),this.token=e,this},t.cleanupTokenFromUrl=function(){try{var e=new URL(window.location.href);if(!e.searchParams.has("token"))return;e.searchParams.delete("token"),window.history.replaceState({},document.title,e.toString())}catch(e){Salla.logger.warn("Failed to cleanup token from URL",e)}},t.setCurrencyAndLanguage=function(e){return this.setHeaders({currency:e.data.currency,"accept-language":e.data.language})},t.request=function(e,t,a,n){var r=this;void 0===t&&(t=void 0),void 0===a&&(a="get"),void 0===n&&(n={});var i={endPoint:e,payload:t,method:a,options:n},o="undefined"!=typeof event?event.currentTarget:null,s=!1;return"SALLA-BUTTON"===(null==o?void 0:o.tagName)&&(s=!0),s&&(null==o||o.load()),this.axios[i.method](i.endPoint,i.payload,i.options).then((function(e){return s&&(null==o||o.stop()),e.data&&e.request&&(e=e.data),r.handleAfterResponseActions(e),e})).catch((function(e){throw s&&(null==o||o.stop()),salla.event.document.requestFailed(i,e),r.handleErrorResponse(e),e}))},t.handleAfterResponseActions=function(e){if(e){var t=e.data,a=e.googleTags,n=void 0===a?null:a,r=t&&t.googleTags?t.googleTags:n;try{dataLayer&&r&&dataLayer.push(r)}catch(e){salla.logger.error(e.message)}this.fireEventsForResponse(e),this.showAlert(e)}},t.fireEventsForResponse=function(e){var t,a,n=(null==e?void 0:e.events)||(null==(t=e.data)?void 0:t.events)||(null==(a=e.error)?void 0:a.events);"string"==typeof n&&(n=JSON.parse(n)),n&&Object.keys(n).forEach((function(e){return salla.event.dispatch(e,n[e])}))},t.handleErrorResponse=function(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)},t.showAlert=function(e){var t,a;if(e&&!this.notifier_handler_disabled)return e.case&&e.msg?salla.notify.fire(e.msg,e.case,e):e.hasOwnProperty("success")&&null!=(t=e.data)&&t.message?salla.notify.fire(null==(a=e.data)?void 0:a.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},t.handleInvalidFields=function(e){var t=e.response.data.error.fields,a=[];Object.keys(t).forEach((function(e){var n=t[e];Array.isArray(n)?n.forEach((function(e){return a.push(e)})):a.push(n)}));var n=(a.length>1?"* ":"")+a.join("\n* ");salla.error(n,e)},t.isFastRequestsAllowed=function(){return Salla.config.get("fastRequests")},t.promise=function(e,t){return void 0===t&&(t=!0),new Promise((function(a,n){return t?a(e):n(e)}))},t.errorPromise=function(e){return this.promise(e,!1)},t.successPromise=function(e){return this.promise(e,!0)},t.getToken=function(){if(Salla.storage.get("token"))return Salla.storage.get("token");try{var e,t=null==(e=new URLSearchParams(window.location.search))?void 0:e.get("token");if(!t)return;if(3!==t.split(".").length)return;return this.cleanupTokenFromUrl(),t}catch(e){Salla.logger.warn("Failed to extract or validate token from URL",e)}},e}(),oe=function(e){function t(){var t;return(t=e.call(this)||this).namespace="component",t.endpoints={getMenus:"menus/{headOrFoot}?store_id={store}&lang={lang}",reviews:"reviews"},t.endpointsMethods={getMenus:"get",reviews:"get"},t}g(t,e);var a=t.prototype;return a.getMenus=async function(e){return void 0===e&&(e="header"),this.request(["getMenus",e,salla.config.get("store.id"),salla.lang.getLocale()]).then((function(e){return salla.event.component.menuFetched(e),e})).catch((function(e){throw salla.event.component.menuFetchFailed(e),e}))},a.getReviews=async function(e){var t=e.per_page,a=void 0===t?5:t,n=e.type,r=void 0===n?"all":n,i=e.items,o=void 0===i?void 0:i;if(!r){var s="Review type cannot be empty. Please provide one.";return salla.event.component.reviewsFetchFailed(s),salla.api.errorPromise(s)}var l=!o||"string"==typeof o&&"[]"===o||Array.isArray(o)&&!o.length;if(!new Set(["all","store","categories","products","json"]).has(r)){var c="Invalid review type. Please provide a valid type.";return salla.event.component.reviewsFetchFailed(c),salla.api.errorPromise(c)}if("all"!==r&&"store"!==r&&l){var u="Items cannot be empty. Please provide one.";return salla.event.component.reviewsFetchFailed(u),salla.api.errorPromise(u)}if(new Set(["products","categories"]).has(r)&&!Array.isArray(o)){var d="Items value must be an array of "+r+" id for review type of "+r+".";return salla.event.component.reviewsFetchFailed(d),salla.api.errorPromise(d)}return this.request(["reviews"],{params:{per_page:a,type:r,items:o}},"get").then((function(e){return salla.event.component.reviewsFetched(e),e})).catch((function(e){throw salla.event.component.reviewsFetchFailed(e),e}))},t}(G),se=function(e){function t(){var t;return(t=e.call(this)||this).namespace="booking",t.endpoints={fetch:"advertisements"},t.endpointsMethods={fetch:"get"},t}return g(t,e),t.prototype.fetch=async function(e){void 0===e&&(e=null);var 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}))},t}(G),le=function(e){function t(){var t;return(t=e.call(this)||this).namespace="navigation",t.endpoints={breadcrumbs:"breadcrumbs"},t.endpointsMethods={breadcrumbs:"get"},t.after_init(),t}return g(t,e),t.prototype.fetchBreadcrumbs=function(e){if(!e.page){var t="The 'page' parameter is required for the Breadcrumb API. Please provide a valid 'page' parameter.";return salla.event.navigation.breadcrumbFetchFailed(t),salla.api.errorPromise(t)}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){var a="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(a),salla.api.errorPromise(a)}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}))},t}(G),ce=function(e){function t(){var t;return(t=e.call(this)||this).namespace="metadata",t.endpoints={fetchValues:"https://api.salla.dev/store/v1/metadata/values"},t.endpointsMethods={fetchValues:"get"},t}return g(t,e),t.prototype.fetchValues=async function(e,t){if(!e||!t){var a="Please provide entity type and entity ids.";return salla.metadata.event.valueNotFetch(a),salla.api.errorPromise(a)}var n={type:e,entities:Array.isArray(t)?t:[t]};return this.request(this.endpoints.fetchValues,{params:n},"get").then((function(e){return salla.metadata.event.valueFetched(e),e})).catch((function(e){throw salla.metadata.event.valueNotFetch(e),e}))},t}(G),ue=function(e){function t(){var t;return(t=e.call(this)||this).auth=new B,t.cart=new z,t.loyalty=new W,t.order=new Q,t.rating=new Y,t.product=new K,t.profile=new J,t.comment=new X,t.currency=new Z,t.document=new $,t.wishlist=new ee,t.scope=new te,t.booking=new ae,t.landing=new ne,t.notifications=new re,t.component=new oe,t.advertisement=new se,t.navigation=new le,t.metadata=new ce,t}return g(t,e),t.prototype.beaconRequest=function(e,t){var a,n,r,i;if(void 0===t&&(t={}),null==(a=window.navigator)||!a.sendBeacon)return fetch(e,t);var o="string"==typeof(null==(n=t)?void 0:n.body)?null==(r=t)?void 0:r.body:JSON.stringify((null==(i=t)?void 0:i.body)||{}),s=new Blob([o],{type:"application/json"});return Salla.log("Beacon payload size: "+s.size+" bytes (~"+(s.size/1024).toFixed(2)+" KB)"),navigator.sendBeacon(e,s),Promise.resolve(new Response('{"status":"sent_via_beacon"}',{status:200,headers:{"Content-Type":"application/json"}}))},t}(ie),de=function(){function t(t){var a,n;if("ready"!==e.status)if(t){var r;if(e.config.merge(t),!["salla.sa","salla.group"].includes(location.hostname)||null!=(a=e.config.get("store.url"))&&a.includes(location.hostname)||!e.config.get("store.username")||e.config.set("store.url",window.location.origin+"/"+e.config.get("store.username")),(null==t?void 0:t.events)&&e.event.dispatchEvents(null==t?void 0:t.events),t._token&&salla.api.setHeader("X-CSRF-TOKEN",t._token),window.self===window.top&&(this.injectMaintenanceAlert(),this.injectThemePreviewAlert()),this.injectTemplateStoreAlert(),this.injectAppInstallAlert(),this.applyContentCopyright(),this.injectEditAlert(),null!=t&&null!=(n=t.user)&&n.language_code)salla.lang.setLocale(null==t||null==(r=t.user)?void 0:r.language_code);salla.lang.loadStoreTranslations(),this.setSallaReady(t),this.afterInit()}else this.setSallaReady(t);else salla.log("Trying to re-initiate Salla, while its status === 'ready'!")}var a=t.prototype;return a.afterInit=function(){e.url.is_page("product.single")&&e.config.isGuest()&&window.addEventListener("mini-checkout::before-init",(function(t){t.preventDefault(),e.event.emit("login::open")}))},a.applyContentCopyright=function(){if(e.config.get("store.settings.content_copyright")){["contextmenu","selectstart","copy"].forEach((function(e){document.addEventListener(e,(function(e){(function(e){var t;if(!e)return!1;var a=null==(t=e.tagName)?void 0:t.toLowerCase();return"input"===a||"textarea"===a})(e.target)||e.preventDefault()}))})),document.addEventListener("keydown",(function(e){var t=e.key.toLowerCase();("f12"===t||e.ctrlKey&&e.shiftKey&&["i","j","c"].includes(t)||e.ctrlKey&&"u"===t)&&(e.preventDefault(),e.stopPropagation())}));var t=document.createElement("style");t.textContent="\n body {\n -webkit-touch-callout: none;\n -webkit-user-select: none;\n -moz-user-select: none;\n -ms-user-select: none;\n user-select: none;\n }\n input, textarea {\n -webkit-touch-callout: auto;\n -webkit-user-select: auto;\n -moz-user-select: auto;\n -ms-user-select: auto;\n user-select: auto;\n }\n img {\n pointer-events: none;\n -webkit-user-drag: none;\n }\n ",document.head.appendChild(t)}},a.injectMaintenanceAlert=function(){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((function(){return document.body.prepend(document.createElement("salla-maintenance-alert"))})))},a.injectTemplateStoreAlert=function(){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((function(){return document.body.append(document.createElement("salla-bottom-alert"))})))},a.injectAppInstallAlert=function(){salla.config.get("store.app_install_prompt")&&salla.config.get("store.apps")&&!salla.storage.get("app_install_prompt_disabled")&&!salla.config.isMobileApp()&&(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((function(){return document.body.append(document.createElement("salla-app-install-alert"))})))},a.injectThemePreviewAlert=function(){"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((function(){var 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)})))},a.injectEditAlert=function(){var e=salla.config.get("edit");e&&(document.querySelector("#s-edit-alert")?salla.logger.warn("#s-edit-alert element Existed before!"):salla.lang.onLoaded((function(){var 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)})))},a.handleElementAjaxRequest=function(e,t){var a=this;if(!(t instanceof HTMLFormElement||t instanceof HTMLAnchorElement))return salla.logger.warn("trying to call ajax from non Element!!"),!1;e.preventDefault();var n=t.getAjaxFormData(e),r=n.method?n.method.toLowerCase():void 0;salla.api.request(n.url,n.formData,r).then((function(e){return e.data&&e.request&&(e=e.data),salla.api.handleAfterResponseActions(e),a.callAjaxEvent(n.events.success,e,n.formData),e})).catch((function(e){throw salla.api.handleErrorResponse(e),a.callAjaxEvent(n.events.fail,e,n.formData),e}))},a.callAjaxEvent=function(e,t,a){if(e){if(a instanceof FormData){var n={};Array.from(a.entries()).forEach((function(e){n[e[0]]=e[1]})),a=n}window[e]?window[e](t,a):salla.event.dispatch(e,t,a)}},a.setSallaReady=function(t){this.storeUTMs(),e.event.emitAsync("twilight::before.ready",t),e.status="ready",e.event.dispatch("twilight::initiated",t),window.dispatchEvent(new CustomEvent("twilight::initiated",{detail:t}))},a.storeUTMs=function(){var e=["fbclid","gad_source","ttclid","twclid","scid"],t=["utm_source","utm_medium","utm_campaign","utm_term","utm_content"].concat(e),a={},n={};window.location.search.replace("?","").split("&").map((function(e){return e.split("=")})).filter((function(e){var a=e[0];return t.includes(a.toLowerCase())})).forEach((function(e){var t=e[0],n=e[1],r=n||"";try{r=decodeURIComponent(n)}catch(e){console.warn("Failed to decode UTM param:",t,n,e)}a[t.toLowerCase()]=r}));var r=e.find((function(e){return a[e]}));!a.utm_source&&r&&(a.utm_source={fbclid:"facebook",gad_source:"google",ttclid:"tiktok",twclid:"twitter",scid:"snapchat"}[r],a.utm_campaign=a.utm_campaign||"Using the CLICKID "+r+" provided by "+a.utm_source,a.utm_term=a.utm_term||r+": "+a[r]),a.utm_source&&(Object.entries(a).filter((function(t){var a=t[0];return!e.includes(a)})).forEach((function(e){var t=e[0],a=e[1];n["s-"+t.replace("_","-")]=a})),n["s-utm-referrer"]=document.referrer,salla.storage.setWithTTL("s-utms",n,129600),this.logUTMVisitData(n))},a.logUTMVisitData=async function(e){var t=e["s-utm-source"],a=e["s-utm-medium"],n=e["s-utm-campaign"];e&&"affiliate"===t&&a&&n&&fetch(salla.config.get("affiliate.utm_url"),{method:"POST",mode:"cors",headers:{"Content-Type":"application/json","s-utm-source":t,"s-utm-medium":a,"s-utm-campaign":n}}).then((function(e){if(e.ok){var t=new URL(window.location.href),a=window.history.state;t.searchParams.delete("utm_source"),t.searchParams.delete("utm_medium"),t.searchParams.delete("utm_campaign"),window.history.replaceState(a,"",t)}}))},t}(),he=function(){function e(){var e=this;Salla.onReady((function(){return e.init()}))}var t=e.prototype;return t.init=function(){var e,t=this;if(salla.config.get("store.features",[]).includes("sso-login")){if(window.location.hostname.includes("salla"))return salla.log("SSO is not supported yet for stores without custom domain.");salla.auth.event.onLoggedOut((function(){return new Promise((function(e){var t=document.createElement("iframe");t.style.display="none",t.src=salla.url.get("sso/logout"),document.body.appendChild(t),t.onload=function(){document.body.removeChild(t),e()}}))})),null==(e=document.querySelector("salla-login-modal"))||e.remove(),Salla.event.removeAllListeners("login::open"),Salla.event.prependListener("login::open",(function(){return t.redirect()})),window.addEventListener("mini-checkout::before-init",(function(e){Salla.config.isUser()||(e.preventDefault(),t.redirect())}))}},t.redirect=function(){var e=window.location.pathname+window.location.search,t=window.location.origin+"/sso/login?intended_to="+encodeURIComponent(e);return console.log("Redirecting to:",t),window.location.href=t,!0},e}(),pe=function(){function e(e){this.item=e[0]}return e.prototype.toSegment=function(){var e,t,a,n;return{event:"Product Added",properties:{cart_id:null==(e=this.item.cart_id)?void 0:e.toString(),product_id:null==(t=this.item.id)?void 0:t.toString(),category:this.item.category,currency:null==(a=Salla.config.currency())?void 0:a.code,name:this.item.name,brand:this.item.brand,variant:null==(n=this.item.variant)?void 0:n.toString(),price:this.item.price,quantity:this.item.quantity,sku:this.item.sku,coupon:this.item.coupon,position:this.item.position,url:this.item.url,image_url:this.item.image_url}}},e.shouldSend=function(){return"customer.wishlist"!==salla.config.get("page.slug")},e}(),fe=function(){function e(e){this.product=e[0]}return e.prototype.toSegment=function(){var e;return{event:"Product Viewed",properties:{product_id:null==(e=this.product.id)?void 0:e.toString(),category:this.product.category,name:this.product.name,brand:this.product.brand,variant:this.product.variant,price:this.product.price,quantity:this.product.quantity,currency:this.product.currency,coupon:this.product.coupon,position:this.product.position,value:this.product.value,sku:this.product.sku,url:this.product.url,image_url:this.product.image_url}}},e}(),ge=function(){function e(e){this.cart=e[0]}return e.prototype.toSegment=function(){var e;return{event:"Cart Viewed",properties:{cart_id:null==(e=this.cart.cart_id)?void 0:e.toString(),products:this.cart.products.map((function(e){var t,a;return{product_id:null==(t=e.id)?void 0:t.toString(),name:e.name,price:e.price,category:e.category,sku:e.sku,position:e.position,url:e.url,image_url:e.image_url,brand:e.brand,currency:null==(a=Salla.config.currency())?void 0:a.code,variant:e.variant,coupon:e.coupon,quantity:e.quantity}}))}}},e}(),ve=function(){function e(e){var t=null==e?void 0:e.nextPage;this.listId=salla.config.get("page.slug"),Salla.config.get("page.id")&&(this.listId+="_"+salla.config.get("page.id")),this.sorts=null;try{if(t){var a=new URL(t).searchParams.get("sort");a&&(this.sorts=[{type:"sort",value:a}])}e.source&&(this.listId=this.listId+"_"+e.source),e.sourceValue&&(this.listId=this.listId+"_"+(Array.isArray(e.sourceValue)?e.sourceValue.join("_"):e.sourceValue))}catch(e){salla.logger.error(e)}this.products=null==e?void 0:e.data}return e.prototype.toSegment=function(){return{event:"Product List Viewed",properties:{list_id:this.listId,category:salla.config.get("page.title"),sorts:this.sorts,products:this.products.map((function(e){var t,a,n,r,i,o;return{product_id:e.id,category:null==(t=e.category)?void 0:t.name,currency:null==(a=Salla.config.currency())?void 0:a.code,name:e.name,brand:null==(n=e.brand)?void 0:n.name,variant:null==(r=e.variant)?void 0:r.toString(),coupon:null==(i=e.coupon)?void 0:i.toString(),price:e.price,quantity:Number(e.quantity),sku:e.sku,position:0,url:e.url,image_url:null==(o=e.image)?void 0:o.url}}))}}},e.shouldSend=function(e){return!((null==e?void 0:e.nextPage)||"").includes("filters")&&!["index","customer.wishlist"].includes(salla.config.get("page.slug"))},e}(),me=function(){function e(e){this.query=e}return e.prototype.toSegment=function(){return{event:"Products Searched",properties:{query:this.query}}},e}(),ye=function(){function e(){this.user=JSON.parse(localStorage.getItem("user"))}return e.prototype.toSegment=function(){var e,t,a,n,r;return{event:"Signed In",properties:{first_name:null==(e=this.user)?void 0:e.first_name,last_name:null==(t=this.user)?void 0:t.last_name,type:null==(a=this.user)?void 0:a.type,mobile:null==(n=this.user)?void 0:n.mobile,email:null==(r=this.user)?void 0:r.email}}},e.shouldSend=function(){return"user"===Salla.config.get("user.type")?!Salla.analytics.history.find((function(e){return"Signed In"===e.eventName})):(Salla.profile.event.onInfoFetched((function(){return Salla.event.emit("Signed In")})),!1)},e}(),we=function(e){function t(){return e.apply(this,arguments)||this}return g(t,e),t.prototype.toSegment=function(){var t=e.prototype.toSegment.call(this);return{event:"Signed Up",properties:null==t?void 0:t.properties}},t.shouldSend=function(){return"user"===Salla.config.get("user.type")||(Salla.profile.event.onInfoFetched((function(){return Salla.event.emit("Signed Up")})),!1)},t}(ye),Se=function(){function e(){}return e.prototype.toSegment=function(){return{event:"Signed Out",properties:{}}},e}(),be=function(){function e(e){this.item=e[0]}return e.prototype.toSegment=function(){var e,t,a,n,r,i,o,s,l,c,u,d,h,p;return{event:"Product Removed",properties:{cart_id:null==(e=this.item)||null==(e=e.cart_id)?void 0:e.toString(),product_id:null==(t=this.item)||null==(t=t.id)?void 0:t.toString(),category:null==(a=this.item)?void 0:a.category,currency:null==(n=Salla.config.currency())?void 0:n.code,name:null==(r=this.item)?void 0:r.name,brand:null==(i=this.item)?void 0:i.brand,variant:null==(o=this.item)?void 0:o.variant,price:null==(s=this.item)?void 0:s.price,quantity:null==(l=this.item)?void 0:l.quantity,sku:null==(c=this.item)?void 0:c.sku,coupon:null==(u=this.item)?void 0:u.coupon,position:null==(d=this.item)?void 0:d.position,url:null==(h=this.item)?void 0:h.url,image_url:null==(p=this.item)?void 0:p.image_url}}},e}(),_e=function(){function e(e){this.product=e.data.product}return e.prototype.toSegment=function(){var e,t,a,n;return{event:"Product Added to Wishlist",properties:(n={wishlist_id:salla.config.get("store.id")+"_"+salla.config.get("user.id"),wishlist_name:salla.config.get("store.name"),product_id:null==(e=this.product.id)?void 0:e.toString(),name:this.product.name,brand:this.product.brand,variant:this.product.variant,price:this.product.price,quantity:Math.max(1,Number(this.product.quantity)),sku:this.product.sku||null,position:Number(this.product.position||0),url:this.product.url,image_url:(null==(t=this.product)?void 0:t.image)||null,category:this.product.category,currency:null==(a=Salla.config.currency())?void 0:a.code},n.brand=this.product.brand,n)}},e}(),Fe=function(){function e(e){this.product=e.data.product}return e.prototype.toSegment=function(){var e,t,a,n;return{event:"Product Removed from Wishlist",properties:(n={wishlist_id:salla.config.get("store.id")+"_"+salla.config.get("user.id"),wishlist_name:salla.config.get("store.name"),product_id:null==(e=this.product.id)?void 0:e.toString(),name:this.product.name,brand:this.product.brand,variant:this.product.variant,price:this.product.price,quantity:Math.max(1,Number(this.product.quantity)),sku:this.product.sku||null,coupon:this.product.coupon||null,position:Number(this.product.position||0),currency:null==(t=Salla.config.currency())?void 0:t.code,url:this.product.url,image_url:(null==(a=this.product)?void 0:a.image)||null,category:this.product.category},n.brand=this.product.brand,n)}},e}(),ke=function(){function e(e){this.details=e[0]}return e.prototype.toSegment=function(){return{event:"Order Completed",properties:this.details}},e}(),Ce=function(){function e(e){this.item=e[0]}return e.prototype.toSegment=function(){var e,t;return{event:"Wishlist Product Added to Cart",properties:{wishlist_id:salla.config.get("store.id")+"_"+salla.config.get("user.id"),wishlist_name:salla.config.get("store.name"),cart_id:null==(e=this.item.cart_id)?void 0:e.toString(),product_id:null==(t=this.item.id)?void 0:t.toString(),category:this.item.category,name:this.item.name,brand:this.item.brand,variant:this.item.variant,price:this.item.price,quantity:this.item.quantity,sku:this.item.sku,coupon:this.item.coupon,position:this.item.position,url:this.item.url,image_url:this.item.image_url}}},e.shouldSend=function(){return"customer.wishlist"===salla.config.get("page.slug")},e}(),Pe=function(){function e(e){this.data=e}return e.prototype.toSegment=function(){var e,t=(null==(e=Salla.analytics.history.find((function(e){return"Product Viewed"===e.eventName})))?void 0:e.payload)||{};return t.share_via=this.data.share_via,{event:"Product Shared",properties:t}},e.shouldSend=function(){return"product.single"===salla.config.get("page.slug")},e}(),Ae=function(){function e(e){this.details=e}return e.prototype.toSegment=function(){return{event:"Product Reviewed",properties:this.details}},e.registerEvent=function(){salla.event.rating.onProductsRated((function(e,t){var a=t.products,n=t.order_id;Object.values(a).forEach((function(e){var t;Salla.event.emit("Product Reviewed",{product_id:null==(t=e.product_id)?void 0:t.toString(),review_id:null==n?void 0:n.toString(),review_body:e.comment,rating:e.rating})}))}))},e}(),qe=function(){function e(e){this.promotion=e[0]}return e.prototype.toSegment=function(){var e;return{event:"Promotion Viewed",properties:{promotion_id:null==(e=this.promotion.id)?void 0:e.toString(),creative:this.promotion.creative,name:this.promotion.name,position:this.promotion.position}}},e}(),Ee=function(){function e(e){this.promotion=e[0]}return e.prototype.toSegment=function(){var e;return{event:"Promotion Clicked",properties:{promotion_id:null==(e=this.promotion.id)?void 0:e.toString(),creative:this.promotion.creative,name:this.promotion.name,position:this.promotion.position}}},e}(),Ie=function(){function e(e){this.transaction=e}var t=e.prototype;return t.getCartId=function(){var e,t;return"cart"===salla.config.get("page.slug")?null==(t=salla.config.get("page.id"))?void 0:t.toString():(null==(e=this.transaction)||null==(e=e.data)||null==(e=e.cart)||null==(e=e.id)?void 0:e.toString())||""},t.toSegment=function(){var e,t;return{event:"Coupon Applied",properties:{cart_id:this.getCartId(),coupon_name:(null==(e=this.transaction)||null==(e=e.data)||null==(e=e.cart)?void 0:e.coupon)||"",discount:(null==(t=this.transaction)||null==(t=t.data)||null==(t=t.cart)?void 0:t.discount)||0,currency:salla.config.get("user.currency")||""}}},e}(),Te=function(){function e(e){this.transaction=e}var t=e.prototype;return t.getCartId=function(){var e;return"cart"===salla.config.get("page.slug")?null==(e=salla.config.get("page.id"))?void 0:e.toString():""},t.getCouponCode=function(){try{var e,t,a=null==(e=this.transaction.response)||null==(e=e.config)?void 0:e.data;return a?null==(t=JSON.parse(a))?void 0:t.coupon:""}catch(e){return""}},t.toSegment=function(){var e;return{event:"Coupon Denied",properties:{cart_id:this.getCartId(),coupon_name:this.getCouponCode(),reason:(null==(e=this.transaction.response)||null==(e=e.data)||null==(e=e.error)?void 0:e.message)||"Unknown error"}}},e}(),xe=function(){function e(e){this.transaction=e}var t=e.prototype;return t.getCartId=function(){var e,t;return"cart"===salla.config.get("page.slug")?null==(t=salla.config.get("page.id"))?void 0:t.toString():(null==(e=this.transaction)||null==(e=e.data)||null==(e=e.cart)||null==(e=e.id)?void 0:e.toString())||""},t.toSegment=function(){var e,t;return{event:"Coupon Removed",properties:{cart_id:this.getCartId(),coupon_name:(null==(e=this.transaction)?void 0:e.coupon)||"",discount:(null==(t=this.transaction)||null==(t=t.data)||null==(t=t.cart)?void 0:t.discount)||0,currency:salla.config.get("user.currency")||""}}},e}(),Le=function(){function e(e){this.details=null==e?void 0:e.data}return e.prototype.toSegment=function(){var t=this,a=["first_name","last_name","birthday","gender"].filter((function(a){var n,r;return e.user[a]!==(null==(n=t.details)?void 0:n[a])&&(void 0!==e.user[a]||void 0!==(null==(r=t.details)?void 0:r[a]))}));return e.setUser(this.details),{event:"User Profile Updated",properties:{updated_fields:a}}},e.registerEvent=function(){Salla.onReady((function(){salla.url.is_page("customer.profile")&&e.setUser(Salla.config.get("user"))}))},e.setUser=function(t){e.user={first_name:null==t?void 0:t.first_name,last_name:null==t?void 0:t.last_name,gender:null==t?void 0:t.gender,birthday:null==t?void 0:t.birthday,avatar:null==t?void 0:t.avatar}},e.shouldSend=function(){return"user"===Salla.config.get("user.type")},e}();Le.user={};var Re=function(e){function t(t){var a;a=e.call(this,t)||this;var n=(null==t?void 0:t.nextPage)||"";return a.filters=a.extractFilters(n),a}g(t,e);var a=t.prototype;return a.extractFilters=function(e){if(!e)return null;try{var t=new URL(e),a=[];return Array.from(t.searchParams.entries()).forEach((function(e){var t=e[0],n=e[1];if(t.startsWith("filters[")){var r=t.match(/^filters\[(.*?)\]/),i=r?r[1]:t;a.push({type:i,value:n})}})),a.length>0?a:null}catch(e){return console.warn("Error extracting filters from URL:",e),null}},a.toSegment=function(){var t=e.prototype.toSegment.call(this);return{event:"Product List Filtered",properties:f({},null==t?void 0:t.properties,{filters:this.filters})}},t.shouldSend=function(e){return((null==e?void 0:e.nextPage)||"").includes("filters")},t}(ve),Oe=function(){function e(e){this.cart=e}return e.prototype.toSegment=function(){var e,t,a,n,r=this;return{event:"Cart Updated",properties:{cart_id:null==(e=this.cart.id)?void 0:e.toString(),value:this.cart.total,revenue:this.cart.sub_total,tax:this.cart.tax_amount,discount:this.cart.total_discount,shipping:this.cart.real_shipping_cost,currency:null==(t=Salla.config.currency())?void 0:t.code,affiliation:null==(a=Salla.storage.getWithTTL("s-utms"))?void 0:a["s-utm-source"],products:null==(n=this.cart.items)?void 0:n.map((function(e){var t,a,n,i,o,s;return{product_id:null==(t=e.product_id)?void 0:t.toString(),name:e.product_name,price:e.product_price,category:null==(a=e.category)?void 0:a.toString(),sku:null==(n=e.product_sku)?void 0:n.toString(),position:e.position,url:e.url,image_url:e.product_image,brand:null==(i=e.brand)?void 0:i.toString(),currency:null==(o=Salla.config.currency())?void 0:o.code,variant:null==(s=e.variant)?void 0:s.toString(),coupon:r.cart.coupon,quantity:e.quantity}}))}}},e.shouldSend=function(){return"cart"===salla.config.get("page.slug")},e}(),je=function(){function e(e){this.scope=e.data}var t=e.prototype;return t.toSegment=function(){return{event:"Market Selected",properties:f({},this.getScope(this.scope),{prev:this.getScope(Salla.config.get("store.scope"))})}},t.getScope=function(e){var t;return{id:null==(t=(e=e||{}).id)?void 0:t.toString(),country:this.getScopeAttribute(e,"countries"),currency:this.getScopeAttribute(e,"currencies"),locale:this.getScopeAttribute(e,"languages")}},t.getScopeAttribute=function(e,t){return e=e[t],Array.isArray(e)?e[0]:e},e}(),De=function(){function e(){}return e.registerEvents=function(){Object.values(this.events).forEach((function(e){e.forEach((function(e){"function"==typeof e.registerEvent&&e.registerEvent()}))}))},e.transform=function(e,t){try{for(var a,n=p(this.events[e]||[]);!(a=n()).done;){var r=a.value;if(r&&("function"!=typeof r.shouldSend||r.shouldSend(t))){var i=new r(t).toSegment();return{event:i.event,properties:i.properties}}}return null}catch(e){return console.error("Failed to transform event:",e),null}},e}();De.events={"Order Completed":[ke],"Product Added":[pe,Ce],"Product Removed":[be],"Product Viewed":[fe],"Product Added to Wishlist":[_e],"Product Removed from Wishlist":[Fe],"Cart Viewed":[ge],"Products Searched":[me],"Product List Viewed":[ve],"Product List Filtered":[Re],"Signed Up":[we],"Signed In":[ye],"Signed Out":[Se],"Product Reviewed":[Ae],"Product Shared":[Pe],"Promotion Viewed":[qe],"Promotion Clicked":[Ee],"Coupon Applied":[Ie],"Coupon Removed":[xe],"Coupon Denied":[Te],"User Profile Updated":[Le],"Cart Updated":[Oe],"Market Selected":[je]};var Ue=function(){function e(){var e=this;this.history=[],this.customTrackers=[],this.mappedEvents={"wishlist::added":"Product Added to Wishlist","wishlist::removed":"Product Removed from Wishlist","salla-products-list::products.fetched":["Product List Viewed","Product List Filtered"],"auth::registered":"Signed Up","auth::logged.in":"Signed In","auth::logged.out":"Signed Out","share-element":"Product Shared","promotion::viewed":"Promotion Viewed","promotion::clicked":"Promotion Clicked","cart::coupon.added":"Coupon Applied","cart::coupon.deleted":"Coupon Removed","cart::coupon.addition.failed":"Coupon Denied","profile::updated":"User Profile Updated","cart::updated":"Cart Updated","scope::changed":"Market Selected"},Salla.event.onAny((function(t,a){try{if(Object.keys(e.mappedEvents).includes(t)){var n=e.mappedEvents[t];return void(Array.isArray(n)?n:[n]).forEach((function(e){return Salla.event.emit(e,a)}))}if(!Salla.config.get("jitsu.events",[]).includes(t))return;var r=De.transform(t,a);r&&e.track(r.event,r.properties)}catch(e){Salla.log("Error in analytics event handling:",e)}})),Salla.event.on("twilight::before.ready",(function(t){var a,n,r,o,s;e.debugAnalytics=i.jitsuAnalytics({host:e.getAnalyticsHost(t),writeKey:"bbLD6Xqr1OKsDJfxZBCy7SJN1RIsrkBp:WEa99iY220v9qX7KiuAlML9ldSFJKW2p",fetch:e.customFetch}),e.debugAnalytics.setContextProperty("library",{twilight:Salla.versions});var l=(null==t?void 0:t.jitsu)||{},c=l.host,u=l.key;if(e.jitsuAnalytics=null,c&&u){var d;if(De.registerEvents(),e.initVisitorData(),e.jitsuAnalytics=i.jitsuAnalytics({host:e.getAnalyticsHost(t),writeKey:u,cookieCapture:{vsc:"vsc"}}),e.setContext("store_id",null==(a=t.store)?void 0:a.id),e.setContext("version",null==(n=t.jitsu)?void 0:n.version),e.setContext("library",{twilight:Salla.versions}),null!=(r=t.jitsu)&&null!=(r=r.context)&&r.extra&&e.setExtraContext(t.jitsu.context.extra),null!=(o=t.store)&&null!=(o=o.scope)&&o.id)e.setContext("scope",null==(d=t.store)?void 0:d.scope);"user"===(null==t||null==(s=t.user)?void 0:s.type)&&e.setContext("traits",e.getFormattedUser(t.user)),e.registerTracker({name:"DefaultSallaTracker",track:function(t,a){return e.jitsuAnalytics.track(t,a)},page:function(t){return e.jitsuAnalytics.page(t)}})}else salla.log("Jitsu configuration is missing. Analytics will not be tracked.")})),Salla.onReady((function(){var t,a={name:Salla.config.get("page.slug",""),id:null==(t=Salla.config.get("page.id",""))?void 0:t.toString()};e.setContext("page",a),e.page(a)}))}var t=e.prototype;return t.setExtraContext=function(e){var t;null!=e&&null!=(t=e.headers)&&t["s-app-os"]&&(this.setContext("app",{version:e.headers["s-app-os-version"],app_release_tag:e.headers["s-app-version"],platform:e.headers["s-app-os"].toLowerCase()}),delete e.headers["s-app-os"],delete e.headers["s-app-os-version"],delete e.headers["s-app-version"],delete e.headers["s-source"]),this.setContext("system",e)},t.getAnalyticsHost=function(e){var t,a="https://salla.cloud/_app/e";if(null==e||null==(t=e.store)||!t.url)return Salla.log("Error getting store url - no config or store URL provided"),a;var n=e.store.url;try{var r="",i=n;if(/https:\/\/demostore\.salla\.sa/.test(i))return Salla.log("demostore.salla.sa detected, using fallback URL"),a;var o=i.match(/(salla\.sa)\/(?:(ar|en)\/)?((?!ar$|en$)[a-zA-Z0-9.-]+)/);if(o){var s=o[3];if(!s||0===s.trim().length||"ar"===s||"en"===s)return Salla.log("Error: invalid or empty store name in salla.sa URL"),a;r=new URL(i).origin+"/"+s}else{r=new URL(i).origin}return r+"/_app/e"}catch(e){return Salla.log("Error getting store url, forwarding to salla.cloud:",e),a}},t.setContext=function(e,t){var a,n;null==(a=this.jitsuAnalytics)||a.setContextProperty(e,t),null==(n=this.debugAnalytics)||n.setContextProperty(e,t)},t.customFetch=function(e,t){var a;return Salla.api.beaconRequest(e+"?writekey="+(null==t||null==(a=t.headers)?void 0:a["X-Write-Key"]),t)},t.track=function(e,t){void 0===t&&(t={}),t=this.finalPayload(t),this.history.push({action:"track",eventName:e,payload:t}),this.pushEventToCustomTrackers("track",e,t)},t.log=function(e,t){var a;return void 0===t&&(t={}),null==(a=this.debugAnalytics)?void 0:a.track(e,t).catch((function(e){return salla.log("Error tracking event:",e),Promise.reject(e)}))},t.page=function(e){var t,a;void 0===e&&(e={}),(e=this.finalPayload(e)).id=null==(t=e.id||Salla.config.get("page.id",""))?void 0:t.toString(),e.name=e.name||Salla.config.get("page.slug"),e.keywords=e.keywords||(null==(a=document.querySelector("meta[name=keywords]"))?void 0:a.content),e.referrer=e.referrer||document.referrer,this.history.push({action:"page",payload:e}),this.pushEventToCustomTrackers("page",e)},t.finalPayload=function(e){void 0===e&&(e={});var t=Salla.storage.getWithTTL("s-utms");if(t){var a,n=t["s-utm-campaign"],r=t["s-utm-source"],i=t["s-utm-medium"],o=t["s-utm-term"],s=t["s-utm-content"],l=t["s-utm-referrer"];null==(a=Salla.analytics)||a.setContext("campaign",{name:n,source:r,medium:i,term:o,content:s,referrer:l})}return f({},{},e)},t.registerTracker=function(e){"object"==typeof e?"string"==typeof e.name&&e.name?"function"==typeof e.track?"function"==typeof e.page?this.customTrackers.find((function(t){return t.name===e.name}))?Salla.log("tracker with the same name already exists!"):(this.customTrackers.push(e),this.history.forEach((function(t){return"track"===t.action?e.track(t.eventName,t.payload):"page"===t.action?e.page(t.payload):void 0}))):Salla.log("tracker.page most be a function!"):Salla.log("tracker.track most be a function!"):Salla.log("tracker.name most be a string!"):Salla.log('tracker most be an object {name:"tracker name", track: callback, page: callback}!')},t.pushEventToCustomTrackers=function(e,t,a){var n=this;void 0===a&&(a={});var r="page"===e?[t]:[t,a];return Promise.allSettled(this.customTrackers.map((function(t){return n.pushEventToCustomTracker(t[e],r)}))).then((function(t){return t.filter((function(e){return"rejected"===e.status})).map((function(t){return Salla.log("Error on customTracker to send "+e,t)}))}))},t.pushEventToCustomTracker=function(e,t){try{var a=e.apply(void 0,t);return Promise.resolve(a).catch((function(e){return Promise.reject(e)}))}catch(e){return Promise.reject(e)}},t.getFormattedUser=function(e){return e.phone=e.mobile,e.country=e.country_code,e.language=e.language_code,e.currency=e.currency_code,e},t.initVisitorData=function(){null!=Salla.cookie.get("vsc")||Salla.cookie.set("vsc",""+Date.now(),1)},e}(),Ne=function(){function e(){var e=this;Salla.onReady((function(){return e.init()}))}var t=e.prototype;return t.init=function(){if(!Salla.config.isUser()){var e=new URLSearchParams(window.location.search);if(e.has("intended_to"))try{var t=new URL(e.get("intended_to"));if(t.hostname!==window.location.hostname)return;return this.handleAfterLoginEvent(t)}catch(e){return void console.warn("Invalid URL provided in intended_to parameter")}}},t.handleAfterLoginEvent=function(e){var t="intend::user.logged.in";Salla.event.on(t,(function(){return window.location=e})),Salla.api.auth.setAfterLoginEvent(t),Salla.api.auth.setCanRedirect(!1),Salla.event.on("salla-login::ready",(function(){return Salla.event.emit("login::open",{withoutReload:!0})}))},e}(),Me=function(){function e(e){var t=this;void 0===e&&(e={}),this.config=f({WHITELIST:[location.hostname,"salla.com","salla.sa","salla.dev","salla.network","salla.group","mtjr.at"],POLL_INTERVAL_MS:500,WHITELIST_PAGES:["customer.orders.single","page-single","blog.single","blog.index"]},e),this.originalMethods={},this.isInitialized=!1,Salla.onReady((function(){return t.init()}))}var t=e.prototype;return t.normalizeUrl=function(e){try{return new URL(e,location.href)}catch(e){return null}},t.shouldIgnoreUrl=function(e){if(!e)return!1;var t="string"==typeof e?e:e.href||String(e),a=t.toLowerCase();if(["tel:","mailto:","javascript:"].some((function(e){return a.startsWith(e)})))return!0;try{var n=new URL(t,location.href).hostname.toLowerCase();return["facebook.com","fb.com","twitter.com","x.com","instagram.com","linkedin.com","youtube.com","youtu.be","tiktok.com","snapchat.com","pinterest.com","whatsapp.com","wa.me","iwtsp.com","telegram.org","t.me","discord.com","discord.gg","reddit.com","tumblr.com","google.com","forms.gle","maps.app.goo.gl","goo.gl","apple.com","smsaexpress.com","aramex.com","aj-ex.com","redboxsa.com","fastcoo-tech.com","express.dhl","najizxpress.net","jtexpress.me","jtexpress-sa.com","tamex.com.sa","aymakan.com.sa","fastlo.com","sls-express.com","logestechs.com","massuul.com","tamara.co","gov.sa","org.sa","stc.com.sa","sa","addtoany.com","wchat.freshchat.com","getbutton.io","heyzine.com","linktr.ee"].some((function(e){return n===e||n.endsWith("."+e)}))}catch(e){return!1}},t.isWhitelisted=function(e){if(!e)return!1;for(var t,a=e.hostname.toLowerCase(),n=p(this.config.WHITELIST);!(t=n()).done;){var r=t.value,i=String(r||"").toLowerCase().trim();if(i&&(a===i||a.endsWith("."+i)))return!0}return!1},t.emit=function(e){try{window.__redirectLogs||(window.__redirectLogs=[]),window.__redirectLogs.push(e);try{Salla.analytics.log("redirect",e)}catch(e){}}catch(e){}},t.logRedirect=function(e,t,a){if(!this.shouldIgnoreUrl(t)){var n=this.normalizeUrl(t),r=this.normalizeUrl(location.href),i=this.isWhitelisted(n),o={redirect_source:e,redirect_from:r?r.href:String(location.href),redirect_to:n?n.href:String(t),redirect_host:n?n.hostname:null,redirect_referrer:document.referrer||null,page_slug:Salla.config.get("page.slug"),whitelisted:i,stack:a&&a.stack?String(a.stack):void 0,meta:a||void 0};i||this.emit(o)}},t.hookHistoryAPIs=function(){var e=this;["pushState","replaceState"].forEach((function(t){try{var a=history[t];"function"==typeof a&&(e.originalMethods["history."+t]=a,history[t]=function(){for(var n=arguments.length,r=new Array(n),i=0;i<n;i++)r[i]=arguments[i];try{var o;e.logRedirect(t,null!=(o=r[2])?o:location.href)}catch(e){}return a.apply(history,r)})}catch(e){}})),window.addEventListener("popstate",(function(){e.logRedirect("popstate",location.href)})),window.addEventListener("hashchange",(function(){e.logRedirect("hashchange",location.href)}))},t.hookLocationMethods=function(){var e=this;try{var t=location.assign.bind(location);this.originalMethods["location.assign"]=t,location.assign=function(a){return e.logRedirect("location.assign",a,{stack:(new Error).stack}),t(a)}}catch(e){}try{var a=location.replace.bind(location);this.originalMethods["location.replace"]=a,location.replace=function(t){return e.logRedirect("location.replace",t,{stack:(new Error).stack}),a(t)}}catch(e){}},t.hookWindowOpen=function(){var e=this;try{var t=window.open;this.originalMethods["window.open"]=t,window.open=function(a){a&&e.logRedirect("window.open",a,{stack:(new Error).stack});for(var n=arguments.length,r=new Array(n>1?n-1:0),i=1;i<n;i++)r[i-1]=arguments[i];return t.apply(window,[a].concat(r))}}catch(e){}},t.setupEventListeners=function(){var e=this;this.handleLinkClick=function(t){var a=t.target&&t.target.closest?t.target.closest("a[href]"):null;if(a){var n=a.getAttribute("href");if(n&&!n.startsWith("#")&&!e.shouldIgnoreUrl(n)){var r=a.getAttribute("target")||"_self";setTimeout((function(){e.logRedirect("link-click",n,{target:r})}),0)}}},document.addEventListener("click",this.handleLinkClick,!0),this.handleFormSubmit=function(t){var a=t.target,n=a&&a.getAttribute&&a.getAttribute("action")||location.href,r=(a&&a.method?String(a.method):"GET").toUpperCase();e.logRedirect("form-submit",n,{method:r})},document.addEventListener("submit",this.handleFormSubmit,!0)},t.setupPerformanceObserver=function(){var e=this;try{this.performanceObserver=new PerformanceObserver((function(t){for(var a,n=p(t.getEntries());!(a=n()).done;){var r=a.value;"navigation"===r.entryType&&e.logRedirect("performance-navigation",location.href,{type:r.type,redirectCount:r.redirectCount})}})),this.performanceObserver.observe({type:"navigation",buffered:!0})}catch(e){}},t.init=function(){if(!this.config.WHITELIST_PAGES.includes(Salla.config.get("page.slug"))&&!this.isInitialized){var e=new URL(Salla.config.get("store.url")).hostname.split(".").slice(-2).join(".");this.config.WHITELIST.includes(e)||this.config.WHITELIST.push(e),this.hookHistoryAPIs(),this.hookLocationMethods(),this.hookWindowOpen(),this.setupEventListeners(),this.setupPerformanceObserver(),this.isInitialized=!0}},t.destroy=function(){var e=this;this.isInitialized&&(Object.keys(this.originalMethods).forEach((function(t){var a=t.split("."),n=a[0],r=a[1];"history"===n&&e.originalMethods[t]?history[r]=e.originalMethods[t]:"location"===n&&e.originalMethods[t]?location[r]=e.originalMethods[t]:"window"===n&&"open"===r&&e.originalMethods[t]&&(window.open=e.originalMethods[t])})),this.handleLinkClick&&document.removeEventListener("click",this.handleLinkClick,!0),this.handleFormSubmit&&document.removeEventListener("submit",this.handleFormSubmit,!0),this.performanceObserver&&this.performanceObserver.disconnect(),this.isInitialized=!1)},e}(),He=function(){function e(){this._store=new Map,this._whitelist=new Map([["salla-add-product-button",new Set(["validate","componentDidLoad"])],["salla-products-list",new Set(["componentDidLoad"])]]),this._componentHistory=new Map}var t=e.prototype;return t.registerHook=function(e,t,a,n){var r=this;if(void 0===n&&(n={}),!this._isAllowed(e,t))return console.warn('[Hooks] Hook "'+e+":"+t+'" is not allowed'),function(){};var i=0|n.priority,o=!!n.once,s=this._ensureTag(e),l=s.get(t)||[];return l.push({cb:a,p:i,once:o}),l.sort((function(e,t){return t.p-e.p})),s.set(t,l),"componentDidLoad"===t&&this._callForLoadedComponents(e,a),function(){return r.removeHook(e,t,a)}},t.registerHookOnce=function(e,t,a,n){return void 0===n&&(n={}),this.registerHook(e,t,a,f({},n,{once:!0}))},t.call=async function(e,t,a){var n=this._store.get(e);if(n){var r=n.get(t);if(r&&0!==r.length)for(var i=0,o=[].concat(r);i<o.length;i++){var s=o[i];try{await s.cb(a)}catch(a){console.warn('[Hooks] "'+e+":"+t+'" callback failed:',a)}s.once&&this.removeHook(e,t,s.cb)}}},t.removeHook=function(e,t,a){var n=this._store.get(e);if(!n)return!1;if(!n.has(t))return!1;if(!a)return n.delete(t),0===n.size&&this._store.delete(e),!0;var r=n.get(t),i=r.findIndex((function(e){return e.cb===a}));return i>-1&&(r.splice(i,1),0===r.length&&n.delete(t),0===n.size&&this._store.delete(e),!0)},t.clear=function(e){e?this._store.delete(e):this._store.clear()},t.get=function(e,t){var a,n=this._store.get(e);return n&&(null==(a=n.get(t))?void 0:a.map((function(e){return e.cb})))||[]},t._ensureTag=function(e){var t=this._store.get(e);return t||(t=new Map,this._store.set(e,t)),t},t._isAllowed=function(e,t){var a=this._whitelist.get(e);return a?!!a.has(t)||(console.warn('[Hooks] Hook "'+t+'" is not allowed for tag "'+e+'"'),!1):(console.warn('[Hooks] Tag "'+e+'" is not in the whitelist'),!1)},t.registerComponent=function(e,t){this._componentHistory.has(e)||this._componentHistory.set(e,new Set);var a=this._componentHistory.get(e);if(!a.has(t))return a.add(t),this.call(e,"componentDidLoad",t)},t._callForLoadedComponents=async function(e,t){var a=this._componentHistory.get(e);if(a&&0!==a.size)for(var n,r=p(a);!(n=r()).done;){var i=n.value;try{await t(i)}catch(t){console.warn('[Hooks] "'+e.replace(/[^a-zA-Z0-9-_]/g,"")+':componentDidLoad" callback failed:',t)}}},e}();e.onInitiated=function(e){return salla.event.once("twilight::initiated",e)},e.onReady=e.onReady||function(t){return new Promise((function(a){return"ready"===salla.status?a(t?t(salla.config.all()):salla.config.all()):e.onInitiated((function(e){return a(t?t(e):e)}))}))},e.status="loading",e.notify=c,e.lang=new V,e.form=new H,e.infiniteScroll=new M(void 0,salla.event.infiniteScroll),e.api=new ue,e.sso=new he,e.intend=new Ne,e.hooks=new He,["cart","auth","order","scope","rating","comment","loyalty","product","profile","currency","document","wishlist","booking","landing","metadata"].forEach((function(t){return e[t]=new u(e.api[t],e.event[t])})),e.call=function(t){for(var a=e,n=t.split(".");n.length&&(a=a[n.shift()]););return a},e.analytics=new Ue,e.init=function(e){return new de(e)},new Me,salla.event.once("twilight::init",salla.init),salla.event.on("twilight::api",(function(e){var t=null==e?void 0:e.events;t&&salla.event.dispatchEvents(t)})),e.success=e.notify.success,e.error=e.notify.error,e.versions.twilight="2.14.307",window.dispatchEvent(new CustomEvent("salla::created")),module.exports=e;
|
|
2
2
|
//# sourceMappingURL=index.js.map
|