@salla.sa/twilight 2.6.18 → 2.6.20

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
@@ -6,7 +6,7 @@
6
6
  * Copyright (c) 2013 hij1nx
7
7
  * Licensed under the MIT license.
8
8
  */
9
- module=eventemitter2$1,function(e){var t=Object.hasOwnProperty,r=Array.isArray?Array.isArray:function(e){return"[object Array]"===Object.prototype.toString.call(e)},i="object"==typeof process&&"function"==typeof process.nextTick,n="function"==typeof Symbol,a="object"==typeof Reflect,s="function"==typeof setImmediate?setImmediate:setTimeout,o=n?a&&"function"==typeof Reflect.ownKeys?Reflect.ownKeys:function(e){var t=Object.getOwnPropertyNames(e);return t.push.apply(t,Object.getOwnPropertySymbols(e)),t}:Object.keys;function l(){this._events={},this._conf&&c.call(this,this._conf)}function c(t){t&&(this._conf=t,t.delimiter&&(this.delimiter=t.delimiter),t.maxListeners!==e&&(this._maxListeners=t.maxListeners),t.wildcard&&(this.wildcard=t.wildcard),t.newListener&&(this._newListener=t.newListener),t.removeListener&&(this._removeListener=t.removeListener),t.verboseMemoryLeak&&(this.verboseMemoryLeak=t.verboseMemoryLeak),t.ignoreErrors&&(this.ignoreErrors=t.ignoreErrors),this.wildcard&&(this.listenerTree={}))}function u(e,t){var r="(node) warning: possible EventEmitter memory leak detected. "+e+" listeners added. Use emitter.setMaxListeners() to increase limit.";if(this.verboseMemoryLeak&&(r+=" Event name: "+t+"."),"undefined"!=typeof process&&process.emitWarning){var i=new Error(r);i.name="MaxListenersExceededWarning",i.emitter=this,i.count=e,process.emitWarning(i)}else console.error(r),console.trace&&console.trace()}var h=function(e,t,r){var i=arguments.length;switch(i){case 0:return[];case 1:return[e];case 2:return[e,t];case 3:return[e,t,r];default:for(var n=new Array(i);i--;)n[i]=arguments[i];return n}};function d(t,r){for(var i={},n=t.length,a=r?r.length:0,s=0;s<n;s++)i[t[s]]=s<a?r[s]:e;return i}function p(e,t,r){var i,n;if(this._emitter=e,this._target=t,this._listeners={},this._listenersCount=0,(r.on||r.off)&&(i=r.on,n=r.off),t.addEventListener?(i=t.addEventListener,n=t.removeEventListener):t.addListener?(i=t.addListener,n=t.removeListener):t.on&&(i=t.on,n=t.off),!i&&!n)throw Error("target does not implement any known event API");if("function"!=typeof i)throw TypeError("on method must be a function");if("function"!=typeof n)throw TypeError("off method must be a function");this._on=i,this._off=n;var a=e._observers;a?a.push(this):e._observers=[this]}function f(r,i,n,a){var s=Object.assign({},i);if(!r)return s;if("object"!=typeof r)throw TypeError("options must be an object");var o,l,c,u=Object.keys(r),h=u.length;function d(e){throw Error('Invalid "'+o+'" option value'+(e?". Reason: "+e:""))}for(var p=0;p<h;p++){if(o=u[p],!a&&!t.call(i,o))throw Error('Unknown "'+o+'" option');(l=r[o])!==e&&(c=n[o],s[o]=c?c(l,d):l)}return s}function g(e,t){return"function"==typeof e&&e.hasOwnProperty("prototype")||t("value must be a constructor"),e}function m(e){var t="value must be type of "+e.join("|"),r=e.length,i=e[0],n=e[1];return 1===r?function(e,r){if(typeof e===i)return e;r(t)}:2===r?function(e,r){var a=typeof e;if(a===i||a===n)return e;r(t)}:function(i,n){for(var a=typeof i,s=r;s-- >0;)if(a===e[s])return i;n(t)}}Object.assign(p.prototype,{subscribe:function(e,t,r){var i=this,n=this._target,a=this._emitter,s=this._listeners,o=function(){var i=h.apply(null,arguments),s={data:i,name:t,original:e};if(r){var o=r.call(n,s);!1!==o&&a.emit.apply(a,[s.name].concat(i))}else a.emit.apply(a,[t].concat(i))};if(s[e])throw Error("Event '"+e+"' is already listening");this._listenersCount++,a._newListener&&a._removeListener&&!i._onNewListener?(this._onNewListener=function(r){r===t&&null===s[e]&&(s[e]=o,i._on.call(n,e,o))},a.on("newListener",this._onNewListener),this._onRemoveListener=function(r){r===t&&!a.hasListeners(r)&&s[e]&&(s[e]=null,i._off.call(n,e,o))},s[e]=null,a.on("removeListener",this._onRemoveListener)):(s[e]=o,i._on.call(n,e,o))},unsubscribe:function(e){var t,r,i,n=this,a=this._listeners,s=this._emitter,l=this._off,c=this._target;if(e&&"string"!=typeof e)throw TypeError("event must be a string");function u(){n._onNewListener&&(s.off("newListener",n._onNewListener),s.off("removeListener",n._onRemoveListener),n._onNewListener=null,n._onRemoveListener=null);var e=_.call(s,n);s._observers.splice(e,1)}if(e){if(!(t=a[e]))return;l.call(c,e,t),delete a[e],--this._listenersCount||u()}else{for(i=(r=o(a)).length;i-- >0;)e=r[i],l.call(c,e,a[e]);this._listeners={},this._listenersCount=0,u()}}});var v=m(["function"]),y=m(["object","function"]);function b(e,t,r){var i,n,a,s=0,o=new e((function(l,c,u){function h(){n&&(n=null),s&&(clearTimeout(s),s=0)}r=f(r,{timeout:0,overload:!1},{timeout:function(e,t){return("number"!=typeof(e*=1)||e<0||!Number.isFinite(e))&&t("timeout must be a positive number"),e}}),i=!r.overload&&"function"==typeof e.prototype.cancel&&"function"==typeof u;var d=function(e){h(),l(e)},p=function(e){h(),c(e)};i?t(d,p,u):(n=[function(e){p(e||Error("canceled"))}],t(d,p,(function(e){if(a)throw Error("Unable to subscribe on cancel event asynchronously");if("function"!=typeof e)throw TypeError("onCancel callback must be a function");n.push(e)})),a=!0),r.timeout>0&&(s=setTimeout((function(){var e=Error("timeout");e.code="ETIMEDOUT",s=0,o.cancel(e),c(e)}),r.timeout))}));return i||(o.cancel=function(e){if(n){for(var t=n.length,r=1;r<t;r++)n[r](e);n[0](e),n=null}}),o}function _(e){var t=this._observers;if(!t)return-1;for(var r=t.length,i=0;i<r;i++)if(t[i]._target===e)return i;return-1}function w(e,t,r,i,n){if(!r)return null;if(0===i){var a=typeof t;if("string"===a){var s,l,c=0,u=0,h=this.delimiter,d=h.length;if(-1!==(l=t.indexOf(h))){s=new Array(5);do{s[c++]=t.slice(u,l),u=l+d}while(-1!==(l=t.indexOf(h,u)));s[c++]=t.slice(u),t=s,n=c}else t=[t],n=1}else"object"===a?n=t.length:(t=[t],n=1)}var p,f,g,m,v,y,b,_=null,S=t[i],$=t[i+1];if(i===n)r._listeners&&("function"==typeof r._listeners?(e&&e.push(r._listeners),_=[r]):(e&&e.push.apply(e,r._listeners),_=[r]));else{if("*"===S){for(l=(y=o(r)).length;l-- >0;)"_listeners"!==(p=y[l])&&(b=w(e,t,r[p],i+1,n))&&(_?_.push.apply(_,b):_=b);return _}if("**"===S){for((v=i+1===n||i+2===n&&"*"===$)&&r._listeners&&(_=w(e,t,r,n,n)),l=(y=o(r)).length;l-- >0;)"_listeners"!==(p=y[l])&&("*"===p||"**"===p?(r[p]._listeners&&!v&&(b=w(e,t,r[p],n,n))&&(_?_.push.apply(_,b):_=b),b=w(e,t,r[p],i,n)):b=w(e,t,r[p],p===$?i+2:i,n),b&&(_?_.push.apply(_,b):_=b));return _}r[S]&&(_=w(e,t,r[S],i+1,n))}if((f=r["*"])&&w(e,t,f,i+1,n),g=r["**"])if(i<n)for(g._listeners&&w(e,t,g,n,n),l=(y=o(g)).length;l-- >0;)"_listeners"!==(p=y[l])&&(p===$?w(e,t,g[p],i+2,n):p===S?w(e,t,g[p],i+1,n):((m={})[p]=g[p],w(e,t,{"**":m},i+1,n)));else g._listeners?w(e,t,g,n,n):g["*"]&&g["*"]._listeners&&w(e,t,g["*"],n,n);return _}function S(e,t,r){var i,n,a=0,s=0,o=this.delimiter,l=o.length;if("string"==typeof e)if(-1!==(i=e.indexOf(o))){n=new Array(5);do{n[a++]=e.slice(s,i),s=i+l}while(-1!==(i=e.indexOf(o,s)));n[a++]=e.slice(s)}else n=[e],a=1;else n=e,a=e.length;if(a>1)for(i=0;i+1<a;i++)if("**"===n[i]&&"**"===n[i+1])return;var c,h=this.listenerTree;for(i=0;i<a;i++)if(h=h[c=n[i]]||(h[c]={}),i===a-1)return h._listeners?("function"==typeof h._listeners&&(h._listeners=[h._listeners]),r?h._listeners.unshift(t):h._listeners.push(t),!h._listeners.warned&&this._maxListeners>0&&h._listeners.length>this._maxListeners&&(h._listeners.warned=!0,u.call(this,h._listeners.length,c))):h._listeners=t,!0;return!0}function $(e,t,r,i){for(var n,a,s,l,c=o(e),u=c.length,h=e._listeners;u-- >0;)n=e[a=c[u]],s="_listeners"===a?r:r?r.concat(a):[a],l=i||"symbol"==typeof a,h&&t.push(l?s:s.join(this.delimiter)),"object"==typeof n&&$.call(this,n,t,s,l);return t}function E(e){for(var t,r,i,n=o(e),a=n.length;a-- >0;)(t=e[r=n[a]])&&(i=!0,"_listeners"===r||E(t)||delete e[r]);return i}function A(e,t,r){this.emitter=e,this.event=t,this.listener=r}function C(t,r,n){if(!0===n)o=!0;else if(!1===n)a=!0;else{if(!n||"object"!=typeof n)throw TypeError("options should be an object or true");var a=n.async,o=n.promisify,l=n.nextTick,c=n.objectify}if(a||l||o){var u=r,h=r._origin||r;if(l&&!i)throw Error("process.nextTick is not supported");o===e&&(o="AsyncFunction"===r.constructor.name),r=function(){var e=arguments,t=this,r=this.event;return o?l?Promise.resolve():new Promise((function(e){s(e)})).then((function(){return t.event=r,u.apply(t,e)})):(l?process.nextTick:s)((function(){t.event=r,u.apply(t,e)}))},r._async=!0,r._origin=h}return[r,c?new A(this,t,r):this]}function x(e){this._events={},this._newListener=!1,this._removeListener=!1,this.verboseMemoryLeak=!1,c.call(this,e)}A.prototype.off=function(){return this.emitter.off(this.event,this.listener),this},x.EventEmitter2=x,x.prototype.listenTo=function(t,i,n){if("object"!=typeof t)throw TypeError("target musts be an object");var a=this;function s(e){if("object"!=typeof e)throw TypeError("events must be an object");var r,i=n.reducers,s=_.call(a,t);r=-1===s?new p(a,t,n):a._observers[s];for(var l,c=o(e),u=c.length,h="function"==typeof i,d=0;d<u;d++)l=c[d],r.subscribe(l,e[l]||l,h?i:i&&i[l])}return n=f(n,{on:e,off:e,reducers:e},{on:v,off:v,reducers:y}),r(i)?s(d(i)):s("string"==typeof i?d(i.split(/\s+/)):i),this},x.prototype.stopListeningTo=function(e,t){var r=this._observers;if(!r)return!1;var i,n=r.length,a=!1;if(e&&"object"!=typeof e)throw TypeError("target should be an object");for(;n-- >0;)i=r[n],e&&i._target!==e||(i.unsubscribe(t),a=!0);return a},x.prototype.delimiter=".",x.prototype.setMaxListeners=function(t){t!==e&&(this._maxListeners=t,this._conf||(this._conf={}),this._conf.maxListeners=t)},x.prototype.getMaxListeners=function(){return this._maxListeners},x.prototype.event="",x.prototype.once=function(e,t,r){return this._once(e,t,!1,r)},x.prototype.prependOnceListener=function(e,t,r){return this._once(e,t,!0,r)},x.prototype._once=function(e,t,r,i){return this._many(e,1,t,r,i)},x.prototype.many=function(e,t,r,i){return this._many(e,t,r,!1,i)},x.prototype.prependMany=function(e,t,r,i){return this._many(e,t,r,!0,i)},x.prototype._many=function(e,t,r,i,n){var a=this;if("function"!=typeof r)throw new Error("many only accepts instances of Function");function s(){return 0==--t&&a.off(e,s),r.apply(this,arguments)}return s._origin=r,this._on(e,s,i,n)},x.prototype.emit=function(){if(!this._events&&!this._all)return!1;this._events||l.call(this);var e,t,r,i,a,s,o=arguments[0],c=this.wildcard;if("newListener"===o&&!this._newListener&&!this._events.newListener)return!1;if(c&&(e=o,"newListener"!==o&&"removeListener"!==o&&"object"==typeof o)){if(r=o.length,n)for(i=0;i<r;i++)if("symbol"==typeof o[i]){s=!0;break}s||(o=o.join(this.delimiter))}var u,h=arguments.length;if(this._all&&this._all.length)for(i=0,r=(u=this._all.slice()).length;i<r;i++)switch(this.event=o,h){case 1:u[i].call(this,o);break;case 2:u[i].call(this,o,arguments[1]);break;case 3:u[i].call(this,o,arguments[1],arguments[2]);break;default:u[i].apply(this,arguments)}if(c)u=[],w.call(this,u,e,this.listenerTree,0,r);else{if("function"==typeof(u=this._events[o])){switch(this.event=o,h){case 1:u.call(this);break;case 2:u.call(this,arguments[1]);break;case 3:u.call(this,arguments[1],arguments[2]);break;default:for(t=new Array(h-1),a=1;a<h;a++)t[a-1]=arguments[a];u.apply(this,t)}return!0}u&&(u=u.slice())}if(u&&u.length){if(h>3)for(t=new Array(h-1),a=1;a<h;a++)t[a-1]=arguments[a];for(i=0,r=u.length;i<r;i++)switch(this.event=o,h){case 1:u[i].call(this);break;case 2:u[i].call(this,arguments[1]);break;case 3:u[i].call(this,arguments[1],arguments[2]);break;default:u[i].apply(this,t)}return!0}if(!this.ignoreErrors&&!this._all&&"error"===o)throw arguments[1]instanceof Error?arguments[1]:new Error("Uncaught, unspecified 'error' event.");return!!this._all},x.prototype.emitAsync=function(){if(!this._events&&!this._all)return!1;this._events||l.call(this);var e,t,r,i,a,s,o=arguments[0],c=this.wildcard;if("newListener"===o&&!this._newListener&&!this._events.newListener)return Promise.resolve([!1]);if(c&&(e=o,"newListener"!==o&&"removeListener"!==o&&"object"==typeof o)){if(i=o.length,n)for(a=0;a<i;a++)if("symbol"==typeof o[a]){t=!0;break}t||(o=o.join(this.delimiter))}var u,h=[],d=arguments.length;if(this._all)for(a=0,i=this._all.length;a<i;a++)switch(this.event=o,d){case 1:h.push(this._all[a].call(this,o));break;case 2:h.push(this._all[a].call(this,o,arguments[1]));break;case 3:h.push(this._all[a].call(this,o,arguments[1],arguments[2]));break;default:h.push(this._all[a].apply(this,arguments))}if(c?(u=[],w.call(this,u,e,this.listenerTree,0)):u=this._events[o],"function"==typeof u)switch(this.event=o,d){case 1:h.push(u.call(this));break;case 2:h.push(u.call(this,arguments[1]));break;case 3:h.push(u.call(this,arguments[1],arguments[2]));break;default:for(r=new Array(d-1),s=1;s<d;s++)r[s-1]=arguments[s];h.push(u.apply(this,r))}else if(u&&u.length){if(u=u.slice(),d>3)for(r=new Array(d-1),s=1;s<d;s++)r[s-1]=arguments[s];for(a=0,i=u.length;a<i;a++)switch(this.event=o,d){case 1:h.push(u[a].call(this));break;case 2:h.push(u[a].call(this,arguments[1]));break;case 3:h.push(u[a].call(this,arguments[1],arguments[2]));break;default:h.push(u[a].apply(this,r))}}else if(!this.ignoreErrors&&!this._all&&"error"===o)return arguments[1]instanceof Error?Promise.reject(arguments[1]):Promise.reject("Uncaught, unspecified 'error' event.");return Promise.all(h)},x.prototype.on=function(e,t,r){return this._on(e,t,!1,r)},x.prototype.prependListener=function(e,t,r){return this._on(e,t,!0,r)},x.prototype.onAny=function(e){return this._onAny(e,!1)},x.prototype.prependAny=function(e){return this._onAny(e,!0)},x.prototype.addListener=x.prototype.on,x.prototype._onAny=function(e,t){if("function"!=typeof e)throw new Error("onAny only accepts instances of Function");return this._all||(this._all=[]),t?this._all.unshift(e):this._all.push(e),this},x.prototype._on=function(t,r,i,n){if("function"==typeof t)return this._onAny(t,r),this;if("function"!=typeof r)throw new Error("on only accepts instances of Function");this._events||l.call(this);var a,s=this;return n!==e&&(r=(a=C.call(this,t,r,n))[0],s=a[1]),this._newListener&&this.emit("newListener",t,r),this.wildcard?(S.call(this,t,r,i),s):(this._events[t]?("function"==typeof this._events[t]&&(this._events[t]=[this._events[t]]),i?this._events[t].unshift(r):this._events[t].push(r),!this._events[t].warned&&this._maxListeners>0&&this._events[t].length>this._maxListeners&&(this._events[t].warned=!0,u.call(this,this._events[t].length,t))):this._events[t]=r,s)},x.prototype.off=function(e,t){if("function"!=typeof t)throw new Error("removeListener only takes instances of Function");var i,n=[];if(this.wildcard){var a="string"==typeof e?e.split(this.delimiter):e.slice();if(!(n=w.call(this,null,a,this.listenerTree,0)))return this}else{if(!this._events[e])return this;i=this._events[e],n.push({_listeners:i})}for(var s=0;s<n.length;s++){var o=n[s];if(i=o._listeners,r(i)){for(var l=-1,c=0,u=i.length;c<u;c++)if(i[c]===t||i[c].listener&&i[c].listener===t||i[c]._origin&&i[c]._origin===t){l=c;break}if(l<0)continue;return this.wildcard?o._listeners.splice(l,1):this._events[e].splice(l,1),0===i.length&&(this.wildcard?delete o._listeners:delete this._events[e]),this._removeListener&&this.emit("removeListener",e,t),this}(i===t||i.listener&&i.listener===t||i._origin&&i._origin===t)&&(this.wildcard?delete o._listeners:delete this._events[e],this._removeListener&&this.emit("removeListener",e,t))}return this.listenerTree&&E(this.listenerTree),this},x.prototype.offAny=function(e){var t,r=0,i=0;if(e&&this._all&&this._all.length>0){for(r=0,i=(t=this._all).length;r<i;r++)if(e===t[r])return t.splice(r,1),this._removeListener&&this.emit("removeListenerAny",e),this}else{if(t=this._all,this._removeListener)for(r=0,i=t.length;r<i;r++)this.emit("removeListenerAny",t[r]);this._all=[]}return this},x.prototype.removeListener=x.prototype.off,x.prototype.removeAllListeners=function(t){if(t===e)return!this._events||l.call(this),this;if(this.wildcard){var r,i=w.call(this,null,t,this.listenerTree,0);if(!i)return this;for(r=0;r<i.length;r++)i[r]._listeners=null;this.listenerTree&&E(this.listenerTree)}else this._events&&(this._events[t]=null);return this},x.prototype.listeners=function(t){var r,i,n,a,s,l=this._events;if(t===e){if(this.wildcard)throw Error("event name required for wildcard emitter");if(!l)return[];for(a=(r=o(l)).length,n=[];a-- >0;)"function"==typeof(i=l[r[a]])?n.push(i):n.push.apply(n,i);return n}if(this.wildcard){if(!(s=this.listenerTree))return[];var c=[],u="string"==typeof t?t.split(this.delimiter):t.slice();return w.call(this,c,u,s,0),c}return l&&(i=l[t])?"function"==typeof i?[i]:i:[]},x.prototype.eventNames=function(e){var t=this._events;return this.wildcard?$.call(this,this.listenerTree,[],null,e):t?o(t):[]},x.prototype.listenerCount=function(e){return this.listeners(e).length},x.prototype.hasListeners=function(t){if(this.wildcard){var r=[],i="string"==typeof t?t.split(this.delimiter):t.slice();return w.call(this,r,i,this.listenerTree,0),r.length>0}var n=this._events,a=this._all;return!!(a&&a.length||n&&(t===e?o(n).length:n[t]))},x.prototype.listenersAny=function(){return this._all?this._all:[]},x.prototype.waitFor=function(t,r){var i=this,n=typeof r;return"number"===n?r={timeout:r}:"function"===n&&(r={filter:r}),b((r=f(r,{timeout:0,filter:e,handleError:!1,Promise:Promise,overload:!1},{filter:v,Promise:g})).Promise,(function(e,n,a){function s(){var a=r.filter;if(!a||a.apply(i,arguments))if(i.off(t,s),r.handleError){var o=arguments[0];o?n(o):e(h.apply(null,arguments).slice(1))}else e(h.apply(null,arguments))}a((function(){i.off(t,s)})),i._on(t,s,!1)}),{timeout:r.timeout,overload:r.overload})};var P=x.prototype;Object.defineProperties(x,{defaultMaxListeners:{get:function(){return P._maxListeners},set:function(e){if("number"!=typeof e||e<0||Number.isNaN(e))throw TypeError("n must be a non-negative number");P._maxListeners=e},enumerable:!0},once:{value:function(e,t,r){return b((r=f(r,{Promise:Promise,timeout:0,overload:!1},{Promise:g})).Promise,(function(r,i,n){var a;if("function"==typeof e.addEventListener)return a=function(){r(h.apply(null,arguments))},n((function(){e.removeEventListener(t,a)})),void e.addEventListener(t,a,{once:!0});var s,o=function(){s&&e.removeListener("error",s),r(h.apply(null,arguments))};"error"!==t&&(s=function(r){e.removeListener(t,o),i(r)},e.once("error",s)),n((function(){s&&e.removeListener("error",s),e.removeListener(t,o)})),e.once(t,o)}),{timeout:r.timeout,overload:r.overload})},writable:!0,configurable:!0}}),Object.defineProperties(P,{_maxListeners:{value:10,writable:!0,configurable:!0},_observers:{value:null,writable:!0,configurable:!0}}),module.exports=x}();var eventemitter2=eventemitter2$1.exports;class InfiniteScrollEvents extends BaseEvent{constructor(e){super(e),this.namespace="infiniteScroll",this.events={scrollThreshold:"scroll.threshold",request:"request",load:"load",append:"append",error:"error",last:"last",history:"history"},this.after_init()}}class sallaEmitter extends eventemitter2{constructor(){super({wildcard:!0,delimiter:"::",newListener:!1,removeListener:!1,maxListeners:10,verboseMemoryLeak:!1,ignoreErrors:!1}),this.globalListners={},this.delimiter="::",this.auth=new AuthEvents(this),this.cart=new CartEvents(this),this.order=new OrderEvents(this),this.scope=new ScopeEvents(this),this.rating=new RatingEvents(this),this.comment=new CommentEvents(this),this.loyalty=new LoyaltyEvents(this),this.product=new ProductEvents(this),this.profile=new ProfileEvents(this),this.currency=new CurrencyEvents(this),this.document=new DocumentEvents(this),this.twilight=new TwilightEvents(this),this.wishlist=new WishlistEvents(this),this.infiniteScroll=new InfiniteScrollEvents(this),this.body=document.querySelector("body"),this.logableEvents=["cart::item.added.failed","cart::item.deleted.failed"],this.ingoreLogEvents=["document::click","document::keyup","document::change"],this.noneFireableActions=["document.request"],this.on("twilight::initiated",this.initiateSallaInAllClasses)}initiateSallaInAllClasses(){let e=this;Object.keys(salla).forEach((t=>{"object"==typeof(t=salla[t])&&(e.callSallaInitiate(t),Object.keys(t).forEach((r=>{e.callSallaInitiate(t[r])})))}))}callSallaInitiate(e){e&&e.sallaInitiated&&!e.initiated&&(e.sallaInitiated(),e.initiated=!0)}createAndDispatch(e,...t){this.dispatch(e,...t)}dispatch(e,...t){let r=e.replace("::",".");if(!this.noneFireableActions.includes(r)&&"function"==typeof salla.call(r))return salla.log(`'salla.${r}(...)' triggered using event '${e}'`),r=r.split("."),void salla[r[0]][r[1]](...t);this.emit(e,...t),window.dataLayer=window.dataLayer||[],window.dataLayer.push(Object.assign({event:e},...t.values())),this.ingoreLogEvents.includes(e)||!salla.config.get("debug")&&!this.logableEvents.includes(e)||salla.logger.event(e,...t);let i=this;Object.keys(this.globalListners).forEach((function(r){i.globalListners[r](e,...t)})),this.dispatchMobileEvent(e,{...t.values()})}dispatchEvents(e){if(e&&"object"==typeof e)for(const[t,r]of Object.entries(e))this.dispatch(t,r);else salla.log("No Events To Dispatch!",e)}addListener(e,t){this.on(e,t)}addEventListener(e,t){this.addListener(e,t)}listen(e,t){this.addListener(e,t)}registerGlobalListener(e,t){this.globalListners[e]=t}dispatchMobileEvent(e,t={}){if(!(window.dataLayer&&dataLayer[0]&&dataLayer[0].page&&dataLayer[0].page.mobileApp))return"";if(window.webkit)try{window.webkit.messageHandlers.callbackHandler.postMessage(JSON.stringify({event:e,details:t}))}catch(e){console.log(e,"The native context does not exist yet")}else if(Android)try{Android.customEventWithData(e,JSON.stringify({details:t}))}catch(e){console.log(e,"The native context does not exist yet")}}}class BaseApi{constructor(e){this.parent=e,this.endpoints={},this.webEndpoints=[],this.namespace="BaseApi",this.endpointsMethods={},this.endpointsHeaders={};var t=/function (.{1,})\(/.exec(this.constructor.toString());this.className=(t&&t.length>1?t[1]:"").toLowerCase(),this.debounce={request:void 0,time:300,enabled:!0,exclude:[]}}after_init(){}normalRequest(e,t,r=null){let i=this,n=Array.isArray(e),a=n?this.getUrl(...e):this.getUrl(e);e=n?e[0]:e,r=r||this.endpointsMethods[e]||"post";let s=this.endpointsHeaders[e];if("get"===r&&t instanceof FormData){var o={};Array.from(t.entries()).forEach((function(e){o[e[0]]=e[1]})),t={params:o}}s&&"get"===r&&(t=t?Object.assign(t,s):s);let l={namespace:this.namespace,action:e,url:a,payload:t,method:r,headers:s};try{salla.event.document.request(l)}catch(e){return salla.event.document.requestFailed(l),new Promise((()=>{throw e}))}this.webEndpoints.includes(e)?a=salla.url.get(a):"http"!==a.substring(0,4)&&(a=salla.url.api(a));let c="undefined"!=typeof event?event.currentTarget:null,u=!1;return"SALLA-BUTTON"===c?.tagName&&(u=!0),u&&c?.load(),this.parent[r](a,t,{headers:s}).then((e=>(u&&c?.stop(),e.data&&e.request&&(e=e.data),i.handleAfterResponseActions(e),e))).catch((e=>{throw u&&c?.stop(),salla.event.document.requestFailed(l,e),i.handleErrorResponse(e),e}))}request(e,t,r=null){return!this.isFastRequestsAllowed()&&this.debounce.enabled?(this.debounce.request||(this.debounce.request=salla.helpers.debounce(this.normalRequest.bind(this),this.debounce.time)),this.debounce.request(e,t,r)):this.normalRequest(e,t,r)}getUrl(e){let t=this.endpoints[e]||e;const r=/{[^{}]+}/i;for(let e=1;e<arguments.length;e++)t=t.replace(r,arguments[e]);return t}handleAfterResponseActions(e){if(!e)return;let{data:t,googleTags:r=null}=e,i=t&&t.googleTags?t.googleTags:r;dataLayer&&i&&dataLayer.push(i),this.fireEventsForResponse(e),this.renderSections(e),this.showAlert(e),e.data?.token&&salla.event.auth.tokenFetched(e.data.token)}fireEventsForResponse(e){let t=e.events||e.data?.events||e.error?.events;"string"==typeof t&&(t=JSON.parse(t)),t&&Object.keys(t).forEach((e=>salla.event.dispatch(e,t[e])))}renderSections(e){e.sections&&Object.keys(e.sections).forEach((t=>{document.querySelectorAll(t.toSelector()).forEach((function(r){r.innerHTML=e.sections[t]}))}))}handleErrorResponse(e){if(e.response&&e.response.data)return e.response.data.error&&e.response.data.error.fields?this.handleInvalidFields(e):this.handleAfterResponseActions(e.response.data)}showAlert(e){if(e)return e.case&&e.msg?salla.notify.fire(e.msg,e.case,e):e.hasOwnProperty("success")&&e.data?.message?salla.notify.fire(e.data?.message,e.success?salla.notify.types.success:salla.notify.types.error,e):e.error&&e.error.message&&"FORBIDDEN"!==e.error.message?salla.error(e.error.message,e):void 0}handleInvalidFields(e){let t=e.response.data.error.fields,r=[];Object.keys(t).forEach((e=>{let i=t[e];Array.isArray(i)?i.forEach((e=>r.push(e))):r.push(i)}));let i=(r.length>1?"* ":"")+r.join("\n* ");salla.error(i,e)}event(){return salla.event[this.className]}getPossibleValue(e,t,r=!1){if(!e)return;if("object"!=typeof e)return e;let i;for(let r=0;r<t.length&&!(i=e[t[r]])&&!("undefined"!=typeof FormData&&e instanceof FormData&&(i=e.get(t[r])));r++);return i=i||e,"object"!=typeof i||r?i:void 0}isFastRequestsAllowed(){return salla.config.get("fastRequests")}promise(e,t=!0){return new Promise(((r,i)=>t?r(e):i(e)))}errorPromise(e){return this.promise(e,!1)}successPromise(e){return this.promise(e,!0)}}class CartApi extends BaseApi{constructor(e){super(e),this.namespace="cart",this.endpoints={latest:"cart/latest",details:"cart/{cart}",quickAdd:"cart/{cart}/item/{product}/quick-add",addItem:"cart/{cart}/item/{product}/add",deleteItem:"cart/{cart}/item/{item}",updateItem:"cart/{cart}/item/{item}",deleteImage:"cart/{cart}/image/{image}",uploadImage:"cart/{cart}/image",status:"cart/{cart}/status",addCoupon:"cart/{id}/coupon",deleteCoupon:"cart/{id}/coupon"},this.endpointsMethods={latest:"get",details:"get",status:"get",updateItem:"post",deleteItem:"delete",deleteImage:"delete",deleteCoupon:"put"},this.webEndpoints=["latest"],this.after_init()}async getCurrentCartId(){return salla.storage.get("cart.id")||(await this.latest()).data.cart.id}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(){let e=await this.getCurrentCartId();return this.request(["details",e]).then((function(e){return salla.cart.event.detailsFetched(e),e})).catch((function(e){throw salla.cart.event.detailsNotFetched(e),e}))}async quickAdd(e){return this.addItem(e)}async addItem(e){let t=this.getCartPayload(e);if(!t.id){let e='There is no product "id"!';return salla.cart.event.itemAddedFailed(e),this.errorPromise(e)}let r=this.getPossibleValue(t.payload,["quantity","donating_amount"])?"addItem":"quickAdd",i=await this.getCurrentCartId();return this.request([r,i,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),this.errorPromise(e)}let r=await this.getCurrentCartId();return this.request(["deleteItem",r,t.id]).then((function(e){return salla.cart.event.itemDeleted(e,t.id),e})).catch((function(e){throw salla.cart.event.itemDeletedFailed(e,t.id),e}))}async updateItem(e){let t=this.getCartPayload(e);if(!t.id){let e='There is no "id"!';return salla.cart.event.itemUpdatedFailed(e),this.errorPromise(e)}let r=await this.getCurrentCartId();return"Object"===t.payload.constructor?.name?t.payload._method="PUT":t.payload.append("_method","PUT"),this.request(["updateItem",r,t.id],t.payload).then((function(e){return salla.cart.event.itemUpdated(e,t.id),e})).catch((function(e){throw salla.cart.event.itemUpdatedFailed(e,t.id),e}))}async deleteImage(e){if(!(e=this.getPossibleValue(e,["id","image_id","photo_id"]))){let e='There is no "id"!';return salla.cart.event.imageNotDeleted(e),this.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()])}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?this.getPossibleValue(t,["prod_id","product_id","item_id","id"]):e,t="object"==typeof t?t:void 0,{id:e,payload:t}}handleAfterResponseActions(e){if(403===e.status){salla.storage.remove("cart");let e=salla.lang.get("pages.checkout.try_again");throw salla.error(e),e}super.handleAfterResponseActions(e)}reset(){salla.storage.remove("cart"),salla.cart.event.successReset()}async addCoupon(e){if(e=e.data||e,!(e=this.getPossibleValue(e,["coupon"]))){let e=new Error('There is no "Coupon Code"!');return e.name="EmptyCoupon",salla.event.cart.couponAdditionFailed(e),this.errorPromise(e)}let t=await salla.cart.api.getCurrentCartId();return this.request(["addCoupon",t],{coupon:e}).then((function(e){return salla.event.cart.couponAdded(e,t),e})).catch((function(e){throw salla.event.cart.couponAdditionFailed(e,t),e}))}async deleteCoupon(){let 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}))}}class LoyaltyApi extends BaseApi{constructor(e){super(e),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=this.getPossibleValue(e,["id","loyalty_prize_id","prize_id"]))){let e="Unable to find cart id. Please provide one.";return salla.loyalty.event.exchangeFailed(e),this.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),this.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),this.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 AuthApi extends BaseApi{constructor(e){super(e),this.namespace="auth",this.canRedirect_=!0,this.endpoints={login:"auth/{type}/send_verification",resend:"auth/resend_verification",verify:"auth/{type}/verify",register:"auth/register",logout:"logout",refresh:"auth/refresh"},this.webEndpoints=["logout","auth/jwt","refresh"],this.endpointsMethods={logout:"get"},this.after_init()}setCanRedirect(e){salla.api.auth.canRedirect_=e}canRedirect(){return salla.api.auth.canRedirect_}login(e){e.data&&(e=e.data);let t=this.getPossibleValue(e,["type"]);if(!["email","mobile"].includes(t)){let e="Login type should be in: [email, mobile]";return salla.auth.event.codeNotSent(e),this.errorPromise(e)}return this.request(["login",t],e).then((function(e){return salla.auth.event.codeSent(e,t),e})).catch((function(e){throw salla.auth.event.codeNotSent(e,t),e}))}async verify(e,t=!0){let r=this.getPossibleValue(e,["type"]);if(!r){let e="Failed to know what's login type!";return salla.auth.event.verificationFailed(e),this.errorPromise(e)}t=!1!==this.getPossibleValue(e,["supportWebAuth"])&&t,salla.auth.event.next_event&&(e.next_event=salla.auth.event.next_event);let i=await this.request(["verify",r],e);return 200!==i?.status?(salla.auth.event.verificationFailed(i,r),this.errorPromise(i)):(t&&await this.request("auth/jwt"),"authenticated"===i.data?.case&&salla.auth.event.loggedIn(i),salla.auth.event.verified(i,r),this.successPromise(i))}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),this.errorPromise(t)):(salla.auth.event.codeNotSent(t="There is no phone or country_code!",e),this.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((function(e){return salla.auth.event.registered.call(t,e),"authenticated"===e.data?.case&&salla.auth.event.loggedIn(e),e})).catch((function(e){throw salla.auth.event.registrationFailed.call(t,e),e}))}logout(){return this.request("logout").then((function(e){return salla.auth.event.loggedOut(e),salla.log("Reloading after 0.1 sec..."),setTimeout((()=>location.reload()),100),e})).catch((function(e){throw salla.auth.event.failedLogout(e),e}))}refresh(){return this.request("refresh").catch((function(e){throw salla.auth.event.refreshFailed(e),e}))}}class OrderApi extends BaseApi{constructor(e){super(e),this.namespace="order",this.endpoints={cancel:"orders/cancel/{id}",createCartFromOrder:"reorder/{id}",sendInvoice:"orders/send/{id}"},this.endpointsMethods={createCartFromOrder:"get"},this.after_init()}show(e){let t=this.getPossibleValue(e?.data||e,["id","order_id"]);salla.event.dispatch("mobile::order.placed",{order_id:t}),location.href=this.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.storage.set("cart",{id:t.data.cart_id,user_id:salla.config.get("user.id")}),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=this.getPossibleValue(e,["id"])||salla.config.get("page.id");if(!t||isNaN(t)){let e="There is no id!";return salla.order.event.invoiceNotSent(e),this.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 ProductApi extends BaseApi{constructor(e){super(e),this.namespace="product",this.previousQuery="",this.endpoints={getPrice:"products/{id}/price",availabilitySubscribe:"products/{id}/availability-notify",search:"products/search",categories:"products/categories/{?id}",purchaseNow:"checkout/quick-purchase/{id}",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"},this.endpointsMethods={giftDetail:"get"},this.webEndpoints=["purchaseNow"],this.after_init()}getPrice(e){let t=e.data||e,r=this.getPossibleValue(t,["id","prod_id","product_id"]);return this.request(["getPrice",r],"object"==typeof t?t:void 0).then((function(e){return salla.product.event.priceUpdated(e,r),e})).catch((function(e){throw salla.product.event.priceUpdateFailed(e,r),e}))}categories(e){return this.request(["categories",e||""],null,"get").then((function(e){return salla.product.event.categoriesFetched(e),e})).catch((function(e){throw salla.product.event.categoriesFailed(e),e}))}availabilitySubscribe(e){let t=e.data||e;return e=this.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.availabilitySubscribedFailed(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),this.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,this.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=this.getPossibleValue(e?.data|e,["product_id","id"]))){let e='There is no "product_id"!';return salla.offer.event.fetchDetailsFailed(e),this.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.fetchFffersFailed(t,e),t}))}purchaseNow(e){if(salla.config.isGuest())return salla.auth.event.dispatch("login");let t=e.product_data,r=this.getPossibleValue(t,["id","prod_id"]);if(!e.is_applepay)return this.request(["quickPurchase",r],"object"==typeof t?t:void 0).then((function(e){return e})).catch((function(e){throw e}));salla.event.dispatch("payments::apple-pay.start-transaction",{amount:e.total,currency:e.currency,requiredShippingContactFields:e.require_shipping?["postalAddress"]:null,shippingMethods:e.require_shipping?[]:null,supportedNetworks:e.applepay_supported_networks,validateMerchant:{url:baseUrl+"checkout/applepay/validate",onFailed:({response:e})=>{console.log("validateMerchant Failed!")},onSuccess:e=>(console.log("validateMerchant Success"),this.request(["quickPurchase",r],"object"==typeof t?t:void 0))},authorized:{url:baseUrl+"/checkout/{id}/payments/submit",onFailed:e=>{console.log("authorized Failed!"),window.Salla.Payments.ApplePay.onCancel({},e.data.error.message)},onSuccess:e=>{console.log(e),window.location.href=e.redirect.url,console.log("authorized Success:: redirect to thank you page, order placed")}},shippingMethodSelected:e.require_shipping?{url:baseUrl+"/checkout/{id}/shipping/details",onFailed:e=>{console.log("select shipping method failed!")},onSuccess:e=>{console.log("select shipping method success")}}:null,shippingContactSelected:e.require_shipping?{url:baseUrl+"/checkout/{id}/address/add",onFailed:e=>{console.log("created contact failed!")},onSuccess:e=>{console.log("created contact success : ",e.data.address_id)}}:null,recalculateTotal:{url:baseUrl+"/checkout/{id}/payments/recalculate"},onError:function(e){console.log(e),salla.notify.error(e)}})}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}))}addGiftToCart(e,t,r=!1){return this.request(["giftToCart",e],t).then((t=>(salla.product.event.addGiftToCartSucceeded(t,e),r&&(window.location.href=t.redirect),response))).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}))}}class ProfileApi extends BaseApi{constructor(e){super(e),this.namespace="profile",this.endpoints={info:"auth/user",update:"profile/update",updateContacts:"profile/contacts/update",verify:"profile/verify"},this.after_init()}info(){return this.request("info",null,"get").then((e=>(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}))}}class CommentApi extends BaseApi{constructor(e){super(e),this.namespace="comment",this.endpoints={add:"{type}/{id}/comments"},this.after_init()}add(e){e?.data&&(e=e.data);let t,{id:r,type:i,comment:n}=Object.fromEntries(e);return r?i&&["products","pages","product","page"].includes(i)?n?(i+=["product","page"].includes(i)?"s":"",this.request(["add",i,r],{comment:n}).then((function(e){return salla.event.comment.added(e,r),e})).catch((function(e){throw salla.event.comment.additionFailed(e,r),e}))):(salla.event.comment.additionFailed(t="can't find comment content!"),this.errorPromise(t)):(salla.event.comment.additionFailed(t="Failed to get type one of:(products, product, page, pages)!"),this.errorPromise(t)):(salla.event.comment.additionFailed(t="Failed to get id!"),this.errorPromise(t))}}class CurrencyApi extends BaseApi{constructor(e){super(e),this.namespace="currency",this.endpoints={change:"/",list:"currencies"},this.endpointsMethods={change:"get",list:"get"},this.webEndpoints=["change"],this.after_init()}change(e){if(!(e=this.getPossibleValue(e.data||e,["currency","code"]))){let e="Can't find currency code!";return salla.currency.event.failed(e),this.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 DocumentApi extends BaseApi{constructor(e){super(e),this.namespace="document"}}class RatingApi extends BaseApi{constructor(e){super(e),this.namespace="rating",this.endpoints={store:"rating/store",products:"rating/products",shipping:"rating/shipping",order:"rating/{order_id}"},this.endpointsMethods={order:"get"},this.after_init()}order(e){let t="object"==typeof e?e:{},r=this.getPossibleValue(e?.data||e,["order_id","id"]);if(!r){let e='There is no "order_id"!';return salla.event.rating.orderNotFetched(e),this.errorPromise(e)}return this.request(["order",r],t).then((function(e){return salla.event.rating.orderFetched(e,r),e})).catch((function(e){throw salla.event.rating.orderNotFetched(e,r),e}))}store(e){if(!(e=e.data||e)){let e='There is no "data"!';return salla.event.rating.storeFailed(e),this.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),this.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),this.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 SallaInit{constructor(e){salla.config.merge(e),e?(e._token&&(salla.api.defaults.headers.common["X-CSRF-TOKEN"]=e._token),this.injectMaintenanceAlert(),this.injectThemePreviewAlert(),this.injectEditAlert(),e?.user?.language_code&&salla.lang.setLocale(e?.user?.language_code),salla.lang.loadStoreTranslations(),salla.twilight.event.initiated(e)):salla.twilight.event.initiated(e)}injectMaintenanceAlert(){salla.config.get("maintenance")&&(document.querySelector(".store-notify")?salla.logger.warn(".store-notify element Existed before!"):salla.lang.onLoaded((()=>{var e=document.createElement("div");e.classList.add("store-notify"),e.style="background-color: #d63031; color: #fff; padding: 10px 15px; text-align: center; font-size: 17px;",e.innerHTML=`<p style="margin:0 !important;">${salla.lang.get("blocks.header.maintenance_alert")}</p>`,document.body.prepend(e)})))}injectThemePreviewAlert(){"preview"===salla.config.get("theme.mode")&&(document.querySelector("#s-theme_preview_bar")?salla.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 r=t.getAjaxFormData(e),i=r.method?r.method.toLowerCase():void 0;salla.api.document.request(r.url,r.formData,i).then((e=>(e.data&&e.request&&(e=e.data),salla.api.document.handleAfterResponseActions(e),this.callAjaxEvent(r.events.success,e,r.formData),e))).catch((e=>{throw salla.api.document.handleErrorResponse(e),this.callAjaxEvent(r.events.fail,e,r.formData),e}))}callAjaxEvent(e,t,r){if(e){if(r instanceof FormData){var i={};Array.from(r.entries()).forEach((function(e){i[e[0]]=e[1]})),r=i}window[e]?window[e](t,r):salla.event.dispatch(e,t,r)}}}class TwilightApi extends BaseApi{constructor(e){super(e),this.namespace="twilight",this.after_init()}init(e){let t=e?.events;return salla.isInitiated||(delete e.events,new SallaInit(e),salla.isInitiated=!0),t&&salla.event.dispatchEvents(t),this.successPromise(e)}api(e){let t=e?.events;return t&&salla.event.dispatchEvents(t),this.successPromise(e)}}class WishlistApi extends BaseApi{constructor(e){super(e),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),this.errorPromise(t)):(e=this.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!"),this.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),this.errorPromise(t)):(e=this.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!"),this.errorPromise(t))}updateWishlistStorage(e,t=!0){let r=salla.storage.get("salla::wishlist",[]);t?r.push(e):r.splice(r.indexOf(e),1),salla.storage.set("salla::wishlist",r)}}class ScopeApi extends BaseApi{constructor(e){super(e),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),resp}))}}function e(e){this.message=e}e.prototype=new Error,e.prototype.name="InvalidCharacterError";var r="undefined"!=typeof window&&window.atob&&window.atob.bind(window)||function(t){var r=String(t).replace(/=+$/,"");if(r.length%4==1)throw new e("'atob' failed: The string to be decoded is not correctly encoded.");for(var i,n,a=0,s=0,o="";n=r.charAt(s++);~n&&(i=a%4?64*i+n:n,a++%4)?o+=String.fromCharCode(255&i>>(-2*a&6)):0)n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(n);return o};function t(e){var t=e.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw"Illegal base64url string!"}try{return function(e){return decodeURIComponent(r(e).replace(/(.)/g,(function(e,t){var r=t.charCodeAt(0).toString(16).toUpperCase();return r.length<2&&(r="0"+r),"%"+r})))}(t)}catch(e){return r(t)}}function n(e){this.message=e}function o(e,r){if("string"!=typeof e)throw new n("Invalid token specified");var i=!0===(r=r||{}).header?0:1;try{return JSON.parse(t(e.split(".")[i]))}catch(e){throw new n("Invalid token specified: "+e.message)}}n.prototype=new Error,n.prototype.name="InvalidTokenError";const axios=require("axios");class sallaRequest{constructor(e){return e.on("twilight::initiated",(()=>this.initiateRequest())),e.on("profile::info.fetched",this.setCurrencyAndLanguage),e.on("auth::token.fetched",(e=>this.handleToken(e))),e.on("document::request.failed",((e,t)=>{salla.logger.warn(t,e)})),axios.create({headers:{common:{"X-Requested-With":"XMLHttpRequest","S-SOURCE":"twilight","S-APP-VERSION":"v2.0.0","S-APP-OS":"browser"}}})}initiateRequest(){salla.api.defaults.baseURL=salla.config.get("store.api",salla.config.get("store.url")),salla.api.defaults.headers.common["Store-Identifier"]=salla.config.get("store.id"),salla.api.defaults.headers.common.currency=salla.config.get("user.currency_code","SAR"),salla.infiniteScroll.fetchOptions.headers["Accept-Language"]=salla.api.defaults.headers.common["accept-language"]=salla.lang.getLocale(),salla.api.defaults.headers.common["s-user-id"]=salla.config.get("user.id"),this.injectTokenToTheRequests()}injectTokenToTheRequests(){let e=salla.storage.get("token"),t=salla.config.isGuest(),r=salla.storage.get("cart");if(r&&(r.user_id!==salla.config.get("user.id")||r.store_id!==salla.config.get("store.id")))return salla.log("Auth:: The cart is not belong to current "+(r.user_id!==salla.config.get("user.id")?"user":"store")+"!"),void salla.cart.api.reset();if(t&&!e)return;if(t&&e)return salla.log("Auth:: Token without user!"),salla.storage.remove("token"),void salla.cart.api.reset();if(!e)return salla.cart.api.reset(),void salla.auth.api.refresh();let i=o(e);return Date.now()/1e3>i.exp?(salla.log("Auth:: An expired token!"),salla.storage.remove("token"),salla.cart.api.reset(),void salla.auth.api.refresh()):i.sub!==salla.config.get("user.id")?(salla.log("Auth:: The user id is not match the token details!"),salla.storage.remove("token"),salla.cart.api.reset(),void salla.auth.api.refresh()):void this.setToken(e)}handleToken(e){salla.storage.set("token",e),this.setToken(e),salla.cart.api.reset()}setToken(e){salla.api.defaults.headers.common.Authorization="Bearer "+e}setCurrencyAndLanguage(e){salla.api.defaults.headers.common.currency=e.data.currency,salla.api.defaults.headers.common["accept-language"]=e.data.language,salla.infiniteScroll.fetchOptions.headers["Accept-Language"]=e.data.language}}class SallaApi extends sallaRequest{constructor(e){super(e),this.apis={auth:new AuthApi(this),cart:new CartApi(this),loyalty:new LoyaltyApi(this),order:new OrderApi(this),rating:new RatingApi(this),product:new ProductApi(this),profile:new ProfileApi(this),comment:new CommentApi(this),currency:new CurrencyApi(this),document:new DocumentApi(this),twilight:new TwilightApi(this),wishlist:new WishlistApi(this),scope:new ScopeApi(this)},Object.assign(this,this.apis),this.getHeaders=()=>this.defaults.headers.common}}class Action{constructor(e,t){return this.api=e,this.event=t,new Proxy(this,{get:function(r,i){return"event"===i?t:"api"===i&&"twilight"!==e?.namespace?e:e&&e[i]||r[i]}})}}var version={build:5,date:"9/1/2022, 9:09:49 AM",package_version:"2.6.18"},js={exports:{}},core={exports:{}},evEmitter={exports:{}},hasRequiredEvEmitter;function requireEvEmitter(){return hasRequiredEvEmitter||(hasRequiredEvEmitter=1,function(e){!function(t,r){e.exports?e.exports=r():t.EvEmitter=r()}("undefined"!=typeof window?window:commonjsGlobal,(function(){function e(){}let t=e.prototype;return t.on=function(e,t){if(!e||!t)return this;let r=this._events=this._events||{},i=r[e]=r[e]||[];return i.includes(t)||i.push(t),this},t.once=function(e,t){if(!e||!t)return this;this.on(e,t);let r=this._onceEvents=this._onceEvents||{};return(r[e]=r[e]||{})[t]=!0,this},t.off=function(e,t){let r=this._events&&this._events[e];if(!r||!r.length)return this;let i=r.indexOf(t);return-1!=i&&r.splice(i,1),this},t.emitEvent=function(e,t){let r=this._events&&this._events[e];if(!r||!r.length)return this;r=r.slice(0),t=t||[];let i=this._onceEvents&&this._onceEvents[e];for(let n of r){i&&i[n]&&(this.off(e,n),delete i[n]),n.apply(this,t)}return this},t.allOff=function(){return delete this._events,delete this._onceEvents,this},e}))}(evEmitter)),evEmitter.exports}var utils={exports:{}},hasRequiredUtils,hasRequiredCore;function requireUtils(){return hasRequiredUtils||(hasRequiredUtils=1,function(e){!function(t,r){e.exports?e.exports=r(t):t.fizzyUIUtils=r(t)}(commonjsGlobal,(function(e){let t={extend:function(e,t){return Object.assign(e,t)},modulo:function(e,t){return(e%t+t)%t},makeArray:function(e){if(Array.isArray(e))return e;if(null==e)return[];return"object"==typeof e&&"number"==typeof e.length?[...e]:[e]},removeFrom:function(e,t){let r=e.indexOf(t);-1!=r&&e.splice(r,1)},getParent:function(e,t){for(;e.parentNode&&e!=document.body;)if((e=e.parentNode).matches(t))return e},getQueryElement:function(e){return"string"==typeof e?document.querySelector(e):e},handleEvent:function(e){let t="on"+e.type;this[t]&&this[t](e)},filterFindElements:function(e,r){return(e=t.makeArray(e)).filter((e=>e instanceof HTMLElement)).reduce(((e,t)=>{if(!r)return e.push(t),e;t.matches(r)&&e.push(t);let i=t.querySelectorAll(r);return e=e.concat(...i)}),[])},debounceMethod:function(e,t,r){r=r||100;let i=e.prototype[t],n=t+"Timeout";e.prototype[t]=function(){clearTimeout(this[n]);let e=arguments;this[n]=setTimeout((()=>{i.apply(this,e),delete this[n]}),r)}},docReady:function(e){let t=document.readyState;"complete"==t||"interactive"==t?setTimeout(e):document.addEventListener("DOMContentLoaded",e)},toDashed:function(e){return e.replace(/(.)([A-Z])/g,(function(e,t,r){return t+"-"+r})).toLowerCase()}},r=e.console;return t.htmlInit=function(i,n){t.docReady((function(){let a="data-"+t.toDashed(n),s=document.querySelectorAll(`[${a}]`),o=e.jQuery;[...s].forEach((e=>{let t,s=e.getAttribute(a);try{t=s&&JSON.parse(s)}catch(t){return void(r&&r.error(`Error parsing ${a} on ${e.className}: ${t}`))}let l=new i(e,t);o&&o.data(e,n,l)}))}))},t}))}(utils)),utils.exports}function requireCore(){return hasRequiredCore||(hasRequiredCore=1,function(e){!function(t,r){e.exports?e.exports=r(t,requireEvEmitter(),requireUtils()):t.InfiniteScroll=r(t,t.EvEmitter,t.fizzyUIUtils)}(window,(function(e,t,r){let i=e.jQuery,n={};function a(e,t){let s=r.getQueryElement(e);if(s){if((e=s).infiniteScrollGUID){let r=n[e.infiniteScrollGUID];return r.option(t),r}this.element=e,this.options={...a.defaults},this.option(t),i&&(this.$element=i(this.element)),this.create()}else console.error("Bad element for InfiniteScroll: "+(s||e))}a.defaults={},a.create={},a.destroy={};let s=a.prototype;Object.assign(s,t.prototype);let o=0;s.create=function(){let e=this.guid=++o;if(this.element.infiniteScrollGUID=e,n[e]=this,this.pageIndex=1,this.loadCount=0,this.updateGetPath(),this.getPath&&this.getPath()){this.updateGetAbsolutePath(),this.log("initialized",[this.element.className]),this.callOnInit();for(let e in a.create)a.create[e].call(this)}else console.error("Disabling InfiniteScroll")},s.option=function(e){Object.assign(this.options,e)},s.callOnInit=function(){let e=this.options.onInit;e&&e.call(this,this)},s.dispatchEvent=function(e,t,r){this.log(e,r);let n=t?[t].concat(r):r;if(this.emitEvent(e,n),!i||!this.$element)return;let a=e+=".infiniteScroll";if(t){let r=i.Event(t);r.type=e,a=r}this.$element.trigger(a,r)};let l={initialized:e=>`on ${e}`,request:e=>`URL: ${e}`,load:(e,t)=>`${e.title||""}. URL: ${t}`,error:(e,t)=>`${e}. URL: ${t}`,append:(e,t,r)=>`${r.length} items. URL: ${t}`,last:(e,t)=>`URL: ${t}`,history:(e,t)=>`URL: ${t}`,pageIndex:function(e,t){return`current page determined to be: ${e} from ${t}`}};s.log=function(e,t){if(!this.options.debug)return;let r=`[InfiniteScroll] ${e}`,i=l[e];i&&(r+=". "+i.apply(this,t)),console.log(r)},s.updateMeasurements=function(){this.windowHeight=e.innerHeight;let t=this.element.getBoundingClientRect();this.top=t.top+e.scrollY},s.updateScroller=function(){let t=this.options.elementScroll;if(t){if(this.scroller=!0===t?this.element:r.getQueryElement(t),!this.scroller)throw new Error(`Unable to find elementScroll: ${t}`)}else this.scroller=e},s.updateGetPath=function(){let e=this.options.path;if(!e)return void console.error(`InfiniteScroll path option required. Set as: ${e}`);let t=typeof e;"function"!=t?"string"==t&&e.match("{{#}}")?this.updateGetPathTemplate(e):this.updateGetPathSelector(e):this.getPath=e},s.updateGetPathTemplate=function(e){this.getPath=()=>{let t=this.pageIndex+1;return e.replace("{{#}}",t)};let t=e.replace(/(\\\?|\?)/,"\\?").replace("{{#}}","(\\d\\d?\\d?)"),r=new RegExp(t),i=location.href.match(r);i&&(this.pageIndex=parseInt(i[1],10),this.log("pageIndex",[this.pageIndex,"template string"]))};let c=[/^(.*?\/?page\/?)(\d\d?\d?)(.*?$)/,/^(.*?\/?\?page=)(\d\d?\d?)(.*?$)/,/(.*?)(\d\d?\d?)(?!.*\d)(.*?$)/],u=a.getPathParts=function(e){if(e)for(let t of c){let r=e.match(t);if(r){let[,e,t,i]=r;return{begin:e,index:t,end:i}}}};s.updateGetPathSelector=function(e){let t=document.querySelector(e);if(!t)return void console.error(`Bad InfiniteScroll path option. Next link not found: ${e}`);let r=t.getAttribute("href"),i=u(r);if(!i)return void console.error(`InfiniteScroll unable to parse next link href: ${r}`);let{begin:n,index:a,end:s}=i;this.isPathSelector=!0,this.getPath=()=>n+(this.pageIndex+1)+s,this.pageIndex=parseInt(a,10)-1,this.log("pageIndex",[this.pageIndex,"next link"])},s.updateGetAbsolutePath=function(){let e=this.getPath();if(e.match(/^http/)||e.match(/^\//))return void(this.getAbsolutePath=this.getPath);let{pathname:t}=location,r=e.match(/^\?/),i=t.substring(0,t.lastIndexOf("/")),n=r?t:i+"/";this.getAbsolutePath=()=>n+this.getPath()},a.create.hideNav=function(){let e=r.getQueryElement(this.options.hideNav);e&&(e.style.display="none",this.nav=e)},a.destroy.hideNav=function(){this.nav&&(this.nav.style.display="")},s.destroy=function(){this.allOff();for(let e in a.destroy)a.destroy[e].call(this);delete this.element.infiniteScrollGUID,delete n[this.guid],i&&this.$element&&i.removeData(this.element,"infiniteScroll")},a.throttle=function(e,t){let r,i;return t=t||200,function(){let n=+new Date,a=arguments,s=()=>{r=n,e.apply(this,a)};r&&n<r+t?(clearTimeout(i),i=setTimeout(s,t)):s()}},a.data=function(e){let t=(e=r.getQueryElement(e))&&e.infiniteScrollGUID;return t&&n[t]},a.setJQuery=function(e){i=e},r.htmlInit(a,"infinite-scroll"),s._init=function(){};let{jQueryBridget:h}=e;return i&&h&&h("infiniteScroll",a,i),a}))}(core)),core.exports}var pageLoad={exports:{}},hasRequiredPageLoad;function requirePageLoad(){return hasRequiredPageLoad||(hasRequiredPageLoad=1,function(e){!function(t,r){e.exports?e.exports=r(t,requireCore()):r(t,t.InfiniteScroll)}(window,(function(e,t){let r=t.prototype;Object.assign(t.defaults,{loadOnScroll:!0,checkLastPage:!0,responseBody:"text",domParseResponse:!0}),t.create.pageLoad=function(){this.canLoad=!0,this.on("scrollThreshold",this.onScrollThresholdLoad),this.on("load",this.checkLastPage),this.options.outlayer&&this.on("append",this.onAppendOutlayer)},r.onScrollThresholdLoad=function(){this.options.loadOnScroll&&this.loadNextPage()};let i=new DOMParser;function n(e){let t=document.createDocumentFragment();return e&&t.append(...e),t}return r.loadNextPage=function(){if(this.isLoading||!this.canLoad)return;let{responseBody:e,domParseResponse:t,fetchOptions:r}=this.options,n=this.getAbsolutePath();this.isLoading=!0,"function"==typeof r&&(r=r());let a=fetch(n,r).then((r=>{if(!r.ok){let e=new Error(r.statusText);return this.onPageError(e,n,r),{response:r}}return r[e]().then((a=>("text"==e&&t&&(a=i.parseFromString(a,"text/html")),204==r.status?(this.lastPageReached(a,n),{body:a,response:r}):this.onPageLoad(a,n,r))))})).catch((e=>{this.onPageError(e,n)}));return this.dispatchEvent("request",null,[n,a]),a},r.onPageLoad=function(e,t,r){return this.options.append||(this.isLoading=!1),this.pageIndex++,this.loadCount++,this.dispatchEvent("load",null,[e,t,r]),this.appendNextPage(e,t,r)},r.appendNextPage=function(e,t,r){let{append:i,responseBody:a,domParseResponse:s}=this.options;if(!("text"==a&&s)||!i)return{body:e,response:r};let o=e.querySelectorAll(i),l={body:e,response:r,items:o};if(!o||!o.length)return this.lastPageReached(e,t),l;let c=n(o),u=()=>(this.appendItems(o,c),this.isLoading=!1,this.dispatchEvent("append",null,[e,t,o,r]),l);return this.options.outlayer?this.appendOutlayerItems(c,u):u()},r.appendItems=function(e,t){e&&e.length&&(function(e){let t=e.querySelectorAll("script");for(let e of t){let t=document.createElement("script"),r=e.attributes;for(let e of r)t.setAttribute(e.name,e.value);t.innerHTML=e.innerHTML,e.parentNode.replaceChild(t,e)}}(t=t||n(e)),this.element.appendChild(t))},r.appendOutlayerItems=function(r,i){let n=t.imagesLoaded||e.imagesLoaded;return n?new Promise((function(e){n(r,(function(){let t=i();e(t)}))})):(console.error("[InfiniteScroll] imagesLoaded required for outlayer option"),void(this.isLoading=!1))},r.onAppendOutlayer=function(e,t,r){this.options.outlayer.appended(r)},r.checkLastPage=function(e,t){let r,{checkLastPage:i,path:n}=this.options;if(i){if("function"==typeof n){if(!this.getPath())return void this.lastPageReached(e,t)}"string"==typeof i?r=i:this.isPathSelector&&(r=n),r&&e.querySelector&&(e.querySelector(r)||this.lastPageReached(e,t))}},r.lastPageReached=function(e,t){this.canLoad=!1,this.dispatchEvent("last",null,[e,t])},r.onPageError=function(e,t,r){return this.isLoading=!1,this.canLoad=!1,this.dispatchEvent("error",null,[e,t,r]),e},t.create.prefill=function(){if(!this.options.prefill)return;let e=this.options.append;e?(this.updateMeasurements(),this.updateScroller(),this.isPrefilling=!0,this.on("append",this.prefill),this.once("error",this.stopPrefill),this.once("last",this.stopPrefill),this.prefill()):console.error(`append option required for prefill. Set as :${e}`)},r.prefill=function(){let e=this.getPrefillDistance();this.isPrefilling=e>=0,this.isPrefilling?(this.log("prefill"),this.loadNextPage()):this.stopPrefill()},r.getPrefillDistance=function(){return this.options.elementScroll?this.scroller.clientHeight-this.scroller.scrollHeight:this.windowHeight-this.element.clientHeight},r.stopPrefill=function(){this.log("stopPrefill"),this.off("append",this.prefill)},t}))}(pageLoad)),pageLoad.exports}var scrollWatch={exports:{}},hasRequiredScrollWatch;function requireScrollWatch(){return hasRequiredScrollWatch||(hasRequiredScrollWatch=1,function(e){!function(t,r){e.exports?e.exports=r(t,requireCore(),requireUtils()):r(t,t.InfiniteScroll,t.fizzyUIUtils)}(window,(function(e,t,r){let i=t.prototype;return Object.assign(t.defaults,{scrollThreshold:400}),t.create.scrollWatch=function(){this.pageScrollHandler=this.onPageScroll.bind(this),this.resizeHandler=this.onResize.bind(this);let e=this.options.scrollThreshold;(e||0===e)&&this.enableScrollWatch()},t.destroy.scrollWatch=function(){this.disableScrollWatch()},i.enableScrollWatch=function(){this.isScrollWatching||(this.isScrollWatching=!0,this.updateMeasurements(),this.updateScroller(),this.on("last",this.disableScrollWatch),this.bindScrollWatchEvents(!0))},i.disableScrollWatch=function(){this.isScrollWatching&&(this.bindScrollWatchEvents(!1),delete this.isScrollWatching)},i.bindScrollWatchEvents=function(t){let r=t?"addEventListener":"removeEventListener";this.scroller[r]("scroll",this.pageScrollHandler),e[r]("resize",this.resizeHandler)},i.onPageScroll=t.throttle((function(){this.getBottomDistance()<=this.options.scrollThreshold&&this.dispatchEvent("scrollThreshold")})),i.getBottomDistance=function(){let t,r;return this.options.elementScroll?(t=this.scroller.scrollHeight,r=this.scroller.scrollTop+this.scroller.clientHeight):(t=this.top+this.element.clientHeight,r=e.scrollY+this.windowHeight),t-r},i.onResize=function(){this.updateMeasurements()},r.debounceMethod(t,"onResize",150),t}))}(scrollWatch)),scrollWatch.exports}var history$1={exports:{}},hasRequiredHistory;function requireHistory(){return hasRequiredHistory||(hasRequiredHistory=1,function(e){!function(t,r){e.exports?e.exports=r(t,requireCore(),requireUtils()):r(t,t.InfiniteScroll,t.fizzyUIUtils)}(window,(function(e,t,r){let i=t.prototype;Object.assign(t.defaults,{history:"replace"});let n=document.createElement("a");return t.create.history=function(){if(!this.options.history)return;n.href=this.getAbsolutePath(),(n.origin||n.protocol+"//"+n.host)==location.origin?this.options.append?this.createHistoryAppend():this.createHistoryPageLoad():console.error(`[InfiniteScroll] cannot set history with different origin: ${n.origin} on ${location.origin} . History behavior disabled.`)},i.createHistoryAppend=function(){this.updateMeasurements(),this.updateScroller(),this.scrollPages=[{top:0,path:location.href,title:document.title}],this.scrollPage=this.scrollPages[0],this.scrollHistoryHandler=this.onScrollHistory.bind(this),this.unloadHandler=this.onUnload.bind(this),this.scroller.addEventListener("scroll",this.scrollHistoryHandler),this.on("append",this.onAppendHistory),this.bindHistoryAppendEvents(!0)},i.bindHistoryAppendEvents=function(t){let r=t?"addEventListener":"removeEventListener";this.scroller[r]("scroll",this.scrollHistoryHandler),e[r]("unload",this.unloadHandler)},i.createHistoryPageLoad=function(){this.on("load",this.onPageLoadHistory)},t.destroy.history=i.destroyHistory=function(){this.options.history&&this.options.append&&this.bindHistoryAppendEvents(!1)},i.onAppendHistory=function(e,t,r){if(!r||!r.length)return;let i=r[0],a=this.getElementScrollY(i);n.href=t,this.scrollPages.push({top:a,path:n.href,title:e.title})},i.getElementScrollY=function(t){if(this.options.elementScroll)return t.offsetTop-this.top;return t.getBoundingClientRect().top+e.scrollY},i.onScrollHistory=function(){let e=this.getClosestScrollPage();e!=this.scrollPage&&(this.scrollPage=e,this.setHistory(e.title,e.path))},r.debounceMethod(t,"onScrollHistory",150),i.getClosestScrollPage=function(){let t,r;t=this.options.elementScroll?this.scroller.scrollTop+this.scroller.clientHeight/2:e.scrollY+this.windowHeight/2;for(let e of this.scrollPages){if(e.top>=t)break;r=e}return r},i.setHistory=function(e,t){let r=this.options.history;r&&history[r+"State"]&&(history[r+"State"](null,e,t),this.options.historyTitle&&(document.title=e),this.dispatchEvent("history",null,[e,t]))},i.onUnload=function(){if(0===this.scrollPage.top)return;let t=e.scrollY-this.scrollPage.top+this.top;this.destroyHistory(),scrollTo(0,t)},i.onPageLoadHistory=function(e,t){this.setHistory(e.title,t)},t}))}(history$1)),history$1.exports}var button={exports:{}},hasRequiredButton;function requireButton(){return hasRequiredButton||(hasRequiredButton=1,function(e){!function(t,r){e.exports?e.exports=r(t,requireCore(),requireUtils()):r(t,t.InfiniteScroll,t.fizzyUIUtils)}(window,(function(e,t,r){class i{constructor(e,t){this.element=e,this.infScroll=t,this.clickHandler=this.onClick.bind(this),this.element.addEventListener("click",this.clickHandler),t.on("request",this.disable.bind(this)),t.on("load",this.enable.bind(this)),t.on("error",this.hide.bind(this)),t.on("last",this.hide.bind(this))}onClick(e){e.preventDefault(),this.infScroll.loadNextPage()}enable(){this.element.removeAttribute("disabled")}disable(){this.element.disabled="disabled"}hide(){this.element.style.display="none"}destroy(){this.element.removeEventListener("click",this.clickHandler)}}return t.create.button=function(){let e=r.getQueryElement(this.options.button);e&&(this.button=new i(e,this))},t.destroy.button=function(){this.button&&this.button.destroy()},t.Button=i,t}))}(button)),button.exports}var status={exports:{}},hasRequiredStatus;function requireStatus(){return hasRequiredStatus||(hasRequiredStatus=1,function(e){!function(t,r){e.exports?e.exports=r(t,requireCore(),requireUtils()):r(t,t.InfiniteScroll,t.fizzyUIUtils)}(window,(function(e,t,r){let i=t.prototype;function n(e){s(e,"none")}function a(e){s(e,"block")}function s(e,t){e&&(e.style.display=t)}return t.create.status=function(){let e=r.getQueryElement(this.options.status);e&&(this.statusElement=e,this.statusEventElements={request:e.querySelector(".infinite-scroll-request"),error:e.querySelector(".infinite-scroll-error"),last:e.querySelector(".infinite-scroll-last")},this.on("request",this.showRequestStatus),this.on("error",this.showErrorStatus),this.on("last",this.showLastStatus),this.bindHideStatus("on"))},i.bindHideStatus=function(e){let t=this.options.append?"append":"load";this[e](t,this.hideAllStatus)},i.showRequestStatus=function(){this.showStatus("request")},i.showErrorStatus=function(){this.showStatus("error")},i.showLastStatus=function(){this.showStatus("last"),this.bindHideStatus("off")},i.showStatus=function(e){a(this.statusElement),this.hideStatusEventElements(),a(this.statusEventElements[e])},i.hideAllStatus=function(){n(this.statusElement),this.hideStatusEventElements()},i.hideStatusEventElements=function(){for(let e in this.statusEventElements){n(this.statusEventElements[e])}},t}))}(status)),status.exports}
9
+ module=eventemitter2$1,function(e){var t=Object.hasOwnProperty,r=Array.isArray?Array.isArray:function(e){return"[object Array]"===Object.prototype.toString.call(e)},i="object"==typeof process&&"function"==typeof process.nextTick,n="function"==typeof Symbol,a="object"==typeof Reflect,s="function"==typeof setImmediate?setImmediate:setTimeout,o=n?a&&"function"==typeof Reflect.ownKeys?Reflect.ownKeys:function(e){var t=Object.getOwnPropertyNames(e);return t.push.apply(t,Object.getOwnPropertySymbols(e)),t}:Object.keys;function l(){this._events={},this._conf&&c.call(this,this._conf)}function c(t){t&&(this._conf=t,t.delimiter&&(this.delimiter=t.delimiter),t.maxListeners!==e&&(this._maxListeners=t.maxListeners),t.wildcard&&(this.wildcard=t.wildcard),t.newListener&&(this._newListener=t.newListener),t.removeListener&&(this._removeListener=t.removeListener),t.verboseMemoryLeak&&(this.verboseMemoryLeak=t.verboseMemoryLeak),t.ignoreErrors&&(this.ignoreErrors=t.ignoreErrors),this.wildcard&&(this.listenerTree={}))}function u(e,t){var r="(node) warning: possible EventEmitter memory leak detected. "+e+" listeners added. Use emitter.setMaxListeners() to increase limit.";if(this.verboseMemoryLeak&&(r+=" Event name: "+t+"."),"undefined"!=typeof process&&process.emitWarning){var i=new Error(r);i.name="MaxListenersExceededWarning",i.emitter=this,i.count=e,process.emitWarning(i)}else console.error(r),console.trace&&console.trace()}var h=function(e,t,r){var i=arguments.length;switch(i){case 0:return[];case 1:return[e];case 2:return[e,t];case 3:return[e,t,r];default:for(var n=new Array(i);i--;)n[i]=arguments[i];return n}};function d(t,r){for(var i={},n=t.length,a=r?r.length:0,s=0;s<n;s++)i[t[s]]=s<a?r[s]:e;return i}function p(e,t,r){var i,n;if(this._emitter=e,this._target=t,this._listeners={},this._listenersCount=0,(r.on||r.off)&&(i=r.on,n=r.off),t.addEventListener?(i=t.addEventListener,n=t.removeEventListener):t.addListener?(i=t.addListener,n=t.removeListener):t.on&&(i=t.on,n=t.off),!i&&!n)throw Error("target does not implement any known event API");if("function"!=typeof i)throw TypeError("on method must be a function");if("function"!=typeof n)throw TypeError("off method must be a function");this._on=i,this._off=n;var a=e._observers;a?a.push(this):e._observers=[this]}function f(r,i,n,a){var s=Object.assign({},i);if(!r)return s;if("object"!=typeof r)throw TypeError("options must be an object");var o,l,c,u=Object.keys(r),h=u.length;function d(e){throw Error('Invalid "'+o+'" option value'+(e?". Reason: "+e:""))}for(var p=0;p<h;p++){if(o=u[p],!a&&!t.call(i,o))throw Error('Unknown "'+o+'" option');(l=r[o])!==e&&(c=n[o],s[o]=c?c(l,d):l)}return s}function g(e,t){return"function"==typeof e&&e.hasOwnProperty("prototype")||t("value must be a constructor"),e}function m(e){var t="value must be type of "+e.join("|"),r=e.length,i=e[0],n=e[1];return 1===r?function(e,r){if(typeof e===i)return e;r(t)}:2===r?function(e,r){var a=typeof e;if(a===i||a===n)return e;r(t)}:function(i,n){for(var a=typeof i,s=r;s-- >0;)if(a===e[s])return i;n(t)}}Object.assign(p.prototype,{subscribe:function(e,t,r){var i=this,n=this._target,a=this._emitter,s=this._listeners,o=function(){var i=h.apply(null,arguments),s={data:i,name:t,original:e};if(r){var o=r.call(n,s);!1!==o&&a.emit.apply(a,[s.name].concat(i))}else a.emit.apply(a,[t].concat(i))};if(s[e])throw Error("Event '"+e+"' is already listening");this._listenersCount++,a._newListener&&a._removeListener&&!i._onNewListener?(this._onNewListener=function(r){r===t&&null===s[e]&&(s[e]=o,i._on.call(n,e,o))},a.on("newListener",this._onNewListener),this._onRemoveListener=function(r){r===t&&!a.hasListeners(r)&&s[e]&&(s[e]=null,i._off.call(n,e,o))},s[e]=null,a.on("removeListener",this._onRemoveListener)):(s[e]=o,i._on.call(n,e,o))},unsubscribe:function(e){var t,r,i,n=this,a=this._listeners,s=this._emitter,l=this._off,c=this._target;if(e&&"string"!=typeof e)throw TypeError("event must be a string");function u(){n._onNewListener&&(s.off("newListener",n._onNewListener),s.off("removeListener",n._onRemoveListener),n._onNewListener=null,n._onRemoveListener=null);var e=_.call(s,n);s._observers.splice(e,1)}if(e){if(!(t=a[e]))return;l.call(c,e,t),delete a[e],--this._listenersCount||u()}else{for(i=(r=o(a)).length;i-- >0;)e=r[i],l.call(c,e,a[e]);this._listeners={},this._listenersCount=0,u()}}});var v=m(["function"]),y=m(["object","function"]);function b(e,t,r){var i,n,a,s=0,o=new e((function(l,c,u){function h(){n&&(n=null),s&&(clearTimeout(s),s=0)}r=f(r,{timeout:0,overload:!1},{timeout:function(e,t){return("number"!=typeof(e*=1)||e<0||!Number.isFinite(e))&&t("timeout must be a positive number"),e}}),i=!r.overload&&"function"==typeof e.prototype.cancel&&"function"==typeof u;var d=function(e){h(),l(e)},p=function(e){h(),c(e)};i?t(d,p,u):(n=[function(e){p(e||Error("canceled"))}],t(d,p,(function(e){if(a)throw Error("Unable to subscribe on cancel event asynchronously");if("function"!=typeof e)throw TypeError("onCancel callback must be a function");n.push(e)})),a=!0),r.timeout>0&&(s=setTimeout((function(){var e=Error("timeout");e.code="ETIMEDOUT",s=0,o.cancel(e),c(e)}),r.timeout))}));return i||(o.cancel=function(e){if(n){for(var t=n.length,r=1;r<t;r++)n[r](e);n[0](e),n=null}}),o}function _(e){var t=this._observers;if(!t)return-1;for(var r=t.length,i=0;i<r;i++)if(t[i]._target===e)return i;return-1}function w(e,t,r,i,n){if(!r)return null;if(0===i){var a=typeof t;if("string"===a){var s,l,c=0,u=0,h=this.delimiter,d=h.length;if(-1!==(l=t.indexOf(h))){s=new Array(5);do{s[c++]=t.slice(u,l),u=l+d}while(-1!==(l=t.indexOf(h,u)));s[c++]=t.slice(u),t=s,n=c}else t=[t],n=1}else"object"===a?n=t.length:(t=[t],n=1)}var p,f,g,m,v,y,b,_=null,S=t[i],$=t[i+1];if(i===n)r._listeners&&("function"==typeof r._listeners?(e&&e.push(r._listeners),_=[r]):(e&&e.push.apply(e,r._listeners),_=[r]));else{if("*"===S){for(l=(y=o(r)).length;l-- >0;)"_listeners"!==(p=y[l])&&(b=w(e,t,r[p],i+1,n))&&(_?_.push.apply(_,b):_=b);return _}if("**"===S){for((v=i+1===n||i+2===n&&"*"===$)&&r._listeners&&(_=w(e,t,r,n,n)),l=(y=o(r)).length;l-- >0;)"_listeners"!==(p=y[l])&&("*"===p||"**"===p?(r[p]._listeners&&!v&&(b=w(e,t,r[p],n,n))&&(_?_.push.apply(_,b):_=b),b=w(e,t,r[p],i,n)):b=w(e,t,r[p],p===$?i+2:i,n),b&&(_?_.push.apply(_,b):_=b));return _}r[S]&&(_=w(e,t,r[S],i+1,n))}if((f=r["*"])&&w(e,t,f,i+1,n),g=r["**"])if(i<n)for(g._listeners&&w(e,t,g,n,n),l=(y=o(g)).length;l-- >0;)"_listeners"!==(p=y[l])&&(p===$?w(e,t,g[p],i+2,n):p===S?w(e,t,g[p],i+1,n):((m={})[p]=g[p],w(e,t,{"**":m},i+1,n)));else g._listeners?w(e,t,g,n,n):g["*"]&&g["*"]._listeners&&w(e,t,g["*"],n,n);return _}function S(e,t,r){var i,n,a=0,s=0,o=this.delimiter,l=o.length;if("string"==typeof e)if(-1!==(i=e.indexOf(o))){n=new Array(5);do{n[a++]=e.slice(s,i),s=i+l}while(-1!==(i=e.indexOf(o,s)));n[a++]=e.slice(s)}else n=[e],a=1;else n=e,a=e.length;if(a>1)for(i=0;i+1<a;i++)if("**"===n[i]&&"**"===n[i+1])return;var c,h=this.listenerTree;for(i=0;i<a;i++)if(h=h[c=n[i]]||(h[c]={}),i===a-1)return h._listeners?("function"==typeof h._listeners&&(h._listeners=[h._listeners]),r?h._listeners.unshift(t):h._listeners.push(t),!h._listeners.warned&&this._maxListeners>0&&h._listeners.length>this._maxListeners&&(h._listeners.warned=!0,u.call(this,h._listeners.length,c))):h._listeners=t,!0;return!0}function $(e,t,r,i){for(var n,a,s,l,c=o(e),u=c.length,h=e._listeners;u-- >0;)n=e[a=c[u]],s="_listeners"===a?r:r?r.concat(a):[a],l=i||"symbol"==typeof a,h&&t.push(l?s:s.join(this.delimiter)),"object"==typeof n&&$.call(this,n,t,s,l);return t}function E(e){for(var t,r,i,n=o(e),a=n.length;a-- >0;)(t=e[r=n[a]])&&(i=!0,"_listeners"===r||E(t)||delete e[r]);return i}function A(e,t,r){this.emitter=e,this.event=t,this.listener=r}function C(t,r,n){if(!0===n)o=!0;else if(!1===n)a=!0;else{if(!n||"object"!=typeof n)throw TypeError("options should be an object or true");var a=n.async,o=n.promisify,l=n.nextTick,c=n.objectify}if(a||l||o){var u=r,h=r._origin||r;if(l&&!i)throw Error("process.nextTick is not supported");o===e&&(o="AsyncFunction"===r.constructor.name),r=function(){var e=arguments,t=this,r=this.event;return o?l?Promise.resolve():new Promise((function(e){s(e)})).then((function(){return t.event=r,u.apply(t,e)})):(l?process.nextTick:s)((function(){t.event=r,u.apply(t,e)}))},r._async=!0,r._origin=h}return[r,c?new A(this,t,r):this]}function x(e){this._events={},this._newListener=!1,this._removeListener=!1,this.verboseMemoryLeak=!1,c.call(this,e)}A.prototype.off=function(){return this.emitter.off(this.event,this.listener),this},x.EventEmitter2=x,x.prototype.listenTo=function(t,i,n){if("object"!=typeof t)throw TypeError("target musts be an object");var a=this;function s(e){if("object"!=typeof e)throw TypeError("events must be an object");var r,i=n.reducers,s=_.call(a,t);r=-1===s?new p(a,t,n):a._observers[s];for(var l,c=o(e),u=c.length,h="function"==typeof i,d=0;d<u;d++)l=c[d],r.subscribe(l,e[l]||l,h?i:i&&i[l])}return n=f(n,{on:e,off:e,reducers:e},{on:v,off:v,reducers:y}),r(i)?s(d(i)):s("string"==typeof i?d(i.split(/\s+/)):i),this},x.prototype.stopListeningTo=function(e,t){var r=this._observers;if(!r)return!1;var i,n=r.length,a=!1;if(e&&"object"!=typeof e)throw TypeError("target should be an object");for(;n-- >0;)i=r[n],e&&i._target!==e||(i.unsubscribe(t),a=!0);return a},x.prototype.delimiter=".",x.prototype.setMaxListeners=function(t){t!==e&&(this._maxListeners=t,this._conf||(this._conf={}),this._conf.maxListeners=t)},x.prototype.getMaxListeners=function(){return this._maxListeners},x.prototype.event="",x.prototype.once=function(e,t,r){return this._once(e,t,!1,r)},x.prototype.prependOnceListener=function(e,t,r){return this._once(e,t,!0,r)},x.prototype._once=function(e,t,r,i){return this._many(e,1,t,r,i)},x.prototype.many=function(e,t,r,i){return this._many(e,t,r,!1,i)},x.prototype.prependMany=function(e,t,r,i){return this._many(e,t,r,!0,i)},x.prototype._many=function(e,t,r,i,n){var a=this;if("function"!=typeof r)throw new Error("many only accepts instances of Function");function s(){return 0==--t&&a.off(e,s),r.apply(this,arguments)}return s._origin=r,this._on(e,s,i,n)},x.prototype.emit=function(){if(!this._events&&!this._all)return!1;this._events||l.call(this);var e,t,r,i,a,s,o=arguments[0],c=this.wildcard;if("newListener"===o&&!this._newListener&&!this._events.newListener)return!1;if(c&&(e=o,"newListener"!==o&&"removeListener"!==o&&"object"==typeof o)){if(r=o.length,n)for(i=0;i<r;i++)if("symbol"==typeof o[i]){s=!0;break}s||(o=o.join(this.delimiter))}var u,h=arguments.length;if(this._all&&this._all.length)for(i=0,r=(u=this._all.slice()).length;i<r;i++)switch(this.event=o,h){case 1:u[i].call(this,o);break;case 2:u[i].call(this,o,arguments[1]);break;case 3:u[i].call(this,o,arguments[1],arguments[2]);break;default:u[i].apply(this,arguments)}if(c)u=[],w.call(this,u,e,this.listenerTree,0,r);else{if("function"==typeof(u=this._events[o])){switch(this.event=o,h){case 1:u.call(this);break;case 2:u.call(this,arguments[1]);break;case 3:u.call(this,arguments[1],arguments[2]);break;default:for(t=new Array(h-1),a=1;a<h;a++)t[a-1]=arguments[a];u.apply(this,t)}return!0}u&&(u=u.slice())}if(u&&u.length){if(h>3)for(t=new Array(h-1),a=1;a<h;a++)t[a-1]=arguments[a];for(i=0,r=u.length;i<r;i++)switch(this.event=o,h){case 1:u[i].call(this);break;case 2:u[i].call(this,arguments[1]);break;case 3:u[i].call(this,arguments[1],arguments[2]);break;default:u[i].apply(this,t)}return!0}if(!this.ignoreErrors&&!this._all&&"error"===o)throw arguments[1]instanceof Error?arguments[1]:new Error("Uncaught, unspecified 'error' event.");return!!this._all},x.prototype.emitAsync=function(){if(!this._events&&!this._all)return!1;this._events||l.call(this);var e,t,r,i,a,s,o=arguments[0],c=this.wildcard;if("newListener"===o&&!this._newListener&&!this._events.newListener)return Promise.resolve([!1]);if(c&&(e=o,"newListener"!==o&&"removeListener"!==o&&"object"==typeof o)){if(i=o.length,n)for(a=0;a<i;a++)if("symbol"==typeof o[a]){t=!0;break}t||(o=o.join(this.delimiter))}var u,h=[],d=arguments.length;if(this._all)for(a=0,i=this._all.length;a<i;a++)switch(this.event=o,d){case 1:h.push(this._all[a].call(this,o));break;case 2:h.push(this._all[a].call(this,o,arguments[1]));break;case 3:h.push(this._all[a].call(this,o,arguments[1],arguments[2]));break;default:h.push(this._all[a].apply(this,arguments))}if(c?(u=[],w.call(this,u,e,this.listenerTree,0)):u=this._events[o],"function"==typeof u)switch(this.event=o,d){case 1:h.push(u.call(this));break;case 2:h.push(u.call(this,arguments[1]));break;case 3:h.push(u.call(this,arguments[1],arguments[2]));break;default:for(r=new Array(d-1),s=1;s<d;s++)r[s-1]=arguments[s];h.push(u.apply(this,r))}else if(u&&u.length){if(u=u.slice(),d>3)for(r=new Array(d-1),s=1;s<d;s++)r[s-1]=arguments[s];for(a=0,i=u.length;a<i;a++)switch(this.event=o,d){case 1:h.push(u[a].call(this));break;case 2:h.push(u[a].call(this,arguments[1]));break;case 3:h.push(u[a].call(this,arguments[1],arguments[2]));break;default:h.push(u[a].apply(this,r))}}else if(!this.ignoreErrors&&!this._all&&"error"===o)return arguments[1]instanceof Error?Promise.reject(arguments[1]):Promise.reject("Uncaught, unspecified 'error' event.");return Promise.all(h)},x.prototype.on=function(e,t,r){return this._on(e,t,!1,r)},x.prototype.prependListener=function(e,t,r){return this._on(e,t,!0,r)},x.prototype.onAny=function(e){return this._onAny(e,!1)},x.prototype.prependAny=function(e){return this._onAny(e,!0)},x.prototype.addListener=x.prototype.on,x.prototype._onAny=function(e,t){if("function"!=typeof e)throw new Error("onAny only accepts instances of Function");return this._all||(this._all=[]),t?this._all.unshift(e):this._all.push(e),this},x.prototype._on=function(t,r,i,n){if("function"==typeof t)return this._onAny(t,r),this;if("function"!=typeof r)throw new Error("on only accepts instances of Function");this._events||l.call(this);var a,s=this;return n!==e&&(r=(a=C.call(this,t,r,n))[0],s=a[1]),this._newListener&&this.emit("newListener",t,r),this.wildcard?(S.call(this,t,r,i),s):(this._events[t]?("function"==typeof this._events[t]&&(this._events[t]=[this._events[t]]),i?this._events[t].unshift(r):this._events[t].push(r),!this._events[t].warned&&this._maxListeners>0&&this._events[t].length>this._maxListeners&&(this._events[t].warned=!0,u.call(this,this._events[t].length,t))):this._events[t]=r,s)},x.prototype.off=function(e,t){if("function"!=typeof t)throw new Error("removeListener only takes instances of Function");var i,n=[];if(this.wildcard){var a="string"==typeof e?e.split(this.delimiter):e.slice();if(!(n=w.call(this,null,a,this.listenerTree,0)))return this}else{if(!this._events[e])return this;i=this._events[e],n.push({_listeners:i})}for(var s=0;s<n.length;s++){var o=n[s];if(i=o._listeners,r(i)){for(var l=-1,c=0,u=i.length;c<u;c++)if(i[c]===t||i[c].listener&&i[c].listener===t||i[c]._origin&&i[c]._origin===t){l=c;break}if(l<0)continue;return this.wildcard?o._listeners.splice(l,1):this._events[e].splice(l,1),0===i.length&&(this.wildcard?delete o._listeners:delete this._events[e]),this._removeListener&&this.emit("removeListener",e,t),this}(i===t||i.listener&&i.listener===t||i._origin&&i._origin===t)&&(this.wildcard?delete o._listeners:delete this._events[e],this._removeListener&&this.emit("removeListener",e,t))}return this.listenerTree&&E(this.listenerTree),this},x.prototype.offAny=function(e){var t,r=0,i=0;if(e&&this._all&&this._all.length>0){for(r=0,i=(t=this._all).length;r<i;r++)if(e===t[r])return t.splice(r,1),this._removeListener&&this.emit("removeListenerAny",e),this}else{if(t=this._all,this._removeListener)for(r=0,i=t.length;r<i;r++)this.emit("removeListenerAny",t[r]);this._all=[]}return this},x.prototype.removeListener=x.prototype.off,x.prototype.removeAllListeners=function(t){if(t===e)return!this._events||l.call(this),this;if(this.wildcard){var r,i=w.call(this,null,t,this.listenerTree,0);if(!i)return this;for(r=0;r<i.length;r++)i[r]._listeners=null;this.listenerTree&&E(this.listenerTree)}else this._events&&(this._events[t]=null);return this},x.prototype.listeners=function(t){var r,i,n,a,s,l=this._events;if(t===e){if(this.wildcard)throw Error("event name required for wildcard emitter");if(!l)return[];for(a=(r=o(l)).length,n=[];a-- >0;)"function"==typeof(i=l[r[a]])?n.push(i):n.push.apply(n,i);return n}if(this.wildcard){if(!(s=this.listenerTree))return[];var c=[],u="string"==typeof t?t.split(this.delimiter):t.slice();return w.call(this,c,u,s,0),c}return l&&(i=l[t])?"function"==typeof i?[i]:i:[]},x.prototype.eventNames=function(e){var t=this._events;return this.wildcard?$.call(this,this.listenerTree,[],null,e):t?o(t):[]},x.prototype.listenerCount=function(e){return this.listeners(e).length},x.prototype.hasListeners=function(t){if(this.wildcard){var r=[],i="string"==typeof t?t.split(this.delimiter):t.slice();return w.call(this,r,i,this.listenerTree,0),r.length>0}var n=this._events,a=this._all;return!!(a&&a.length||n&&(t===e?o(n).length:n[t]))},x.prototype.listenersAny=function(){return this._all?this._all:[]},x.prototype.waitFor=function(t,r){var i=this,n=typeof r;return"number"===n?r={timeout:r}:"function"===n&&(r={filter:r}),b((r=f(r,{timeout:0,filter:e,handleError:!1,Promise:Promise,overload:!1},{filter:v,Promise:g})).Promise,(function(e,n,a){function s(){var a=r.filter;if(!a||a.apply(i,arguments))if(i.off(t,s),r.handleError){var o=arguments[0];o?n(o):e(h.apply(null,arguments).slice(1))}else e(h.apply(null,arguments))}a((function(){i.off(t,s)})),i._on(t,s,!1)}),{timeout:r.timeout,overload:r.overload})};var P=x.prototype;Object.defineProperties(x,{defaultMaxListeners:{get:function(){return P._maxListeners},set:function(e){if("number"!=typeof e||e<0||Number.isNaN(e))throw TypeError("n must be a non-negative number");P._maxListeners=e},enumerable:!0},once:{value:function(e,t,r){return b((r=f(r,{Promise:Promise,timeout:0,overload:!1},{Promise:g})).Promise,(function(r,i,n){var a;if("function"==typeof e.addEventListener)return a=function(){r(h.apply(null,arguments))},n((function(){e.removeEventListener(t,a)})),void e.addEventListener(t,a,{once:!0});var s,o=function(){s&&e.removeListener("error",s),r(h.apply(null,arguments))};"error"!==t&&(s=function(r){e.removeListener(t,o),i(r)},e.once("error",s)),n((function(){s&&e.removeListener("error",s),e.removeListener(t,o)})),e.once(t,o)}),{timeout:r.timeout,overload:r.overload})},writable:!0,configurable:!0}}),Object.defineProperties(P,{_maxListeners:{value:10,writable:!0,configurable:!0},_observers:{value:null,writable:!0,configurable:!0}}),module.exports=x}();var eventemitter2=eventemitter2$1.exports;class InfiniteScrollEvents extends BaseEvent{constructor(e){super(e),this.namespace="infiniteScroll",this.events={scrollThreshold:"scroll.threshold",request:"request",load:"load",append:"append",error:"error",last:"last",history:"history"},this.after_init()}}class sallaEmitter extends eventemitter2{constructor(){super({wildcard:!0,delimiter:"::",newListener:!1,removeListener:!1,maxListeners:10,verboseMemoryLeak:!1,ignoreErrors:!1}),this.globalListners={},this.delimiter="::",this.auth=new AuthEvents(this),this.cart=new CartEvents(this),this.order=new OrderEvents(this),this.scope=new ScopeEvents(this),this.rating=new RatingEvents(this),this.comment=new CommentEvents(this),this.loyalty=new LoyaltyEvents(this),this.product=new ProductEvents(this),this.profile=new ProfileEvents(this),this.currency=new CurrencyEvents(this),this.document=new DocumentEvents(this),this.twilight=new TwilightEvents(this),this.wishlist=new WishlistEvents(this),this.infiniteScroll=new InfiniteScrollEvents(this),this.body=document.querySelector("body"),this.logableEvents=["cart::item.added.failed","cart::item.deleted.failed"],this.ingoreLogEvents=["document::click","document::keyup","document::change"],this.noneFireableActions=["document.request"],this.on("twilight::initiated",this.initiateSallaInAllClasses)}initiateSallaInAllClasses(){let e=this;Object.keys(salla).forEach((t=>{"object"==typeof(t=salla[t])&&(e.callSallaInitiate(t),Object.keys(t).forEach((r=>{e.callSallaInitiate(t[r])})))}))}callSallaInitiate(e){e&&e.sallaInitiated&&!e.initiated&&(e.sallaInitiated(),e.initiated=!0)}createAndDispatch(e,...t){this.dispatch(e,...t)}dispatch(e,...t){let r=e.replace("::",".");if(!this.noneFireableActions.includes(r)&&"function"==typeof salla.call(r))return salla.log(`'salla.${r}(...)' triggered using event '${e}'`),r=r.split("."),void salla[r[0]][r[1]](...t);this.emit(e,...t),window.dataLayer=window.dataLayer||[],window.dataLayer.push(Object.assign({event:e},...t.values())),this.ingoreLogEvents.includes(e)||!salla.config.get("debug")&&!this.logableEvents.includes(e)||salla.logger.event(e,...t);let i=this;Object.keys(this.globalListners).forEach((function(r){i.globalListners[r](e,...t)})),this.dispatchMobileEvent(e,{...t.values()})}dispatchEvents(e){if(e&&"object"==typeof e)for(const[t,r]of Object.entries(e))this.dispatch(t,r);else salla.log("No Events To Dispatch!",e)}addListener(e,t){this.on(e,t)}addEventListener(e,t){this.addListener(e,t)}listen(e,t){this.addListener(e,t)}registerGlobalListener(e,t){this.globalListners[e]=t}dispatchMobileEvent(e,t={}){if(!(window.dataLayer&&dataLayer[0]&&dataLayer[0].page&&dataLayer[0].page.mobileApp))return"";if(window.webkit)try{window.webkit.messageHandlers.callbackHandler.postMessage(JSON.stringify({event:e,details:t}))}catch(e){console.log(e,"The native context does not exist yet")}else if(Android)try{Android.customEventWithData(e,JSON.stringify({details:t}))}catch(e){console.log(e,"The native context does not exist yet")}}}class BaseApi{constructor(e){this.parent=e,this.endpoints={},this.webEndpoints=[],this.namespace="BaseApi",this.endpointsMethods={},this.endpointsHeaders={};var t=/function (.{1,})\(/.exec(this.constructor.toString());this.className=(t&&t.length>1?t[1]:"").toLowerCase(),this.debounce={request:void 0,time:300,enabled:!0,exclude:[]}}after_init(){}normalRequest(e,t,r=null){let i=this,n=Array.isArray(e),a=n?this.getUrl(...e):this.getUrl(e);e=n?e[0]:e,r=r||this.endpointsMethods[e]||"post";let s=this.endpointsHeaders[e];if("get"===r&&t instanceof FormData){var o={};Array.from(t.entries()).forEach((function(e){o[e[0]]=e[1]})),t={params:o}}s&&"get"===r&&(t=t?Object.assign(t,s):s);let l={namespace:this.namespace,action:e,url:a,payload:t,method:r,headers:s};try{salla.event.document.request(l)}catch(e){return salla.event.document.requestFailed(l),new Promise((()=>{throw e}))}this.webEndpoints.includes(e)?a=salla.url.get(a):"http"!==a.substring(0,4)&&(a=salla.url.api(a));let c="undefined"!=typeof event?event.currentTarget:null,u=!1;return"SALLA-BUTTON"===c?.tagName&&(u=!0),u&&c?.load(),this.parent[r](a,t,{headers:s}).then((e=>(u&&c?.stop(),e.data&&e.request&&(e=e.data),i.handleAfterResponseActions(e),e))).catch((e=>{throw u&&c?.stop(),salla.event.document.requestFailed(l,e),i.handleErrorResponse(e),e}))}request(e,t,r=null){return!this.isFastRequestsAllowed()&&this.debounce.enabled?(this.debounce.request||(this.debounce.request=salla.helpers.debounce(this.normalRequest.bind(this),this.debounce.time)),this.debounce.request(e,t,r)):this.normalRequest(e,t,r)}getUrl(e){let t=this.endpoints[e]||e;const r=/{[^{}]+}/i;for(let e=1;e<arguments.length;e++)t=t.replace(r,arguments[e]);return t}handleAfterResponseActions(e){if(!e)return;let{data:t,googleTags:r=null}=e,i=t&&t.googleTags?t.googleTags:r;dataLayer&&i&&dataLayer.push(i),this.fireEventsForResponse(e),this.renderSections(e),this.showAlert(e),e.data?.token&&salla.event.auth.tokenFetched(e.data.token)}fireEventsForResponse(e){let t=e.events||e.data?.events||e.error?.events;"string"==typeof t&&(t=JSON.parse(t)),t&&Object.keys(t).forEach((e=>salla.event.dispatch(e,t[e])))}renderSections(e){e.sections&&Object.keys(e.sections).forEach((t=>{document.querySelectorAll(t.toSelector()).forEach((function(r){r.innerHTML=e.sections[t]}))}))}handleErrorResponse(e){if(e.response&&e.response.data)return e.response.data.error&&e.response.data.error.fields?this.handleInvalidFields(e):this.handleAfterResponseActions(e.response.data)}showAlert(e){if(e)return e.case&&e.msg?salla.notify.fire(e.msg,e.case,e):e.hasOwnProperty("success")&&e.data?.message?salla.notify.fire(e.data?.message,e.success?salla.notify.types.success:salla.notify.types.error,e):e.error&&e.error.message&&"FORBIDDEN"!==e.error.message?salla.error(e.error.message,e):void 0}handleInvalidFields(e){let t=e.response.data.error.fields,r=[];Object.keys(t).forEach((e=>{let i=t[e];Array.isArray(i)?i.forEach((e=>r.push(e))):r.push(i)}));let i=(r.length>1?"* ":"")+r.join("\n* ");salla.error(i,e)}event(){return salla.event[this.className]}getPossibleValue(e,t,r=!1){if(!e)return;if("object"!=typeof e)return e;let i;for(let r=0;r<t.length&&!(i=e[t[r]])&&!("undefined"!=typeof FormData&&e instanceof FormData&&(i=e.get(t[r])));r++);return i=i||e,"object"!=typeof i||r?i:void 0}isFastRequestsAllowed(){return salla.config.get("fastRequests")}promise(e,t=!0){return new Promise(((r,i)=>t?r(e):i(e)))}errorPromise(e){return this.promise(e,!1)}successPromise(e){return this.promise(e,!0)}}class CartApi extends BaseApi{constructor(e){super(e),this.namespace="cart",this.endpoints={latest:"cart/latest",details:"cart/{cart}",quickAdd:"cart/{cart}/item/{product}/quick-add",addItem:"cart/{cart}/item/{product}/add",deleteItem:"cart/{cart}/item/{item}",updateItem:"cart/{cart}/item/{item}",deleteImage:"cart/{cart}/image/{image}",uploadImage:"cart/{cart}/image",status:"cart/{cart}/status",addCoupon:"cart/{id}/coupon",deleteCoupon:"cart/{id}/coupon"},this.endpointsMethods={latest:"get",details:"get",status:"get",updateItem:"post",deleteItem:"delete",deleteImage:"delete",deleteCoupon:"put"},this.webEndpoints=["latest"],this.after_init()}async getCurrentCartId(){return salla.storage.get("cart.id")||(await this.latest()).data.cart.id}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(){let e=await this.getCurrentCartId();return this.request(["details",e]).then((function(e){return salla.cart.event.detailsFetched(e),e})).catch((function(e){throw salla.cart.event.detailsNotFetched(e),e}))}async quickAdd(e){return this.addItem(e)}async addItem(e){let t=this.getCartPayload(e);if(!t.id){let e='There is no product "id"!';return salla.cart.event.itemAddedFailed(e),this.errorPromise(e)}let r=this.getPossibleValue(t.payload,["quantity","donating_amount"])?"addItem":"quickAdd",i=await this.getCurrentCartId();return this.request([r,i,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),this.errorPromise(e)}let r=await this.getCurrentCartId();return this.request(["deleteItem",r,t.id]).then((function(e){return salla.cart.event.itemDeleted(e,t.id),e})).catch((function(e){throw salla.cart.event.itemDeletedFailed(e,t.id),e}))}async updateItem(e){let t=this.getCartPayload(e);if(!t.id){let e='There is no "id"!';return salla.cart.event.itemUpdatedFailed(e),this.errorPromise(e)}let r=await this.getCurrentCartId();return"Object"===t.payload.constructor?.name?t.payload._method="PUT":t.payload.append("_method","PUT"),this.request(["updateItem",r,t.id],t.payload).then((function(e){return salla.cart.event.itemUpdated(e,t.id),e})).catch((function(e){throw salla.cart.event.itemUpdatedFailed(e,t.id),e}))}async deleteImage(e){if(!(e=this.getPossibleValue(e,["id","image_id","photo_id"]))){let e='There is no "id"!';return salla.cart.event.imageNotDeleted(e),this.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()])}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?this.getPossibleValue(t,["prod_id","product_id","item_id","id"]):e,t="object"==typeof t?t:void 0,{id:e,payload:t}}handleAfterResponseActions(e){if(403===e.status){salla.storage.remove("cart");let e=salla.lang.get("pages.checkout.try_again");throw salla.error(e),e}super.handleAfterResponseActions(e)}reset(){salla.storage.remove("cart"),salla.cart.event.successReset()}async addCoupon(e){if(e=e.data||e,!(e=this.getPossibleValue(e,["coupon"]))){let e=new Error('There is no "Coupon Code"!');return e.name="EmptyCoupon",salla.event.cart.couponAdditionFailed(e),this.errorPromise(e)}let t=await salla.cart.api.getCurrentCartId();return this.request(["addCoupon",t],{coupon:e}).then((function(e){return salla.event.cart.couponAdded(e,t),e})).catch((function(e){throw salla.event.cart.couponAdditionFailed(e,t),e}))}async deleteCoupon(){let 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}))}}class LoyaltyApi extends BaseApi{constructor(e){super(e),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=this.getPossibleValue(e,["id","loyalty_prize_id","prize_id"]))){let e="Unable to find cart id. Please provide one.";return salla.loyalty.event.exchangeFailed(e),this.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),this.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),this.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 AuthApi extends BaseApi{constructor(e){super(e),this.namespace="auth",this.canRedirect_=!0,this.endpoints={login:"auth/{type}/send_verification",resend:"auth/resend_verification",verify:"auth/{type}/verify",register:"auth/register",logout:"logout",refresh:"auth/refresh"},this.webEndpoints=["logout","auth/jwt","refresh"],this.endpointsMethods={logout:"get"},this.after_init()}setCanRedirect(e){salla.api.auth.canRedirect_=e}canRedirect(){return salla.api.auth.canRedirect_}login(e){e.data&&(e=e.data);let t=this.getPossibleValue(e,["type"]);if(!["email","mobile"].includes(t)){let e="Login type should be in: [email, mobile]";return salla.auth.event.codeNotSent(e),this.errorPromise(e)}return this.request(["login",t],e).then((function(e){return salla.auth.event.codeSent(e,t),e})).catch((function(e){throw salla.auth.event.codeNotSent(e,t),e}))}async verify(e,t=!0){let r=this.getPossibleValue(e,["type"]);if(!r){let e="Failed to know what's login type!";return salla.auth.event.verificationFailed(e),this.errorPromise(e)}t=!1!==this.getPossibleValue(e,["supportWebAuth"])&&t,salla.auth.event.next_event&&(e.next_event=salla.auth.event.next_event);let i=await this.request(["verify",r],e);return 200!==i?.status?(salla.auth.event.verificationFailed(i,r),this.errorPromise(i)):(t&&await this.request("auth/jwt"),"authenticated"===i.data?.case&&salla.auth.event.loggedIn(i),salla.auth.event.verified(i,r),this.successPromise(i))}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),this.errorPromise(t)):(salla.auth.event.codeNotSent(t="There is no phone or country_code!",e),this.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((function(e){return salla.auth.event.registered.call(t,e),"authenticated"===e.data?.case&&salla.auth.event.loggedIn(e),e})).catch((function(e){throw salla.auth.event.registrationFailed.call(t,e),e}))}logout(){return this.request("logout").then((function(e){return salla.auth.event.loggedOut(e),salla.log("Reloading after 0.1 sec..."),setTimeout((()=>location.reload()),100),e})).catch((function(e){throw salla.auth.event.failedLogout(e),e}))}refresh(){return this.request("refresh").catch((function(e){throw salla.auth.event.refreshFailed(e),e}))}}class OrderApi extends BaseApi{constructor(e){super(e),this.namespace="order",this.endpoints={cancel:"orders/cancel/{id}",createCartFromOrder:"reorder/{id}",sendInvoice:"orders/send/{id}"},this.endpointsMethods={createCartFromOrder:"get"},this.after_init()}show(e){let t=this.getPossibleValue(e?.data||e,["id","order_id"]);salla.event.dispatch("mobile::order.placed",{order_id:t}),location.href=this.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.storage.set("cart",{id:t.data.cart_id,user_id:salla.config.get("user.id")}),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=this.getPossibleValue(e,["id"])||salla.config.get("page.id");if(!t||isNaN(t)){let e="There is no id!";return salla.order.event.invoiceNotSent(e),this.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 ProductApi extends BaseApi{constructor(e){super(e),this.namespace="product",this.previousQuery="",this.endpoints={getPrice:"products/{id}/price",availabilitySubscribe:"products/{id}/availability-notify",search:"products/search",categories:"products/categories/{?id}",purchaseNow:"checkout/quick-purchase/{id}",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"},this.endpointsMethods={giftDetail:"get"},this.webEndpoints=["purchaseNow"],this.after_init()}getPrice(e){let t=e.data||e,r=this.getPossibleValue(t,["id","prod_id","product_id"]);return this.request(["getPrice",r],"object"==typeof t?t:void 0).then((function(e){return salla.product.event.priceUpdated(e,r),e})).catch((function(e){throw salla.product.event.priceUpdateFailed(e,r),e}))}categories(e){return this.request(["categories",e||""],null,"get").then((function(e){return salla.product.event.categoriesFetched(e),e})).catch((function(e){throw salla.product.event.categoriesFailed(e),e}))}availabilitySubscribe(e){let t=e.data||e;return e=this.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.availabilitySubscribedFailed(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),this.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,this.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=this.getPossibleValue(e?.data|e,["product_id","id"]))){let e='There is no "product_id"!';return salla.offer.event.fetchDetailsFailed(e),this.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.fetchFffersFailed(t,e),t}))}purchaseNow(e){if(salla.config.isGuest())return salla.auth.event.dispatch("login");let t=e.product_data,r=this.getPossibleValue(t,["id","prod_id"]);if(!e.is_applepay)return this.request(["quickPurchase",r],"object"==typeof t?t:void 0).then((function(e){return e})).catch((function(e){throw e}));salla.event.dispatch("payments::apple-pay.start-transaction",{amount:e.total,currency:e.currency,requiredShippingContactFields:e.require_shipping?["postalAddress"]:null,shippingMethods:e.require_shipping?[]:null,supportedNetworks:e.applepay_supported_networks,validateMerchant:{url:baseUrl+"checkout/applepay/validate",onFailed:({response:e})=>{console.log("validateMerchant Failed!")},onSuccess:e=>(console.log("validateMerchant Success"),this.request(["quickPurchase",r],"object"==typeof t?t:void 0))},authorized:{url:baseUrl+"/checkout/{id}/payments/submit",onFailed:e=>{console.log("authorized Failed!"),window.Salla.Payments.ApplePay.onCancel({},e.data.error.message)},onSuccess:e=>{console.log(e),window.location.href=e.redirect.url,console.log("authorized Success:: redirect to thank you page, order placed")}},shippingMethodSelected:e.require_shipping?{url:baseUrl+"/checkout/{id}/shipping/details",onFailed:e=>{console.log("select shipping method failed!")},onSuccess:e=>{console.log("select shipping method success")}}:null,shippingContactSelected:e.require_shipping?{url:baseUrl+"/checkout/{id}/address/add",onFailed:e=>{console.log("created contact failed!")},onSuccess:e=>{console.log("created contact success : ",e.data.address_id)}}:null,recalculateTotal:{url:baseUrl+"/checkout/{id}/payments/recalculate"},onError:function(e){console.log(e),salla.notify.error(e)}})}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}))}addGiftToCart(e,t,r=!1){return this.request(["giftToCart",e],t).then((t=>(salla.product.event.addGiftToCartSucceeded(t,e),r&&(window.location.href=t.redirect),response))).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}))}}class ProfileApi extends BaseApi{constructor(e){super(e),this.namespace="profile",this.endpoints={info:"auth/user",update:"profile/update",updateContacts:"profile/contacts/update",verify:"profile/verify"},this.after_init()}info(){return this.request("info",null,"get").then((e=>(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}))}}class CommentApi extends BaseApi{constructor(e){super(e),this.namespace="comment",this.endpoints={add:"{type}/{id}/comments"},this.after_init()}add(e){e?.data&&(e=e.data);let t,{id:r,type:i,comment:n}=Object.fromEntries(e);return r?i&&["products","pages","product","page"].includes(i)?n?(i+=["product","page"].includes(i)?"s":"",this.request(["add",i,r],{comment:n}).then((function(e){return salla.event.comment.added(e,r),e})).catch((function(e){throw salla.event.comment.additionFailed(e,r),e}))):(salla.event.comment.additionFailed(t="can't find comment content!"),this.errorPromise(t)):(salla.event.comment.additionFailed(t="Failed to get type one of:(products, product, page, pages)!"),this.errorPromise(t)):(salla.event.comment.additionFailed(t="Failed to get id!"),this.errorPromise(t))}}class CurrencyApi extends BaseApi{constructor(e){super(e),this.namespace="currency",this.endpoints={change:"/",list:"currencies"},this.endpointsMethods={change:"get",list:"get"},this.webEndpoints=["change"],this.after_init()}change(e){if(!(e=this.getPossibleValue(e.data||e,["currency","code"]))){let e="Can't find currency code!";return salla.currency.event.failed(e),this.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 DocumentApi extends BaseApi{constructor(e){super(e),this.namespace="document"}}class RatingApi extends BaseApi{constructor(e){super(e),this.namespace="rating",this.endpoints={store:"rating/store",products:"rating/products",shipping:"rating/shipping",order:"rating/{order_id}"},this.endpointsMethods={order:"get"},this.after_init()}order(e){let t="object"==typeof e?e:{},r=this.getPossibleValue(e?.data||e,["order_id","id"]);if(!r){let e='There is no "order_id"!';return salla.event.rating.orderNotFetched(e),this.errorPromise(e)}return this.request(["order",r],t).then((function(e){return salla.event.rating.orderFetched(e,r),e})).catch((function(e){throw salla.event.rating.orderNotFetched(e,r),e}))}store(e){if(!(e=e.data||e)){let e='There is no "data"!';return salla.event.rating.storeFailed(e),this.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),this.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),this.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 SallaInit{constructor(e){salla.config.merge(e),e?(e._token&&(salla.api.defaults.headers.common["X-CSRF-TOKEN"]=e._token),this.injectMaintenanceAlert(),this.injectThemePreviewAlert(),this.injectEditAlert(),e?.user?.language_code&&salla.lang.setLocale(e?.user?.language_code),salla.lang.loadStoreTranslations(),salla.twilight.event.initiated(e)):salla.twilight.event.initiated(e)}injectMaintenanceAlert(){salla.config.get("maintenance")&&(document.querySelector(".store-notify")?salla.logger.warn(".store-notify element Existed before!"):salla.lang.onLoaded((()=>{var e=document.createElement("div");e.classList.add("store-notify"),e.style="background-color: #d63031; color: #fff; padding: 10px 15px; text-align: center; font-size: 17px;",e.innerHTML=`<p style="margin:0 !important;">${salla.lang.get("blocks.header.maintenance_alert")}</p>`,document.body.prepend(e)})))}injectThemePreviewAlert(){"preview"===salla.config.get("theme.mode")&&(document.querySelector("#s-theme_preview_bar")?salla.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 r=t.getAjaxFormData(e),i=r.method?r.method.toLowerCase():void 0;salla.api.document.request(r.url,r.formData,i).then((e=>(e.data&&e.request&&(e=e.data),salla.api.document.handleAfterResponseActions(e),this.callAjaxEvent(r.events.success,e,r.formData),e))).catch((e=>{throw salla.api.document.handleErrorResponse(e),this.callAjaxEvent(r.events.fail,e,r.formData),e}))}callAjaxEvent(e,t,r){if(e){if(r instanceof FormData){var i={};Array.from(r.entries()).forEach((function(e){i[e[0]]=e[1]})),r=i}window[e]?window[e](t,r):salla.event.dispatch(e,t,r)}}}class TwilightApi extends BaseApi{constructor(e){super(e),this.namespace="twilight",this.after_init()}init(e){let t=e?.events;return salla.isInitiated||(delete e.events,new SallaInit(e),salla.isInitiated=!0),t&&salla.event.dispatchEvents(t),this.successPromise(e)}api(e){let t=e?.events;return t&&salla.event.dispatchEvents(t),this.successPromise(e)}}class WishlistApi extends BaseApi{constructor(e){super(e),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),this.errorPromise(t)):(e=this.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!"),this.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),this.errorPromise(t)):(e=this.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!"),this.errorPromise(t))}updateWishlistStorage(e,t=!0){let r=salla.storage.get("salla::wishlist",[]);t?r.push(e):r.splice(r.indexOf(e),1),salla.storage.set("salla::wishlist",r)}}class ScopeApi extends BaseApi{constructor(e){super(e),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),resp}))}}function e(e){this.message=e}e.prototype=new Error,e.prototype.name="InvalidCharacterError";var r="undefined"!=typeof window&&window.atob&&window.atob.bind(window)||function(t){var r=String(t).replace(/=+$/,"");if(r.length%4==1)throw new e("'atob' failed: The string to be decoded is not correctly encoded.");for(var i,n,a=0,s=0,o="";n=r.charAt(s++);~n&&(i=a%4?64*i+n:n,a++%4)?o+=String.fromCharCode(255&i>>(-2*a&6)):0)n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(n);return o};function t(e){var t=e.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw"Illegal base64url string!"}try{return function(e){return decodeURIComponent(r(e).replace(/(.)/g,(function(e,t){var r=t.charCodeAt(0).toString(16).toUpperCase();return r.length<2&&(r="0"+r),"%"+r})))}(t)}catch(e){return r(t)}}function n(e){this.message=e}function o(e,r){if("string"!=typeof e)throw new n("Invalid token specified");var i=!0===(r=r||{}).header?0:1;try{return JSON.parse(t(e.split(".")[i]))}catch(e){throw new n("Invalid token specified: "+e.message)}}n.prototype=new Error,n.prototype.name="InvalidTokenError";const axios=require("axios");class sallaRequest{constructor(e){return e.on("twilight::initiated",(()=>this.initiateRequest())),e.on("profile::info.fetched",this.setCurrencyAndLanguage),e.on("auth::token.fetched",(e=>this.handleToken(e))),e.on("document::request.failed",((e,t)=>{salla.logger.warn(t,e)})),axios.create({headers:{common:{"X-Requested-With":"XMLHttpRequest","S-SOURCE":"twilight","S-APP-VERSION":"v2.0.0","S-APP-OS":"browser"}}})}initiateRequest(){salla.api.defaults.baseURL=salla.config.get("store.api",salla.config.get("store.url")),salla.api.defaults.headers.common["Store-Identifier"]=salla.config.get("store.id"),salla.api.defaults.headers.common.currency=salla.config.get("user.currency_code","SAR"),salla.infiniteScroll.fetchOptions.headers["Accept-Language"]=salla.api.defaults.headers.common["accept-language"]=salla.lang.getLocale(),salla.api.defaults.headers.common["s-user-id"]=salla.config.get("user.id"),salla.api.defaults.headers.common["s-scope"]=salla.storage.get("scope"),this.injectTokenToTheRequests()}injectTokenToTheRequests(){let e=salla.storage.get("token"),t=salla.config.isGuest(),r=salla.storage.get("cart");if(r&&(r.user_id!==salla.config.get("user.id")||r.store_id!==salla.config.get("store.id")))return salla.log("Auth:: The cart is not belong to current "+(r.user_id!==salla.config.get("user.id")?"user":"store")+"!"),void salla.cart.api.reset();if(t&&!e)return;if(t&&e)return salla.log("Auth:: Token without user!"),salla.storage.remove("token"),void salla.cart.api.reset();if(!e)return salla.cart.api.reset(),void salla.auth.api.refresh();let i=o(e);return Date.now()/1e3>i.exp?(salla.log("Auth:: An expired token!"),salla.storage.remove("token"),salla.cart.api.reset(),void salla.auth.api.refresh()):i.sub!==salla.config.get("user.id")?(salla.log("Auth:: The user id is not match the token details!"),salla.storage.remove("token"),salla.cart.api.reset(),void salla.auth.api.refresh()):void this.setToken(e)}handleToken(e){salla.storage.set("token",e),this.setToken(e),salla.cart.api.reset()}setToken(e){salla.api.defaults.headers.common.Authorization="Bearer "+e}setCurrencyAndLanguage(e){salla.api.defaults.headers.common.currency=e.data.currency,salla.api.defaults.headers.common["accept-language"]=e.data.language,salla.infiniteScroll.fetchOptions.headers["Accept-Language"]=e.data.language}}class SallaApi extends sallaRequest{constructor(e){super(e),this.apis={auth:new AuthApi(this),cart:new CartApi(this),loyalty:new LoyaltyApi(this),order:new OrderApi(this),rating:new RatingApi(this),product:new ProductApi(this),profile:new ProfileApi(this),comment:new CommentApi(this),currency:new CurrencyApi(this),document:new DocumentApi(this),twilight:new TwilightApi(this),wishlist:new WishlistApi(this),scope:new ScopeApi(this)},Object.assign(this,this.apis),this.getHeaders=()=>this.defaults.headers.common}}class Action{constructor(e,t){return this.api=e,this.event=t,new Proxy(this,{get:function(r,i){return"event"===i?t:"api"===i&&"twilight"!==e?.namespace?e:e&&e[i]||r[i]}})}}var version={build:6,date:"9/4/2022, 3:58:15 PM",package_version:"2.6.20"},js={exports:{}},core={exports:{}},evEmitter={exports:{}},hasRequiredEvEmitter;function requireEvEmitter(){return hasRequiredEvEmitter||(hasRequiredEvEmitter=1,function(e){!function(t,r){e.exports?e.exports=r():t.EvEmitter=r()}("undefined"!=typeof window?window:commonjsGlobal,(function(){function e(){}let t=e.prototype;return t.on=function(e,t){if(!e||!t)return this;let r=this._events=this._events||{},i=r[e]=r[e]||[];return i.includes(t)||i.push(t),this},t.once=function(e,t){if(!e||!t)return this;this.on(e,t);let r=this._onceEvents=this._onceEvents||{};return(r[e]=r[e]||{})[t]=!0,this},t.off=function(e,t){let r=this._events&&this._events[e];if(!r||!r.length)return this;let i=r.indexOf(t);return-1!=i&&r.splice(i,1),this},t.emitEvent=function(e,t){let r=this._events&&this._events[e];if(!r||!r.length)return this;r=r.slice(0),t=t||[];let i=this._onceEvents&&this._onceEvents[e];for(let n of r){i&&i[n]&&(this.off(e,n),delete i[n]),n.apply(this,t)}return this},t.allOff=function(){return delete this._events,delete this._onceEvents,this},e}))}(evEmitter)),evEmitter.exports}var utils={exports:{}},hasRequiredUtils,hasRequiredCore;function requireUtils(){return hasRequiredUtils||(hasRequiredUtils=1,function(e){!function(t,r){e.exports?e.exports=r(t):t.fizzyUIUtils=r(t)}(commonjsGlobal,(function(e){let t={extend:function(e,t){return Object.assign(e,t)},modulo:function(e,t){return(e%t+t)%t},makeArray:function(e){if(Array.isArray(e))return e;if(null==e)return[];return"object"==typeof e&&"number"==typeof e.length?[...e]:[e]},removeFrom:function(e,t){let r=e.indexOf(t);-1!=r&&e.splice(r,1)},getParent:function(e,t){for(;e.parentNode&&e!=document.body;)if((e=e.parentNode).matches(t))return e},getQueryElement:function(e){return"string"==typeof e?document.querySelector(e):e},handleEvent:function(e){let t="on"+e.type;this[t]&&this[t](e)},filterFindElements:function(e,r){return(e=t.makeArray(e)).filter((e=>e instanceof HTMLElement)).reduce(((e,t)=>{if(!r)return e.push(t),e;t.matches(r)&&e.push(t);let i=t.querySelectorAll(r);return e=e.concat(...i)}),[])},debounceMethod:function(e,t,r){r=r||100;let i=e.prototype[t],n=t+"Timeout";e.prototype[t]=function(){clearTimeout(this[n]);let e=arguments;this[n]=setTimeout((()=>{i.apply(this,e),delete this[n]}),r)}},docReady:function(e){let t=document.readyState;"complete"==t||"interactive"==t?setTimeout(e):document.addEventListener("DOMContentLoaded",e)},toDashed:function(e){return e.replace(/(.)([A-Z])/g,(function(e,t,r){return t+"-"+r})).toLowerCase()}},r=e.console;return t.htmlInit=function(i,n){t.docReady((function(){let a="data-"+t.toDashed(n),s=document.querySelectorAll(`[${a}]`),o=e.jQuery;[...s].forEach((e=>{let t,s=e.getAttribute(a);try{t=s&&JSON.parse(s)}catch(t){return void(r&&r.error(`Error parsing ${a} on ${e.className}: ${t}`))}let l=new i(e,t);o&&o.data(e,n,l)}))}))},t}))}(utils)),utils.exports}function requireCore(){return hasRequiredCore||(hasRequiredCore=1,function(e){!function(t,r){e.exports?e.exports=r(t,requireEvEmitter(),requireUtils()):t.InfiniteScroll=r(t,t.EvEmitter,t.fizzyUIUtils)}(window,(function(e,t,r){let i=e.jQuery,n={};function a(e,t){let s=r.getQueryElement(e);if(s){if((e=s).infiniteScrollGUID){let r=n[e.infiniteScrollGUID];return r.option(t),r}this.element=e,this.options={...a.defaults},this.option(t),i&&(this.$element=i(this.element)),this.create()}else console.error("Bad element for InfiniteScroll: "+(s||e))}a.defaults={},a.create={},a.destroy={};let s=a.prototype;Object.assign(s,t.prototype);let o=0;s.create=function(){let e=this.guid=++o;if(this.element.infiniteScrollGUID=e,n[e]=this,this.pageIndex=1,this.loadCount=0,this.updateGetPath(),this.getPath&&this.getPath()){this.updateGetAbsolutePath(),this.log("initialized",[this.element.className]),this.callOnInit();for(let e in a.create)a.create[e].call(this)}else console.error("Disabling InfiniteScroll")},s.option=function(e){Object.assign(this.options,e)},s.callOnInit=function(){let e=this.options.onInit;e&&e.call(this,this)},s.dispatchEvent=function(e,t,r){this.log(e,r);let n=t?[t].concat(r):r;if(this.emitEvent(e,n),!i||!this.$element)return;let a=e+=".infiniteScroll";if(t){let r=i.Event(t);r.type=e,a=r}this.$element.trigger(a,r)};let l={initialized:e=>`on ${e}`,request:e=>`URL: ${e}`,load:(e,t)=>`${e.title||""}. URL: ${t}`,error:(e,t)=>`${e}. URL: ${t}`,append:(e,t,r)=>`${r.length} items. URL: ${t}`,last:(e,t)=>`URL: ${t}`,history:(e,t)=>`URL: ${t}`,pageIndex:function(e,t){return`current page determined to be: ${e} from ${t}`}};s.log=function(e,t){if(!this.options.debug)return;let r=`[InfiniteScroll] ${e}`,i=l[e];i&&(r+=". "+i.apply(this,t)),console.log(r)},s.updateMeasurements=function(){this.windowHeight=e.innerHeight;let t=this.element.getBoundingClientRect();this.top=t.top+e.scrollY},s.updateScroller=function(){let t=this.options.elementScroll;if(t){if(this.scroller=!0===t?this.element:r.getQueryElement(t),!this.scroller)throw new Error(`Unable to find elementScroll: ${t}`)}else this.scroller=e},s.updateGetPath=function(){let e=this.options.path;if(!e)return void console.error(`InfiniteScroll path option required. Set as: ${e}`);let t=typeof e;"function"!=t?"string"==t&&e.match("{{#}}")?this.updateGetPathTemplate(e):this.updateGetPathSelector(e):this.getPath=e},s.updateGetPathTemplate=function(e){this.getPath=()=>{let t=this.pageIndex+1;return e.replace("{{#}}",t)};let t=e.replace(/(\\\?|\?)/,"\\?").replace("{{#}}","(\\d\\d?\\d?)"),r=new RegExp(t),i=location.href.match(r);i&&(this.pageIndex=parseInt(i[1],10),this.log("pageIndex",[this.pageIndex,"template string"]))};let c=[/^(.*?\/?page\/?)(\d\d?\d?)(.*?$)/,/^(.*?\/?\?page=)(\d\d?\d?)(.*?$)/,/(.*?)(\d\d?\d?)(?!.*\d)(.*?$)/],u=a.getPathParts=function(e){if(e)for(let t of c){let r=e.match(t);if(r){let[,e,t,i]=r;return{begin:e,index:t,end:i}}}};s.updateGetPathSelector=function(e){let t=document.querySelector(e);if(!t)return void console.error(`Bad InfiniteScroll path option. Next link not found: ${e}`);let r=t.getAttribute("href"),i=u(r);if(!i)return void console.error(`InfiniteScroll unable to parse next link href: ${r}`);let{begin:n,index:a,end:s}=i;this.isPathSelector=!0,this.getPath=()=>n+(this.pageIndex+1)+s,this.pageIndex=parseInt(a,10)-1,this.log("pageIndex",[this.pageIndex,"next link"])},s.updateGetAbsolutePath=function(){let e=this.getPath();if(e.match(/^http/)||e.match(/^\//))return void(this.getAbsolutePath=this.getPath);let{pathname:t}=location,r=e.match(/^\?/),i=t.substring(0,t.lastIndexOf("/")),n=r?t:i+"/";this.getAbsolutePath=()=>n+this.getPath()},a.create.hideNav=function(){let e=r.getQueryElement(this.options.hideNav);e&&(e.style.display="none",this.nav=e)},a.destroy.hideNav=function(){this.nav&&(this.nav.style.display="")},s.destroy=function(){this.allOff();for(let e in a.destroy)a.destroy[e].call(this);delete this.element.infiniteScrollGUID,delete n[this.guid],i&&this.$element&&i.removeData(this.element,"infiniteScroll")},a.throttle=function(e,t){let r,i;return t=t||200,function(){let n=+new Date,a=arguments,s=()=>{r=n,e.apply(this,a)};r&&n<r+t?(clearTimeout(i),i=setTimeout(s,t)):s()}},a.data=function(e){let t=(e=r.getQueryElement(e))&&e.infiniteScrollGUID;return t&&n[t]},a.setJQuery=function(e){i=e},r.htmlInit(a,"infinite-scroll"),s._init=function(){};let{jQueryBridget:h}=e;return i&&h&&h("infiniteScroll",a,i),a}))}(core)),core.exports}var pageLoad={exports:{}},hasRequiredPageLoad;function requirePageLoad(){return hasRequiredPageLoad||(hasRequiredPageLoad=1,function(e){!function(t,r){e.exports?e.exports=r(t,requireCore()):r(t,t.InfiniteScroll)}(window,(function(e,t){let r=t.prototype;Object.assign(t.defaults,{loadOnScroll:!0,checkLastPage:!0,responseBody:"text",domParseResponse:!0}),t.create.pageLoad=function(){this.canLoad=!0,this.on("scrollThreshold",this.onScrollThresholdLoad),this.on("load",this.checkLastPage),this.options.outlayer&&this.on("append",this.onAppendOutlayer)},r.onScrollThresholdLoad=function(){this.options.loadOnScroll&&this.loadNextPage()};let i=new DOMParser;function n(e){let t=document.createDocumentFragment();return e&&t.append(...e),t}return r.loadNextPage=function(){if(this.isLoading||!this.canLoad)return;let{responseBody:e,domParseResponse:t,fetchOptions:r}=this.options,n=this.getAbsolutePath();this.isLoading=!0,"function"==typeof r&&(r=r());let a=fetch(n,r).then((r=>{if(!r.ok){let e=new Error(r.statusText);return this.onPageError(e,n,r),{response:r}}return r[e]().then((a=>("text"==e&&t&&(a=i.parseFromString(a,"text/html")),204==r.status?(this.lastPageReached(a,n),{body:a,response:r}):this.onPageLoad(a,n,r))))})).catch((e=>{this.onPageError(e,n)}));return this.dispatchEvent("request",null,[n,a]),a},r.onPageLoad=function(e,t,r){return this.options.append||(this.isLoading=!1),this.pageIndex++,this.loadCount++,this.dispatchEvent("load",null,[e,t,r]),this.appendNextPage(e,t,r)},r.appendNextPage=function(e,t,r){let{append:i,responseBody:a,domParseResponse:s}=this.options;if(!("text"==a&&s)||!i)return{body:e,response:r};let o=e.querySelectorAll(i),l={body:e,response:r,items:o};if(!o||!o.length)return this.lastPageReached(e,t),l;let c=n(o),u=()=>(this.appendItems(o,c),this.isLoading=!1,this.dispatchEvent("append",null,[e,t,o,r]),l);return this.options.outlayer?this.appendOutlayerItems(c,u):u()},r.appendItems=function(e,t){e&&e.length&&(function(e){let t=e.querySelectorAll("script");for(let e of t){let t=document.createElement("script"),r=e.attributes;for(let e of r)t.setAttribute(e.name,e.value);t.innerHTML=e.innerHTML,e.parentNode.replaceChild(t,e)}}(t=t||n(e)),this.element.appendChild(t))},r.appendOutlayerItems=function(r,i){let n=t.imagesLoaded||e.imagesLoaded;return n?new Promise((function(e){n(r,(function(){let t=i();e(t)}))})):(console.error("[InfiniteScroll] imagesLoaded required for outlayer option"),void(this.isLoading=!1))},r.onAppendOutlayer=function(e,t,r){this.options.outlayer.appended(r)},r.checkLastPage=function(e,t){let r,{checkLastPage:i,path:n}=this.options;if(i){if("function"==typeof n){if(!this.getPath())return void this.lastPageReached(e,t)}"string"==typeof i?r=i:this.isPathSelector&&(r=n),r&&e.querySelector&&(e.querySelector(r)||this.lastPageReached(e,t))}},r.lastPageReached=function(e,t){this.canLoad=!1,this.dispatchEvent("last",null,[e,t])},r.onPageError=function(e,t,r){return this.isLoading=!1,this.canLoad=!1,this.dispatchEvent("error",null,[e,t,r]),e},t.create.prefill=function(){if(!this.options.prefill)return;let e=this.options.append;e?(this.updateMeasurements(),this.updateScroller(),this.isPrefilling=!0,this.on("append",this.prefill),this.once("error",this.stopPrefill),this.once("last",this.stopPrefill),this.prefill()):console.error(`append option required for prefill. Set as :${e}`)},r.prefill=function(){let e=this.getPrefillDistance();this.isPrefilling=e>=0,this.isPrefilling?(this.log("prefill"),this.loadNextPage()):this.stopPrefill()},r.getPrefillDistance=function(){return this.options.elementScroll?this.scroller.clientHeight-this.scroller.scrollHeight:this.windowHeight-this.element.clientHeight},r.stopPrefill=function(){this.log("stopPrefill"),this.off("append",this.prefill)},t}))}(pageLoad)),pageLoad.exports}var scrollWatch={exports:{}},hasRequiredScrollWatch;function requireScrollWatch(){return hasRequiredScrollWatch||(hasRequiredScrollWatch=1,function(e){!function(t,r){e.exports?e.exports=r(t,requireCore(),requireUtils()):r(t,t.InfiniteScroll,t.fizzyUIUtils)}(window,(function(e,t,r){let i=t.prototype;return Object.assign(t.defaults,{scrollThreshold:400}),t.create.scrollWatch=function(){this.pageScrollHandler=this.onPageScroll.bind(this),this.resizeHandler=this.onResize.bind(this);let e=this.options.scrollThreshold;(e||0===e)&&this.enableScrollWatch()},t.destroy.scrollWatch=function(){this.disableScrollWatch()},i.enableScrollWatch=function(){this.isScrollWatching||(this.isScrollWatching=!0,this.updateMeasurements(),this.updateScroller(),this.on("last",this.disableScrollWatch),this.bindScrollWatchEvents(!0))},i.disableScrollWatch=function(){this.isScrollWatching&&(this.bindScrollWatchEvents(!1),delete this.isScrollWatching)},i.bindScrollWatchEvents=function(t){let r=t?"addEventListener":"removeEventListener";this.scroller[r]("scroll",this.pageScrollHandler),e[r]("resize",this.resizeHandler)},i.onPageScroll=t.throttle((function(){this.getBottomDistance()<=this.options.scrollThreshold&&this.dispatchEvent("scrollThreshold")})),i.getBottomDistance=function(){let t,r;return this.options.elementScroll?(t=this.scroller.scrollHeight,r=this.scroller.scrollTop+this.scroller.clientHeight):(t=this.top+this.element.clientHeight,r=e.scrollY+this.windowHeight),t-r},i.onResize=function(){this.updateMeasurements()},r.debounceMethod(t,"onResize",150),t}))}(scrollWatch)),scrollWatch.exports}var history$1={exports:{}},hasRequiredHistory;function requireHistory(){return hasRequiredHistory||(hasRequiredHistory=1,function(e){!function(t,r){e.exports?e.exports=r(t,requireCore(),requireUtils()):r(t,t.InfiniteScroll,t.fizzyUIUtils)}(window,(function(e,t,r){let i=t.prototype;Object.assign(t.defaults,{history:"replace"});let n=document.createElement("a");return t.create.history=function(){if(!this.options.history)return;n.href=this.getAbsolutePath(),(n.origin||n.protocol+"//"+n.host)==location.origin?this.options.append?this.createHistoryAppend():this.createHistoryPageLoad():console.error(`[InfiniteScroll] cannot set history with different origin: ${n.origin} on ${location.origin} . History behavior disabled.`)},i.createHistoryAppend=function(){this.updateMeasurements(),this.updateScroller(),this.scrollPages=[{top:0,path:location.href,title:document.title}],this.scrollPage=this.scrollPages[0],this.scrollHistoryHandler=this.onScrollHistory.bind(this),this.unloadHandler=this.onUnload.bind(this),this.scroller.addEventListener("scroll",this.scrollHistoryHandler),this.on("append",this.onAppendHistory),this.bindHistoryAppendEvents(!0)},i.bindHistoryAppendEvents=function(t){let r=t?"addEventListener":"removeEventListener";this.scroller[r]("scroll",this.scrollHistoryHandler),e[r]("unload",this.unloadHandler)},i.createHistoryPageLoad=function(){this.on("load",this.onPageLoadHistory)},t.destroy.history=i.destroyHistory=function(){this.options.history&&this.options.append&&this.bindHistoryAppendEvents(!1)},i.onAppendHistory=function(e,t,r){if(!r||!r.length)return;let i=r[0],a=this.getElementScrollY(i);n.href=t,this.scrollPages.push({top:a,path:n.href,title:e.title})},i.getElementScrollY=function(t){if(this.options.elementScroll)return t.offsetTop-this.top;return t.getBoundingClientRect().top+e.scrollY},i.onScrollHistory=function(){let e=this.getClosestScrollPage();e!=this.scrollPage&&(this.scrollPage=e,this.setHistory(e.title,e.path))},r.debounceMethod(t,"onScrollHistory",150),i.getClosestScrollPage=function(){let t,r;t=this.options.elementScroll?this.scroller.scrollTop+this.scroller.clientHeight/2:e.scrollY+this.windowHeight/2;for(let e of this.scrollPages){if(e.top>=t)break;r=e}return r},i.setHistory=function(e,t){let r=this.options.history;r&&history[r+"State"]&&(history[r+"State"](null,e,t),this.options.historyTitle&&(document.title=e),this.dispatchEvent("history",null,[e,t]))},i.onUnload=function(){if(0===this.scrollPage.top)return;let t=e.scrollY-this.scrollPage.top+this.top;this.destroyHistory(),scrollTo(0,t)},i.onPageLoadHistory=function(e,t){this.setHistory(e.title,t)},t}))}(history$1)),history$1.exports}var button={exports:{}},hasRequiredButton;function requireButton(){return hasRequiredButton||(hasRequiredButton=1,function(e){!function(t,r){e.exports?e.exports=r(t,requireCore(),requireUtils()):r(t,t.InfiniteScroll,t.fizzyUIUtils)}(window,(function(e,t,r){class i{constructor(e,t){this.element=e,this.infScroll=t,this.clickHandler=this.onClick.bind(this),this.element.addEventListener("click",this.clickHandler),t.on("request",this.disable.bind(this)),t.on("load",this.enable.bind(this)),t.on("error",this.hide.bind(this)),t.on("last",this.hide.bind(this))}onClick(e){e.preventDefault(),this.infScroll.loadNextPage()}enable(){this.element.removeAttribute("disabled")}disable(){this.element.disabled="disabled"}hide(){this.element.style.display="none"}destroy(){this.element.removeEventListener("click",this.clickHandler)}}return t.create.button=function(){let e=r.getQueryElement(this.options.button);e&&(this.button=new i(e,this))},t.destroy.button=function(){this.button&&this.button.destroy()},t.Button=i,t}))}(button)),button.exports}var status={exports:{}},hasRequiredStatus;function requireStatus(){return hasRequiredStatus||(hasRequiredStatus=1,function(e){!function(t,r){e.exports?e.exports=r(t,requireCore(),requireUtils()):r(t,t.InfiniteScroll,t.fizzyUIUtils)}(window,(function(e,t,r){let i=t.prototype;function n(e){s(e,"none")}function a(e){s(e,"block")}function s(e,t){e&&(e.style.display=t)}return t.create.status=function(){let e=r.getQueryElement(this.options.status);e&&(this.statusElement=e,this.statusEventElements={request:e.querySelector(".infinite-scroll-request"),error:e.querySelector(".infinite-scroll-error"),last:e.querySelector(".infinite-scroll-last")},this.on("request",this.showRequestStatus),this.on("error",this.showErrorStatus),this.on("last",this.showLastStatus),this.bindHideStatus("on"))},i.bindHideStatus=function(e){let t=this.options.append?"append":"load";this[e](t,this.hideAllStatus)},i.showRequestStatus=function(){this.showStatus("request")},i.showErrorStatus=function(){this.showStatus("error")},i.showLastStatus=function(){this.showStatus("last"),this.bindHideStatus("off")},i.showStatus=function(e){a(this.statusElement),this.hideStatusEventElements(),a(this.statusEventElements[e])},i.hideAllStatus=function(){n(this.statusElement),this.hideStatusEventElements()},i.hideStatusEventElements=function(){for(let e in this.statusEventElements){n(this.statusEventElements[e])}},t}))}(status)),status.exports}
10
10
  /*!
11
11
  * Infinite Scroll v4.0.1
12
12
  * Automatically add next page