@salla.sa/twilight 2.12.2 → 2.12.3
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/cjs/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var e=require("infinite-scroll"),t=require("lang.js"),a=require("axios"),n=require("jwt-decode");function r(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var i=r(e),o=r(t),l=r(a),s=r(n),c=function(e,t,a){return alert(e)},d=function(e,t){return c(e,u.error,t)},u={error:"error",success:"success",info:"info"},p={fire:function(e,t,a){return c(e,t,a)},setNotifier:function(e){c=e,salla.event.emit("twilight::notifier.changed")},error:d,success:function(e,t){return c(e,u.success,t)},info:function(e,t){return c(e,u.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){d(decodeURI(e.replace("?danger=","").replace("&danger=","")),{})}))})))},types:u},h=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]}})},f=function(e,t){return f=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var a in t)Object.prototype.hasOwnProperty.call(t,a)&&(e[a]=t[a])},f(e,t)};function g(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function a(){this.constructor=e}f(e,t),e.prototype=null===t?Object.create(t):(a.prototype=t.prototype,new a)}var v=function(){return v=Object.assign||function(e){for(var t,a=1,n=arguments.length;a<n;a++)for(var r in t=arguments[a])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e},v.apply(this,arguments)};function m(e,t,a,n){return new(a||(a=Promise))((function(r,i){function o(e){try{s(n.next(e))}catch(e){i(e)}}function l(e){try{s(n.throw(e))}catch(e){i(e)}}function s(e){var t;e.done?r(e.value):(t=e.value,t instanceof a?t:new a((function(e){e(t)}))).then(o,l)}s((n=n.apply(e,t||[])).next())}))}function y(e,t){var a,n,r,i,o={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return i={next:l(0),throw:l(1),return:l(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function l(l){return function(s){return function(l){if(a)throw new TypeError("Generator is already executing.");for(;i&&(i=0,l[0]&&(o=0)),o;)try{if(a=1,n&&(r=2&l[0]?n.return:l[0]?n.throw||((r=n.return)&&r.call(n),0):n.next)&&!(r=r.call(n,l[1])).done)return r;switch(n=0,r&&(l=[2&l[0],r.value]),l[0]){case 0:case 1:r=l;break;case 4:return o.label++,{value:l[1],done:!1};case 5:o.label++,n=l[1],l=[0];continue;case 7:l=o.ops.pop(),o.trys.pop();continue;default:if(!(r=o.trys,(r=r.length>0&&r[r.length-1])||6!==l[0]&&2!==l[0])){o=0;continue}if(3===l[0]&&(!r||l[1]>r[0]&&l[1]<r[3])){o.label=l[1];break}if(6===l[0]&&o.label<r[1]){o.label=r[1],r=l;break}if(r&&o.label<r[2]){o.label=r[2],o.ops.push(l);break}r[2]&&o.ops.pop(),o.trys.pop();continue}l=t.call(e,o)}catch(e){l=[6,e],n=0}finally{a=r=0}if(5&l[0])throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}([l,s])}}}function w(e,t,a){if(a||2===arguments.length)for(var n,r=0,i=t.length;r<i;r++)!n&&r in t||(n||(n=Array.prototype.slice.call(t,0,r)),n[r]=t[r]);return e.concat(n||Array.prototype.slice.call(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){for(var t,a=[],n=1;n<arguments.length;n++)a[n-1]=arguments[n];if(this.getAttribute){if(this.hasAttribute("data-json"))try{return JSON.parse(this.getAttribute("data-json"))}catch(e){}var r=this.getAttribute("data-function");if(r&&window[r])return"function"==typeof window[r]?this.getFilteredData((t=window[r]).call.apply(t,w([this],a,!1))):this.getFilteredData(window[r]);var i=this.hasAttribute("data-form-selector")?document.querySelector(this.dataset.formSelector):void 0;if((i="FORM"===this.tagName?this:i||this.closest("form")||this.closest("[salla-form-data]")||this)&&"FORM"===i.tagName)return this.getFilteredData(new FormData(i),null,i);var o=i.querySelectorAll("[name]");if(!o.length)return this.getFilteredData();var l=Object.assign({},this.dataset);return o.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=this;return void 0===e&&(e=null),void 0===t&&(t=null),void 0===a&&(a=null),e=e||(null==a?void 0:a.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(r){var i=(null==a?void 0:a.dataset[r])||n.dataset[r];if(i){var o=window[i];if("function"==typeof o){if(!o(e,a||n,t)&&e)throw"Data failed to be pass verify function window.".concat(i,"(formData, element, event)!");return o(e,a||n,t)}Salla.log("window."+i+"() 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 b=function(){function e(){this.events={},this.namespace="";var e=/function (.{1,})\(/.exec(this.constructor.toString());this.className=(e&&e.length>1?e[1]:"").toLowerCase()}return e.prototype.after_init=function(){this.createDynamicFunctions()},e.prototype.createDynamicFunctions=function(){var e=this;Object.keys(this.events).forEach((function(t){e.createDynamicEventFuns(t),e.createDynamicListenerFuns(t)}))},e.prototype.createDynamicEventFuns=function(e){if(!this[e]){var t=this;this[e]=function(){for(var a=[],n=0;n<arguments.length;n++)a[n]=arguments[n];return t.dispatch.apply(t,w([e],a,!1))}}},e.prototype.createDynamicListenerFuns=function(e){var t="on"+e.charAt(0).toUpperCase()+e.slice(1);if(!this[t]){var a=this;this[t]=function(t){var n=this;return a.on(e,(function(){for(var e=[],a=0;a<arguments.length;a++)e[a]=arguments[a];return m(n,void 0,void 0,(function(){return y(this,(function(a){return[2,t.apply(void 0,e)]}))}))}))}}},e.prototype.getEventName=function(e){return e=this.events[e]||e,!this.namespace||e.includes("::")?e:this.namespace+Salla.event.delimiter+e},e.prototype.dispatch=function(e){for(var t,a=[],n=1;n<arguments.length;n++)a[n-1]=arguments[n];return(t=Salla.event).emitAsync.apply(t,w([this.getEventName(e)],a,!1))},e.prototype.on=function(e,t){return Salla.event.addListener(this.getEventName(e),t)},e.prototype.once=function(e,t){return Salla.event.once(this.getEventName(e),t)},e}(),F=function(e){function t(){var t=e.call(this)||this;return t.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"},t.after_init(),t}return g(t,e),t.prototype.login=function(e){return e?(e.type&&this.setTypeActionOnVerified(e.type),this.next_event=e.next_event||null,this.dispatch.apply(this,w(["login"],arguments,!1))):(this.next_event=null,this.dispatch.apply(this,w(["login"],arguments,!1)))},t.prototype.loggedIn=function(e){var t=this;return Salla.profile.info().finally((function(){return t.dispatch("loggedIn",e)}))},t.prototype.setTypeActionOnVerified=function(e){this.type_action_on_verified=e},t.prototype.getTypeActionOnVerified=function(){return this.type_action_on_verified||"redirect"},t}(b),S=function(e){function t(){var t=e.call(this)||this;return t.namespace="cart",t.events={latestFetched:"latest.fetched",latestFailed:"latest.failed",updated:"updated",itemUpdated:"item.updated",itemUpdatedFailed:"item.updated.failed",itemAdded:"item.added",itemAddedFailed:"item.added.failed",itemDeleted:"item.deleted",itemDeletedFailed:"item.deleted.failed",submitted:"submitted",submitFailed:"submit.failed",imageDeleted:"image.deleted",imageNotDeleted:"image.not.deleted",detailsFetched:"details.fetched",detailsNotFetched:"details.not.fetched",successReset:"success.reset",priceQuoteSucceeded:"price-quote.succeeded",priceQuoteFailed:"price-quote.failed",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"},t.after_init(),t}return g(t,e),t.prototype.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,real_shipping_cost:e.cart.real_shipping_cost,count:e.cart.count,shipping_cost:(null===(t=e.cart.free_shipping_bar)||void 0===t?void 0: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"))},t.prototype.latestFetched=function(e){return this.updated(e.data),this.dispatch("latestFetched",e)},t.prototype.itemAdded=function(e,t){return this.updated(e.data),this.dispatch("itemAdded",e,t)},t.prototype.itemDeleted=function(e,t){return this.updated(e.data),this.dispatch("itemDeleted",e,t)},t.prototype.itemUpdated=function(e,t){return this.updated(e.data),this.dispatch("itemUpdated",e,t)},t.prototype.couponAdded=function(e,t){return this.updated(e.data),this.dispatch("couponAdded",e,t)},t.prototype.couponDeleted=function(e,t){return this.updated(e.data),this.dispatch("couponDeleted",e,t)},t}(b),_=function(e){function t(){var t=e.call(this)||this;return t.namespace="order",t.events={canceled:"canceled",notCanceled:"not.canceled",orderCreated:"order.created",orderCreationFailed:"order.creation.failed",invoiceSent:"invoice.sent",invoiceNotSent:"invoice.not.sent"},t.after_init(),t}return g(t,e),t}(b),q=function(e){function t(){var t=e.call(this)||this;return t.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}(b),A=function(e){function t(){var t=e.call(this)||this;return t.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}(b),C=function(e){function t(){var t=e.call(this)||this;return t.namespace="comment",t.events={added:"added",additionFailed:"addition.failed",fetched:"fetched",fetchFailed:"fetch.failed"},t.after_init(),t}return g(t,e),t}(b),k=function(e){function t(){var t=e.call(this)||this;return t.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}return g(t,e),t.prototype.exchangeSucceeded=function(e,t){return salla.cart.event.updated(e.data),this.dispatch("exchangeSucceeded",e,t)},t.prototype.resetSucceeded=function(e){return salla.cart.event.updated(e.data),this.dispatch("resetSucceeded",e)},t}(b),P=function(e){function t(){var t=e.call(this)||this;return t.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}(b),E=function(e){function t(){var t=e.call(this)||this;return t.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"},t.after_init(),t}return g(t,e),t}(b),x=function(e){function t(){var t=e.call(this)||this;return t.namespace="document",t.events={click:"click",change:"change",submit:"submit",keyup:"keyup",leaving:"leaving",request:"request",requestFailed:"request.failed"},t.after_init(),t}return g(t,e),t.prototype.onClick=function(e,t){this.fireCallableFuns("click",e,t)},t.prototype.onChange=function(e,t){this.fireCallableFuns("change",e,t)},t.prototype.onSubmit=function(e,t){this.fireCallableFuns("submit",e,t)},t.prototype.onKeyup=function(e,t){this.fireCallableFuns("keyup",e,t)},t.prototype.fireCallableFuns=function(e,t,a){this.on(e,(function(e){"function"!=typeof t?"function"==typeof a&&e.target.matches(t)&&a(e):t(e)}))},t.prototype.fireEvent=function(e,t){for(var a=[],n=2;n<arguments.length;n++)a[n-2]=arguments[n];return this.fireEventForElements.apply(this,w([e,t,!1],a,!1))},t.prototype.fireEventForAll=function(e,t){for(var a=[],n=2;n<arguments.length;n++)a[n-2]=arguments[n];return this.fireEventForElements.apply(this,w([e,t,!0],a,!1))},t.prototype.fireEventForElements=function(e,t,a){for(var n=this,r=[],i=3;i<arguments.length;i++)r[i-3]=arguments[i];if("string"==typeof e){if(a)return document.querySelectorAll(e).forEach((function(e){return n.fireEventForElements.apply(n,w([e,t,!1],r,!1))}));e=document.querySelector(e)}if(e){var o=new(CustomEvent.bind.apply(CustomEvent,w([void 0,t],r,!1)));return e.dispatchEvent(o)}salla.log("Failed To get element to fire event: "+t)},t}(b),T=function(e){function t(){var t=e.call(this)||this;return t.namespace="wishlist",t.events={added:"added",removed:"removed",additionFailed:"addition.failed",removingFailed:"removing.failed"},t.after_init(),t}return g(t,e),t}(b),D=function(e){function t(){var t=e.call(this)||this;return t.namespace="currency",t.events={changed:"changed",failed:"failed",fetched:"fetched",failedToFetch:"failed.to.fetch"},t.after_init(),t}return g(t,e),t}(b),O=function(e){function t(){var t=e.call(this)||this;return t.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}(b),I=function(e){function t(){var t=e.call(this)||this;return t.namespace="booking",t.events={added:"added",additionFailed:"addition.failed"},t.after_init(),t}return g(t,e),t}(b),L=function(e){function t(){var t=e.call(this)||this;return t.namespace="landing",t.events={detailsFetched:"order.fetched",getDetailsFailed:"get.details.failed",orderCreated:"order.created",orderCreationFailed:"order.creation.failed"},t.after_init(),t}return g(t,e),t}(b);function R(e){e&&e.sallaInitiated&&!e.initiated&&(e.sallaInitiated(),e.initiated=!0)}Salla.event.auth=new F,Salla.event.cart=new S,Salla.event.order=new _,Salla.event.scope=new q,Salla.event.rating=new A,Salla.event.booking=new I,Salla.event.comment=new C,Salla.event.landing=new L,Salla.event.loyalty=new k,Salla.event.product=new E,Salla.event.profile=new P,Salla.event.currency=new D,Salla.event.document=new x,Salla.event.wishlist=new T,Salla.event.infiniteScroll=new O,Salla.event.on("twilight::initiated",(function(){Object.keys(Salla).forEach((function(e){"object"==typeof(e=Salla[e])&&(R(e),Object.keys(e).forEach((function(t){R(e[t])})))}))}));var j=void 0;Salla.config.default_properties={debug:"undefined"!=typeof process&&"development"===process.env.NODE_ENV,token:null,fastRequests:!0,canLeave:!0,store:{api:"https://api.salla.dev/store/v1/"},currencies:{SAR:{code:"SAR",name:"ريال سعودي",symbol:"ر.س",amount:1,country_code:"sa"}}},Salla.config.merge(Salla.config.default_properties),Salla.config.triedToGetCurrencies_=!1,Salla.config.triedToGetLanguages_=!1,Salla.config.isUser=function(){return"user"===Salla.config.get("user.type")},Salla.config.isGuest=function(){return!Salla.config.isUser()},Salla.config.languages=function(){return __awaiter(j,void 0,void 0,(function(){var e,t,a,n;return __generator(this,(function(r){switch(r.label){case 0:return Salla.config.triedToGetLanguages_?[2,Salla.config.get("languages")]:(Salla.config.triedToGetLanguages_=!0,e=!0,t=[],[4,salla.document.api.request("languages",null,"get")]);case 1:return null===(n=null===(a=r.sent())||void 0===a?void 0:a.data)||void 0===n||n.map((function(a){e&&(t=[],e=!1),a.code=a.code||a.iso_code,a.url=salla.url.get(a.code),a.is_rtl=a.is_rtl||a.rtl,t.push(a)})),Salla.config.set("languages",t),[2,t]}}))}))},Salla.config.currencies=function(){return __awaiter(j,void 0,void 0,(function(){var e,t,a,n;return __generator(this,(function(r){switch(r.label){case 0:return Salla.config.triedToGetCurrencies_?[2,Salla.config.get("currencies")]:(Salla.config.triedToGetCurrencies_=!0,e=!0,t={},[4,salla.currency.api.list()]);case 1:return null===(n=null===(a=r.sent())||void 0===a?void 0:a.data)||void 0===n||n.map((function(a){e&&(t={},e=!1),a.country_code=a.code.substr(0,2).toLowerCase(),t[a.code]=a})),Salla.config.set("currencies",t),[2,t]}}))}))};var N=function(e){function t(t,a){var n=e.call(this,t,a)||this;return n.options={path:".infinite-scroll-btn",history:"push",status:".infinite-scroll-status",append:".list-block"},n.fetchOptions={headers:{"S-INFINITE-SCROLL":!0}},n.instances=[],n}return g(t,e),t.prototype.initiate=function(e,t,a,n){void 0===n&&(n=!1),n?((a=a||{}).fetchOptions=v(v({},this.fetchOptions),a.fetchOptions||{}),a.responseBody="json"):a=this.getCustomOptions(t,a);var r="string"!=typeof e?e:document.querySelector(e),o=a.path;if(r&&o&&("string"!=typeof o||document.querySelector(o))){var l=new i.default(r,a);return l.on("scrollThreshold",Salla.infiniteScroll.event.scrollThreshold),l.on("request",Salla.infiniteScroll.event.request),l.on("load",Salla.infiniteScroll.event.load),l.on("append",Salla.infiniteScroll.event.append),l.on("error",Salla.infiniteScroll.event.error),l.on("last",Salla.infiniteScroll.event.last),l.on("history",Salla.infiniteScroll.event.history),this.instances.push(l),l}Salla.logger.warn(r?"Path Option (a link that has next page link) Not Existed!":"Container For InfiniteScroll not Existed!")},t.prototype.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},t.prototype.loadNextPage=function(e){("string"!=typeof e?e:document.querySelector(e)).loadNextPage()},t.prototype.destroy=function(e){("string"!=typeof e?e:document.querySelector(e)).destroy()},t}(h),U=function(){function e(){}return e.prototype.submit=function(e,t){var a,n,r,i;return void 0===t&&(t=null),m(this,void 0,void 0,(function(){var o,l,s;return y(this,(function(c){switch(c.label){case 0:if(o=t,"SubmitEvent"===(null===(a=null==t?void 0:t.constructor)||void 0===a?void 0:a.name)||"submit"===(null==t?void 0:t.type)){if(t.preventDefault(),"FORM"!==(null===(n=t.target)||void 0===n?void 0:n.tagName))return Salla.logger.warn("Failed find the target element for submit action. make sure you submit a form element"),[2,new Promise((function(){throw"Failed find the target element for submit action. make sure you submit a form element"}))];"SALLA-BUTTON"===(null===(i=null===(r=null==t?void 0:t.submitter)||void 0===r?void 0:r.parentElement)||void 0===i?void 0:i.tagName)&&t.submitter.parentElement.load(),o=t.target.getElementSallaData(),salla.log("Data from element",o)}return/^https?:\/\/(?:www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)$/gm.test(e)?[2,salla.api.request(e,o,"post").finally((function(){var e;loaderSupported&&(null===(e=null==t?void 0:t.submitter)||void 0===e||e.parentElement.stop())}))]:(l=e.split("."),s=l.splice(-1),[4,salla.call(l.join("."))[s](o).finally((function(){var e,a;return null===(a=null===(e=null==t?void 0:t.submitter)||void 0===e?void 0:e.parentElement)||void 0===a?void 0:a.stop()})).catch((function(e){throw salla.logger.warn(e),e}))]);case 1:return[2,c.sent()]}}))}))},e.prototype.onSubmit=function(e,t){return salla.form.submit(e,t),!1},e.prototype.onChange=function(e,t){var a;return(null==t?void 0:t.currentTarget)?"FORM"!==(null===(a=null==t?void 0:t.currentTarget)||void 0===a?void 0:a.tagName)||t.currentTarget.checkValidity()?(salla.form.submit(e,t.currentTarget.getElementSallaData()),!0):(salla.logger.warn("Trying to trigger '".concat(e,"' without filling required fields!")),!1):(salla.logger.warn("Trying to trigger '".concat(e,"' without event!")),!1)},e.prototype.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}(),M=function(e){function t(t){var a=this;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}return g(t,e),t.prototype.onLoaded=function(e){if(this.translationsLoaded)return e();Salla.event.once("languages::translations.loaded",e)},t.prototype.loadStoreTranslations=function(){if(this.hash=salla.config.get("theme.translations_hash",salla.config.get("store.id","twilight")),this.messages||(salla.log("try to load translations from localstorage"),this.messages=salla.storage.get("s_translations.".concat(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/".concat(this.hash,".js"))):this.loadScript("https://cdn.salla.network/js/translations.js",!1)},t.prototype.setMessages=function(t){e.prototype.setMessages.call(this,t),salla.event.dispatch("languages::translations.loaded"),this.translationsLoaded=!0},t.prototype.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)},t.prototype.getWithDefault=function(e,t,a,n){var r=this.get(e,a,n);return r!==e?r:t},t.prototype.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)},t.prototype.set=function(e,t){return salla.helpers.setNested(this.messages[this.getLocale()+".trans"],e,t),this},t}(o.default),V=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:[]}}return e.prototype.after_init=function(){},e.prototype.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})},e.prototype.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)},e.prototype.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},e.prototype.event=function(){return salla.event[this.className]},e}(),G=function(e){function t(){var t=e.call(this)||this;return t.namespace="cart",t.endpoints={latest:"cart/latest",details:"cart/{cart}",quickAdd:"cart/{cart}/item/{product}/quick-add",addItem:"cart/{cart}/item/{product}/add",deleteItem:"cart/{cart}/item/{item}",updateItem:"cart/{cart}/item/{item}",deleteImage:"cart/{cart}/image/{image}",uploadImage:"cart/{cart}/image",status:"cart/{cart}/status",addCoupon:"cart/{id}/coupon",deleteCoupon:"cart/{id}/coupon",getQuickOrderSettings:"checkout/quick-order",createQuickOrder:"checkout/quick-order",priceQuote:"cart/{cartId}/price-quote"},t.endpointsMethods={latest:"get",details:"get",status:"get",updateItem:"post",deleteItem:"delete",deleteImage:"delete",deleteCoupon:"put",getQuickOrderSettings:"get"},t.webEndpoints=["latest"],t.latestCart=null,t.after_init(),salla.event.on("api::initiated",(function(){return t.getCurrentCartId()})),t}return g(t,e),t.prototype.getCurrentCartId=function(){return m(this,void 0,void 0,(function(){var e,t;return y(this,(function(a){switch(a.label){case 0:return salla.cart.api.latestCart?[2,salla.cart.api.latestCart.cart.id]:(e=salla.storage.get("cart.id"))?[2,e]:[4,this.latest()];case 1:return t=a.sent(),salla.cart.api.latestCart=t.data,[2,salla.cart.api.latestCart.cart.id]}}))}))},t.prototype.getUploadImageEndpoint=function(e){return salla.url.api(this.getUrl("uploadImage",e||salla.storage.get("cart.id")))},t.prototype.latest=function(){return this.request("latest",{params:{source:""}}).then((function(e){return salla.storage.set("cart",e.data.cart),salla.event.cart.latestFetched(e),e})).catch((function(e){throw salla.storage.set("cart",""),salla.event.cart.latestFailed(e),e}))},t.prototype.details=function(e,t){return void 0===t&&(t=[]),m(this,void 0,void 0,(function(){var a;return y(this,(function(n){switch(n.label){case 0:return(a=e)?[3,2]:[4,this.getCurrentCartId()];case 1:a=n.sent(),n.label=2;case 2:return e=a,[2,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}))]}}))}))},t.prototype.quickAdd=function(e,t){return m(this,void 0,void 0,(function(){return y(this,(function(a){return[2,this.addItem({id:e,quantity:t,endpoint:"quickAdd"})]}))}))},t.prototype.addItem=function(e){return m(this,void 0,void 0,(function(){var t,a,n,r;return y(this,(function(i){switch(i.label){case 0:return(t=this.getCartPayload(e)).id?((n=salla.form.getPossibleValue(t.payload,["endpoint"]))&&["addItem","quickAdd"].includes(n)||(n=salla.form.getPossibleValue(t.payload,["quantity","donating_amount"])?"addItem":"quickAdd"),[4,this.getCurrentCartId()]):(a='There is no product "id"!',salla.cart.event.itemAddedFailed(a),[2,salla.api.errorPromise(a)]);case 1:return r=i.sent(),[2,this.request([n,r,t.id],t.payload).then((function(e){return salla.cart.event.itemAdded(e,t.id),e})).catch((function(e){throw salla.cart.event.itemAddedFailed(e,t.id),e}))]}}))}))},t.prototype.deleteItem=function(e){return m(this,void 0,void 0,(function(){var t,a,n;return y(this,(function(r){switch(r.label){case 0:return(t=this.getCartPayload(e)).id?[4,this.getCurrentCartId()]:(a='There is no "id"!',salla.cart.event.itemDeletedFailed(a),[2,salla.api.errorPromise(a)]);case 1:return n=r.sent(),[2,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}))]}}))}))},t.prototype.updateItem=function(e){var t;return m(this,void 0,void 0,(function(){var a,n,r;return y(this,(function(i){switch(i.label){case 0:return(a=this.getCartPayload(e)).id?[4,this.getCurrentCartId()]:(n='There is no "id"!',salla.cart.event.itemUpdatedFailed(n),[2,salla.api.errorPromise(n)]);case 1:return r=i.sent(),"Object"===(null===(t=a.payload.constructor)||void 0===t?void 0:t.name)?a.payload._method="PUT":a.payload.append("_method","PUT"),[2,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}))]}}))}))},t.prototype.deleteImage=function(e){return m(this,void 0,void 0,(function(){var t,a;return y(this,(function(n){switch(n.label){case 0:return(e=salla.form.getPossibleValue(e,["id","image_id","photo_id"]))?[4,this.getCurrentCartId()]:(t='There is no "id"!',salla.cart.event.imageNotDeleted(t),[2,salla.api.errorPromise(t)]);case 1:return a=n.sent(),[2,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}))]}}))}))},t.prototype.status=function(e){return m(this,void 0,void 0,(function(){var t,a,n;return y(this,(function(r){switch(r.label){case 0:return t=this.request,a=["status"],(n=e)?[3,2]:[4,this.getCurrentCartId()];case 1:n=r.sent(),r.label=2;case 2:return[2,t.apply(this,[a.concat([n]),{params:{has_apple_pay:!!window.ApplePaySession}}])]}}))}))},t.prototype.submit=function(){return m(this,void 0,void 0,(function(){var e,t=this;return y(this,(function(a){switch(a.label){case 0:return e=this.status,[4,this.getCurrentCartId()];case 1:return e.apply(this,[a.sent()]).then((function(e){var a=e.data.next_step.to;if(!["checkout","refresh","login"].includes(a)){var n="Can't find next_step );";throw salla.cart.event.submitFailed(n),n}if(salla.cart.event.submitted(e),"login"===a)return salla.auth.setCanRedirect(!1),salla.event.dispatch("login::open"),void salla.auth.event.onLoggedIn((function(e){salla.event.dispatch("login::close"),t.submit()}));"checkout"===a?window.location.href=e.data.next_step.url+(window.ApplePaySession?"?has_apple_pay=true":""):window.location.reload()})).catch((function(e){throw salla.cart.event.submitFailed(e),e})),[2]}}))}))},t.prototype.getCartPayload=function(e){var t=(null==e?void 0:e.data)||("object"==typeof e?e:void 0);return{id:e=t?salla.form.getPossibleValue(t,["prod_id","product_id","item_id","id"]):e,payload:t="object"==typeof t?t:void 0}},t.prototype.normalRequest=function(t,a,n){return void 0===a&&(a=void 0),void 0===n&&(n=null),e.prototype.normalRequest.call(this,t,a,n).catch((function(e){var t;throw 403===(null===(t=null==e?void 0:e.response)||void 0===t?void 0:t.status)&&(salla.cart.api.reset(),salla.error(salla.lang.get("pages.checkout.try_again"))),e}))},t.prototype.reset=function(){salla.api.cart.latestCart=null,salla.storage.remove("cart"),salla.cart.event.successReset()},t.prototype.addCoupon=function(e){return m(this,void 0,void 0,(function(){var t,a;return y(this,(function(n){switch(n.label){case 0:return e=e.data||e,(e=salla.form.getPossibleValue(e,["coupon"]))?[4,salla.cart.api.getCurrentCartId()]:((t=new Error('There is no "Coupon Code"!')).name="EmptyCoupon",salla.event.cart.couponAdditionFailed(t),[2,salla.api.errorPromise(t)]);case 1:return a=n.sent(),[2,this.request(["addCoupon",a],{coupon:e}).then((function(e){return salla.event.cart.couponAdded(e,a),e})).catch((function(e){throw salla.event.cart.couponAdditionFailed(e,a),e}))]}}))}))},t.prototype.deleteCoupon=function(){return m(this,void 0,void 0,(function(){var e;return y(this,(function(t){switch(t.label){case 0:return[4,salla.cart.api.getCurrentCartId()];case 1:return e=t.sent(),[2,this.request(["deleteCoupon",e],{}).then((function(t){return salla.event.cart.couponDeleted(t,e),t})).catch((function(t){throw salla.event.cart.couponDeletionFailed(t,e),t}))]}}))}))},t.prototype.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}))},t.prototype.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}))},t.prototype.priceQuote=function(e){return m(this,void 0,void 0,(function(){var t,a,n;return y(this,(function(r){switch(r.label){case 0:return salla.config.isGuest()?(salla.auth.api.setAfterLoginEvent("cart::priceQuote",e),salla.event.dispatch("login::open"),[2]):(t=this.request,a=["priceQuote"],(n=e)?[3,2]:[4,this.getCurrentCartId()]);case 1:n=r.sent(),r.label=2;case 2:return[2,t.apply(this,[a.concat([n])]).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?void 0:t.code)&&window.location.reload(),e}))}))]}}))}))},t}(V),H=function(e){function t(){var t=e.call(this)||this;return t.namespace="loyalty",t.endpoints={getProgram:"loyalty",exchange:"loyalty/exchange",reset:"loyalty/exchange"},t.endpointsMethods={getProgram:"get",reset:"put"},t.after_init(),t}return g(t,e),t.prototype.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}))},t.prototype.exchange=function(e,t){return void 0===t&&(t=null),m(this,void 0,void 0,(function(){var a,n;return y(this,(function(r){switch(r.label){case 0:return(e=salla.form.getPossibleValue(e,["id","loyalty_prize_id","prize_id"]))?(a=t)?[3,2]:[4,salla.cart.getCurrentCartId()]:(n="Unable to find cart id. Please provide one.",salla.loyalty.event.exchangeFailed(n),[2,salla.api.errorPromise(n)]);case 1:a=r.sent(),r.label=2;case 2:return(t=a)?[2,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}))]:(n="Unable to find cart id. Please provide one.",salla.loyalty.event.exchangeFailed(n),[2,salla.api.errorPromise(n)])}}))}))},t.prototype.reset=function(e){return void 0===e&&(e=null),m(this,void 0,void 0,(function(){var t,a;return y(this,(function(n){switch(n.label){case 0:return(t=e)?[3,2]:[4,salla.cart.getCurrentCartId()];case 1:t=n.sent(),n.label=2;case 2:return(e=t)?[2,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}))]:(a="Unable to find cart id. Please provide one.",salla.loyalty.event.resetFailed(a),[2,salla.api.errorPromise(a)])}}))}))},t}(V),Q=function(e){function t(){var t=e.call(this)||this;return t.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.after_init(),t}return g(t,e),t.prototype.setAfterLoginEvent=function(e,t){salla.api.auth.afterLoginEvent={event:e,payload:t}},t.prototype.setCanRedirect=function(e){salla.api.auth.canRedirect_=e},t.prototype.canRedirect=function(){return salla.api.auth.canRedirect_&&!salla.api.auth.afterLoginEvent.event},t.prototype.login=function(e){(null==e?void 0:e.data)&&(e=e.data);var t=salla.form.getPossibleValue(e,["type"]);if(!["email","mobile"].includes(t)){var a="Login type should be in: [email, mobile]";return salla.auth.event.codeNotSent(a),salla.api.errorPromise(a)}return this.request(["login",t],e).then((function(e){return salla.auth.event.codeSent(e,t),e})).catch((function(e){throw salla.auth.event.codeNotSent(e,t),e}))},t.prototype.verify=function(e,t){var a;return void 0===t&&(t=!0),m(this,void 0,void 0,(function(){var n,r,i,o;return y(this,(function(l){switch(l.label){case 0:return(n=salla.form.getPossibleValue(e,["type"]))?(t=!1!==salla.form.getPossibleValue(e,["supportWebAuth"])&&t,salla.auth.event.next_event&&(e.next_event=salla.auth.event.next_event),[4,salla.auth.api.request(["verify",n],e)]):(r="Failed to know what's login type!",salla.auth.event.verificationFailed(r),[2,salla.api.errorPromise(r)]);case 1:return 200!==(null==(i=l.sent())?void 0:i.status)?(salla.auth.event.verificationFailed(i,n),[2,salla.api.errorPromise(i)]):((o="authenticated"===(null===(a=i.data)||void 0===a?void 0:a.case))&&salla.auth.event.tokenFetched(i.data.token),t?[4,salla.auth.api.request("auth/jwt")]:[3,3]);case 2:l.sent(),l.label=3;case 3:return o&&salla.auth.event.loggedIn(i).then((function(){return salla.auth.api.afterUserLogin()})),salla.auth.event.verified(i,n),[2,salla.api.successPromise(i)]}}))}))},t.prototype.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),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))},t.prototype.register=function(e){var t;return e.data&&(t=e.element,e=e.data),salla.auth.event.next_event&&(e.next_event=salla.auth.event.next_event),this.request("register",e).then((function(e){var a;return m(this,void 0,void 0,(function(){return y(this,(function(n){switch(n.label){case 0:return salla.auth.event.registered.call(t,e),"authenticated"!==(null===(a=e.data)||void 0===a?void 0:a.case)?[3,2]:(salla.auth.event.tokenFetched(e.data.token),[4,salla.auth.request("auth/jwt")]);case 1:n.sent(),salla.auth.event.loggedIn(e),salla.auth.api.afterUserLogin(),n.label=2;case 2:return[2,e]}}))}))})).catch((function(e){throw salla.auth.event.registrationFailed.call(t,e),e}))},t.prototype.logout=function(){return salla.storage.clearAll(),salla.cookie.clearAll(),salla.auth.event.loggedOut().then((function(){var e=salla.url.get("logout");console.log("Going to ".concat(e,", to do any thing before this action use: salla.auth.even.onLoggedOut(()=>{...})"));try{location.href=e}catch(e){salla.log(e)}}))},t.prototype.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}))},t.prototype.afterUserLogin=function(){this.afterLoginEvent.event&&salla.event.emit(this.afterLoginEvent.event,this.afterLoginEvent.payload)},t}(V),z=function(e){function t(){var t=e.call(this)||this;return t.namespace="order",t.endpoints={cancel:"orders/cancel/{id}",createCartFromOrder:"reorder/{id}",sendInvoice:"orders/send/{id}"},t.endpointsMethods={createCartFromOrder:"get"},t.after_init(),t}return g(t,e),t.prototype.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"])},t.prototype.cancel=function(e){return e=e||Salla.config.get("page.id"),this.request(["cancel",e],{params:{has_apple_pay:!!window.ApplePaySession}}).then((function(t){return salla.event.order.canceled(t,e),t})).catch((function(t){throw salla.event.order.notCanceled(t,e),t}))},t.prototype.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}))},t.prototype.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}))},t}(V),B=function(e){function t(){var t=e.call(this)||this;return t.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",giftDetail:"products/{product_id}/buy-as-gift",giftToCart:"products/{product_id}/buy-as-gift",giftImage:"products/buy-as-gift/image",buyNow:"products/{product_id}/buy-now",fetch:"products"},t.endpointsMethods={details:"get",giftDetail:"get",fetch:"get"},t.after_init(),t}return g(t,e),t.prototype.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}))},t.prototype.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}))},t.prototype.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}))},t.prototype.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?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){n="Query is same as previous one!";return salla.product.event.searchFailed(n),salla.api.product.previousQuery=null,salla.api.errorPromise(n)}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}))},t.prototype.offers=function(e){if(!(e=salla.form.getPossibleValue((null==e?void 0:e.data)|e,["product_id","id"]))){var t='There is no "product_id"!';return salla.product.event.fetchOffersFailed(t),salla.api.errorPromise(t)}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}))},t.prototype.getSizeGuides=function(e){return this.request("products/".concat(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}))},t.prototype.getGiftDetails=function(e){return this.request(["giftDetail",e]).then((function(t){return salla.product.event.giftFetched(t,e),t})).catch((function(t){throw salla.product.event.giftFetchFailed(t,e),t}))},t.prototype.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){a="productId is not passed.";return salla.product.event.detailFetchFailed(a),salla.api.errorPromise(a)}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}))},t.prototype.addGiftToCart=function(e,t,a){return void 0===a&&(a=!1),this.request(["giftToCart",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}))},t.prototype.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}))},t.prototype.fetch=function(e){if(!e.source){var t="Source can not be empty. Please provide one.";return salla.product.event.productListFetchFailed(t),salla.api.errorPromise(t)}if(["categories","brands","tags","selected"].includes(e.source)&&!Array.isArray(e.source_value)||"search"===e.source&&"string"!=typeof e.source_value||"related"===e.source&&isNaN(e.source_value)){t="SourceValue type error.";return salla.product.event.productListFetchFailed(t),salla.api.errorPromise(t)}return this.request(this.endpoints.fetch,{params:e},"get").then((function(e){return salla.product.event.productListFetchSucceeded(e),e})).catch((function(e){throw salla.product.event.productListFetchFailed(e),e}))},t}(V),W=function(e){function t(){var t=e.call(this)||this;return t.namespace="profile",t.endpoints={info:"auth/user",update:"profile/update",updateContacts:"profile/contacts/update",updateSettings:"profile/settings",verify:"profile/verify",delete:"profile"},t.endpointsMethods={delete:"delete"},t.after_init(),t}return g(t,e),t.prototype.info=function(){return this.request("info",null,"get").then((function(e){var t={id:e.data.id,type:"user",email:e.data.email,mobile:e.data.phone.code+e.data.phone.number,country_code:e.data.phone.country,language_code:e.data.language,currency_code:e.data.currency,notifications:e.data.notifications,pending_orders:e.data.pending_orders,avatar:e.data.avatar,first_name:e.data.first_name,last_name:e.data.last_name,fetched_at:Date.now()};return salla.config.set("user",t),salla.storage.set("user",t),salla.profile.event.infoFetched(e),e})).catch((function(e){throw salla.profile.event.infoNotFetched(e),e}))},t.prototype.update=function(e){return this.request("update",e).then((function(e){return salla.profile.event.updated(e),e})).catch((function(e){throw salla.event.profile.updateFailed(e),e}))},t.prototype.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}))},t.prototype.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}))},t.prototype.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}))},t.prototype.delete=function(){return this.request("delete").then((function(e){return salla.storage.clearAll(),salla.cookie.clearAll(),salla.event.profile.deleted(e),window.location.href=salla.url.get("logout"),e})).catch((function(e){throw salla.event.profile.notDeleted(e),e}))},t}(V),X=function(e){function t(){var t=e.call(this)||this;return t.namespace="comment",t.endpoints={comments:"{type}/{id}/comments"},t.after_init(),t}return g(t,e),t.prototype.add=function(e){if((null==e?void 0:e.data)&&(e=e.data),"string"==typeof(e=this.getCommentPayload(e)))return salla.event.comment.additionFailed(e),salla.api.errorPromise(e);if(!e.comment){var t="can't find comment content!";return salla.event.comment.additionFailed(t),salla.api.errorPromise(t)}return this.request(["comments",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}))},t.prototype.getCommentPayload=function(e){var t={};return["id","type","comment","per_page","page"].forEach((function(a){var n=salla.form.getPossibleValue(e,[a]);n&&(t[a]=n)})),t.id?t.type&&["products","pages","product","page"].includes(t.type)?(t.type+=["product","page"].includes(t.type)?"s":"",t):"Failed to get type one of:(products, product, page, pages)!":"Failed to get id!"},t.prototype.fetch=function(e){return"string"==typeof(e=this.getCommentPayload(e))?(salla.event.comment.fetchFailed(e),salla.api.errorPromise(e)):this.request(["comments",e.type,e.id],{params:e},"get").then((function(t){return salla.event.comment.fetched(t,e),t})).catch((function(t){throw salla.event.comment.fetchFailed(t,e),t}))},t.prototype.getPageComments=function(e,t,a){return void 0===t&&(t=1),void 0===a&&(a=10),this.fetch({id:e,type:"pages",page:t,per_page:a})},t.prototype.getProductComments=function(e,t,a){return void 0===t&&(t=1),void 0===a&&(a=10),this.fetch({id:e,type:"products",page:t,per_page:a})},t}(V),Z=function(e){function t(){var t=e.call(this)||this;return t.namespace="currency",t.endpoints={change:"/",list:"currencies"},t.endpointsMethods={change:"get",list:"get"},t.webEndpoints=["change"],t.after_init(),t}return g(t,e),t.prototype.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}))},t.prototype.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}(V),J=function(e){function t(){var t=e.call(this)||this;return t.namespace="document",t}return g(t,e),t}(V),K=function(e){function t(){var t=e.call(this)||this;return t.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}return g(t,e),t.prototype.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}))},t.prototype.store=function(e){if(!(e=(null==e?void 0:e.data)||e)){var t='There is no "data"!';return salla.event.rating.storeFailed(t),salla.api.errorPromise(t)}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}))},t.prototype.products=function(e){if(!(e=(null==e?void 0:e.data)||e)){var t='There is no "data"!';return salla.event.rating.productsFailed(t),salla.api.errorPromise(t)}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}))},t.prototype.shipping=function(e){if(!(e=(null==e?void 0:e.data)||e)){var t='There is no "data"!';return salla.event.rating.shippingFailed(t),salla.api.errorPromise(t)}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}(V),$=function(e){function t(){var t=e.call(this)||this;return t.namespace="wishlist",t.endpoints={add:"products/favorites/{id}",remove:"products/favorites/{id}"},t.endpointsMethods={remove:"delete"},t.after_init(),t}return g(t,e),t.prototype.toggle=function(e){return salla.storage.get("salla::wishlist",[]).includes(e)?this.remove(e):this.add(e)},t.prototype.add=function(e){var t,a=this;return salla.config.isGuest()?(salla.wishlist.event.additionFailed(t=salla.lang.get("common.messages.must_login")),salla.error(t),salla.api.errorPromise(t)):(e=salla.form.getPossibleValue((null==e?void 0:e.data)||e,["product_id","id"]))?this.request(["add",e]).then((function(t){return a.updateWishlistStorage(e),salla.wishlist.event.added(t,e),t})).catch((function(t){throw salla.wishlist.event.additionFailed(t,e),t})):(salla.wishlist.event.additionFailed(t="Failed to get product id!"),salla.api.errorPromise(t))},t.prototype.remove=function(e){var t,a=this;return salla.config.isGuest()?(salla.wishlist.event.additionFailed(t=salla.lang.get("common.messages.must_login")),salla.error(t),salla.api.errorPromise(t)):(e=salla.form.getPossibleValue((null==e?void 0:e.data)||e,["product_id","id"]))?this.request(["remove",e]).then((function(t){return a.updateWishlistStorage(e,!1),salla.wishlist.event.removed(t,e),t})).catch((function(t){throw salla.wishlist.event.removingFailed(t,e),t})):(salla.wishlist.event.removingFailed(t="Failed to get id!"),salla.api.errorPromise(t))},t.prototype.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}(V),Y=function(e){function t(){var t=e.call(this)||this;return t.namespace="scopes",t.endpoints={get:"scopes",change:"scopes",getProductAvailability:"scopes/availability?product_id={id}"},t.after_init(),t}return g(t,e),t.prototype.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}))},t.prototype.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}))},t.prototype.getProductAvailability=function(e){return void 0===e&&(e=null),this.request("scopes/availability?product_id=".concat(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}(V),ee=function(e){function t(){var t=e.call(this)||this;return t.namespace="booking",t.endpoints={add:"cart/booking/product/{id}"},t.endpointsMethods={add:"get"},t}return g(t,e),t.prototype.add=function(e,t){return void 0===t&&(t=!0),m(this,void 0,void 0,(function(){var a;return y(this,(function(n){return e?[2,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}))]:(a="Please provide product id.",salla.booking.event.additionFailed(a),[2,salla.api.errorPromise(a)])}))}))},t}(V),te=function(e){function t(){var t=e.call(this)||this;return t.namespace="landing",t.endpoints={getDetails:"landing/{landing_page_id}",createCartFromPage:"landing/{landing_page_id}"},t.endpointsMethods={getDetails:"get"},t.after_init(),t}return g(t,e),t.prototype.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}))},t.prototype.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}))},t}(V),ae=function(){function e(){var e=this;salla.event.on("twilight::before.ready",(function(t){return e.initiateRequest(t)})),salla.event.on("profile::info.fetched",(function(t){return e.setCurrencyAndLanguage(t)})),salla.event.on("auth::token.fetched",(function(t){salla.storage.set("token",t),e.setToken(t),salla.cart.api.reset()})),this.notifier_handler_disabled=!1,this.axios=l.default.create({headers:{common:{"X-Requested-With":"XMLHttpRequest","S-SOURCE":"twilight","S-APP-VERSION":"v2.0.0","S-APP-OS":"browser"}}})}return e.prototype.getHeaders=function(){return this.axios.defaults.headers.common},e.prototype.setHeaders=function(e){var t=this;return Object.entries(e).forEach((function(e){return t.setHeader(e[0],e[1])})),this},e.prototype.setHeader=function(e,t){return salla.infiniteScroll.fetchOptions.headers[e]=this.axios.defaults.headers.common[e]=t,this},e.prototype.withoutNotifier=function(e){return m(this,void 0,void 0,(function(){var t=this;return y(this,(function(a){switch(a.label){case 0:return this.notifier_handler_disabled=!0,[4,e().finally((function(){t.notifier_handler_disabled=!1}))];case 1:return[2,a.sent()]}}))}))},e.prototype.initiateRequest=function(e){var t,a;this.axios.defaults.baseURL=Salla.config.get("store.api",Salla.config.get("store.url")),this.setHeaders({"Store-Identifier":Salla.config.get("store.id"),currency:(null===(t=e.user)||void 0===t?void 0:t.currency_code)||"SAR","accept-language":salla.lang.getLocale(),"s-user-id":null===(a=e.user)||void 0===a?void 0:a.id});var n=salla.storage.get("scope");n&&this.setHeaders({"s-scope-type":n.type,"s-scope-id":n.id}),this.injectTokenToTheRequests(e),salla.storage.get("affiliate_code")&&this.setHeader("s-affiliate-code",salla.storage.get("affiliate_code"))},e.prototype.injectTokenToTheRequests=function(e){var t,a,n,r=salla.storage.get("token"),i="guest"===e.user.type,o=salla.storage.get("cart"),l=null===(t=e.user)||void 0===t?void 0:t.id,c=salla.storage.get("user.id");if(c&&c!==l&&(salla.log("Api:: case1 = >user in localStorage is not same as user in the config"),salla.storage.remove("user")),o&&(o.user_id!==l||o.store_id!==(null===(a=e.store)||void 0===a?void 0:a.id)))return salla.log("cart",{user_id:o.user_id,store_id:o.store_id}),salla.log("current",{user_id:l,store_id:null===(n=e.store)||void 0===n?void 0:n.id}),salla.log("Api:: case2 => The cart is not belong to current "+(o.user_id!==l?"user":"store")+"!"),void salla.cart.api.reset();if(!i||r){if(i&&r)return salla.log("Api:: case4 => there is a token and current user is guest"),salla.log("Auth:: Token without user!"),salla.storage.remove("token"),void salla.cart.api.reset();if(!r)return salla.log("Api:: case5 => current user is logged-in but there is no token"),salla.cart.api.reset(),void salla.auth.api.refresh();var d=s.default(r);if(Date.now()/1e3>d.exp)return salla.log("Api:: case6 => current user is logged-in and there is a token, but it's expired"),salla.storage.remove("token"),salla.cart.api.reset(),void salla.auth.api.refresh();if(d.sub!==l)return salla.log("Api:: case7 => The user id is not match the token details"),salla.storage.remove("token"),salla.cart.api.reset(),void salla.auth.api.refresh();this.setToken(r),salla.log("Api:: case8 => current user is logged-in and there is a token, and it's not expired"),salla.event.emit("api::initiated")}else salla.log("Api:: case3 => current user is a guest and there is no token")},e.prototype.setToken=function(e){return this.setHeader("Authorization","Bearer "+e),salla.event.emit("api::token.injected",e),this.token=e,this},e.prototype.setCurrencyAndLanguage=function(e){return this.setHeaders({currency:e.data.currency,"accept-language":e.data.language})},e.prototype.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,l=!1;return"SALLA-BUTTON"===(null==o?void 0:o.tagName)&&(l=!0),l&&(null==o||o.load()),this.axios[i.method](i.endPoint,i.payload,i.options).then((function(e){return l&&(null==o||o.stop()),e.data&&e.request&&(e=e.data),r.handleAfterResponseActions(e),e})).catch((function(e){throw l&&(null==o||o.stop()),salla.event.document.requestFailed(i,e),r.handleErrorResponse(e),e}))},e.prototype.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{window.dataLayer&&r&&window.dataLayer.push(r)}catch(e){salla.logger.error(e.message)}this.fireEventsForResponse(e),this.showAlert(e)}},e.prototype.fireEventsForResponse=function(e){var t,a,n=(null==e?void 0:e.events)||(null===(t=e.data)||void 0===t?void 0:t.events)||(null===(a=e.error)||void 0===a?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])}))},e.prototype.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)},e.prototype.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)||void 0===t?void 0:t.message)?salla.notify.fire(null===(a=e.data)||void 0===a?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},e.prototype.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)},e.prototype.isFastRequestsAllowed=function(){return Salla.config.get("fastRequests")},e.prototype.promise=function(e,t){return void 0===t&&(t=!0),new Promise((function(a,n){return t?a(e):n(e)}))},e.prototype.errorPromise=function(e){return this.promise(e,!1)},e.prototype.successPromise=function(e){return this.promise(e,!0)},e}(),ne=function(e){function t(){var t=e.call(this)||this;return t.auth=new Q,t.cart=new G,t.loyalty=new H,t.order=new z,t.rating=new K,t.product=new B,t.profile=new W,t.comment=new X,t.currency=new Z,t.document=new J,t.wishlist=new $,t.scope=new Y,t.booking=new ee,t.landing=new te,t}return g(t,e),t}(ae),re=function(){function e(e){var t,a;"ready"!==Salla.status?e?(Salla.config.merge(e),(null==e?void 0:e.events)&&Salla.event.dispatchEvents(null==e?void 0:e.events),e._token&&salla.api.setHeader("X-CSRF-TOKEN",e._token),this.injectMaintenanceAlert(),this.injectThemePreviewAlert(),this.injectEditAlert(),(null===(t=null==e?void 0:e.user)||void 0===t?void 0:t.language_code)&&salla.lang.setLocale(null===(a=null==e?void 0:e.user)||void 0===a?void 0:a.language_code),salla.lang.loadStoreTranslations(),this.setSallaReady(e)):this.setSallaReady(e):salla.log("Trying to re-initiate Salla, while its status === 'ready'!")}return e.prototype.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"))})))},e.prototype.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://assets.salla.sa/cp/assets/images/logo-new.png">\n <span style="margin:0 10px;">'.concat(salla.lang.get("blocks.header.preview_mode"),': <span style="background:rgba(255,255,255,0.25);border-radius:15px; padding:2px 15px 4px">').concat(salla.config.get("theme.name"),'</span></span>\n </div>\n <a href="').concat(salla.url.get("preview_theme/cancel/preview"),'" style="line-height:32px; width:32px;"><i class="sicon-cancel"></i></a>\n '),document.body.prepend(e)})))},e.prototype.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="'.concat(e,'" style="display:block; background-color:').concat(salla.config.get("theme.color.primary","#5cd5c4"),"; color:").concat(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 ').concat(salla.lang.get("pages.products.quick_edit"),"\n </a>\n "),document.body.prepend(t)})))},e.prototype.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}))},e.prototype.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)}},e.prototype.setSallaReady=function(e){Salla.event.dispatch("twilight::before.ready",e),Salla.status="ready",Salla.event.dispatch("twilight::initiated",e),window.dispatchEvent(new CustomEvent("twilight::initiated",{detail:e}))},e}();Salla.status="loading",Salla.notify=p,Salla.lang=new M,Salla.form=new U,Salla.infiniteScroll=new N(void 0,salla.event.infiniteScroll),Salla.api=new ne,["cart","auth","order","scope","rating","comment","loyalty","product","profile","currency","document","wishlist","booking","landing"].forEach((function(e){return Salla[e]=new h(Salla.api[e],Salla.event[e])})),Salla.call=function(e){for(var t=Salla,a=e.split(".");a.length&&(t=t[a.shift()]););return t},Salla.init=function(e){return new re(e)},salla.event.once("twilight::init",salla.init),salla.event.once("twilight::api",(function(e){var t=null==e?void 0:e.events;t&&salla.event.dispatchEvents(t)})),Salla.success=Salla.notify.success,Salla.error=Salla.notify.error,Salla.versions.twilight="[VI]{version}[/VI]",Salla.onInitiated=function(e){return salla.event.once("twilight::initiated",e)},Salla.onReady=Salla.onReady||function(e){"ready"!==salla.status?Salla.onInitiated(e):e(salla.config.all())},window.dispatchEvent(new CustomEvent("salla::created"));
|
|
1
|
+
"use strict";var e=require("@salla.sa/base"),t=require("infinite-scroll"),a=require("lang.js"),s=require("axios"),r=require("jwt-decode");function i(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var n=i(e),l=i(t),o=i(a),d=i(s),c=i(r);let u=function(e,t,a){return alert(e)},h=function(e,t){return u(e,p.error,t)},p={error:"error",success:"success",info:"info"};var g={fire:function(e,t,a){return u(e,t,a)},setNotifier:function(e){u=e,salla.event.emit("twilight::notifier.changed")},error:h,success:function(e,t){return u(e,p.success,t)},info:function(e,t){return u(e,p.info,t)},sallaInitiated:function(){let e=window.location.href.match(/([\?\&]danger=)[^&]+/g);e&&(window.history.replaceState(null,document.title,window.location.pathname),salla.event.once("twilight::notifier.changed",(()=>{e.forEach((e=>{h(decodeURI(e.replace("?danger=","").replace("&danger=","")))}))})))},types:p};class f{constructor(e,t){return this.api=e,this.event=t,new Proxy(this,{get:function(a,s){return"event"===s?t:"api"===s?e:e&&e[s]||a[s]}})}}Element.prototype.matches||(Element.prototype.matches=Element.prototype.msMatchesSelector),Element.prototype.closest||(Element.prototype.closest=function(e){for(var t=this;t;){if(t.matches(e))return t;t=t.parentElement}}),Element.prototype.getElementSallaData=function(e,...t){if(!this.getAttribute)return;if(this.hasAttribute("data-json"))try{return JSON.parse(this.getAttribute("data-json"))}catch(e){}let a=this.getAttribute("data-function");if(a&&window[a])return"function"==typeof window[a]?this.getFilteredData(window[a].call(this,...t)):this.getFilteredData(window[a]);let s=this.hasAttribute("data-form-selector")?document.querySelector(this.dataset.formSelector):void 0;if(s="FORM"===this.tagName?this:s||this.closest("form")||this.closest("[salla-form-data]")||this,s&&"FORM"===s.tagName)return this.getFilteredData(new FormData(s),null,s);let r=s.querySelectorAll("[name]");if(!r.length)return this.getFilteredData();let i=Object.assign({},this.dataset);return r.forEach((e=>{if(!["checkbox","radio"].includes(e.type)||e.checked)try{let t=Salla.helpers.inputData(e.name,e.value,i);i[t.name]=t.value}catch(t){Salla.log(e.name+" can't be send")}})),this.getFilteredData(i)},Element.prototype.canEventFireHook=function(e){return!!this.hasAttribute&&this.hasAttribute(Salla.api.hooksPrefix+e.type)},Element.prototype.hasAttributeStartsWith=function(e,t){e=e.toLowerCase();for(var a=0;a<this.attributes.length;a++){let s=this.attributes[a].name.toLowerCase();if(0===s.indexOf(e))return!t||s}return!1},HTMLFormElement.prototype.getAjaxFormData=function(e){var t=this.querySelectorAll('input[type="file"]');t.forEach((e=>{e.files.length||e.setAttribute("disabled","")}));var a=new FormData(this);return t.forEach((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=null,t=null,a=null){return e=e||a?.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((s=>{let r=a?.dataset[s]||this.dataset[s];if(r){var i=window[r];if("function"==typeof i){if(!i(e,a||this,t)&&e)throw`Data failed to be pass verify function window.${r}(formData, element, event)!`;return i(e,a||this,t)}Salla.log("window."+r+"() not found!")}})),e},HTMLAnchorElement.prototype.getAjaxFormData=function(e){return{formData:this.getFilteredData(null,e),url:this.getAttribute("href"),method:this.dataset.type||"get",events:{success:this.dataset.onSuccess,fail:this.dataset.onFail}}};class m{constructor(){this.events={},this.namespace="";let e=/function (.{1,})\(/.exec(this.constructor.toString());this.className=(e&&e.length>1?e[1]:"").toLowerCase()}after_init(){this.createDynamicFunctions()}createDynamicFunctions(){Object.keys(this.events).forEach((e=>{this.createDynamicEventFuns(e),this.createDynamicListenerFuns(e)}))}createDynamicEventFuns(e){if(this[e])return;let t=this;this[e]=function(...a){return t.dispatch(e,...a)}}createDynamicListenerFuns(e){let t="on"+e.charAt(0).toUpperCase()+e.slice(1);if(this[t])return;let a=this;this[t]=function(t){return a.on(e,(async(...e)=>t(...e)))}}getEventName(e){return e=this.events[e]||e,!this.namespace||e.includes("::")?e:this.namespace+Salla.event.delimiter+e}dispatch(e,...t){return Salla.event.emitAsync(this.getEventName(e),...t)}on(e,t){return Salla.event.addListener(this.getEventName(e),t)}once(e,t){return Salla.event.once(this.getEventName(e),t)}}function v(e){e&&e.sallaInitiated&&!e.initiated&&(e.sallaInitiated(),e.initiated=!0)}Salla.event.auth=new class extends m{constructor(){super(),this.namespace="auth",this.events={login:"login",logout:"logout",codeSent:"code.sent",codeNotSent:"code.not-sent",verified:"verified",verificationFailed:"verification.failed",loggedIn:"logged.in",registered:"registered",registrationFailed:"registration.failed",loggedOut:"logged.out",failedLogout:"failed.logout",refreshFailed:"refresh.failed",tokenFetched:"token.fetched"},this.after_init()}login(e){return e?(e.type&&this.setTypeActionOnVerified(e.type),this.next_event=e.next_event||null,this.dispatch("login",...arguments)):(this.next_event=null,this.dispatch("login",...arguments))}loggedIn(e){return Salla.profile.info().finally((()=>this.dispatch("loggedIn",e)))}setTypeActionOnVerified(e){this.type_action_on_verified=e}getTypeActionOnVerified(){return this.type_action_on_verified||"redirect"}},Salla.event.cart=new class extends m{constructor(){super(),this.namespace="cart",this.events={latestFetched:"latest.fetched",latestFailed:"latest.failed",updated:"updated",itemUpdated:"item.updated",itemUpdatedFailed:"item.updated.failed",itemAdded:"item.added",itemAddedFailed:"item.added.failed",itemDeleted:"item.deleted",itemDeletedFailed:"item.deleted.failed",submitted:"submitted",submitFailed:"submit.failed",imageDeleted:"image.deleted",imageNotDeleted:"image.not.deleted",detailsFetched:"details.fetched",detailsNotFetched:"details.not.fetched",successReset:"success.reset",priceQuoteSucceeded:"price-quote.succeeded",priceQuoteFailed:"price-quote.failed",couponAdded:"coupon.added",couponDeleted:"coupon.deleted",couponAdditionFailed:"coupon.addition.failed",couponDeletionFailed:"coupon.deletion.failed",quickOrderSettingFetched:"quick-order.fetched",quickOrderSettingFailed:"quick-order.failed",quickOrderSucceeded:"quick-order.succeeded",quickOrderFailed:"quick-order.failed"},this.after_init()}updated(e){return Salla.cookie.set("fresh_summary",1),e&&"object"==typeof e?(e.offer&&salla.product.event.offerExisted(e.offer),e.redirect&&(salla.log("The current cart is purchased!"),salla.cart.api.reset()),e.cart?(salla.storage.set("cart.summary",{total:e.cart.total,sub_total:e.cart.sub_total,discount:e.cart.discount,real_shipping_cost:e.cart.real_shipping_cost,count:e.cart.count,shipping_cost:e.cart.free_shipping_bar?.has_free_shipping?0:e.cart.real_shipping_cost}),this.dispatch("updated",e.cart)):void salla.log("Failed to get the cart summary!")):(Salla.logger.info("Cart summary not an object!",e),this.dispatch("updated"))}latestFetched(e){return this.updated(e.data),this.dispatch("latestFetched",e)}itemAdded(e,t){return this.updated(e.data),this.dispatch("itemAdded",e,t)}itemDeleted(e,t){return this.updated(e.data),this.dispatch("itemDeleted",e,t)}itemUpdated(e,t){return this.updated(e.data),this.dispatch("itemUpdated",e,t)}couponAdded(e,t){return this.updated(e.data),this.dispatch("couponAdded",e,t)}couponDeleted(e,t){return this.updated(e.data),this.dispatch("couponDeleted",e,t)}},Salla.event.order=new class extends m{constructor(){super(),this.namespace="order",this.events={canceled:"canceled",notCanceled:"not.canceled",orderCreated:"order.created",orderCreationFailed:"order.creation.failed",invoiceSent:"invoice.sent",invoiceNotSent:"invoice.not.sent"},this.after_init()}},Salla.event.scope=new class extends m{constructor(){super(),this.namespace="scope",this.events={fetched:"fetched",notFetched:"not.fetched",productAvailabilityFetched:"product-availability.fetched",productAvailabilityNotFetched:"product-availability.not.fetched",changeSucceeded:"changed",changeFailed:"not.changed"},this.after_init()}},Salla.event.rating=new class extends m{constructor(){super(),this.namespace="rating",this.events={orderNotFetched:"order.not.fetched",orderFetched:"order.fetched",storeRated:"store.rated",storeFailed:"store.failed",productsRated:"products.rated",productsFailed:"products.failed",shippingRated:"shipping.rated",shippingFailed:"shipping.failed"},this.after_init()}},Salla.event.booking=new class extends m{constructor(){super(),this.namespace="booking",this.events={added:"added",additionFailed:"addition.failed"},this.after_init()}},Salla.event.comment=new class extends m{constructor(){super(),this.namespace="comment",this.events={added:"added",additionFailed:"addition.failed",fetched:"fetched",fetchFailed:"fetch.failed"},this.after_init()}},Salla.event.landing=new class extends m{constructor(){super(),this.namespace="landing",this.events={detailsFetched:"order.fetched",getDetailsFailed:"get.details.failed",orderCreated:"order.created",orderCreationFailed:"order.creation.failed"},this.after_init()}},Salla.event.loyalty=new class extends m{constructor(){super(),this.namespace="loyalty",this.events={exchangeSucceeded:"exchange.succeeded",exchangeFailed:"exchange.failed",programFetched:"program.fetched",programNotFetched:"program.not.fetched",resetSucceeded:"exchange-reset.succeeded",resetFailed:"exchange-reset.failed"},this.after_init()}exchangeSucceeded(e,t){return salla.cart.event.updated(e.data),this.dispatch("exchangeSucceeded",e,t)}resetSucceeded(e){return salla.cart.event.updated(e.data),this.dispatch("resetSucceeded",e)}},Salla.event.product=new class extends m{constructor(){super(),this.namespace="product",this.events={priceUpdated:"price.updated",priceUpdateFailed:"price.updated.failed",availabilitySubscribed:"availability.subscribed",availabilitySubscribeFailed:"availability.subscribe.failed",categoriesFetched:"categories.fetched",categoriesFailed:"categories.failed",searchFailed:"search.failed",searchResults:"search.results",offerExisted:"offer.existed",fetchOffersFailed:"fetch.offers.failed",offersFetched:"offers.fetched",sizeGuideFetched:"size-guide.fetched",sizeGuideFetchFailed:"size-guide.failed",giftFetched:"gift.fetched",giftFetchFailed:"gift.failed",detailFetched:"detail.fetched",detailFetchFailed:"detail.failed",addGiftToCartSucceeded:"gift.add-to-cart.succeeded",addGiftToCartFailed:"gift.add-to-cart.failed",giftImageUploadSucceeded:"gift.image-upload.succeeded",giftImageUploadFailed:"gift.image-upload.failed",productListFetchSucceeded:"fetch.succeeded",productListFetchFailed:"fetch.failed"},this.after_init()}},Salla.event.profile=new class extends m{constructor(){super(),this.namespace="profile",this.events={updated:"updated",updateFailed:"update.failed",verificationCodeSent:"verification.code.sent",updateContactsFailed:"update.contacts.failed",verified:"verified",unverified:"unverified",infoFetched:"info.fetched",infoNotFetched:"info.not.fetched",settingsUpdated:"settings.updated",updateSettingsFailed:"update.settings.failed",deleted:"deleted",notDeleted:"not.deleted"},this.after_init()}},Salla.event.currency=new class extends m{constructor(){super(),this.namespace="currency",this.events={changed:"changed",failed:"failed",fetched:"fetched",failedToFetch:"failed.to.fetch"},this.after_init()}},Salla.event.document=new class extends m{constructor(){super(),this.namespace="document",this.events={click:"click",change:"change",submit:"submit",keyup:"keyup",leaving:"leaving",request:"request",requestFailed:"request.failed"},this.after_init()}onClick(e,t){this.fireCallableFuns("click",e,t)}onChange(e,t){this.fireCallableFuns("change",e,t)}onSubmit(e,t){this.fireCallableFuns("submit",e,t)}onKeyup(e,t){this.fireCallableFuns("keyup",e,t)}fireCallableFuns(e,t,a){this.on(e,(e=>{"function"!=typeof t?"function"==typeof a&&e.target.matches(t)&&a(e):t(e)}))}fireEvent(e,t,...a){return this.fireEventForElements(e,t,!1,...a)}fireEventForAll(e,t,...a){return this.fireEventForElements(e,t,!0,...a)}fireEventForElements(e,t,a,...s){if("string"==typeof e){if(a)return document.querySelectorAll(e).forEach((e=>this.fireEventForElements(e,t,!1,...s)));e=document.querySelector(e)}if(!e)return void salla.log("Failed To get element to fire event: "+t);const r=new CustomEvent(t,...s);return e.dispatchEvent(r)}},Salla.event.wishlist=new class extends m{constructor(){super(),this.namespace="wishlist",this.events={added:"added",removed:"removed",additionFailed:"addition.failed",removingFailed:"removing.failed"},this.after_init()}},Salla.event.infiniteScroll=new class extends m{constructor(){super(),this.namespace="infiniteScroll",this.events={scrollThreshold:"scroll.threshold",request:"request",load:"load",append:"append",error:"error",last:"last",history:"history"},this.after_init()}},Salla.event.on("twilight::initiated",(()=>{Object.keys(Salla).forEach((e=>{"object"==typeof(e=Salla[e])&&(v(e),Object.keys(e).forEach((t=>{v(e[t])})))}))})),Salla.config.default_properties={debug:"undefined"!=typeof process&&"development"===process.env.NODE_ENV,token:null,fastRequests:!0,canLeave:!0,store:{api:"https://api.salla.dev/store/v1/"},currencies:{SAR:{code:"SAR",name:"ريال سعودي",symbol:"ر.س",amount:1,country_code:"sa"}}},Salla.config.merge(Salla.config.default_properties),Salla.config.triedToGetCurrencies_=!1,Salla.config.triedToGetLanguages_=!1,Salla.config.isUser=()=>"user"===Salla.config.get("user.type"),Salla.config.isGuest=()=>!Salla.config.isUser(),Salla.config.languages=async()=>{if(Salla.config.triedToGetLanguages_)return Salla.config.get("languages");Salla.config.triedToGetLanguages_=!0;let e=!0,t=[];return(await salla.document.api.request("languages",null,"get"))?.data?.map((a=>{e&&(t=[],e=!1),a.code=a.code||a.iso_code,a.url=salla.url.get(a.code),a.is_rtl=a.is_rtl||a.rtl,t.push(a)})),Salla.config.set("languages",t),t},Salla.config.currencies=async()=>{if(Salla.config.triedToGetCurrencies_)return Salla.config.get("currencies");Salla.config.triedToGetCurrencies_=!0;let e=!0,t={};return(await salla.currency.api.list())?.data?.map((a=>{e&&(t={},e=!1),a.country_code=a.code.substr(0,2).toLowerCase(),t[a.code]=a})),Salla.config.set("currencies",t),t};class y extends o.default{constructor(e){(e=e||{}).messages=e.messages||window.translations,e.locale=e.locale||(window.locale||navigator.language||navigator.userLanguage||"ar").split("-")[0],e.fallback=e.fallback||e.locale,super(e),this.translationsLoaded=!1}onLoaded(e){if(this.translationsLoaded)return e();Salla.event.once("languages::translations.loaded",e)}loadStoreTranslations(){if(this.hash=salla.config.get("theme.translations_hash",salla.config.get("store.id","twilight")),this.message||(salla.log("try to load translations from localstorage"),this.messages=salla.storage.get(`s_translations.${this.hash}`),this.messages&&(this.translationsLoaded=!0)&&super.setMessages(this.messages)),this.messages)return salla.event.dispatch("languages::translations.loaded"),void salla.logger.info("The messages of transactions is already loaded");salla.url.get("")?this.loadScript(salla.url.get(`languages/assets/${this.hash}.js`)):this.loadScript("https://cdn.salla.network/js/translations.js",!1)}setMessages(e){super.setMessages(e),salla.event.dispatch("languages::translations.loaded"),this.translationsLoaded=!0}loadScript(e,t=!0){let a=document.createElement("script");a.src=e,a.onload=()=>{if(window.translations)return salla.storage.remove("s_translations"),salla.storage.set("s_translations",{[this.hash]:window.translations}),this.setMessages(window.translations);a.onerror()},a.onerror=()=>{if(t)return salla.logger.warn("Failed to load Translations for store, lets try load it from CDN"),this.loadScript("https://cdn.salla.network/js/translations.js",!1);salla.logger.error("Failed to load Translations, check your network logs for more details\nor: salla.lang.setMessages({....}), see https://docs.salla.dev for more information's.")},document.head.appendChild(a)}getWithDefault(e,t,a,s){let r=this.get(e,a,s);return r!==e?r:t}get(e,t,a){let s=e;(window.translations||this.translationsLoaded)&&(s="trans."+e);let r=super.get(s,t,a);return r!==s?r:super.get(s,t,"en").replace(s,e)}set(e,t){return salla.helpers.setNested(this.messages[this.getLocale()+".trans"],e,t),this}}class w{constructor(){this.endpoints={},this.webEndpoints=[],this.namespace="BaseApi",this.endpointsMethods={},this.endpointsHeaders={};let e=/function (.{1,})\(/.exec(this.constructor.toString());this.className=(e&&e.length>1?e[1]:"").toLowerCase(),this.debounce={request:void 0,time:300,enabled:!0,exclude:[]}}after_init(){}normalRequest(e,t,a=null){let s=Array.isArray(e),r=s?this.getUrl(...e):this.getUrl(e);e=s?e[0]:e,a=a||this.endpointsMethods[e]||"post";let i=this.endpointsHeaders[e];if("get"===a&&t instanceof FormData){let e={};Array.from(t.entries()).forEach((function(t){e[t[0]]=t[1]})),t={params:e}}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})}request(e,t,a=null){return!salla.api.isFastRequestsAllowed()&&this.debounce.enabled?(this.debounce.request||(this.debounce.request=salla.helpers.debounce(this.normalRequest.bind(this),this.debounce.time)),this.debounce.request(e,t,a)):this.normalRequest(e,t,a)}getUrl(e){let t=this.endpoints[e]||e;const a=/{[^{}]+}/i;for(let e=1;e<arguments.length;e++)t=t.replace(a,arguments[e]);return t}event(){return salla.event[this.className]}}class F extends w{constructor(){super(),this.namespace="cart",this.endpoints={latest:"cart/latest",details:"cart/{cart}",quickAdd:"cart/{cart}/item/{product}/quick-add",addItem:"cart/{cart}/item/{product}/add",deleteItem:"cart/{cart}/item/{item}",updateItem:"cart/{cart}/item/{item}",deleteImage:"cart/{cart}/image/{image}",uploadImage:"cart/{cart}/image",status:"cart/{cart}/status",addCoupon:"cart/{id}/coupon",deleteCoupon:"cart/{id}/coupon",getQuickOrderSettings:"checkout/quick-order",createQuickOrder:"checkout/quick-order",priceQuote:"cart/{cartId}/price-quote"},this.endpointsMethods={latest:"get",details:"get",status:"get",updateItem:"post",deleteItem:"delete",deleteImage:"delete",deleteCoupon:"put",getQuickOrderSettings:"get"},this.webEndpoints=["latest"],this.latestCart=null,this.after_init(),salla.event.on("api::initiated",(()=>this.getCurrentCartId()))}async getCurrentCartId(){if(salla.cart.api.latestCart)return salla.cart.api.latestCart.cart.id;let e=salla.storage.get("cart.id");if(e)return e;let t=await this.latest();return salla.cart.api.latestCart=t.data,salla.cart.api.latestCart.cart.id}getUploadImageEndpoint(e){return salla.url.api(this.getUrl("uploadImage",e||salla.storage.get("cart.id")))}latest(){return this.request("latest",{params:{source:""}}).then((e=>(salla.storage.set("cart",e.data.cart),salla.event.cart.latestFetched(e),e))).catch((e=>{throw salla.storage.set("cart",""),salla.event.cart.latestFailed(e),e}))}async details(e,t=[]){return e=e||await this.getCurrentCartId(),this.request(["details",e],{params:{with:t}}).then((function(e){return salla.cart.event.detailsFetched(e),e})).catch((function(e){throw salla.cart.event.detailsNotFetched(e),e}))}async quickAdd(e,t){return this.addItem({id:e,quantity:t,endpoint:"quickAdd"})}async addItem(e){let t=this.getCartPayload(e);if(!t.id){let e='There is no product "id"!';return salla.cart.event.itemAddedFailed(e),salla.api.errorPromise(e)}let a=salla.form.getPossibleValue(t.payload,["endpoint"]);a&&["addItem","quickAdd"].includes(a)||(a=salla.form.getPossibleValue(t.payload,["quantity","donating_amount"])?"addItem":"quickAdd");let s=await this.getCurrentCartId();return this.request([a,s,t.id],t.payload).then((function(e){return salla.cart.event.itemAdded(e,t.id),e})).catch((function(e){throw salla.cart.event.itemAddedFailed(e,t.id),e}))}async deleteItem(e){let t=this.getCartPayload(e);if(!t.id){let e='There is no "id"!';return salla.cart.event.itemDeletedFailed(e),salla.api.errorPromise(e)}let a=await this.getCurrentCartId();return this.request(["deleteItem",a,t.id]).then((function(e){return salla.cart.event.itemDeleted(e,t.id),e})).catch((function(e){throw salla.cart.event.itemDeletedFailed(e,t.id),e}))}async updateItem(e){let t=this.getCartPayload(e);if(!t.id){let e='There is no "id"!';return salla.cart.event.itemUpdatedFailed(e),salla.api.errorPromise(e)}let a=await this.getCurrentCartId();return"Object"===t.payload.constructor?.name?t.payload._method="PUT":t.payload.append("_method","PUT"),this.request(["updateItem",a,t.id],t.payload).then((function(e){return salla.cart.event.itemUpdated(e,t.id),e})).catch((function(e){throw salla.cart.event.itemUpdatedFailed(e,t.id),e}))}async deleteImage(e){if(!(e=salla.form.getPossibleValue(e,["id","image_id","photo_id"]))){let e='There is no "id"!';return salla.cart.event.imageNotDeleted(e),salla.api.errorPromise(e)}let t=await this.getCurrentCartId();return this.request(["deleteImage",t,e]).then((function(t){return salla.cart.event.imageDeleted(t,e),t})).catch((function(t){throw salla.cart.event.imageNotDeleted(t,e),t}))}async status(e){return this.request(["status",e||await this.getCurrentCartId()],{params:{has_apple_pay:!!window.ApplePaySession}})}async submit(){this.status(await this.getCurrentCartId()).then((e=>{let t=e.data.next_step.to;if(!["checkout","refresh","login"].includes(t)){let e="Can't find next_step );";throw salla.cart.event.submitFailed(e),e}if(salla.cart.event.submitted(e),"login"===t)return salla.auth.setCanRedirect(!1),salla.event.dispatch("login::open"),void salla.auth.event.onLoggedIn((e=>{salla.event.dispatch("login::close"),this.submit()}));"checkout"===t?window.location.href=e.data.next_step.url+(window.ApplePaySession?"?has_apple_pay=true":""):window.location.reload()})).catch((function(e){throw salla.cart.event.submitFailed(e),e}))}getCartPayload(e){let t=e?.data||("object"==typeof e?e:void 0);return e=t?salla.form.getPossibleValue(t,["prod_id","product_id","item_id","id"]):e,t="object"==typeof t?t:void 0,{id:e,payload:t}}normalRequest(e,t,a=null){return super.normalRequest(e,t,a).catch((e=>{throw 403===e?.response?.status&&(salla.cart.api.reset(),salla.error(salla.lang.get("pages.checkout.try_again"))),e}))}reset(){salla.api.cart.latestCart=null,salla.storage.remove("cart"),salla.cart.event.successReset()}async addCoupon(e){if(e=e.data||e,!(e=salla.form.getPossibleValue(e,["coupon"]))){let e=new Error('There is no "Coupon Code"!');return e.name="EmptyCoupon",salla.event.cart.couponAdditionFailed(e),salla.api.errorPromise(e)}let t=await salla.cart.api.getCurrentCartId();return this.request(["addCoupon",t],{coupon:e}).then((function(e){return salla.event.cart.couponAdded(e,t),e})).catch((function(e){throw salla.event.cart.couponAdditionFailed(e,t),e}))}async deleteCoupon(){let e=await salla.cart.api.getCurrentCartId();return this.request(["deleteCoupon",e],{}).then((function(t){return salla.event.cart.couponDeleted(t,e),t})).catch((function(t){throw salla.event.cart.couponDeletionFailed(t,e),t}))}getQuickOrderSettings(){return this.request("getQuickOrderSettings").then((e=>(salla.event.cart.quickOrderSettingFetched(e),e))).catch((e=>{throw salla.event.cart.quickOrderSettingFailed(e),e}))}createQuickOrder(e){return this.request("createQuickOrder",e).then((e=>(salla.event.cart.quickOrderSucceeded(e),e))).catch((e=>{throw salla.event.cart.quickOrderFailed(e),e}))}async priceQuote(e){return salla.config.isGuest()?(salla.auth.api.setAfterLoginEvent("cart::priceQuote",e),void salla.event.dispatch("login::open")):this.request(["priceQuote",e||await this.getCurrentCartId()]).then((e=>(salla.cart.api.reset(),salla.event.cart.priceQuoteSucceeded(e).then((()=>(setTimeout((()=>window.location.href=salla.url.get("/")),1e3),e)))))).catch((e=>salla.event.cart.priceQuoteFailed(e).then((()=>{throw 404===e.error?.code&&window.location.reload(),e}))))}}class b extends w{constructor(){super(),this.namespace="loyalty",this.endpoints={getProgram:"loyalty",exchange:"loyalty/exchange",reset:"loyalty/exchange"},this.endpointsMethods={getProgram:"get",reset:"put"},this.after_init()}getProgram(){return this.request("getProgram").then((e=>(salla.loyalty.event.programFetched(e),e))).catch((e=>{throw salla.loyalty.event.programNotFetched(e),e}))}async exchange(e,t=null){if(!(e=salla.form.getPossibleValue(e,["id","loyalty_prize_id","prize_id"]))){let e="Unable to find cart id. Please provide one.";return salla.loyalty.event.exchangeFailed(e),salla.api.errorPromise(e)}if(!(t=t||await salla.cart.getCurrentCartId())){let e="Unable to find cart id. Please provide one.";return salla.loyalty.event.exchangeFailed(e),salla.api.errorPromise(e)}return this.request("exchange",{loyalty_prize_id:e,cart_id:t}).then((function(t){return salla.loyalty.event.exchangeSucceeded(t,e),t})).catch((function(t){throw salla.loyalty.event.exchangeFailed(t,e),t}))}async reset(e=null){if(!(e=e||await salla.cart.getCurrentCartId())){let e="Unable to find cart id. Please provide one.";return salla.loyalty.event.resetFailed(e),salla.api.errorPromise(e)}return this.request("reset",{cart_id:e}).then((e=>(salla.loyalty.event.resetSucceeded(e),e))).catch((e=>{throw salla.loyalty.event.resetFailed(e),e}))}}class S extends w{constructor(){super(),this.namespace="auth",this.canRedirect_=!0,this.afterLoginEvent={event:null,payload:null},this.endpoints={login:"auth/{type}/send_verification",resend:"auth/resend_verification",verify:"auth/{type}/verify",register:"auth/register",logout:"logout",refresh:"auth/refresh"},this.webEndpoints=["logout","auth/jwt","refresh"],this.endpointsMethods={logout:"get"},this.after_init()}setAfterLoginEvent(e,t){salla.api.auth.afterLoginEvent={event:e,payload:t}}setCanRedirect(e){salla.api.auth.canRedirect_=e}canRedirect(){return salla.api.auth.canRedirect_&&!salla.api.auth.afterLoginEvent.event}login(e){e?.data&&(e=e.data);let t=salla.form.getPossibleValue(e,["type"]);if(!["email","mobile"].includes(t)){let e="Login type should be in: [email, mobile]";return salla.auth.event.codeNotSent(e),salla.api.errorPromise(e)}return this.request(["login",t],e).then((function(e){return salla.auth.event.codeSent(e,t),e})).catch((function(e){throw salla.auth.event.codeNotSent(e,t),e}))}async verify(e,t=!0){let a=salla.form.getPossibleValue(e,["type"]);if(!a){let e="Failed to know what's login type!";return salla.auth.event.verificationFailed(e),salla.api.errorPromise(e)}t=!1!==salla.form.getPossibleValue(e,["supportWebAuth"])&&t,salla.auth.event.next_event&&(e.next_event=salla.auth.event.next_event);let s=await salla.auth.api.request(["verify",a],e);if(200!==s?.status)return salla.auth.event.verificationFailed(s,a),salla.api.errorPromise(s);let r="authenticated"===s.data?.case;return r&&salla.auth.event.tokenFetched(s.data.token),t&&await salla.auth.api.request("auth/jwt"),r&&salla.auth.event.loggedIn(s).then((()=>salla.auth.api.afterUserLogin())),salla.auth.event.verified(s,a),salla.api.successPromise(s)}resend(e){let t;return(e=e.data||e).type=e.type||"mobile","mobile"!==e.type||e.phone&&e.country_code?"email"!==e.type||e.email?this.request("resend",e).then((function(t){return salla.auth.event.codeSent(t,e),t})).catch((function(t){throw salla.auth.event.codeNotSent(t,e),t})):(salla.auth.event.codeNotSent(t="There is no email!",e),salla.api.errorPromise(t)):(salla.auth.event.codeNotSent(t="There is no phone or country_code!",e),salla.api.errorPromise(t))}register(e){let t;return e.data&&(t=e.element,e=e.data),salla.auth.event.next_event&&(e.next_event=salla.auth.event.next_event),this.request("register",e).then((async function(e){return salla.auth.event.registered.call(t,e),"authenticated"===e.data?.case&&(salla.auth.event.tokenFetched(e.data.token),await salla.auth.request("auth/jwt"),salla.auth.event.loggedIn(e),salla.auth.api.afterUserLogin()),e})).catch((function(e){throw salla.auth.event.registrationFailed.call(t,e),e}))}logout(){return salla.storage.clearAll(),salla.cookie.clearAll(),salla.auth.event.loggedOut().then((()=>{let e=salla.url.get("logout");console.log(`Going to ${e}, to do any thing before this action use: salla.auth.even.onLoggedOut(()=>{...})`);try{location.href=e}catch(e){salla.log(e)}}))}refresh(){return this.request("refresh").then((function(e){return salla.auth.event.tokenFetched(e.data.token),e})).catch((function(e){throw salla.auth.event.refreshFailed(e),e}))}afterUserLogin(){this.afterLoginEvent.event&&salla.event.emit(this.afterLoginEvent.event,this.afterLoginEvent.payload)}}class _ extends w{constructor(){super(),this.namespace="order",this.endpoints={cancel:"orders/cancel/{id}",createCartFromOrder:"reorder/{id}",sendInvoice:"orders/send/{id}"},this.endpointsMethods={createCartFromOrder:"get"},this.after_init()}show(e){let t=salla.form.getPossibleValue(e?.data||e,["id","order_id"]);salla.event.dispatch("mobile::order.placed",{order_id:t}),location.href=salla.form.getPossibleValue(e?.data||e,["url"])}cancel(e){return e=e||Salla.config.get("page.id"),this.request(["cancel",e],{params:{has_apple_pay:!!window.ApplePaySession}}).then((function(t){return salla.event.order.canceled(t,e),t})).catch((function(t){throw salla.event.order.notCanceled(t,e),t}))}createCartFromOrder(e){return e=e||salla.config.get("page.id"),this.request(["createCartFromOrder",e]).then((function(t){return salla.cart.reset(),salla.event.order.orderCreated(t,e),window.location.href=t.data.url,t})).catch((function(t){throw salla.event.order.orderCreationFailed(t,e),t}))}sendInvoice(e){let t=salla.form.getPossibleValue(e,["id"])||salla.config.get("page.id");if(!t||isNaN(t)){let e="There is no id!";return salla.order.event.invoiceNotSent(e),salla.api.errorPromise(e)}return this.request(["sendInvoice",t],e).then((e=>(salla.event.order.invoiceSent(e,t),e))).catch((e=>{throw salla.event.order.invoiceNotSent(e,t),e}))}}class q extends w{constructor(){super(),this.namespace="product",this.previousQuery="",this.endpoints={getPrice:"products/{id}/price",availabilitySubscribe:"products/{id}/availability-notify",search:"products/search",details:"products/{product_id}/details",categories:"products/categories/{?id}",offers:"products/{product_id}/specialoffer",getSizeGuides:"products/{prod_id}/size-guides",giftDetail:"products/{product_id}/buy-as-gift",giftToCart:"products/{product_id}/buy-as-gift",giftImage:"products/buy-as-gift/image",buyNow:"products/{product_id}/buy-now",fetch:"products"},this.endpointsMethods={details:"get",giftDetail:"get",fetch:"get"},this.after_init()}getPrice(e){let 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}))}categories(e){return this.request(["categories",e||""],null,"get").then((function(e){return salla.product.event.categoriesFetched(e),e})).catch((function(e){throw salla.product.event.categoriesFailed(e),e}))}availabilitySubscribe(e){let t=e.data||e;return e=salla.form.getPossibleValue(t,["id","prod_id"]),this.request(["availabilitySubscribe",e],"object"==typeof t?t:void 0).then((function(t){return salla.product.event.availabilitySubscribed(t,e),t})).catch((function(t){throw salla.product.event.availabilitySubscribeFailed(t,e),t}))}search(e){let t=e.data;if(t||(t={params:"string"==typeof e?{query:e}:e}),!(e=t instanceof FormData?t.get("query"):t.query||t.params?.query)){let e='There is no "query"!';return salla.product.event.searchFailed(e),salla.api.errorPromise(e)}if(e===salla.api.product.previousQuery){let e="Query is same as previous one!";return salla.product.event.searchFailed(e),salla.api.product.previousQuery=null,salla.api.errorPromise(e)}return salla.api.product.previousQuery=e,this.request("search",t,"get").then((function(t){return salla.product.event.searchResults(t,e),t})).catch((function(t){throw salla.product.event.searchFailed(t,e),t}))}offers(e){if(!(e=salla.form.getPossibleValue(e?.data|e,["product_id","id"]))){let e='There is no "product_id"!';return salla.product.event.fetchOffersFailed(e),salla.api.errorPromise(e)}return this.request(["offers",e]).then((function(t){return salla.product.event.offersFetched(t,e),t})).catch((function(t){throw salla.product.event.fetchOffersFailed(t,e),t}))}getSizeGuides(e){return this.request(`products/${e}/size-guides`,null,"get").then((t=>(salla.product.event.sizeGuideFetched(t,e),t))).catch((t=>{throw salla.product.event.sizeGuideFetchFailed(t,e),t}))}getGiftDetails(e){return this.request(["giftDetail",e]).then((t=>(salla.product.event.giftFetched(t,e),t))).catch((t=>{throw salla.product.event.giftFetchFailed(t,e),t}))}getDetails(e,t=[]){if(!Array.isArray(t)){let e="withItems should be array.";return salla.product.event.detailFetchFailed(e),salla.api.errorPromise(e)}if(!e){let e="productId is not passed.";return salla.product.event.detailFetchFailed(e),salla.api.errorPromise(e)}return this.request(["details",e],{params:{with:t}}).then((function(t){return salla.product.event.detailFetched(t,e),t})).catch((function(t){throw salla.product.event.availabilitySubscribeFailed(t,e),t}))}addGiftToCart(e,t,a=!1){return this.request(["giftToCart",e],t).then((t=>(salla.product.event.addGiftToCartSucceeded(t,e),a&&(window.location.href=t.redirect),t))).catch((t=>{throw salla.product.event.addGiftToCartFailed(t,e),t}))}uploadGiftImage(e){return this.request("giftImage",e).then((e=>(salla.product.event.giftImageUploadSucceeded(e),e))).catch((e=>{throw salla.product.event.giftImageUploadFailed(e),e}))}fetch(e){if(!e.source){let e="Source can not be empty. Please provide one.";return salla.product.event.productListFetchFailed(e),salla.api.errorPromise(e)}if(["categories","brands","tags","selected"].includes(e.source)&&!Array.isArray(e.source_value)||"search"===e.source&&"string"!=typeof e.source_value||"related"===e.source&&isNaN(e.source_value)){let e="SourceValue type error.";return salla.product.event.productListFetchFailed(e),salla.api.errorPromise(e)}return this.request(this.endpoints.fetch,{params:e},"get").then((e=>(salla.product.event.productListFetchSucceeded(e),e))).catch((e=>{throw salla.product.event.productListFetchFailed(e),e}))}}class C extends w{constructor(){super(),this.namespace="profile",this.endpoints={info:"auth/user",update:"profile/update",updateContacts:"profile/contacts/update",updateSettings:"profile/settings",verify:"profile/verify",delete:"profile"},this.endpointsMethods={delete:"delete"},this.after_init()}info(){return this.request("info",null,"get").then((e=>{let t={id:e.data.id,type:"user",email:e.data.email,mobile:e.data.phone.code+e.data.phone.number,country_code:e.data.phone.country,language_code:e.data.language,currency_code:e.data.currency,notifications:e.data.notifications,pending_orders:e.data.pending_orders,avatar:e.data.avatar,first_name:e.data.first_name,last_name:e.data.last_name,fetched_at:Date.now()};return salla.config.set("user",t),salla.storage.set("user",t),salla.profile.event.infoFetched(e),e})).catch((e=>{throw salla.profile.event.infoNotFetched(e),e}))}update(e){return this.request("update",e).then((e=>(salla.profile.event.updated(e),e))).catch((e=>{throw salla.event.profile.updateFailed(e),e}))}updateContacts(e){return this.request("updateContacts",e).then((e=>(salla.profile.event.verificationCodeSent(e),e))).catch((e=>{throw salla.event.profile.updateContactsFailed(e),e}))}verify(e){return this.request("verify",e).then((e=>(salla.profile.event.verified(e),e))).catch((e=>{throw salla.event.profile.unverified(e),e}))}updateSettings(e){return this.request("updateSettings",e).then((e=>(salla.event.profile.settingsUpdated(e),e))).catch((e=>{throw salla.event.profile.updateSettingsFailed(e),e}))}delete(){return this.request("delete").then((e=>(salla.storage.clearAll(),salla.cookie.clearAll(),salla.event.profile.deleted(e),window.location.href=salla.url.get("logout"),e))).catch((e=>{throw salla.event.profile.notDeleted(e),e}))}}class A extends w{constructor(){super(),this.namespace="comment",this.endpoints={comments:"{type}/{id}/comments"},this.after_init()}add(e){if(e?.data&&(e=e.data),"string"==typeof(e=this.getCommentPayload(e,!0)))return salla.event.comment.additionFailed(e),salla.api.errorPromise(e);if(!e.comment){let e="can't find comment content!";return salla.event.comment.additionFailed(e),salla.api.errorPromise(e)}return this.request(["comments",e.type,e.id],{comment:e.comment}).then((function(t){return salla.event.comment.added(t,e.id),t})).catch((function(t){throw salla.event.comment.additionFailed(t,e.id),t}))}getCommentPayload(e){let t={};return["id","type","comment","per_page","page"].forEach((a=>{let s=salla.form.getPossibleValue(e,[a]);s&&(t[a]=s)})),t.id?t.type&&["products","pages","product","page"].includes(t.type)?(t.type+=["product","page"].includes(t.type)?"s":"",t):"Failed to get type one of:(products, product, page, pages)!":"Failed to get id!"}fetch(e){return"string"==typeof(e=this.getCommentPayload(e))?(salla.event.comment.fetchFailed(e),salla.api.errorPromise(e)):this.request(["comments",e.type,e.id],{params:e},"get").then((function(t){return salla.event.comment.fetched(t,e),t})).catch((function(t){throw salla.event.comment.fetchFailed(t,e),t}))}getPageComments(e,t=1,a=10){return this.fetch({id:e,type:"pages",page:t,per_page:a})}getProductComments(e,t=1,a=10){return this.fetch({id:e,type:"products",page:t,per_page:a})}}class x extends w{constructor(){super(),this.namespace="currency",this.endpoints={change:"/",list:"currencies"},this.endpointsMethods={change:"get",list:"get"},this.webEndpoints=["change"],this.after_init()}change(e){if(!(e=salla.form.getPossibleValue(e.data||e,["currency","code"]))){let e="Can't find currency code!";return salla.currency.event.failed(e),salla.api.errorPromise(e)}return this.request("change",{params:{change_currency:"",currency:e}}).then((function(t){return salla.cookie.set("fresh_summary",1),salla.storage.set("cart",""),salla.currency.event.changed(t,e),t})).catch((function(t){throw salla.currency.event.failed(t,e),t}))}list(){return this.request("list").then((function(e){return salla.currency.event.fetched(e),e})).catch((function(e){throw salla.currency.event.failedToFetch(e),e}))}}class k extends w{constructor(){super(),this.namespace="document"}}class P extends w{constructor(){super(),this.namespace="rating",this.endpoints={store:"rating/store",products:"rating/products",shipping:"rating/shipping",order:"rating/{order_id}"},this.endpointsMethods={order:"get"},this.after_init()}order(e){let t="object"==typeof e?e:{},a=salla.form.getPossibleValue(e?.data||e,["order_id","id"]);if(!a){let e='There is no "order_id"!';return salla.event.rating.orderNotFetched(e),salla.api.errorPromise(e)}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}))}store(e){if(!(e=e?.data||e)){let e='There is no "data"!';return salla.event.rating.storeFailed(e),salla.api.errorPromise(e)}return this.request("store",e).then((function(t){return salla.event.rating.storeRated(t,e),t})).catch((function(t){throw salla.event.rating.storeFailed(t,e),t}))}products(e){if(!(e=e?.data||e)){let e='There is no "data"!';return salla.event.rating.productsFailed(e),salla.api.errorPromise(e)}return this.request("products",e).then((function(t){return salla.event.rating.productsRated(t,e),t})).catch((function(t){throw salla.event.rating.productsFailed(t,e),t}))}shipping(e){if(!(e=e?.data||e)){let e='There is no "data"!';return salla.event.rating.shippingFailed(e),salla.api.errorPromise(e)}return this.request("shipping",e).then((function(t){return salla.event.rating.shippingRated(t,e),t})).catch((function(t){throw salla.event.rating.shippingFailed(t,e),t}))}}class E extends w{constructor(){super(),this.namespace="wishlist",this.endpoints={add:"products/favorites/{id}",remove:"products/favorites/{id}"},this.endpointsMethods={remove:"delete"},this.after_init()}toggle(e){return salla.storage.get("salla::wishlist",[]).includes(e)?this.remove(e):this.add(e)}add(e){let t;return salla.config.isGuest()?(salla.wishlist.event.additionFailed(t=salla.lang.get("common.messages.must_login")),salla.error(t),salla.api.errorPromise(t)):(e=salla.form.getPossibleValue(e?.data||e,["product_id","id"]))?this.request(["add",e]).then((t=>(this.updateWishlistStorage(e),salla.wishlist.event.added(t,e),t))).catch((function(t){throw salla.wishlist.event.additionFailed(t,e),t})):(salla.wishlist.event.additionFailed(t="Failed to get product id!"),salla.api.errorPromise(t))}remove(e){let t;return salla.config.isGuest()?(salla.wishlist.event.additionFailed(t=salla.lang.get("common.messages.must_login")),salla.error(t),salla.api.errorPromise(t)):(e=salla.form.getPossibleValue(e?.data||e,["product_id","id"]))?this.request(["remove",e]).then((t=>(this.updateWishlistStorage(e,!1),salla.wishlist.event.removed(t,e),t))).catch((function(t){throw salla.wishlist.event.removingFailed(t,e),t})):(salla.wishlist.event.removingFailed(t="Failed to get id!"),salla.api.errorPromise(t))}updateWishlistStorage(e,t=!0){let a=salla.storage.get("salla::wishlist",[]);t?a.push(e):a.splice(a.indexOf(e),1),salla.storage.set("salla::wishlist",a)}}class T extends w{constructor(){super(),this.namespace="scopes",this.endpoints={get:"scopes",change:"scopes",getProductAvailability:"scopes/availability?product_id={id}"},this.after_init()}get(){return this.request("scopes",null,"get").then((e=>(salla.scope.event.fetched(e),e))).catch((e=>{throw salla.scope.event.notFetched(e),e}))}change(e){return this.request("scopes",e).then((e=>(salla.scope.event.changeSucceeded(e),e))).catch((e=>{throw salla.scope.event.changeFailed(e),e}))}getProductAvailability(e=null){return this.request(`scopes/availability?product_id=${e}`,null,"get").then((t=>(salla.scope.event.productAvailabilityFetched(t,e),t))).catch((e=>{throw salla.scope.event.productAvailabilityNotFetched(e),e}))}}class D extends w{constructor(){super(),this.namespace="booking",this.endpoints={add:"cart/booking/product/{id}"},this.endpointsMethods={add:"get"}}async add(e,t=!0){if(!e){let e="Please provide product id.";return salla.booking.event.additionFailed(e),salla.api.errorPromise(e)}return this.request(["add",e]).then((function(e){return salla.booking.event.added(e),t&&"booking"===e.data.redirect.to&&(window.location.href=e.data.redirect.url),e})).catch((function(e){throw salla.booking.event.additionFailed(e),e}))}}class I extends w{constructor(){super(),this.namespace="landing",this.endpoints={getDetails:"landing/{landing_page_id}",createCartFromPage:"landing/{landing_page_id}"},this.endpointsMethods={getDetails:"get"},this.after_init()}getDetails(e){if(!e){let e="page landing id not passed";return salla.event.landing.getDetailsFailed(e),salla.api.errorPromise(e)}return this.request(["getDetails",e]).then((function(t){return salla.event.landing.detailsFetched(t,e),t})).catch((function(t){throw salla.event.landing.getDetailsFailed(t,e),t}))}createCartFromPage(e){if(!e){let e="page landing id not passed";return salla.event.landing.orderCreationFailed(e),salla.api.errorPromise(e)}return salla.config.isGuest()?(salla.auth.api.setAfterLoginEvent("landing::createCartFromPage",e),salla.event.dispatch("login::open"),salla.api.successPromise("")):this.request(["createCartFromPage",e]).then((function(t){return salla.event.landing.orderCreated(t,e).then((()=>location.href=t.data.url)),t})).catch((function(t){throw salla.event.landing.orderCreationFailed(t,e),t}))}}class L{constructor(){salla.event.on("twilight::before.ready",(e=>this.initiateRequest(e))),salla.event.on("profile::info.fetched",(e=>this.setCurrencyAndLanguage(e))),salla.event.on("auth::token.fetched",(e=>{salla.storage.set("token",e),this.setToken(e),salla.cart.api.reset()})),this.notifier_handler_disabled=!1,this.axios=d.default.create({headers:{common:{"X-Requested-With":"XMLHttpRequest","S-SOURCE":"twilight","S-APP-VERSION":"v2.0.0","S-APP-OS":"browser"}}})}getHeaders(){return this.axios.defaults.headers.common}setHeaders(e){return Object.entries(e).forEach((e=>this.setHeader(e[0],e[1]))),this}setHeader(e,t){return salla.infiniteScroll.fetchOptions.headers[e]=this.axios.defaults.headers.common[e]=t,this}async withoutNotifier(e){return this.notifier_handler_disabled=!0,await e().finally((()=>{this.notifier_handler_disabled=!1}))}initiateRequest(e){this.axios.defaults.baseURL=Salla.config.get("store.api",Salla.config.get("store.url")),this.setHeaders({"Store-Identifier":Salla.config.get("store.id"),currency:e.user?.currency_code||"SAR","accept-language":salla.lang.getLocale(),"s-user-id":e.user?.id});let t=salla.storage.get("scope");t&&this.setHeaders({"s-scope-type":t.type,"s-scope-id":t.id}),this.injectTokenToTheRequests(e),salla.storage.get("affiliate_code")&&this.setHeader("s-affiliate-code",salla.storage.get("affiliate_code"))}injectTokenToTheRequests(e){let t=salla.storage.get("token"),a="guest"===e.user.type,s=salla.storage.get("cart"),r=e.user?.id,i=salla.storage.get("user.id");if(i&&i!==r&&(salla.log("Api:: case1 = >user in localStorage is not same as user in the config"),salla.storage.remove("user")),s&&(s.user_id!==r||s.store_id!==e.store?.id))return salla.log("cart",{user_id:s.user_id,store_id:s.store_id}),salla.log("current",{user_id:r,store_id:e.store?.id}),salla.log("Api:: case2 => The cart is not belong to current "+(s.user_id!==r?"user":"store")+"!"),void salla.cart.api.reset();if(a&&!t)return void salla.log("Api:: case3 => current user is a guest and there is no token");if(a&&t)return salla.log("Api:: case4 => there is a token and current user is guest"),salla.log("Auth:: Token without user!"),salla.storage.remove("token"),void salla.cart.api.reset();if(!t)return salla.log("Api:: case5 => current user is logged-in but there is no token"),salla.cart.api.reset(),void salla.auth.api.refresh();let n=c.default(t);return Date.now()/1e3>n.exp?(salla.log("Api:: case6 => current user is logged-in and there is a token, but it's expired"),salla.storage.remove("token"),salla.cart.api.reset(),void salla.auth.api.refresh()):n.sub!==r?(salla.log("Api:: case7 => The user id is not match the token details"),salla.storage.remove("token"),salla.cart.api.reset(),void salla.auth.api.refresh()):(this.setToken(t),salla.log("Api:: case8 => current user is logged-in and there is a token, and it's not expired"),void salla.event.emit("api::initiated"))}setToken(e){return this.setHeader("Authorization","Bearer "+e),salla.event.emit("api::token.injected",e),this.token=e,this}setCurrencyAndLanguage(e){return this.setHeaders({currency:e.data.currency,"accept-language":e.data.language})}request(e,t,a="get",s={}){let r={endPoint:e,payload:t,method:a,options:s},i="undefined"!=typeof event?event.currentTarget:null,n=!1;return"SALLA-BUTTON"===i?.tagName&&(n=!0),n&&i?.load(),this.axios[r.method](r.endPoint,r.payload,r.options).then((e=>(n&&i?.stop(),e.data&&e.request&&(e=e.data),this.handleAfterResponseActions(e),e))).catch((e=>{throw n&&i?.stop(),salla.event.document.requestFailed(r,e),this.handleErrorResponse(e),e}))}handleAfterResponseActions(e){if(!e)return;let{data:t,googleTags:a=null}=e,s=t&&t.googleTags?t.googleTags:a;try{dataLayer&&s&&dataLayer.push(s)}catch(e){salla.logger.error(e.message)}this.fireEventsForResponse(e),this.showAlert(e)}fireEventsForResponse(e){let t=e?.events||e.data?.events||e.error?.events;"string"==typeof t&&(t=JSON.parse(t)),t&&Object.keys(t).forEach((e=>salla.event.dispatch(e,t[e])))}handleErrorResponse(e){if(e.response&&e.response.data)return e.response.data.error&&e.response.data.error.fields&&!this.notifier_handler_disabled?this.handleInvalidFields(e):this.handleAfterResponseActions(e.response.data)}showAlert(e){if(e&&!this.notifier_handler_disabled)return e.case&&e.msg?salla.notify.fire(e.msg,e.case,e):e.hasOwnProperty("success")&&e.data?.message?salla.notify.fire(e.data?.message,e.success?salla.notify.types.success:salla.notify.types.error,e):e.error&&e.error.message&&"FORBIDDEN"!==e.error.message?salla.error(e.error.message,e):void 0}handleInvalidFields(e){let t=e.response.data.error.fields,a=[];Object.keys(t).forEach((e=>{let s=t[e];Array.isArray(s)?s.forEach((e=>a.push(e))):a.push(s)}));let s=(a.length>1?"* ":"")+a.join("\n* ");salla.error(s,e)}isFastRequestsAllowed(){return Salla.config.get("fastRequests")}promise(e,t=!0){return new Promise(((a,s)=>t?a(e):s(e)))}errorPromise(e){return this.promise(e,!1)}successPromise(e){return this.promise(e,!0)}}class O{constructor(e){"ready"!==n.default.status?e?(n.default.config.merge(e),e?.events&&n.default.event.dispatchEvents(e?.events),e._token&&salla.api.setHeader("X-CSRF-TOKEN",e._token),this.injectMaintenanceAlert(),this.injectThemePreviewAlert(),this.injectEditAlert(),e?.user?.language_code&&salla.lang.setLocale(e?.user?.language_code),salla.lang.loadStoreTranslations(),this.setSallaReady(e)):this.setSallaReady(e):salla.log("Trying to re-initiate Salla, while its status === 'ready'!")}injectMaintenanceAlert(){salla.config.get("maintenance")&&(document.body.classList.add("has-maintenance-bar"),document.querySelector("salla-maintenance-alert")?salla.logger.warn("salla-maintenance-alert element Existed before!"):salla.lang.onLoaded((()=>document.body.prepend(document.createElement("salla-maintenance-alert")))))}injectThemePreviewAlert(){"preview"===salla.config.get("theme.mode")&&(document.body.classList.add("has-preview-bar"),document.querySelector("#s-theme_preview_bar")?salla.logger.warn("#s-theme_preview_bar element Existed before!"):salla.lang.onLoaded((()=>{let e=document.createElement("div");e.id="s-theme_preview_bar",e.setAttribute("style","display: flex; justify-content: space-between; text-align: center; background-color: #232323; color: #fff; padding: 10px; font-size: 0.875rem; line-height: 1.25rem; position: relative;"),e.innerHTML=`\n <div style="display:flex; align-items:center;">\n <img width="32" src="https://assets.salla.sa/cp/assets/images/logo-new.png">\n <span style="margin:0 10px;">${salla.lang.get("blocks.header.preview_mode")}: <span style="background:rgba(255,255,255,0.25);border-radius:15px; padding:2px 15px 4px">${salla.config.get("theme.name")}</span></span>\n </div>\n <a href="${salla.url.get("preview_theme/cancel/preview")}" style="line-height:32px; width:32px;"><i class="sicon-cancel"></i></a>\n `,document.body.prepend(e)})))}injectEditAlert(){let e=salla.config.get("edit");e&&(document.querySelector("#s-edit-alert")?salla.logger.warn("#s-edit-alert element Existed before!"):salla.lang.onLoaded((()=>{let t=document.createElement("div");t.id="s-edit-alert",t.innerHTML=`\n <a href="${e}" style="display:block; background-color:${salla.config.get("theme.color.primary","#5cd5c4")}; color:${salla.config.get("theme.color.reverse","#fff")}; padding: 10px; text-align:center; font-size: 0.875rem; line-height: 1.25rem;">\n <i class="sicon-edit"></i> \n ${salla.lang.get("pages.products.quick_edit")}\n </a>\n `,document.body.prepend(t)})))}handleElementAjaxRequest(e,t){if(!(t instanceof HTMLFormElement||t instanceof HTMLAnchorElement))return salla.logger.warn("trying to call ajax from non Element!!"),!1;e.preventDefault();let a=t.getAjaxFormData(e),s=a.method?a.method.toLowerCase():void 0;salla.api.request(a.url,a.formData,s).then((e=>(e.data&&e.request&&(e=e.data),salla.api.handleAfterResponseActions(e),this.callAjaxEvent(a.events.success,e,a.formData),e))).catch((e=>{throw salla.api.handleErrorResponse(e),this.callAjaxEvent(a.events.fail,e,a.formData),e}))}callAjaxEvent(e,t,a){if(e){if(a instanceof FormData){const e={};Array.from(a.entries()).forEach((function(t){e[t[0]]=t[1]})),a=e}window[e]?window[e](t,a):salla.event.dispatch(e,t,a)}}setSallaReady(e){n.default.event.dispatch("twilight::before.ready",e),n.default.status="ready",n.default.event.dispatch("twilight::initiated",e),window.dispatchEvent(new CustomEvent("twilight::initiated",{detail:e}))}}n.default.status="loading",n.default.notify=g,n.default.lang=new y,n.default.form=new class{async submit(e,t=null){let a=t;if("SubmitEvent"===t?.constructor?.name||"submit"===t?.type){if(t.preventDefault(),"FORM"!==t.target?.tagName)return Salla.logger.warn("Failed find the target element for submit action. make sure you submit a form element"),new Promise((()=>{throw"Failed find the target element for submit action. make sure you submit a form element"}));"SALLA-BUTTON"===t?.submitter?.parentElement?.tagName&&t.submitter.parentElement.load(),a=t.target.getElementSallaData(),salla.log("Data from element",a)}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,a,"post").finally((()=>{loaderSupported&&t?.submitter?.parentElement.stop()}));let s=e.split("."),r=s.splice(-1);return await salla.call(s.join("."))[r](a).finally((()=>t?.submitter?.parentElement?.stop())).catch((e=>{throw salla.logger.warn(e),e}))}onSubmit(e,t){return salla.form.submit(e,t),!1}onChange(e,t){return t?.currentTarget?"FORM"!==t?.currentTarget?.tagName||t.currentTarget.checkValidity()?(salla.form.submit(e,t.currentTarget.getElementSallaData()),!0):(salla.logger.warn(`Trying to trigger '${e}' without filling required fields!`),!1):(salla.logger.warn(`Trying to trigger '${e}' without event!`),!1)}getPossibleValue(e,t,a=!1){if(!e)return;if("object"!=typeof e)return e;let s;for(let a=0;a<t.length&&!(s=e[t[a]])&&!("undefined"!=typeof FormData&&e instanceof FormData&&(s=e.get(t[a])));a++);return s=s||e,"object"!=typeof s||a?s:void 0}},n.default.infiniteScroll=new class extends f{constructor(e,t){super(e,t),this.options={path:".infinite-scroll-btn",history:"push",status:".infinite-scroll-status",append:".list-block"},this.fetchOptions={headers:{"S-INFINITE-SCROLL":!0}},this.instances=[]}initiate(e,t,a,s=!1){s?((a=a||{}).fetchOptions={...this.fetchOptions,...a.fetchOptions||{}},a.responseBody="json"):a=this.getCustomOptions(t,a);let r="string"!=typeof e?e:document.querySelector(e),i=a.path;if(!r||!i||"string"==typeof i&&!document.querySelector(i))return void Salla.logger.warn(r?"Path Option (a link that has next page link) Not Existed!":"Container For InfiniteScroll not Existed!");let n=new l.default(r,a);return n.on("scrollThreshold",Salla.infiniteScroll.event.scrollThreshold),n.on("request",Salla.infiniteScroll.event.request),n.on("load",Salla.infiniteScroll.event.load),n.on("append",Salla.infiniteScroll.event.append),n.on("error",Salla.infiniteScroll.event.error),n.on("last",Salla.infiniteScroll.event.last),n.on("history",Salla.infiniteScroll.event.history),this.instances.push(n),n}getCustomOptions(e,t){return(t="object"==typeof e&&e||t||this.options).fetchOptions=this.fetchOptions,t.path=t.path||this.options.path,t.button=t.button||t.path,t.status=t.status||this.options.status,t.hasOwnProperty("history")||(t.history=this.options.history),t.nextPage=t.nextPage||t.next_page,t.append="string"==typeof e&&e||t.append||this.options.append,t}loadNextPage(e){("string"!=typeof e?e:document.querySelector(e)).loadNextPage()}destroy(e){("string"!=typeof e?e:document.querySelector(e)).destroy()}}(void 0,salla.event.infiniteScroll),n.default.api=new class extends L{constructor(){super(),this.auth=new S,this.cart=new F,this.loyalty=new b,this.order=new _,this.rating=new P,this.product=new q,this.profile=new C,this.comment=new A,this.currency=new x,this.document=new k,this.wishlist=new E,this.scope=new T,this.booking=new D,this.landing=new I}},["cart","auth","order","scope","rating","comment","loyalty","product","profile","currency","document","wishlist","booking","landing"].forEach((e=>n.default[e]=new f(n.default.api[e],n.default.event[e]))),n.default.call=e=>{let t=n.default,a=e.split(".");for(;a.length&&(t=t[a.shift()]););return t},n.default.init=e=>new O(e),salla.event.once("twilight::init",salla.init),salla.event.once("twilight::api",(e=>{let t=e?.events;t&&salla.event.dispatchEvents(t)})),n.default.success=n.default.notify.success,n.default.error=n.default.notify.error,n.default.versions.twilight="[VI]{version}[/VI]",n.default.onInitiated=e=>salla.event.once("twilight::initiated",e),n.default.onReady=n.default.onReady||function(e){"ready"!==salla.status?n.default.onInitiated(e):e(salla.config.all())},window.dispatchEvent(new CustomEvent("salla::created")),module.exports=n.default;
|
|
2
2
|
//# sourceMappingURL=index.js.map
|