@salla.sa/twilight-components 2.11.21 → 2.11.23

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.
@@ -3,6 +3,232 @@
3
3
  */
4
4
  import { c as commonjsGlobal, a as createCommonjsModule } from './_commonjsHelpers-1415ffd3.js';
5
5
 
6
+ const global$1 = (typeof global !== "undefined" ? global :
7
+ typeof self !== "undefined" ? self :
8
+ typeof window !== "undefined" ? window : {});
9
+
10
+ // shim for using process in browser
11
+ // based off https://github.com/defunctzombie/node-process/blob/master/browser.js
12
+
13
+ function defaultSetTimout() {
14
+ throw new Error('setTimeout has not been defined');
15
+ }
16
+ function defaultClearTimeout () {
17
+ throw new Error('clearTimeout has not been defined');
18
+ }
19
+ var cachedSetTimeout = defaultSetTimout;
20
+ var cachedClearTimeout = defaultClearTimeout;
21
+ if (typeof global$1.setTimeout === 'function') {
22
+ cachedSetTimeout = setTimeout;
23
+ }
24
+ if (typeof global$1.clearTimeout === 'function') {
25
+ cachedClearTimeout = clearTimeout;
26
+ }
27
+
28
+ function runTimeout(fun) {
29
+ if (cachedSetTimeout === setTimeout) {
30
+ //normal enviroments in sane situations
31
+ return setTimeout(fun, 0);
32
+ }
33
+ // if setTimeout wasn't available but was latter defined
34
+ if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
35
+ cachedSetTimeout = setTimeout;
36
+ return setTimeout(fun, 0);
37
+ }
38
+ try {
39
+ // when when somebody has screwed with setTimeout but no I.E. maddness
40
+ return cachedSetTimeout(fun, 0);
41
+ } catch(e){
42
+ try {
43
+ // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
44
+ return cachedSetTimeout.call(null, fun, 0);
45
+ } catch(e){
46
+ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
47
+ return cachedSetTimeout.call(this, fun, 0);
48
+ }
49
+ }
50
+
51
+
52
+ }
53
+ function runClearTimeout(marker) {
54
+ if (cachedClearTimeout === clearTimeout) {
55
+ //normal enviroments in sane situations
56
+ return clearTimeout(marker);
57
+ }
58
+ // if clearTimeout wasn't available but was latter defined
59
+ if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
60
+ cachedClearTimeout = clearTimeout;
61
+ return clearTimeout(marker);
62
+ }
63
+ try {
64
+ // when when somebody has screwed with setTimeout but no I.E. maddness
65
+ return cachedClearTimeout(marker);
66
+ } catch (e){
67
+ try {
68
+ // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
69
+ return cachedClearTimeout.call(null, marker);
70
+ } catch (e){
71
+ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
72
+ // Some versions of I.E. have different rules for clearTimeout vs setTimeout
73
+ return cachedClearTimeout.call(this, marker);
74
+ }
75
+ }
76
+
77
+
78
+
79
+ }
80
+ var queue = [];
81
+ var draining = false;
82
+ var currentQueue;
83
+ var queueIndex = -1;
84
+
85
+ function cleanUpNextTick() {
86
+ if (!draining || !currentQueue) {
87
+ return;
88
+ }
89
+ draining = false;
90
+ if (currentQueue.length) {
91
+ queue = currentQueue.concat(queue);
92
+ } else {
93
+ queueIndex = -1;
94
+ }
95
+ if (queue.length) {
96
+ drainQueue();
97
+ }
98
+ }
99
+
100
+ function drainQueue() {
101
+ if (draining) {
102
+ return;
103
+ }
104
+ var timeout = runTimeout(cleanUpNextTick);
105
+ draining = true;
106
+
107
+ var len = queue.length;
108
+ while(len) {
109
+ currentQueue = queue;
110
+ queue = [];
111
+ while (++queueIndex < len) {
112
+ if (currentQueue) {
113
+ currentQueue[queueIndex].run();
114
+ }
115
+ }
116
+ queueIndex = -1;
117
+ len = queue.length;
118
+ }
119
+ currentQueue = null;
120
+ draining = false;
121
+ runClearTimeout(timeout);
122
+ }
123
+ function nextTick(fun) {
124
+ var args = new Array(arguments.length - 1);
125
+ if (arguments.length > 1) {
126
+ for (var i = 1; i < arguments.length; i++) {
127
+ args[i - 1] = arguments[i];
128
+ }
129
+ }
130
+ queue.push(new Item(fun, args));
131
+ if (queue.length === 1 && !draining) {
132
+ runTimeout(drainQueue);
133
+ }
134
+ }
135
+ // v8 likes predictible objects
136
+ function Item(fun, array) {
137
+ this.fun = fun;
138
+ this.array = array;
139
+ }
140
+ Item.prototype.run = function () {
141
+ this.fun.apply(null, this.array);
142
+ };
143
+ var title = 'browser';
144
+ var platform = 'browser';
145
+ var browser = true;
146
+ var env = {};
147
+ var argv = [];
148
+ var version = ''; // empty string to avoid regexp issues
149
+ var versions = {};
150
+ var release = {};
151
+ var config = {};
152
+
153
+ function noop() {}
154
+
155
+ var on = noop;
156
+ var addListener = noop;
157
+ var once = noop;
158
+ var off = noop;
159
+ var removeListener = noop;
160
+ var removeAllListeners = noop;
161
+ var emit = noop;
162
+
163
+ function binding(name) {
164
+ throw new Error('process.binding is not supported');
165
+ }
166
+
167
+ function cwd () { return '/' }
168
+ function chdir (dir) {
169
+ throw new Error('process.chdir is not supported');
170
+ }function umask() { return 0; }
171
+
172
+ // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js
173
+ var performance = global$1.performance || {};
174
+ var performanceNow =
175
+ performance.now ||
176
+ performance.mozNow ||
177
+ performance.msNow ||
178
+ performance.oNow ||
179
+ performance.webkitNow ||
180
+ function(){ return (new Date()).getTime() };
181
+
182
+ // generate timestamp or delta
183
+ // see http://nodejs.org/api/process.html#process_process_hrtime
184
+ function hrtime(previousTimestamp){
185
+ var clocktime = performanceNow.call(performance)*1e-3;
186
+ var seconds = Math.floor(clocktime);
187
+ var nanoseconds = Math.floor((clocktime%1)*1e9);
188
+ if (previousTimestamp) {
189
+ seconds = seconds - previousTimestamp[0];
190
+ nanoseconds = nanoseconds - previousTimestamp[1];
191
+ if (nanoseconds<0) {
192
+ seconds--;
193
+ nanoseconds += 1e9;
194
+ }
195
+ }
196
+ return [seconds,nanoseconds]
197
+ }
198
+
199
+ var startTime = new Date();
200
+ function uptime() {
201
+ var currentTime = new Date();
202
+ var dif = currentTime - startTime;
203
+ return dif / 1000;
204
+ }
205
+
206
+ var browser$1 = {
207
+ nextTick: nextTick,
208
+ title: title,
209
+ browser: browser,
210
+ env: env,
211
+ argv: argv,
212
+ version: version,
213
+ versions: versions,
214
+ on: on,
215
+ addListener: addListener,
216
+ once: once,
217
+ off: off,
218
+ removeListener: removeListener,
219
+ removeAllListeners: removeAllListeners,
220
+ emit: emit,
221
+ binding: binding,
222
+ cwd: cwd,
223
+ chdir: chdir,
224
+ umask: umask,
225
+ hrtime: hrtime,
226
+ platform: platform,
227
+ release: release,
228
+ config: config,
229
+ uptime: uptime
230
+ };
231
+
6
232
  /**
7
233
  * Checks if `value` is classified as an `Array` object.
8
234
  *
@@ -26,9 +252,9 @@ import { c as commonjsGlobal, a as createCommonjsModule } from './_commonjsHelpe
26
252
  * _.isArray(_.noop);
27
253
  * // => false
28
254
  */
29
- var isArray$1 = Array.isArray;
255
+ var isArray$2 = Array.isArray;
30
256
 
31
- var isArray_1 = isArray$1;
257
+ var isArray_1 = isArray$2;
32
258
 
33
259
  /** Detect free variable `global` from Node.js. */
34
260
  var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal;
@@ -1093,11 +1319,11 @@ var _baseToString = baseToString;
1093
1319
  * _.toString([1, 2, 3]);
1094
1320
  * // => '1,2,3'
1095
1321
  */
1096
- function toString$1(value) {
1322
+ function toString$2(value) {
1097
1323
  return value == null ? '' : _baseToString(value);
1098
1324
  }
1099
1325
 
1100
- var toString_1 = toString$1;
1326
+ var toString_1 = toString$2;
1101
1327
 
1102
1328
  /**
1103
1329
  * Casts `value` to a path array if it's not one.
@@ -1197,7 +1423,7 @@ var eventemitter2 = createCommonjsModule(function (module, exports) {
1197
1423
  return Object.prototype.toString.call(obj) === "[object Array]";
1198
1424
  };
1199
1425
  var defaultMaxListeners = 10;
1200
- var nextTickSupported= typeof process=='object' && typeof process.nextTick=='function';
1426
+ var nextTickSupported= typeof browser$1=='object' && typeof browser$1.nextTick=='function';
1201
1427
  var symbolsSupported= typeof Symbol==='function';
1202
1428
  var reflectSupported= typeof Reflect === 'object';
1203
1429
  var setImmediateSupported= typeof setImmediate === 'function';
@@ -1246,12 +1472,12 @@ var eventemitter2 = createCommonjsModule(function (module, exports) {
1246
1472
  errorMsg += ' Event name: ' + eventName + '.';
1247
1473
  }
1248
1474
 
1249
- if(typeof process !== 'undefined' && process.emitWarning){
1475
+ if(typeof browser$1 !== 'undefined' && browser$1.emitWarning){
1250
1476
  var e = new Error(errorMsg);
1251
1477
  e.name = 'MaxListenersExceededWarning';
1252
1478
  e.emitter = this;
1253
1479
  e.count = count;
1254
- process.emitWarning(e);
1480
+ browser$1.emitWarning(e);
1255
1481
  } else {
1256
1482
  console.error(errorMsg);
1257
1483
 
@@ -1957,7 +2183,7 @@ var eventemitter2 = createCommonjsModule(function (module, exports) {
1957
2183
  }).then(function () {
1958
2184
  context.event = event;
1959
2185
  return _listener.apply(context, args)
1960
- })) : (nextTick ? process.nextTick : _setImmediate)(function () {
2186
+ })) : (nextTick ? browser$1.nextTick : _setImmediate)(function () {
1961
2187
  context.event = event;
1962
2188
  _listener.apply(context, args);
1963
2189
  });
@@ -3170,8 +3396,8 @@ var Global$2 = util.Global;
3170
3396
 
3171
3397
  var localStorage_1 = {
3172
3398
  name: 'localStorage',
3173
- read: read$3,
3174
- write: write$3,
3399
+ read: read$4,
3400
+ write: write$4,
3175
3401
  each: each$3,
3176
3402
  remove: remove$3,
3177
3403
  clearAll: clearAll$3,
@@ -3181,18 +3407,18 @@ function localStorage() {
3181
3407
  return Global$2.localStorage
3182
3408
  }
3183
3409
 
3184
- function read$3(key) {
3410
+ function read$4(key) {
3185
3411
  return localStorage().getItem(key)
3186
3412
  }
3187
3413
 
3188
- function write$3(key, data) {
3414
+ function write$4(key, data) {
3189
3415
  return localStorage().setItem(key, data)
3190
3416
  }
3191
3417
 
3192
3418
  function each$3(fn) {
3193
3419
  for (var i = localStorage().length - 1; i >= 0; i--) {
3194
3420
  var key = localStorage().key(i);
3195
- fn(read$3(key), key);
3421
+ fn(read$4(key), key);
3196
3422
  }
3197
3423
  }
3198
3424
 
@@ -3208,8 +3434,8 @@ var Global$1 = util.Global;
3208
3434
 
3209
3435
  var sessionStorage_1 = {
3210
3436
  name: 'sessionStorage',
3211
- read: read$2,
3212
- write: write$2,
3437
+ read: read$3,
3438
+ write: write$3,
3213
3439
  each: each$2,
3214
3440
  remove: remove$2,
3215
3441
  clearAll: clearAll$2
@@ -3219,18 +3445,18 @@ function sessionStorage() {
3219
3445
  return Global$1.sessionStorage
3220
3446
  }
3221
3447
 
3222
- function read$2(key) {
3448
+ function read$3(key) {
3223
3449
  return sessionStorage().getItem(key)
3224
3450
  }
3225
3451
 
3226
- function write$2(key, data) {
3452
+ function write$3(key, data) {
3227
3453
  return sessionStorage().setItem(key, data)
3228
3454
  }
3229
3455
 
3230
3456
  function each$2(fn) {
3231
3457
  for (var i = sessionStorage().length - 1; i >= 0; i--) {
3232
3458
  var key = sessionStorage().key(i);
3233
- fn(read$2(key), key);
3459
+ fn(read$3(key), key);
3234
3460
  }
3235
3461
  }
3236
3462
 
@@ -3252,8 +3478,8 @@ var trim$1 = util.trim;
3252
3478
 
3253
3479
  var cookieStorage = {
3254
3480
  name: 'cookieStorage',
3255
- read: read$1,
3256
- write: write$1,
3481
+ read: read$2,
3482
+ write: write$2,
3257
3483
  each: each$1,
3258
3484
  remove: remove$1,
3259
3485
  clearAll: clearAll$1,
@@ -3261,7 +3487,7 @@ var cookieStorage = {
3261
3487
 
3262
3488
  var doc = Global.document;
3263
3489
 
3264
- function read$1(key) {
3490
+ function read$2(key) {
3265
3491
  if (!key || !_has(key)) { return null }
3266
3492
  var regexpStr = "(?:^|.*;\\s*)" +
3267
3493
  escape(key).replace(/[\-\.\+\*]/g, "\\$&") +
@@ -3282,7 +3508,7 @@ function each$1(callback) {
3282
3508
  }
3283
3509
  }
3284
3510
 
3285
- function write$1(key, data) {
3511
+ function write$2(key, data) {
3286
3512
  if(!key) { return }
3287
3513
  doc.cookie = escape(key) + "=" + escape(data) + "; expires=Tue, 19 Jan 2038 03:14:07 GMT; path=/";
3288
3514
  }
@@ -3311,8 +3537,8 @@ function _has(key) {
3311
3537
 
3312
3538
  var memoryStorage_1 = {
3313
3539
  name: 'memoryStorage',
3314
- read: read,
3315
- write: write,
3540
+ read: read$1,
3541
+ write: write$1,
3316
3542
  each: each,
3317
3543
  remove: remove,
3318
3544
  clearAll: clearAll,
@@ -3320,11 +3546,11 @@ var memoryStorage_1 = {
3320
3546
 
3321
3547
  var memoryStorage = {};
3322
3548
 
3323
- function read(key) {
3549
+ function read$1(key) {
3324
3550
  return memoryStorage[key]
3325
3551
  }
3326
3552
 
3327
- function write(key, data) {
3553
+ function write$1(key, data) {
3328
3554
  memoryStorage[key] = data;
3329
3555
  }
3330
3556
 
@@ -3344,7 +3570,7 @@ function clearAll(key) {
3344
3570
  memoryStorage = {};
3345
3571
  }
3346
3572
 
3347
- function a(e,t=!1){e+="";let r,o=["٠","١","٢","٣","٤","٥","٦","٧","٨","٩"],n=["0","1","2","3","4","5","6","7","8","9"],i=(t=t||!Salla.config.get("store.settings.arabic_numbers_enabled"))?o:n,l=t?n:o;for(let t=0;t<i.length;t++)r=new RegExp(i[t],"g"),e=e.replace(r,l[t]);return e}function s$1(e){let t=(e.match(/\./g)||[]).length;return t&&1!==t?s$1(e.replace(/\.(.+)\./g,".$1")):e}function c$1(e,t,r){let o=e[0];return r&&0==e.length?Array.isArray(r)?(r.push(t),r):[r,t]:Array.isArray(r)?(r.push(t),r):"string"==typeof r?[r,t]:r?(r[o]=c$1(e.slice(1),t,r[o]),r):o?{[o]:c$1(e.slice(1),t)}:""===o?[t]:t}function u$1(e){return Salla.config.get("store.url",window.location.href.split("/").slice(0,-1).join("/")).rtrim("/")+"/"+e.ltrim("/")}var d$1={digitsOnly:function(e){return a(e,!0).replace(/[^0-9.]/g,"").replace("..",".").rtrim(".")},inputDigitsOnly:function e(t,r=!1){if("string"==typeof t)return document.querySelectorAll(t).forEach((t=>e(t,r)));if(!t)return void Salla.logger.warn("Can't find Object With Id: "+t);let o=Salla.helpers.digitsOnly(t.value);return t.min&&o<t.min?t.value=t.min:t.max&&o>t.max?t.value=t.max:t.maxLength>=1&&o.toString().length>t.maxLength?t.value=o.toString().substring(0,t.maxLength):t.value=r||t.dataset.hasOwnProperty("digitsWithDecimal")?s$1(o):o.replace(/\D/g,"")},number:a,money:function(e){let t=Salla.config.currency(e?.currency).symbol;return a(e="object"==typeof e?e.amount:e)+" "+t},setNested:function(e,t,r){let o=e,n=t.split("."),i=n.length;for(let e=0;e<i-1;e++){let t=n[e];o[t]||(o[t]={}),o=o[t];}return o[n[i-1]]=r,e},getNested:function(t,r,o){let n=get_1(t,r);return void 0!==n?n:o},inputData:function(e,t,r={}){if(e.includes("[")){let o=e.split("]").join("").split("[");return {name:o[0],value:c$1(o.slice(1),t,r[o[0]])}}return {name:e,value:t}},url:{get:u$1,asset:function(e){return function(e){return window.location.origin+"/"+e.ltrim("/")}("themes/"+Salla.config.get("theme.name")+"/"+e.ltrim("/"))},cdn:function(e){return "https://cdn.salla.network/"+e.ltrim("/")},is_page:function(e){return e&&Salla.config.get("page.slug")===e},api:function(e){return Salla.config.get("store.api",u$1("")).rtrim("/")+"/"+e.ltrim("/")}},addParamToUrl:function(e,t){if(!t||!e)return window.location.href;let r=new RegExp("([?&])"+e+"=[^&]+[&]?","g"),o=window.location.href.replace(r,"$1").replace(/&$|\?$/,"");return o+=(o.includes("?")?"&":"?")+e+"="+encodeURIComponent(t),o.replace(/&$|\?$/,"")},debounce:function(e,t){t=t||100;let r,o=[];return function(...n){return clearTimeout(r),r=setTimeout((()=>{let t=e(...n);o.forEach((e=>e(t))),o=[];}),t),new Promise((e=>o.push(e)))}}},g$1=function(e){let t={log:function(t,r){if(!e)return;if(!salla.config.isDebug())return;"trace"===salla.config.get("debug")&&(r="trace");let o=e.log,n=void 0===r?o:this.__dict__[r]||o,i=["%cTwilight","color: #5cd5c4;font-weight:bold; border:1px solid #5cd5c4; padding: 2px 6px; border-radius: 5px;"],l={event:"#CFF680",backend:"#7b68ee"}[r];l&&(i[0]+="%c"+r[0].toUpperCase()+r.substring(1),i.push(`margin-left: 5px;color: ${l};font-weight:bold; border:1px solid ${l}; padding: 2px 6px; border-radius: 5px;`)),n.call(e,...i.concat(...t));},__dict__:{trace:e.trace,debug:e.debug,info:e.info,warn:e.warn,error:e.error}};return {event:function(){t.log(arguments,"event");},trace:function(){t.log(arguments,"trace");},debug:function(){t.log(arguments,"debug");},info:function(){t.log(arguments,"info");},warn:function(){t.log(arguments,"warn");},error:function(){t.log(arguments,"error");},log:function(){t.log(arguments,void 0);},backend:function(){t.log(arguments,"backend");},logs:function(e){[e].flat().forEach((e=>e&&t.log([e].flat(),"backend")));}}}(console);const p$1=storeEngine.createStore([localStorage_1,sessionStorage_1,cookieStorage,memoryStorage_1],[]);"undefined"==typeof global?(window.salla=window.salla||window.Salla||{},window.Salla=window.salla):(global.salla=global.salla||global.Salla||{},global.Salla=global.salla),Salla.status="base",Salla.config=new class{constructor(e={},t={}){this.default_properties=t,this.properties_={...this.default_properties,...e};}merge(e){return Object.assign(this.properties_,e),this.properties_.store={...this.default_properties.store,...this.properties_.store},this}set(e,t){return e.includes(".")?(Salla.helpers.setNested(this.properties_,e,t),this):(this.properties_[e]=t,this)}get(e,t=null){return e.includes(".")?Salla.helpers.getNested(this.properties_,e,t):this.properties_.hasOwnProperty(e)?this.properties_[e]||t:t||void 0}all(){return this.properties_}isDebug(){return this.get("debug")||Salla.storage.get("debug")}},Salla.logger=g$1,Salla.event=new class extends eventemitter2{constructor(){super({wildcard:!0,delimiter:"::",newListener:!1,removeListener:!1,maxListeners:10,verboseMemoryLeak:!1,ignoreErrors:!1}),this.delimiter="::","undefined"!=typeof document&&(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"];}createAndDispatch(e,...t){this.dispatch(e,...t);}emit(e,...t){let r=e.replace("::",".");if(!this.noneFireableActions.includes(r)&&void 0!==Salla.call&&"function"==typeof Salla.call(r))return Salla.log(`'Salla.${r}(...)' triggered using event '${e}'`),r=r.split("."),void salla[r[0]][r[1]](...t);if(super.emit(e,...t),"undefined"!=typeof window){window.dataLayer=window.dataLayer||[];let r={event:e};t.map((e=>"object"==typeof e&&(r={...r,...e}))),window.dataLayer.push(r);}Salla.logger&&!this.ingoreLogEvents.includes(e)&&Salla.logger.event(e,...t),this.dispatchMobileEvent(e,{...t.values()});}dispatch(e,...t){return this.emit(e,...t)}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){return this.on(e,t)}addEventListener(e,t){return this.on(e,t)}listen(e,t){return this.on(e,t)}registerGlobalListener(e,t){return this.onAny(t)}dispatchMobileEvent(e,t={}){if(!("undefined"!=typeof window&&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){Salla.log(e,"The native context does not exist yet");}else if(Android)try{Android.customEventWithData(e,JSON.stringify({details:t}));}catch(e){Salla.log(e,"The native context does not exist yet");}}},Salla.storage=new class{constructor(){Salla.event.on("storage::item.remove",(e=>this.remove(e))),Salla.event.on("storage::item.set",((e,t)=>this.set(e,t))),this.store=p$1;}set(e,t){if(e.includes(".")){let r=e.split(".")[0],o={[r]:this.store.get(r)};return o=Salla.helpers.setNested(o,e,t),this.store.set(r,o[r])}return this.store.set(e,t)}remove(e){return this.store.remove(e)}clearAll(){return this.store.clearAll()}get(e,t){if(e.includes(".")){let t=e.split(".")[0];return Salla.helpers.getNested({[t]:this.store.get(t)},e)}return this.store.get(e,t)}},Salla.cookie=new class{constructor(){Salla.event.on("cookies::remove",(e=>this.remove(e))),Salla.event.on("cookies::add",((e,t)=>this.set(e,t)));}get(e){return document.cookie.split("; ").find((t=>t.startsWith(e+"=")))?.split("=")[1]}set(e,t="",r=10){let o="";if(r){let e=new Date;e.setTime(e.getTime()+24*r*60*60*1e3),o="; expires="+e.toUTCString();}return document.cookie=`${e}=${t}${o}"; path=/; secure; SameSite=Lax"`,this}remove(e){return document.cookie=`${e}=; Max-Age=0; path=/;`,this}clearAll(){let e=document.cookie.split(";");for(let t=0;t<e.length;t++){let r=e[t],o=r.indexOf("="),n=o>-1?r.substr(0,o):r;this.remove(n);}}},Salla.helpers=d$1,Salla.log=Salla.logger.log,Salla.money=Salla.helpers.money,Salla.url=Salla.helpers.url,Salla.versions={base:"[VI]{version}[/VI]"};var f$1=Salla;
3573
+ function a(e,t=!1){e+="";let r,o=["٠","١","٢","٣","٤","٥","٦","٧","٨","٩"],n=["0","1","2","3","4","5","6","7","8","9"],i=(t=t||!Salla.config.get("store.settings.arabic_numbers_enabled"))?o:n,l=t?n:o;for(let t=0;t<i.length;t++)r=new RegExp(i[t],"g"),e=e.replace(r,l[t]);return e}function s$1(e){let t=(e.match(/\./g)||[]).length;return t&&1!==t?s$1(e.replace(/\.(.+)\./g,".$1")):e}function c$1(e,t,r){let o=e[0];return r&&0==e.length?Array.isArray(r)?(r.push(t),r):[r,t]:Array.isArray(r)?(r.push(t),r):"string"==typeof r?[r,t]:r?(r[o]=c$1(e.slice(1),t,r[o]),r):o?{[o]:c$1(e.slice(1),t)}:""===o?[t]:t}function u$1(e){return Salla.config.get("store.url",window.location.href.split("/").slice(0,-1).join("/")).rtrim("/")+"/"+e.ltrim("/")}var d$1={digitsOnly:function(e){return a(e,!0).replace(/[^0-9.]/g,"").replace("..",".").rtrim(".")},inputDigitsOnly:function e(t,r=!1){if("string"==typeof t)return document.querySelectorAll(t).forEach((t=>e(t,r)));if(!t)return void Salla.logger.warn("Can't find Object With Id: "+t);let o=Salla.helpers.digitsOnly(t.value);return t.min&&o<t.min?t.value=t.min:t.max&&o>t.max?t.value=t.max:t.maxLength>=1&&o.toString().length>t.maxLength?t.value=o.toString().substring(0,t.maxLength):t.value=r||t.dataset.hasOwnProperty("digitsWithDecimal")?s$1(o):o.replace(/\D/g,"")},number:a,money:function(e){let t=Salla.config.currency(e?.currency).symbol;return a(e="object"==typeof e?e.amount:e)+" "+t},setNested:function(e,t,r){let o=e,n=t.split("."),i=n.length;for(let e=0;e<i-1;e++){let t=n[e];o[t]||(o[t]={}),o=o[t];}return o[n[i-1]]=r,e},getNested:function(t,r,o){let n=get_1(t,r);return void 0!==n?n:o},inputData:function(e,t,r={}){if(e.includes("[")){let o=e.split("]").join("").split("[");return {name:o[0],value:c$1(o.slice(1),t,r[o[0]])}}return {name:e,value:t}},url:{get:u$1,asset:function(e){return function(e){return window.location.origin+"/"+e.ltrim("/")}("themes/"+Salla.config.get("theme.name")+"/"+e.ltrim("/"))},cdn:function(e){return "https://cdn.salla.network/"+e.ltrim("/")},is_page:function(e){return e&&Salla.config.get("page.slug")===e},api:function(e){return Salla.config.get("store.api",u$1("")).rtrim("/")+"/"+e.ltrim("/")}},addParamToUrl:function(e,t){if(!t||!e)return window.location.href;let r=new RegExp("([?&])"+e+"=[^&]+[&]?","g"),o=window.location.href.replace(r,"$1").replace(/&$|\?$/,"");return o.includes("?")?o+="&":o+=(o.endsWith("/")?"":"/")+"?",(o+e+"="+encodeURIComponent(t)).replace(/&$|\?$/,"")},debounce:function(e,t){t=t||100;let r,o=[];return function(...n){return clearTimeout(r),r=setTimeout((()=>{let t=e(...n);o.forEach((e=>e(t))),o=[];}),t),new Promise((e=>o.push(e)))}}},g$1=function(e){let t={log:function(t,r){if(!e)return;if(!salla.config.isDebug())return;"trace"===salla.config.get("debug")&&(r="trace");let o=e.log,n=void 0===r?o:this.__dict__[r]||o,i=["%cTwilight","color: #5cd5c4;font-weight:bold; border:1px solid #5cd5c4; padding: 2px 6px; border-radius: 5px;"],l={event:"#CFF680",backend:"#7b68ee"}[r];l&&(i[0]+="%c"+r[0].toUpperCase()+r.substring(1),i.push(`margin-left: 5px;color: ${l};font-weight:bold; border:1px solid ${l}; padding: 2px 6px; border-radius: 5px;`)),n.call(e,...i.concat(...t));},__dict__:{trace:e.trace,debug:e.debug,info:e.info,warn:e.warn,error:e.error}};return {event:function(){t.log(arguments,"event");},trace:function(){t.log(arguments,"trace");},debug:function(){t.log(arguments,"debug");},info:function(){t.log(arguments,"info");},warn:function(){t.log(arguments,"warn");},error:function(){t.log(arguments,"error");},log:function(){t.log(arguments,void 0);},backend:function(){t.log(arguments,"backend");},logs:function(e){[e].flat().forEach((e=>e&&t.log([e].flat(),"backend")));}}}(console);const p$1=storeEngine.createStore([localStorage_1,sessionStorage_1,cookieStorage,memoryStorage_1],[]);"undefined"==typeof global$1?(window.salla=window.salla||window.Salla||{},window.Salla=window.salla):(global$1.salla=global$1.salla||global$1.Salla||{},global$1.Salla=global$1.salla),Salla.status="base",Salla.config=new class{constructor(e={},t={}){this.default_properties=t,this.properties_={...this.default_properties,...e};}merge(e){return Object.assign(this.properties_,e),this.properties_.store={...this.default_properties.store,...this.properties_.store},this}set(e,t){return e.includes(".")?(Salla.helpers.setNested(this.properties_,e,t),this):(this.properties_[e]=t,this)}get(e,t=null){return e.includes(".")?Salla.helpers.getNested(this.properties_,e,t):this.properties_.hasOwnProperty(e)?this.properties_[e]||t:t||void 0}all(){return this.properties_}isDebug(){return this.get("debug")||Salla.storage.get("debug")}},Salla.logger=g$1,Salla.event=new class extends eventemitter2{constructor(){super({wildcard:!0,delimiter:"::",newListener:!1,removeListener:!1,maxListeners:10,verboseMemoryLeak:!1,ignoreErrors:!1}),this.delimiter="::","undefined"!=typeof document&&(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"];}createAndDispatch(e,...t){this.dispatch(e,...t);}emit(e,...t){let r=e.replace("::",".");if(!this.noneFireableActions.includes(r)&&void 0!==Salla.call&&"function"==typeof Salla.call(r))return Salla.log(`'Salla.${r}(...)' triggered using event '${e}'`),r=r.split("."),void salla[r[0]][r[1]](...t);if(super.emit(e,...t),"undefined"!=typeof window){window.dataLayer=window.dataLayer||[];let r={event:e};t.map((e=>"object"==typeof e&&(r={...r,...e}))),window.dataLayer.push(r);}Salla.logger&&!this.ingoreLogEvents.includes(e)&&Salla.logger.event(e,...t),this.dispatchMobileEvent(e,{...t.values()});}dispatch(e,...t){return this.emit(e,...t)}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){return this.on(e,t)}addEventListener(e,t){return this.on(e,t)}listen(e,t){return this.on(e,t)}registerGlobalListener(e,t){return this.onAny(t)}dispatchMobileEvent(e,t={}){if(!("undefined"!=typeof window&&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){Salla.log(e,"The native context does not exist yet");}else if(Android)try{Android.customEventWithData(e,JSON.stringify({details:t}));}catch(e){Salla.log(e,"The native context does not exist yet");}}},Salla.storage=new class{constructor(){Salla.event.on("storage::item.remove",(e=>this.remove(e))),Salla.event.on("storage::item.set",((e,t)=>this.set(e,t))),this.store=p$1;}set(e,t){if(e.includes(".")){let r=e.split(".")[0],o={[r]:this.store.get(r)};return o=Salla.helpers.setNested(o,e,t),this.store.set(r,o[r])}return this.store.set(e,t)}remove(e){return this.store.remove(e)}clearAll(){return this.store.clearAll()}get(e,t){if(e.includes(".")){let t=e.split(".")[0];return Salla.helpers.getNested({[t]:this.store.get(t)},e)}return this.store.get(e,t)}},Salla.cookie=new class{constructor(){Salla.event.on("cookies::remove",(e=>this.remove(e))),Salla.event.on("cookies::add",((e,t)=>this.set(e,t)));}get(e){return document.cookie.split("; ").find((t=>t.startsWith(e+"=")))?.split("=")[1]}set(e,t="",r=10){let o="";if(r){let e=new Date;e.setTime(e.getTime()+24*r*60*60*1e3),o="; expires="+e.toUTCString();}return document.cookie=`${e}=${t}${o}"; path=/; secure; SameSite=Lax"`,this}remove(e){return document.cookie=`${e}=; Max-Age=0; path=/;`,this}clearAll(){let e=document.cookie.split(";");for(let t=0;t<e.length;t++){let r=e[t],o=r.indexOf("="),n=o>-1?r.substr(0,o):r;this.remove(n);}}},Salla.helpers=d$1,Salla.log=Salla.logger.log,Salla.money=Salla.helpers.money,Salla.url=Salla.helpers.url,Salla.versions={base:"[VI]{version}[/VI]"};var f$1=Salla;
3348
3574
 
3349
3575
  var evEmitter = createCommonjsModule(function (module) {
3350
3576
  /**
@@ -5505,13 +5731,13 @@ var bind = function bind(fn, thisArg) {
5505
5731
 
5506
5732
  // utils is a library of generic helper functions non-specific to axios
5507
5733
 
5508
- var toString = Object.prototype.toString;
5734
+ var toString$1 = Object.prototype.toString;
5509
5735
 
5510
5736
  // eslint-disable-next-line func-names
5511
5737
  var kindOf = (function(cache) {
5512
5738
  // eslint-disable-next-line func-names
5513
5739
  return function(thing) {
5514
- var str = toString.call(thing);
5740
+ var str = toString$1.call(thing);
5515
5741
  return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());
5516
5742
  };
5517
5743
  })(Object.create(null));
@@ -5529,7 +5755,7 @@ function kindOfTest(type) {
5529
5755
  * @param {Object} val The value to test
5530
5756
  * @returns {boolean} True if value is an Array, otherwise false
5531
5757
  */
5532
- function isArray(val) {
5758
+ function isArray$1(val) {
5533
5759
  return Array.isArray(val);
5534
5760
  }
5535
5761
 
@@ -5549,7 +5775,7 @@ function isUndefined(val) {
5549
5775
  * @param {Object} val The value to test
5550
5776
  * @returns {boolean} True if value is a Buffer, otherwise false
5551
5777
  */
5552
- function isBuffer(val) {
5778
+ function isBuffer$1(val) {
5553
5779
  return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor)
5554
5780
  && typeof val.constructor.isBuffer === 'function' && val.constructor.isBuffer(val);
5555
5781
  }
@@ -5668,7 +5894,7 @@ var isFileList = kindOfTest('FileList');
5668
5894
  * @returns {boolean} True if value is a Function, otherwise false
5669
5895
  */
5670
5896
  function isFunction(val) {
5671
- return toString.call(val) === '[object Function]';
5897
+ return toString$1.call(val) === '[object Function]';
5672
5898
  }
5673
5899
 
5674
5900
  /**
@@ -5691,7 +5917,7 @@ function isFormData(thing) {
5691
5917
  var pattern = '[object FormData]';
5692
5918
  return thing && (
5693
5919
  (typeof FormData === 'function' && thing instanceof FormData) ||
5694
- toString.call(thing) === pattern ||
5920
+ toString$1.call(thing) === pattern ||
5695
5921
  (isFunction(thing.toString) && thing.toString() === pattern)
5696
5922
  );
5697
5923
  }
@@ -5765,7 +5991,7 @@ function forEach(obj, fn) {
5765
5991
  obj = [obj];
5766
5992
  }
5767
5993
 
5768
- if (isArray(obj)) {
5994
+ if (isArray$1(obj)) {
5769
5995
  // Iterate over array values
5770
5996
  for (var i = 0, l = obj.length; i < l; i++) {
5771
5997
  fn.call(null, obj[i], i, obj);
@@ -5804,7 +6030,7 @@ function merge(/* obj1, obj2, obj3, ... */) {
5804
6030
  result[key] = merge(result[key], val);
5805
6031
  } else if (isPlainObject(val)) {
5806
6032
  result[key] = merge({}, val);
5807
- } else if (isArray(val)) {
6033
+ } else if (isArray$1(val)) {
5808
6034
  result[key] = val.slice();
5809
6035
  } else {
5810
6036
  result[key] = val;
@@ -5938,9 +6164,9 @@ var isTypedArray = (function(TypedArray) {
5938
6164
  })(typeof Uint8Array !== 'undefined' && Object.getPrototypeOf(Uint8Array));
5939
6165
 
5940
6166
  var utils = {
5941
- isArray: isArray,
6167
+ isArray: isArray$1,
5942
6168
  isArrayBuffer: isArrayBuffer,
5943
- isBuffer: isBuffer,
6169
+ isBuffer: isBuffer$1,
5944
6170
  isFormData: isFormData,
5945
6171
  isArrayBufferView: isArrayBufferView,
5946
6172
  isString: isString,
@@ -6186,6 +6412,1973 @@ var transitional = {
6186
6412
  clarifyTimeoutError: false
6187
6413
  };
6188
6414
 
6415
+ var lookup = [];
6416
+ var revLookup = [];
6417
+ var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array;
6418
+ var inited = false;
6419
+ function init () {
6420
+ inited = true;
6421
+ var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
6422
+ for (var i = 0, len = code.length; i < len; ++i) {
6423
+ lookup[i] = code[i];
6424
+ revLookup[code.charCodeAt(i)] = i;
6425
+ }
6426
+
6427
+ revLookup['-'.charCodeAt(0)] = 62;
6428
+ revLookup['_'.charCodeAt(0)] = 63;
6429
+ }
6430
+
6431
+ function toByteArray (b64) {
6432
+ if (!inited) {
6433
+ init();
6434
+ }
6435
+ var i, j, l, tmp, placeHolders, arr;
6436
+ var len = b64.length;
6437
+
6438
+ if (len % 4 > 0) {
6439
+ throw new Error('Invalid string. Length must be a multiple of 4')
6440
+ }
6441
+
6442
+ // the number of equal signs (place holders)
6443
+ // if there are two placeholders, than the two characters before it
6444
+ // represent one byte
6445
+ // if there is only one, then the three characters before it represent 2 bytes
6446
+ // this is just a cheap hack to not do indexOf twice
6447
+ placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0;
6448
+
6449
+ // base64 is 4/3 + up to two characters of the original data
6450
+ arr = new Arr(len * 3 / 4 - placeHolders);
6451
+
6452
+ // if there are placeholders, only get up to the last complete 4 chars
6453
+ l = placeHolders > 0 ? len - 4 : len;
6454
+
6455
+ var L = 0;
6456
+
6457
+ for (i = 0, j = 0; i < l; i += 4, j += 3) {
6458
+ tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)];
6459
+ arr[L++] = (tmp >> 16) & 0xFF;
6460
+ arr[L++] = (tmp >> 8) & 0xFF;
6461
+ arr[L++] = tmp & 0xFF;
6462
+ }
6463
+
6464
+ if (placeHolders === 2) {
6465
+ tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4);
6466
+ arr[L++] = tmp & 0xFF;
6467
+ } else if (placeHolders === 1) {
6468
+ tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2);
6469
+ arr[L++] = (tmp >> 8) & 0xFF;
6470
+ arr[L++] = tmp & 0xFF;
6471
+ }
6472
+
6473
+ return arr
6474
+ }
6475
+
6476
+ function tripletToBase64 (num) {
6477
+ return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]
6478
+ }
6479
+
6480
+ function encodeChunk (uint8, start, end) {
6481
+ var tmp;
6482
+ var output = [];
6483
+ for (var i = start; i < end; i += 3) {
6484
+ tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]);
6485
+ output.push(tripletToBase64(tmp));
6486
+ }
6487
+ return output.join('')
6488
+ }
6489
+
6490
+ function fromByteArray (uint8) {
6491
+ if (!inited) {
6492
+ init();
6493
+ }
6494
+ var tmp;
6495
+ var len = uint8.length;
6496
+ var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes
6497
+ var output = '';
6498
+ var parts = [];
6499
+ var maxChunkLength = 16383; // must be multiple of 3
6500
+
6501
+ // go through the array every three bytes, we'll deal with trailing stuff later
6502
+ for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
6503
+ parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)));
6504
+ }
6505
+
6506
+ // pad the end with zeros, but make sure to not forget the extra bytes
6507
+ if (extraBytes === 1) {
6508
+ tmp = uint8[len - 1];
6509
+ output += lookup[tmp >> 2];
6510
+ output += lookup[(tmp << 4) & 0x3F];
6511
+ output += '==';
6512
+ } else if (extraBytes === 2) {
6513
+ tmp = (uint8[len - 2] << 8) + (uint8[len - 1]);
6514
+ output += lookup[tmp >> 10];
6515
+ output += lookup[(tmp >> 4) & 0x3F];
6516
+ output += lookup[(tmp << 2) & 0x3F];
6517
+ output += '=';
6518
+ }
6519
+
6520
+ parts.push(output);
6521
+
6522
+ return parts.join('')
6523
+ }
6524
+
6525
+ function read (buffer, offset, isLE, mLen, nBytes) {
6526
+ var e, m;
6527
+ var eLen = nBytes * 8 - mLen - 1;
6528
+ var eMax = (1 << eLen) - 1;
6529
+ var eBias = eMax >> 1;
6530
+ var nBits = -7;
6531
+ var i = isLE ? (nBytes - 1) : 0;
6532
+ var d = isLE ? -1 : 1;
6533
+ var s = buffer[offset + i];
6534
+
6535
+ i += d;
6536
+
6537
+ e = s & ((1 << (-nBits)) - 1);
6538
+ s >>= (-nBits);
6539
+ nBits += eLen;
6540
+ for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
6541
+
6542
+ m = e & ((1 << (-nBits)) - 1);
6543
+ e >>= (-nBits);
6544
+ nBits += mLen;
6545
+ for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
6546
+
6547
+ if (e === 0) {
6548
+ e = 1 - eBias;
6549
+ } else if (e === eMax) {
6550
+ return m ? NaN : ((s ? -1 : 1) * Infinity)
6551
+ } else {
6552
+ m = m + Math.pow(2, mLen);
6553
+ e = e - eBias;
6554
+ }
6555
+ return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
6556
+ }
6557
+
6558
+ function write (buffer, value, offset, isLE, mLen, nBytes) {
6559
+ var e, m, c;
6560
+ var eLen = nBytes * 8 - mLen - 1;
6561
+ var eMax = (1 << eLen) - 1;
6562
+ var eBias = eMax >> 1;
6563
+ var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0);
6564
+ var i = isLE ? 0 : (nBytes - 1);
6565
+ var d = isLE ? 1 : -1;
6566
+ var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0;
6567
+
6568
+ value = Math.abs(value);
6569
+
6570
+ if (isNaN(value) || value === Infinity) {
6571
+ m = isNaN(value) ? 1 : 0;
6572
+ e = eMax;
6573
+ } else {
6574
+ e = Math.floor(Math.log(value) / Math.LN2);
6575
+ if (value * (c = Math.pow(2, -e)) < 1) {
6576
+ e--;
6577
+ c *= 2;
6578
+ }
6579
+ if (e + eBias >= 1) {
6580
+ value += rt / c;
6581
+ } else {
6582
+ value += rt * Math.pow(2, 1 - eBias);
6583
+ }
6584
+ if (value * c >= 2) {
6585
+ e++;
6586
+ c /= 2;
6587
+ }
6588
+
6589
+ if (e + eBias >= eMax) {
6590
+ m = 0;
6591
+ e = eMax;
6592
+ } else if (e + eBias >= 1) {
6593
+ m = (value * c - 1) * Math.pow(2, mLen);
6594
+ e = e + eBias;
6595
+ } else {
6596
+ m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
6597
+ e = 0;
6598
+ }
6599
+ }
6600
+
6601
+ for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
6602
+
6603
+ e = (e << mLen) | m;
6604
+ eLen += mLen;
6605
+ for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
6606
+
6607
+ buffer[offset + i - d] |= s * 128;
6608
+ }
6609
+
6610
+ var toString = {}.toString;
6611
+
6612
+ var isArray = Array.isArray || function (arr) {
6613
+ return toString.call(arr) == '[object Array]';
6614
+ };
6615
+
6616
+ /*!
6617
+ * The buffer module from node.js, for the browser.
6618
+ *
6619
+ * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
6620
+ * @license MIT
6621
+ */
6622
+
6623
+ var INSPECT_MAX_BYTES = 50;
6624
+
6625
+ /**
6626
+ * If `Buffer.TYPED_ARRAY_SUPPORT`:
6627
+ * === true Use Uint8Array implementation (fastest)
6628
+ * === false Use Object implementation (most compatible, even IE6)
6629
+ *
6630
+ * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
6631
+ * Opera 11.6+, iOS 4.2+.
6632
+ *
6633
+ * Due to various browser bugs, sometimes the Object implementation will be used even
6634
+ * when the browser supports typed arrays.
6635
+ *
6636
+ * Note:
6637
+ *
6638
+ * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
6639
+ * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
6640
+ *
6641
+ * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
6642
+ *
6643
+ * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
6644
+ * incorrect length in some situations.
6645
+
6646
+ * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
6647
+ * get the Object implementation, which is slower but behaves correctly.
6648
+ */
6649
+ Buffer.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined
6650
+ ? global$1.TYPED_ARRAY_SUPPORT
6651
+ : true;
6652
+
6653
+ function kMaxLength () {
6654
+ return Buffer.TYPED_ARRAY_SUPPORT
6655
+ ? 0x7fffffff
6656
+ : 0x3fffffff
6657
+ }
6658
+
6659
+ function createBuffer (that, length) {
6660
+ if (kMaxLength() < length) {
6661
+ throw new RangeError('Invalid typed array length')
6662
+ }
6663
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
6664
+ // Return an augmented `Uint8Array` instance, for best performance
6665
+ that = new Uint8Array(length);
6666
+ that.__proto__ = Buffer.prototype;
6667
+ } else {
6668
+ // Fallback: Return an object instance of the Buffer class
6669
+ if (that === null) {
6670
+ that = new Buffer(length);
6671
+ }
6672
+ that.length = length;
6673
+ }
6674
+
6675
+ return that
6676
+ }
6677
+
6678
+ /**
6679
+ * The Buffer constructor returns instances of `Uint8Array` that have their
6680
+ * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
6681
+ * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
6682
+ * and the `Uint8Array` methods. Square bracket notation works as expected -- it
6683
+ * returns a single octet.
6684
+ *
6685
+ * The `Uint8Array` prototype remains unmodified.
6686
+ */
6687
+
6688
+ function Buffer (arg, encodingOrOffset, length) {
6689
+ if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {
6690
+ return new Buffer(arg, encodingOrOffset, length)
6691
+ }
6692
+
6693
+ // Common case.
6694
+ if (typeof arg === 'number') {
6695
+ if (typeof encodingOrOffset === 'string') {
6696
+ throw new Error(
6697
+ 'If encoding is specified then the first argument must be a string'
6698
+ )
6699
+ }
6700
+ return allocUnsafe(this, arg)
6701
+ }
6702
+ return from(this, arg, encodingOrOffset, length)
6703
+ }
6704
+
6705
+ Buffer.poolSize = 8192; // not used by this implementation
6706
+
6707
+ // TODO: Legacy, not needed anymore. Remove in next major version.
6708
+ Buffer._augment = function (arr) {
6709
+ arr.__proto__ = Buffer.prototype;
6710
+ return arr
6711
+ };
6712
+
6713
+ function from (that, value, encodingOrOffset, length) {
6714
+ if (typeof value === 'number') {
6715
+ throw new TypeError('"value" argument must not be a number')
6716
+ }
6717
+
6718
+ if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
6719
+ return fromArrayBuffer(that, value, encodingOrOffset, length)
6720
+ }
6721
+
6722
+ if (typeof value === 'string') {
6723
+ return fromString(that, value, encodingOrOffset)
6724
+ }
6725
+
6726
+ return fromObject(that, value)
6727
+ }
6728
+
6729
+ /**
6730
+ * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
6731
+ * if value is a number.
6732
+ * Buffer.from(str[, encoding])
6733
+ * Buffer.from(array)
6734
+ * Buffer.from(buffer)
6735
+ * Buffer.from(arrayBuffer[, byteOffset[, length]])
6736
+ **/
6737
+ Buffer.from = function (value, encodingOrOffset, length) {
6738
+ return from(null, value, encodingOrOffset, length)
6739
+ };
6740
+
6741
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
6742
+ Buffer.prototype.__proto__ = Uint8Array.prototype;
6743
+ Buffer.__proto__ = Uint8Array;
6744
+ }
6745
+
6746
+ function assertSize (size) {
6747
+ if (typeof size !== 'number') {
6748
+ throw new TypeError('"size" argument must be a number')
6749
+ } else if (size < 0) {
6750
+ throw new RangeError('"size" argument must not be negative')
6751
+ }
6752
+ }
6753
+
6754
+ function alloc (that, size, fill, encoding) {
6755
+ assertSize(size);
6756
+ if (size <= 0) {
6757
+ return createBuffer(that, size)
6758
+ }
6759
+ if (fill !== undefined) {
6760
+ // Only pay attention to encoding if it's a string. This
6761
+ // prevents accidentally sending in a number that would
6762
+ // be interpretted as a start offset.
6763
+ return typeof encoding === 'string'
6764
+ ? createBuffer(that, size).fill(fill, encoding)
6765
+ : createBuffer(that, size).fill(fill)
6766
+ }
6767
+ return createBuffer(that, size)
6768
+ }
6769
+
6770
+ /**
6771
+ * Creates a new filled Buffer instance.
6772
+ * alloc(size[, fill[, encoding]])
6773
+ **/
6774
+ Buffer.alloc = function (size, fill, encoding) {
6775
+ return alloc(null, size, fill, encoding)
6776
+ };
6777
+
6778
+ function allocUnsafe (that, size) {
6779
+ assertSize(size);
6780
+ that = createBuffer(that, size < 0 ? 0 : checked(size) | 0);
6781
+ if (!Buffer.TYPED_ARRAY_SUPPORT) {
6782
+ for (var i = 0; i < size; ++i) {
6783
+ that[i] = 0;
6784
+ }
6785
+ }
6786
+ return that
6787
+ }
6788
+
6789
+ /**
6790
+ * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
6791
+ * */
6792
+ Buffer.allocUnsafe = function (size) {
6793
+ return allocUnsafe(null, size)
6794
+ };
6795
+ /**
6796
+ * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
6797
+ */
6798
+ Buffer.allocUnsafeSlow = function (size) {
6799
+ return allocUnsafe(null, size)
6800
+ };
6801
+
6802
+ function fromString (that, string, encoding) {
6803
+ if (typeof encoding !== 'string' || encoding === '') {
6804
+ encoding = 'utf8';
6805
+ }
6806
+
6807
+ if (!Buffer.isEncoding(encoding)) {
6808
+ throw new TypeError('"encoding" must be a valid string encoding')
6809
+ }
6810
+
6811
+ var length = byteLength(string, encoding) | 0;
6812
+ that = createBuffer(that, length);
6813
+
6814
+ var actual = that.write(string, encoding);
6815
+
6816
+ if (actual !== length) {
6817
+ // Writing a hex string, for example, that contains invalid characters will
6818
+ // cause everything after the first invalid character to be ignored. (e.g.
6819
+ // 'abxxcd' will be treated as 'ab')
6820
+ that = that.slice(0, actual);
6821
+ }
6822
+
6823
+ return that
6824
+ }
6825
+
6826
+ function fromArrayLike (that, array) {
6827
+ var length = array.length < 0 ? 0 : checked(array.length) | 0;
6828
+ that = createBuffer(that, length);
6829
+ for (var i = 0; i < length; i += 1) {
6830
+ that[i] = array[i] & 255;
6831
+ }
6832
+ return that
6833
+ }
6834
+
6835
+ function fromArrayBuffer (that, array, byteOffset, length) {
6836
+
6837
+ if (byteOffset < 0 || array.byteLength < byteOffset) {
6838
+ throw new RangeError('\'offset\' is out of bounds')
6839
+ }
6840
+
6841
+ if (array.byteLength < byteOffset + (length || 0)) {
6842
+ throw new RangeError('\'length\' is out of bounds')
6843
+ }
6844
+
6845
+ if (byteOffset === undefined && length === undefined) {
6846
+ array = new Uint8Array(array);
6847
+ } else if (length === undefined) {
6848
+ array = new Uint8Array(array, byteOffset);
6849
+ } else {
6850
+ array = new Uint8Array(array, byteOffset, length);
6851
+ }
6852
+
6853
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
6854
+ // Return an augmented `Uint8Array` instance, for best performance
6855
+ that = array;
6856
+ that.__proto__ = Buffer.prototype;
6857
+ } else {
6858
+ // Fallback: Return an object instance of the Buffer class
6859
+ that = fromArrayLike(that, array);
6860
+ }
6861
+ return that
6862
+ }
6863
+
6864
+ function fromObject (that, obj) {
6865
+ if (internalIsBuffer(obj)) {
6866
+ var len = checked(obj.length) | 0;
6867
+ that = createBuffer(that, len);
6868
+
6869
+ if (that.length === 0) {
6870
+ return that
6871
+ }
6872
+
6873
+ obj.copy(that, 0, 0, len);
6874
+ return that
6875
+ }
6876
+
6877
+ if (obj) {
6878
+ if ((typeof ArrayBuffer !== 'undefined' &&
6879
+ obj.buffer instanceof ArrayBuffer) || 'length' in obj) {
6880
+ if (typeof obj.length !== 'number' || isnan(obj.length)) {
6881
+ return createBuffer(that, 0)
6882
+ }
6883
+ return fromArrayLike(that, obj)
6884
+ }
6885
+
6886
+ if (obj.type === 'Buffer' && isArray(obj.data)) {
6887
+ return fromArrayLike(that, obj.data)
6888
+ }
6889
+ }
6890
+
6891
+ throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
6892
+ }
6893
+
6894
+ function checked (length) {
6895
+ // Note: cannot use `length < kMaxLength()` here because that fails when
6896
+ // length is NaN (which is otherwise coerced to zero.)
6897
+ if (length >= kMaxLength()) {
6898
+ throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
6899
+ 'size: 0x' + kMaxLength().toString(16) + ' bytes')
6900
+ }
6901
+ return length | 0
6902
+ }
6903
+ Buffer.isBuffer = isBuffer;
6904
+ function internalIsBuffer (b) {
6905
+ return !!(b != null && b._isBuffer)
6906
+ }
6907
+
6908
+ Buffer.compare = function compare (a, b) {
6909
+ if (!internalIsBuffer(a) || !internalIsBuffer(b)) {
6910
+ throw new TypeError('Arguments must be Buffers')
6911
+ }
6912
+
6913
+ if (a === b) return 0
6914
+
6915
+ var x = a.length;
6916
+ var y = b.length;
6917
+
6918
+ for (var i = 0, len = Math.min(x, y); i < len; ++i) {
6919
+ if (a[i] !== b[i]) {
6920
+ x = a[i];
6921
+ y = b[i];
6922
+ break
6923
+ }
6924
+ }
6925
+
6926
+ if (x < y) return -1
6927
+ if (y < x) return 1
6928
+ return 0
6929
+ };
6930
+
6931
+ Buffer.isEncoding = function isEncoding (encoding) {
6932
+ switch (String(encoding).toLowerCase()) {
6933
+ case 'hex':
6934
+ case 'utf8':
6935
+ case 'utf-8':
6936
+ case 'ascii':
6937
+ case 'latin1':
6938
+ case 'binary':
6939
+ case 'base64':
6940
+ case 'ucs2':
6941
+ case 'ucs-2':
6942
+ case 'utf16le':
6943
+ case 'utf-16le':
6944
+ return true
6945
+ default:
6946
+ return false
6947
+ }
6948
+ };
6949
+
6950
+ Buffer.concat = function concat (list, length) {
6951
+ if (!isArray(list)) {
6952
+ throw new TypeError('"list" argument must be an Array of Buffers')
6953
+ }
6954
+
6955
+ if (list.length === 0) {
6956
+ return Buffer.alloc(0)
6957
+ }
6958
+
6959
+ var i;
6960
+ if (length === undefined) {
6961
+ length = 0;
6962
+ for (i = 0; i < list.length; ++i) {
6963
+ length += list[i].length;
6964
+ }
6965
+ }
6966
+
6967
+ var buffer = Buffer.allocUnsafe(length);
6968
+ var pos = 0;
6969
+ for (i = 0; i < list.length; ++i) {
6970
+ var buf = list[i];
6971
+ if (!internalIsBuffer(buf)) {
6972
+ throw new TypeError('"list" argument must be an Array of Buffers')
6973
+ }
6974
+ buf.copy(buffer, pos);
6975
+ pos += buf.length;
6976
+ }
6977
+ return buffer
6978
+ };
6979
+
6980
+ function byteLength (string, encoding) {
6981
+ if (internalIsBuffer(string)) {
6982
+ return string.length
6983
+ }
6984
+ if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&
6985
+ (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {
6986
+ return string.byteLength
6987
+ }
6988
+ if (typeof string !== 'string') {
6989
+ string = '' + string;
6990
+ }
6991
+
6992
+ var len = string.length;
6993
+ if (len === 0) return 0
6994
+
6995
+ // Use a for loop to avoid recursion
6996
+ var loweredCase = false;
6997
+ for (;;) {
6998
+ switch (encoding) {
6999
+ case 'ascii':
7000
+ case 'latin1':
7001
+ case 'binary':
7002
+ return len
7003
+ case 'utf8':
7004
+ case 'utf-8':
7005
+ case undefined:
7006
+ return utf8ToBytes(string).length
7007
+ case 'ucs2':
7008
+ case 'ucs-2':
7009
+ case 'utf16le':
7010
+ case 'utf-16le':
7011
+ return len * 2
7012
+ case 'hex':
7013
+ return len >>> 1
7014
+ case 'base64':
7015
+ return base64ToBytes(string).length
7016
+ default:
7017
+ if (loweredCase) return utf8ToBytes(string).length // assume utf8
7018
+ encoding = ('' + encoding).toLowerCase();
7019
+ loweredCase = true;
7020
+ }
7021
+ }
7022
+ }
7023
+ Buffer.byteLength = byteLength;
7024
+
7025
+ function slowToString (encoding, start, end) {
7026
+ var loweredCase = false;
7027
+
7028
+ // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
7029
+ // property of a typed array.
7030
+
7031
+ // This behaves neither like String nor Uint8Array in that we set start/end
7032
+ // to their upper/lower bounds if the value passed is out of range.
7033
+ // undefined is handled specially as per ECMA-262 6th Edition,
7034
+ // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
7035
+ if (start === undefined || start < 0) {
7036
+ start = 0;
7037
+ }
7038
+ // Return early if start > this.length. Done here to prevent potential uint32
7039
+ // coercion fail below.
7040
+ if (start > this.length) {
7041
+ return ''
7042
+ }
7043
+
7044
+ if (end === undefined || end > this.length) {
7045
+ end = this.length;
7046
+ }
7047
+
7048
+ if (end <= 0) {
7049
+ return ''
7050
+ }
7051
+
7052
+ // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
7053
+ end >>>= 0;
7054
+ start >>>= 0;
7055
+
7056
+ if (end <= start) {
7057
+ return ''
7058
+ }
7059
+
7060
+ if (!encoding) encoding = 'utf8';
7061
+
7062
+ while (true) {
7063
+ switch (encoding) {
7064
+ case 'hex':
7065
+ return hexSlice(this, start, end)
7066
+
7067
+ case 'utf8':
7068
+ case 'utf-8':
7069
+ return utf8Slice(this, start, end)
7070
+
7071
+ case 'ascii':
7072
+ return asciiSlice(this, start, end)
7073
+
7074
+ case 'latin1':
7075
+ case 'binary':
7076
+ return latin1Slice(this, start, end)
7077
+
7078
+ case 'base64':
7079
+ return base64Slice(this, start, end)
7080
+
7081
+ case 'ucs2':
7082
+ case 'ucs-2':
7083
+ case 'utf16le':
7084
+ case 'utf-16le':
7085
+ return utf16leSlice(this, start, end)
7086
+
7087
+ default:
7088
+ if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
7089
+ encoding = (encoding + '').toLowerCase();
7090
+ loweredCase = true;
7091
+ }
7092
+ }
7093
+ }
7094
+
7095
+ // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect
7096
+ // Buffer instances.
7097
+ Buffer.prototype._isBuffer = true;
7098
+
7099
+ function swap (b, n, m) {
7100
+ var i = b[n];
7101
+ b[n] = b[m];
7102
+ b[m] = i;
7103
+ }
7104
+
7105
+ Buffer.prototype.swap16 = function swap16 () {
7106
+ var len = this.length;
7107
+ if (len % 2 !== 0) {
7108
+ throw new RangeError('Buffer size must be a multiple of 16-bits')
7109
+ }
7110
+ for (var i = 0; i < len; i += 2) {
7111
+ swap(this, i, i + 1);
7112
+ }
7113
+ return this
7114
+ };
7115
+
7116
+ Buffer.prototype.swap32 = function swap32 () {
7117
+ var len = this.length;
7118
+ if (len % 4 !== 0) {
7119
+ throw new RangeError('Buffer size must be a multiple of 32-bits')
7120
+ }
7121
+ for (var i = 0; i < len; i += 4) {
7122
+ swap(this, i, i + 3);
7123
+ swap(this, i + 1, i + 2);
7124
+ }
7125
+ return this
7126
+ };
7127
+
7128
+ Buffer.prototype.swap64 = function swap64 () {
7129
+ var len = this.length;
7130
+ if (len % 8 !== 0) {
7131
+ throw new RangeError('Buffer size must be a multiple of 64-bits')
7132
+ }
7133
+ for (var i = 0; i < len; i += 8) {
7134
+ swap(this, i, i + 7);
7135
+ swap(this, i + 1, i + 6);
7136
+ swap(this, i + 2, i + 5);
7137
+ swap(this, i + 3, i + 4);
7138
+ }
7139
+ return this
7140
+ };
7141
+
7142
+ Buffer.prototype.toString = function toString () {
7143
+ var length = this.length | 0;
7144
+ if (length === 0) return ''
7145
+ if (arguments.length === 0) return utf8Slice(this, 0, length)
7146
+ return slowToString.apply(this, arguments)
7147
+ };
7148
+
7149
+ Buffer.prototype.equals = function equals (b) {
7150
+ if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer')
7151
+ if (this === b) return true
7152
+ return Buffer.compare(this, b) === 0
7153
+ };
7154
+
7155
+ Buffer.prototype.inspect = function inspect () {
7156
+ var str = '';
7157
+ var max = INSPECT_MAX_BYTES;
7158
+ if (this.length > 0) {
7159
+ str = this.toString('hex', 0, max).match(/.{2}/g).join(' ');
7160
+ if (this.length > max) str += ' ... ';
7161
+ }
7162
+ return '<Buffer ' + str + '>'
7163
+ };
7164
+
7165
+ Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
7166
+ if (!internalIsBuffer(target)) {
7167
+ throw new TypeError('Argument must be a Buffer')
7168
+ }
7169
+
7170
+ if (start === undefined) {
7171
+ start = 0;
7172
+ }
7173
+ if (end === undefined) {
7174
+ end = target ? target.length : 0;
7175
+ }
7176
+ if (thisStart === undefined) {
7177
+ thisStart = 0;
7178
+ }
7179
+ if (thisEnd === undefined) {
7180
+ thisEnd = this.length;
7181
+ }
7182
+
7183
+ if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
7184
+ throw new RangeError('out of range index')
7185
+ }
7186
+
7187
+ if (thisStart >= thisEnd && start >= end) {
7188
+ return 0
7189
+ }
7190
+ if (thisStart >= thisEnd) {
7191
+ return -1
7192
+ }
7193
+ if (start >= end) {
7194
+ return 1
7195
+ }
7196
+
7197
+ start >>>= 0;
7198
+ end >>>= 0;
7199
+ thisStart >>>= 0;
7200
+ thisEnd >>>= 0;
7201
+
7202
+ if (this === target) return 0
7203
+
7204
+ var x = thisEnd - thisStart;
7205
+ var y = end - start;
7206
+ var len = Math.min(x, y);
7207
+
7208
+ var thisCopy = this.slice(thisStart, thisEnd);
7209
+ var targetCopy = target.slice(start, end);
7210
+
7211
+ for (var i = 0; i < len; ++i) {
7212
+ if (thisCopy[i] !== targetCopy[i]) {
7213
+ x = thisCopy[i];
7214
+ y = targetCopy[i];
7215
+ break
7216
+ }
7217
+ }
7218
+
7219
+ if (x < y) return -1
7220
+ if (y < x) return 1
7221
+ return 0
7222
+ };
7223
+
7224
+ // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
7225
+ // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
7226
+ //
7227
+ // Arguments:
7228
+ // - buffer - a Buffer to search
7229
+ // - val - a string, Buffer, or number
7230
+ // - byteOffset - an index into `buffer`; will be clamped to an int32
7231
+ // - encoding - an optional encoding, relevant is val is a string
7232
+ // - dir - true for indexOf, false for lastIndexOf
7233
+ function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
7234
+ // Empty buffer means no match
7235
+ if (buffer.length === 0) return -1
7236
+
7237
+ // Normalize byteOffset
7238
+ if (typeof byteOffset === 'string') {
7239
+ encoding = byteOffset;
7240
+ byteOffset = 0;
7241
+ } else if (byteOffset > 0x7fffffff) {
7242
+ byteOffset = 0x7fffffff;
7243
+ } else if (byteOffset < -0x80000000) {
7244
+ byteOffset = -0x80000000;
7245
+ }
7246
+ byteOffset = +byteOffset; // Coerce to Number.
7247
+ if (isNaN(byteOffset)) {
7248
+ // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
7249
+ byteOffset = dir ? 0 : (buffer.length - 1);
7250
+ }
7251
+
7252
+ // Normalize byteOffset: negative offsets start from the end of the buffer
7253
+ if (byteOffset < 0) byteOffset = buffer.length + byteOffset;
7254
+ if (byteOffset >= buffer.length) {
7255
+ if (dir) return -1
7256
+ else byteOffset = buffer.length - 1;
7257
+ } else if (byteOffset < 0) {
7258
+ if (dir) byteOffset = 0;
7259
+ else return -1
7260
+ }
7261
+
7262
+ // Normalize val
7263
+ if (typeof val === 'string') {
7264
+ val = Buffer.from(val, encoding);
7265
+ }
7266
+
7267
+ // Finally, search either indexOf (if dir is true) or lastIndexOf
7268
+ if (internalIsBuffer(val)) {
7269
+ // Special case: looking for empty string/buffer always fails
7270
+ if (val.length === 0) {
7271
+ return -1
7272
+ }
7273
+ return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
7274
+ } else if (typeof val === 'number') {
7275
+ val = val & 0xFF; // Search for a byte value [0-255]
7276
+ if (Buffer.TYPED_ARRAY_SUPPORT &&
7277
+ typeof Uint8Array.prototype.indexOf === 'function') {
7278
+ if (dir) {
7279
+ return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
7280
+ } else {
7281
+ return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
7282
+ }
7283
+ }
7284
+ return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
7285
+ }
7286
+
7287
+ throw new TypeError('val must be string, number or Buffer')
7288
+ }
7289
+
7290
+ function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
7291
+ var indexSize = 1;
7292
+ var arrLength = arr.length;
7293
+ var valLength = val.length;
7294
+
7295
+ if (encoding !== undefined) {
7296
+ encoding = String(encoding).toLowerCase();
7297
+ if (encoding === 'ucs2' || encoding === 'ucs-2' ||
7298
+ encoding === 'utf16le' || encoding === 'utf-16le') {
7299
+ if (arr.length < 2 || val.length < 2) {
7300
+ return -1
7301
+ }
7302
+ indexSize = 2;
7303
+ arrLength /= 2;
7304
+ valLength /= 2;
7305
+ byteOffset /= 2;
7306
+ }
7307
+ }
7308
+
7309
+ function read (buf, i) {
7310
+ if (indexSize === 1) {
7311
+ return buf[i]
7312
+ } else {
7313
+ return buf.readUInt16BE(i * indexSize)
7314
+ }
7315
+ }
7316
+
7317
+ var i;
7318
+ if (dir) {
7319
+ var foundIndex = -1;
7320
+ for (i = byteOffset; i < arrLength; i++) {
7321
+ if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
7322
+ if (foundIndex === -1) foundIndex = i;
7323
+ if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
7324
+ } else {
7325
+ if (foundIndex !== -1) i -= i - foundIndex;
7326
+ foundIndex = -1;
7327
+ }
7328
+ }
7329
+ } else {
7330
+ if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength;
7331
+ for (i = byteOffset; i >= 0; i--) {
7332
+ var found = true;
7333
+ for (var j = 0; j < valLength; j++) {
7334
+ if (read(arr, i + j) !== read(val, j)) {
7335
+ found = false;
7336
+ break
7337
+ }
7338
+ }
7339
+ if (found) return i
7340
+ }
7341
+ }
7342
+
7343
+ return -1
7344
+ }
7345
+
7346
+ Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
7347
+ return this.indexOf(val, byteOffset, encoding) !== -1
7348
+ };
7349
+
7350
+ Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
7351
+ return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
7352
+ };
7353
+
7354
+ Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
7355
+ return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
7356
+ };
7357
+
7358
+ function hexWrite (buf, string, offset, length) {
7359
+ offset = Number(offset) || 0;
7360
+ var remaining = buf.length - offset;
7361
+ if (!length) {
7362
+ length = remaining;
7363
+ } else {
7364
+ length = Number(length);
7365
+ if (length > remaining) {
7366
+ length = remaining;
7367
+ }
7368
+ }
7369
+
7370
+ // must be an even number of digits
7371
+ var strLen = string.length;
7372
+ if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')
7373
+
7374
+ if (length > strLen / 2) {
7375
+ length = strLen / 2;
7376
+ }
7377
+ for (var i = 0; i < length; ++i) {
7378
+ var parsed = parseInt(string.substr(i * 2, 2), 16);
7379
+ if (isNaN(parsed)) return i
7380
+ buf[offset + i] = parsed;
7381
+ }
7382
+ return i
7383
+ }
7384
+
7385
+ function utf8Write (buf, string, offset, length) {
7386
+ return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
7387
+ }
7388
+
7389
+ function asciiWrite (buf, string, offset, length) {
7390
+ return blitBuffer(asciiToBytes(string), buf, offset, length)
7391
+ }
7392
+
7393
+ function latin1Write (buf, string, offset, length) {
7394
+ return asciiWrite(buf, string, offset, length)
7395
+ }
7396
+
7397
+ function base64Write (buf, string, offset, length) {
7398
+ return blitBuffer(base64ToBytes(string), buf, offset, length)
7399
+ }
7400
+
7401
+ function ucs2Write (buf, string, offset, length) {
7402
+ return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
7403
+ }
7404
+
7405
+ Buffer.prototype.write = function write (string, offset, length, encoding) {
7406
+ // Buffer#write(string)
7407
+ if (offset === undefined) {
7408
+ encoding = 'utf8';
7409
+ length = this.length;
7410
+ offset = 0;
7411
+ // Buffer#write(string, encoding)
7412
+ } else if (length === undefined && typeof offset === 'string') {
7413
+ encoding = offset;
7414
+ length = this.length;
7415
+ offset = 0;
7416
+ // Buffer#write(string, offset[, length][, encoding])
7417
+ } else if (isFinite(offset)) {
7418
+ offset = offset | 0;
7419
+ if (isFinite(length)) {
7420
+ length = length | 0;
7421
+ if (encoding === undefined) encoding = 'utf8';
7422
+ } else {
7423
+ encoding = length;
7424
+ length = undefined;
7425
+ }
7426
+ // legacy write(string, encoding, offset, length) - remove in v0.13
7427
+ } else {
7428
+ throw new Error(
7429
+ 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
7430
+ )
7431
+ }
7432
+
7433
+ var remaining = this.length - offset;
7434
+ if (length === undefined || length > remaining) length = remaining;
7435
+
7436
+ if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
7437
+ throw new RangeError('Attempt to write outside buffer bounds')
7438
+ }
7439
+
7440
+ if (!encoding) encoding = 'utf8';
7441
+
7442
+ var loweredCase = false;
7443
+ for (;;) {
7444
+ switch (encoding) {
7445
+ case 'hex':
7446
+ return hexWrite(this, string, offset, length)
7447
+
7448
+ case 'utf8':
7449
+ case 'utf-8':
7450
+ return utf8Write(this, string, offset, length)
7451
+
7452
+ case 'ascii':
7453
+ return asciiWrite(this, string, offset, length)
7454
+
7455
+ case 'latin1':
7456
+ case 'binary':
7457
+ return latin1Write(this, string, offset, length)
7458
+
7459
+ case 'base64':
7460
+ // Warning: maxLength not taken into account in base64Write
7461
+ return base64Write(this, string, offset, length)
7462
+
7463
+ case 'ucs2':
7464
+ case 'ucs-2':
7465
+ case 'utf16le':
7466
+ case 'utf-16le':
7467
+ return ucs2Write(this, string, offset, length)
7468
+
7469
+ default:
7470
+ if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
7471
+ encoding = ('' + encoding).toLowerCase();
7472
+ loweredCase = true;
7473
+ }
7474
+ }
7475
+ };
7476
+
7477
+ Buffer.prototype.toJSON = function toJSON () {
7478
+ return {
7479
+ type: 'Buffer',
7480
+ data: Array.prototype.slice.call(this._arr || this, 0)
7481
+ }
7482
+ };
7483
+
7484
+ function base64Slice (buf, start, end) {
7485
+ if (start === 0 && end === buf.length) {
7486
+ return fromByteArray(buf)
7487
+ } else {
7488
+ return fromByteArray(buf.slice(start, end))
7489
+ }
7490
+ }
7491
+
7492
+ function utf8Slice (buf, start, end) {
7493
+ end = Math.min(buf.length, end);
7494
+ var res = [];
7495
+
7496
+ var i = start;
7497
+ while (i < end) {
7498
+ var firstByte = buf[i];
7499
+ var codePoint = null;
7500
+ var bytesPerSequence = (firstByte > 0xEF) ? 4
7501
+ : (firstByte > 0xDF) ? 3
7502
+ : (firstByte > 0xBF) ? 2
7503
+ : 1;
7504
+
7505
+ if (i + bytesPerSequence <= end) {
7506
+ var secondByte, thirdByte, fourthByte, tempCodePoint;
7507
+
7508
+ switch (bytesPerSequence) {
7509
+ case 1:
7510
+ if (firstByte < 0x80) {
7511
+ codePoint = firstByte;
7512
+ }
7513
+ break
7514
+ case 2:
7515
+ secondByte = buf[i + 1];
7516
+ if ((secondByte & 0xC0) === 0x80) {
7517
+ tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F);
7518
+ if (tempCodePoint > 0x7F) {
7519
+ codePoint = tempCodePoint;
7520
+ }
7521
+ }
7522
+ break
7523
+ case 3:
7524
+ secondByte = buf[i + 1];
7525
+ thirdByte = buf[i + 2];
7526
+ if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
7527
+ tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F);
7528
+ if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
7529
+ codePoint = tempCodePoint;
7530
+ }
7531
+ }
7532
+ break
7533
+ case 4:
7534
+ secondByte = buf[i + 1];
7535
+ thirdByte = buf[i + 2];
7536
+ fourthByte = buf[i + 3];
7537
+ if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
7538
+ tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F);
7539
+ if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
7540
+ codePoint = tempCodePoint;
7541
+ }
7542
+ }
7543
+ }
7544
+ }
7545
+
7546
+ if (codePoint === null) {
7547
+ // we did not generate a valid codePoint so insert a
7548
+ // replacement char (U+FFFD) and advance only 1 byte
7549
+ codePoint = 0xFFFD;
7550
+ bytesPerSequence = 1;
7551
+ } else if (codePoint > 0xFFFF) {
7552
+ // encode to utf16 (surrogate pair dance)
7553
+ codePoint -= 0x10000;
7554
+ res.push(codePoint >>> 10 & 0x3FF | 0xD800);
7555
+ codePoint = 0xDC00 | codePoint & 0x3FF;
7556
+ }
7557
+
7558
+ res.push(codePoint);
7559
+ i += bytesPerSequence;
7560
+ }
7561
+
7562
+ return decodeCodePointsArray(res)
7563
+ }
7564
+
7565
+ // Based on http://stackoverflow.com/a/22747272/680742, the browser with
7566
+ // the lowest limit is Chrome, with 0x10000 args.
7567
+ // We go 1 magnitude less, for safety
7568
+ var MAX_ARGUMENTS_LENGTH = 0x1000;
7569
+
7570
+ function decodeCodePointsArray (codePoints) {
7571
+ var len = codePoints.length;
7572
+ if (len <= MAX_ARGUMENTS_LENGTH) {
7573
+ return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
7574
+ }
7575
+
7576
+ // Decode in chunks to avoid "call stack size exceeded".
7577
+ var res = '';
7578
+ var i = 0;
7579
+ while (i < len) {
7580
+ res += String.fromCharCode.apply(
7581
+ String,
7582
+ codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
7583
+ );
7584
+ }
7585
+ return res
7586
+ }
7587
+
7588
+ function asciiSlice (buf, start, end) {
7589
+ var ret = '';
7590
+ end = Math.min(buf.length, end);
7591
+
7592
+ for (var i = start; i < end; ++i) {
7593
+ ret += String.fromCharCode(buf[i] & 0x7F);
7594
+ }
7595
+ return ret
7596
+ }
7597
+
7598
+ function latin1Slice (buf, start, end) {
7599
+ var ret = '';
7600
+ end = Math.min(buf.length, end);
7601
+
7602
+ for (var i = start; i < end; ++i) {
7603
+ ret += String.fromCharCode(buf[i]);
7604
+ }
7605
+ return ret
7606
+ }
7607
+
7608
+ function hexSlice (buf, start, end) {
7609
+ var len = buf.length;
7610
+
7611
+ if (!start || start < 0) start = 0;
7612
+ if (!end || end < 0 || end > len) end = len;
7613
+
7614
+ var out = '';
7615
+ for (var i = start; i < end; ++i) {
7616
+ out += toHex(buf[i]);
7617
+ }
7618
+ return out
7619
+ }
7620
+
7621
+ function utf16leSlice (buf, start, end) {
7622
+ var bytes = buf.slice(start, end);
7623
+ var res = '';
7624
+ for (var i = 0; i < bytes.length; i += 2) {
7625
+ res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256);
7626
+ }
7627
+ return res
7628
+ }
7629
+
7630
+ Buffer.prototype.slice = function slice (start, end) {
7631
+ var len = this.length;
7632
+ start = ~~start;
7633
+ end = end === undefined ? len : ~~end;
7634
+
7635
+ if (start < 0) {
7636
+ start += len;
7637
+ if (start < 0) start = 0;
7638
+ } else if (start > len) {
7639
+ start = len;
7640
+ }
7641
+
7642
+ if (end < 0) {
7643
+ end += len;
7644
+ if (end < 0) end = 0;
7645
+ } else if (end > len) {
7646
+ end = len;
7647
+ }
7648
+
7649
+ if (end < start) end = start;
7650
+
7651
+ var newBuf;
7652
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
7653
+ newBuf = this.subarray(start, end);
7654
+ newBuf.__proto__ = Buffer.prototype;
7655
+ } else {
7656
+ var sliceLen = end - start;
7657
+ newBuf = new Buffer(sliceLen, undefined);
7658
+ for (var i = 0; i < sliceLen; ++i) {
7659
+ newBuf[i] = this[i + start];
7660
+ }
7661
+ }
7662
+
7663
+ return newBuf
7664
+ };
7665
+
7666
+ /*
7667
+ * Need to make sure that buffer isn't trying to write out of bounds.
7668
+ */
7669
+ function checkOffset (offset, ext, length) {
7670
+ if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
7671
+ if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
7672
+ }
7673
+
7674
+ Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
7675
+ offset = offset | 0;
7676
+ byteLength = byteLength | 0;
7677
+ if (!noAssert) checkOffset(offset, byteLength, this.length);
7678
+
7679
+ var val = this[offset];
7680
+ var mul = 1;
7681
+ var i = 0;
7682
+ while (++i < byteLength && (mul *= 0x100)) {
7683
+ val += this[offset + i] * mul;
7684
+ }
7685
+
7686
+ return val
7687
+ };
7688
+
7689
+ Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
7690
+ offset = offset | 0;
7691
+ byteLength = byteLength | 0;
7692
+ if (!noAssert) {
7693
+ checkOffset(offset, byteLength, this.length);
7694
+ }
7695
+
7696
+ var val = this[offset + --byteLength];
7697
+ var mul = 1;
7698
+ while (byteLength > 0 && (mul *= 0x100)) {
7699
+ val += this[offset + --byteLength] * mul;
7700
+ }
7701
+
7702
+ return val
7703
+ };
7704
+
7705
+ Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
7706
+ if (!noAssert) checkOffset(offset, 1, this.length);
7707
+ return this[offset]
7708
+ };
7709
+
7710
+ Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
7711
+ if (!noAssert) checkOffset(offset, 2, this.length);
7712
+ return this[offset] | (this[offset + 1] << 8)
7713
+ };
7714
+
7715
+ Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
7716
+ if (!noAssert) checkOffset(offset, 2, this.length);
7717
+ return (this[offset] << 8) | this[offset + 1]
7718
+ };
7719
+
7720
+ Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
7721
+ if (!noAssert) checkOffset(offset, 4, this.length);
7722
+
7723
+ return ((this[offset]) |
7724
+ (this[offset + 1] << 8) |
7725
+ (this[offset + 2] << 16)) +
7726
+ (this[offset + 3] * 0x1000000)
7727
+ };
7728
+
7729
+ Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
7730
+ if (!noAssert) checkOffset(offset, 4, this.length);
7731
+
7732
+ return (this[offset] * 0x1000000) +
7733
+ ((this[offset + 1] << 16) |
7734
+ (this[offset + 2] << 8) |
7735
+ this[offset + 3])
7736
+ };
7737
+
7738
+ Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
7739
+ offset = offset | 0;
7740
+ byteLength = byteLength | 0;
7741
+ if (!noAssert) checkOffset(offset, byteLength, this.length);
7742
+
7743
+ var val = this[offset];
7744
+ var mul = 1;
7745
+ var i = 0;
7746
+ while (++i < byteLength && (mul *= 0x100)) {
7747
+ val += this[offset + i] * mul;
7748
+ }
7749
+ mul *= 0x80;
7750
+
7751
+ if (val >= mul) val -= Math.pow(2, 8 * byteLength);
7752
+
7753
+ return val
7754
+ };
7755
+
7756
+ Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
7757
+ offset = offset | 0;
7758
+ byteLength = byteLength | 0;
7759
+ if (!noAssert) checkOffset(offset, byteLength, this.length);
7760
+
7761
+ var i = byteLength;
7762
+ var mul = 1;
7763
+ var val = this[offset + --i];
7764
+ while (i > 0 && (mul *= 0x100)) {
7765
+ val += this[offset + --i] * mul;
7766
+ }
7767
+ mul *= 0x80;
7768
+
7769
+ if (val >= mul) val -= Math.pow(2, 8 * byteLength);
7770
+
7771
+ return val
7772
+ };
7773
+
7774
+ Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
7775
+ if (!noAssert) checkOffset(offset, 1, this.length);
7776
+ if (!(this[offset] & 0x80)) return (this[offset])
7777
+ return ((0xff - this[offset] + 1) * -1)
7778
+ };
7779
+
7780
+ Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
7781
+ if (!noAssert) checkOffset(offset, 2, this.length);
7782
+ var val = this[offset] | (this[offset + 1] << 8);
7783
+ return (val & 0x8000) ? val | 0xFFFF0000 : val
7784
+ };
7785
+
7786
+ Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
7787
+ if (!noAssert) checkOffset(offset, 2, this.length);
7788
+ var val = this[offset + 1] | (this[offset] << 8);
7789
+ return (val & 0x8000) ? val | 0xFFFF0000 : val
7790
+ };
7791
+
7792
+ Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
7793
+ if (!noAssert) checkOffset(offset, 4, this.length);
7794
+
7795
+ return (this[offset]) |
7796
+ (this[offset + 1] << 8) |
7797
+ (this[offset + 2] << 16) |
7798
+ (this[offset + 3] << 24)
7799
+ };
7800
+
7801
+ Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
7802
+ if (!noAssert) checkOffset(offset, 4, this.length);
7803
+
7804
+ return (this[offset] << 24) |
7805
+ (this[offset + 1] << 16) |
7806
+ (this[offset + 2] << 8) |
7807
+ (this[offset + 3])
7808
+ };
7809
+
7810
+ Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
7811
+ if (!noAssert) checkOffset(offset, 4, this.length);
7812
+ return read(this, offset, true, 23, 4)
7813
+ };
7814
+
7815
+ Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
7816
+ if (!noAssert) checkOffset(offset, 4, this.length);
7817
+ return read(this, offset, false, 23, 4)
7818
+ };
7819
+
7820
+ Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
7821
+ if (!noAssert) checkOffset(offset, 8, this.length);
7822
+ return read(this, offset, true, 52, 8)
7823
+ };
7824
+
7825
+ Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
7826
+ if (!noAssert) checkOffset(offset, 8, this.length);
7827
+ return read(this, offset, false, 52, 8)
7828
+ };
7829
+
7830
+ function checkInt (buf, value, offset, ext, max, min) {
7831
+ if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
7832
+ if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
7833
+ if (offset + ext > buf.length) throw new RangeError('Index out of range')
7834
+ }
7835
+
7836
+ Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
7837
+ value = +value;
7838
+ offset = offset | 0;
7839
+ byteLength = byteLength | 0;
7840
+ if (!noAssert) {
7841
+ var maxBytes = Math.pow(2, 8 * byteLength) - 1;
7842
+ checkInt(this, value, offset, byteLength, maxBytes, 0);
7843
+ }
7844
+
7845
+ var mul = 1;
7846
+ var i = 0;
7847
+ this[offset] = value & 0xFF;
7848
+ while (++i < byteLength && (mul *= 0x100)) {
7849
+ this[offset + i] = (value / mul) & 0xFF;
7850
+ }
7851
+
7852
+ return offset + byteLength
7853
+ };
7854
+
7855
+ Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
7856
+ value = +value;
7857
+ offset = offset | 0;
7858
+ byteLength = byteLength | 0;
7859
+ if (!noAssert) {
7860
+ var maxBytes = Math.pow(2, 8 * byteLength) - 1;
7861
+ checkInt(this, value, offset, byteLength, maxBytes, 0);
7862
+ }
7863
+
7864
+ var i = byteLength - 1;
7865
+ var mul = 1;
7866
+ this[offset + i] = value & 0xFF;
7867
+ while (--i >= 0 && (mul *= 0x100)) {
7868
+ this[offset + i] = (value / mul) & 0xFF;
7869
+ }
7870
+
7871
+ return offset + byteLength
7872
+ };
7873
+
7874
+ Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
7875
+ value = +value;
7876
+ offset = offset | 0;
7877
+ if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0);
7878
+ if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value);
7879
+ this[offset] = (value & 0xff);
7880
+ return offset + 1
7881
+ };
7882
+
7883
+ function objectWriteUInt16 (buf, value, offset, littleEndian) {
7884
+ if (value < 0) value = 0xffff + value + 1;
7885
+ for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {
7886
+ buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
7887
+ (littleEndian ? i : 1 - i) * 8;
7888
+ }
7889
+ }
7890
+
7891
+ Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
7892
+ value = +value;
7893
+ offset = offset | 0;
7894
+ if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
7895
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
7896
+ this[offset] = (value & 0xff);
7897
+ this[offset + 1] = (value >>> 8);
7898
+ } else {
7899
+ objectWriteUInt16(this, value, offset, true);
7900
+ }
7901
+ return offset + 2
7902
+ };
7903
+
7904
+ Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
7905
+ value = +value;
7906
+ offset = offset | 0;
7907
+ if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
7908
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
7909
+ this[offset] = (value >>> 8);
7910
+ this[offset + 1] = (value & 0xff);
7911
+ } else {
7912
+ objectWriteUInt16(this, value, offset, false);
7913
+ }
7914
+ return offset + 2
7915
+ };
7916
+
7917
+ function objectWriteUInt32 (buf, value, offset, littleEndian) {
7918
+ if (value < 0) value = 0xffffffff + value + 1;
7919
+ for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {
7920
+ buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff;
7921
+ }
7922
+ }
7923
+
7924
+ Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
7925
+ value = +value;
7926
+ offset = offset | 0;
7927
+ if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
7928
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
7929
+ this[offset + 3] = (value >>> 24);
7930
+ this[offset + 2] = (value >>> 16);
7931
+ this[offset + 1] = (value >>> 8);
7932
+ this[offset] = (value & 0xff);
7933
+ } else {
7934
+ objectWriteUInt32(this, value, offset, true);
7935
+ }
7936
+ return offset + 4
7937
+ };
7938
+
7939
+ Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
7940
+ value = +value;
7941
+ offset = offset | 0;
7942
+ if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
7943
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
7944
+ this[offset] = (value >>> 24);
7945
+ this[offset + 1] = (value >>> 16);
7946
+ this[offset + 2] = (value >>> 8);
7947
+ this[offset + 3] = (value & 0xff);
7948
+ } else {
7949
+ objectWriteUInt32(this, value, offset, false);
7950
+ }
7951
+ return offset + 4
7952
+ };
7953
+
7954
+ Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
7955
+ value = +value;
7956
+ offset = offset | 0;
7957
+ if (!noAssert) {
7958
+ var limit = Math.pow(2, 8 * byteLength - 1);
7959
+
7960
+ checkInt(this, value, offset, byteLength, limit - 1, -limit);
7961
+ }
7962
+
7963
+ var i = 0;
7964
+ var mul = 1;
7965
+ var sub = 0;
7966
+ this[offset] = value & 0xFF;
7967
+ while (++i < byteLength && (mul *= 0x100)) {
7968
+ if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
7969
+ sub = 1;
7970
+ }
7971
+ this[offset + i] = ((value / mul) >> 0) - sub & 0xFF;
7972
+ }
7973
+
7974
+ return offset + byteLength
7975
+ };
7976
+
7977
+ Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
7978
+ value = +value;
7979
+ offset = offset | 0;
7980
+ if (!noAssert) {
7981
+ var limit = Math.pow(2, 8 * byteLength - 1);
7982
+
7983
+ checkInt(this, value, offset, byteLength, limit - 1, -limit);
7984
+ }
7985
+
7986
+ var i = byteLength - 1;
7987
+ var mul = 1;
7988
+ var sub = 0;
7989
+ this[offset + i] = value & 0xFF;
7990
+ while (--i >= 0 && (mul *= 0x100)) {
7991
+ if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
7992
+ sub = 1;
7993
+ }
7994
+ this[offset + i] = ((value / mul) >> 0) - sub & 0xFF;
7995
+ }
7996
+
7997
+ return offset + byteLength
7998
+ };
7999
+
8000
+ Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
8001
+ value = +value;
8002
+ offset = offset | 0;
8003
+ if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80);
8004
+ if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value);
8005
+ if (value < 0) value = 0xff + value + 1;
8006
+ this[offset] = (value & 0xff);
8007
+ return offset + 1
8008
+ };
8009
+
8010
+ Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
8011
+ value = +value;
8012
+ offset = offset | 0;
8013
+ if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000);
8014
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
8015
+ this[offset] = (value & 0xff);
8016
+ this[offset + 1] = (value >>> 8);
8017
+ } else {
8018
+ objectWriteUInt16(this, value, offset, true);
8019
+ }
8020
+ return offset + 2
8021
+ };
8022
+
8023
+ Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
8024
+ value = +value;
8025
+ offset = offset | 0;
8026
+ if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000);
8027
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
8028
+ this[offset] = (value >>> 8);
8029
+ this[offset + 1] = (value & 0xff);
8030
+ } else {
8031
+ objectWriteUInt16(this, value, offset, false);
8032
+ }
8033
+ return offset + 2
8034
+ };
8035
+
8036
+ Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
8037
+ value = +value;
8038
+ offset = offset | 0;
8039
+ if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
8040
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
8041
+ this[offset] = (value & 0xff);
8042
+ this[offset + 1] = (value >>> 8);
8043
+ this[offset + 2] = (value >>> 16);
8044
+ this[offset + 3] = (value >>> 24);
8045
+ } else {
8046
+ objectWriteUInt32(this, value, offset, true);
8047
+ }
8048
+ return offset + 4
8049
+ };
8050
+
8051
+ Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
8052
+ value = +value;
8053
+ offset = offset | 0;
8054
+ if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
8055
+ if (value < 0) value = 0xffffffff + value + 1;
8056
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
8057
+ this[offset] = (value >>> 24);
8058
+ this[offset + 1] = (value >>> 16);
8059
+ this[offset + 2] = (value >>> 8);
8060
+ this[offset + 3] = (value & 0xff);
8061
+ } else {
8062
+ objectWriteUInt32(this, value, offset, false);
8063
+ }
8064
+ return offset + 4
8065
+ };
8066
+
8067
+ function checkIEEE754 (buf, value, offset, ext, max, min) {
8068
+ if (offset + ext > buf.length) throw new RangeError('Index out of range')
8069
+ if (offset < 0) throw new RangeError('Index out of range')
8070
+ }
8071
+
8072
+ function writeFloat (buf, value, offset, littleEndian, noAssert) {
8073
+ if (!noAssert) {
8074
+ checkIEEE754(buf, value, offset, 4);
8075
+ }
8076
+ write(buf, value, offset, littleEndian, 23, 4);
8077
+ return offset + 4
8078
+ }
8079
+
8080
+ Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
8081
+ return writeFloat(this, value, offset, true, noAssert)
8082
+ };
8083
+
8084
+ Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
8085
+ return writeFloat(this, value, offset, false, noAssert)
8086
+ };
8087
+
8088
+ function writeDouble (buf, value, offset, littleEndian, noAssert) {
8089
+ if (!noAssert) {
8090
+ checkIEEE754(buf, value, offset, 8);
8091
+ }
8092
+ write(buf, value, offset, littleEndian, 52, 8);
8093
+ return offset + 8
8094
+ }
8095
+
8096
+ Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
8097
+ return writeDouble(this, value, offset, true, noAssert)
8098
+ };
8099
+
8100
+ Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
8101
+ return writeDouble(this, value, offset, false, noAssert)
8102
+ };
8103
+
8104
+ // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
8105
+ Buffer.prototype.copy = function copy (target, targetStart, start, end) {
8106
+ if (!start) start = 0;
8107
+ if (!end && end !== 0) end = this.length;
8108
+ if (targetStart >= target.length) targetStart = target.length;
8109
+ if (!targetStart) targetStart = 0;
8110
+ if (end > 0 && end < start) end = start;
8111
+
8112
+ // Copy 0 bytes; we're done
8113
+ if (end === start) return 0
8114
+ if (target.length === 0 || this.length === 0) return 0
8115
+
8116
+ // Fatal error conditions
8117
+ if (targetStart < 0) {
8118
+ throw new RangeError('targetStart out of bounds')
8119
+ }
8120
+ if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
8121
+ if (end < 0) throw new RangeError('sourceEnd out of bounds')
8122
+
8123
+ // Are we oob?
8124
+ if (end > this.length) end = this.length;
8125
+ if (target.length - targetStart < end - start) {
8126
+ end = target.length - targetStart + start;
8127
+ }
8128
+
8129
+ var len = end - start;
8130
+ var i;
8131
+
8132
+ if (this === target && start < targetStart && targetStart < end) {
8133
+ // descending copy from end
8134
+ for (i = len - 1; i >= 0; --i) {
8135
+ target[i + targetStart] = this[i + start];
8136
+ }
8137
+ } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
8138
+ // ascending copy from start
8139
+ for (i = 0; i < len; ++i) {
8140
+ target[i + targetStart] = this[i + start];
8141
+ }
8142
+ } else {
8143
+ Uint8Array.prototype.set.call(
8144
+ target,
8145
+ this.subarray(start, start + len),
8146
+ targetStart
8147
+ );
8148
+ }
8149
+
8150
+ return len
8151
+ };
8152
+
8153
+ // Usage:
8154
+ // buffer.fill(number[, offset[, end]])
8155
+ // buffer.fill(buffer[, offset[, end]])
8156
+ // buffer.fill(string[, offset[, end]][, encoding])
8157
+ Buffer.prototype.fill = function fill (val, start, end, encoding) {
8158
+ // Handle string cases:
8159
+ if (typeof val === 'string') {
8160
+ if (typeof start === 'string') {
8161
+ encoding = start;
8162
+ start = 0;
8163
+ end = this.length;
8164
+ } else if (typeof end === 'string') {
8165
+ encoding = end;
8166
+ end = this.length;
8167
+ }
8168
+ if (val.length === 1) {
8169
+ var code = val.charCodeAt(0);
8170
+ if (code < 256) {
8171
+ val = code;
8172
+ }
8173
+ }
8174
+ if (encoding !== undefined && typeof encoding !== 'string') {
8175
+ throw new TypeError('encoding must be a string')
8176
+ }
8177
+ if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
8178
+ throw new TypeError('Unknown encoding: ' + encoding)
8179
+ }
8180
+ } else if (typeof val === 'number') {
8181
+ val = val & 255;
8182
+ }
8183
+
8184
+ // Invalid ranges are not set to a default, so can range check early.
8185
+ if (start < 0 || this.length < start || this.length < end) {
8186
+ throw new RangeError('Out of range index')
8187
+ }
8188
+
8189
+ if (end <= start) {
8190
+ return this
8191
+ }
8192
+
8193
+ start = start >>> 0;
8194
+ end = end === undefined ? this.length : end >>> 0;
8195
+
8196
+ if (!val) val = 0;
8197
+
8198
+ var i;
8199
+ if (typeof val === 'number') {
8200
+ for (i = start; i < end; ++i) {
8201
+ this[i] = val;
8202
+ }
8203
+ } else {
8204
+ var bytes = internalIsBuffer(val)
8205
+ ? val
8206
+ : utf8ToBytes(new Buffer(val, encoding).toString());
8207
+ var len = bytes.length;
8208
+ for (i = 0; i < end - start; ++i) {
8209
+ this[i + start] = bytes[i % len];
8210
+ }
8211
+ }
8212
+
8213
+ return this
8214
+ };
8215
+
8216
+ // HELPER FUNCTIONS
8217
+ // ================
8218
+
8219
+ var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g;
8220
+
8221
+ function base64clean (str) {
8222
+ // Node strips out invalid characters like \n and \t from the string, base64-js does not
8223
+ str = stringtrim(str).replace(INVALID_BASE64_RE, '');
8224
+ // Node converts strings with length < 2 to ''
8225
+ if (str.length < 2) return ''
8226
+ // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
8227
+ while (str.length % 4 !== 0) {
8228
+ str = str + '=';
8229
+ }
8230
+ return str
8231
+ }
8232
+
8233
+ function stringtrim (str) {
8234
+ if (str.trim) return str.trim()
8235
+ return str.replace(/^\s+|\s+$/g, '')
8236
+ }
8237
+
8238
+ function toHex (n) {
8239
+ if (n < 16) return '0' + n.toString(16)
8240
+ return n.toString(16)
8241
+ }
8242
+
8243
+ function utf8ToBytes (string, units) {
8244
+ units = units || Infinity;
8245
+ var codePoint;
8246
+ var length = string.length;
8247
+ var leadSurrogate = null;
8248
+ var bytes = [];
8249
+
8250
+ for (var i = 0; i < length; ++i) {
8251
+ codePoint = string.charCodeAt(i);
8252
+
8253
+ // is surrogate component
8254
+ if (codePoint > 0xD7FF && codePoint < 0xE000) {
8255
+ // last char was a lead
8256
+ if (!leadSurrogate) {
8257
+ // no lead yet
8258
+ if (codePoint > 0xDBFF) {
8259
+ // unexpected trail
8260
+ if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
8261
+ continue
8262
+ } else if (i + 1 === length) {
8263
+ // unpaired lead
8264
+ if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
8265
+ continue
8266
+ }
8267
+
8268
+ // valid lead
8269
+ leadSurrogate = codePoint;
8270
+
8271
+ continue
8272
+ }
8273
+
8274
+ // 2 leads in a row
8275
+ if (codePoint < 0xDC00) {
8276
+ if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
8277
+ leadSurrogate = codePoint;
8278
+ continue
8279
+ }
8280
+
8281
+ // valid surrogate pair
8282
+ codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000;
8283
+ } else if (leadSurrogate) {
8284
+ // valid bmp char, but last char was a lead
8285
+ if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
8286
+ }
8287
+
8288
+ leadSurrogate = null;
8289
+
8290
+ // encode utf8
8291
+ if (codePoint < 0x80) {
8292
+ if ((units -= 1) < 0) break
8293
+ bytes.push(codePoint);
8294
+ } else if (codePoint < 0x800) {
8295
+ if ((units -= 2) < 0) break
8296
+ bytes.push(
8297
+ codePoint >> 0x6 | 0xC0,
8298
+ codePoint & 0x3F | 0x80
8299
+ );
8300
+ } else if (codePoint < 0x10000) {
8301
+ if ((units -= 3) < 0) break
8302
+ bytes.push(
8303
+ codePoint >> 0xC | 0xE0,
8304
+ codePoint >> 0x6 & 0x3F | 0x80,
8305
+ codePoint & 0x3F | 0x80
8306
+ );
8307
+ } else if (codePoint < 0x110000) {
8308
+ if ((units -= 4) < 0) break
8309
+ bytes.push(
8310
+ codePoint >> 0x12 | 0xF0,
8311
+ codePoint >> 0xC & 0x3F | 0x80,
8312
+ codePoint >> 0x6 & 0x3F | 0x80,
8313
+ codePoint & 0x3F | 0x80
8314
+ );
8315
+ } else {
8316
+ throw new Error('Invalid code point')
8317
+ }
8318
+ }
8319
+
8320
+ return bytes
8321
+ }
8322
+
8323
+ function asciiToBytes (str) {
8324
+ var byteArray = [];
8325
+ for (var i = 0; i < str.length; ++i) {
8326
+ // Node's code seems to be doing this and not & 0x7F..
8327
+ byteArray.push(str.charCodeAt(i) & 0xFF);
8328
+ }
8329
+ return byteArray
8330
+ }
8331
+
8332
+ function utf16leToBytes (str, units) {
8333
+ var c, hi, lo;
8334
+ var byteArray = [];
8335
+ for (var i = 0; i < str.length; ++i) {
8336
+ if ((units -= 2) < 0) break
8337
+
8338
+ c = str.charCodeAt(i);
8339
+ hi = c >> 8;
8340
+ lo = c % 256;
8341
+ byteArray.push(lo);
8342
+ byteArray.push(hi);
8343
+ }
8344
+
8345
+ return byteArray
8346
+ }
8347
+
8348
+
8349
+ function base64ToBytes (str) {
8350
+ return toByteArray(base64clean(str))
8351
+ }
8352
+
8353
+ function blitBuffer (src, dst, offset, length) {
8354
+ for (var i = 0; i < length; ++i) {
8355
+ if ((i + offset >= dst.length) || (i >= src.length)) break
8356
+ dst[i + offset] = src[i];
8357
+ }
8358
+ return i
8359
+ }
8360
+
8361
+ function isnan (val) {
8362
+ return val !== val // eslint-disable-line no-self-compare
8363
+ }
8364
+
8365
+
8366
+ // the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence
8367
+ // The _isBuffer check is for Safari 5-7 support, because it's missing
8368
+ // Object.prototype.constructor. Remove this eventually
8369
+ function isBuffer(obj) {
8370
+ return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj))
8371
+ }
8372
+
8373
+ function isFastBuffer (obj) {
8374
+ return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
8375
+ }
8376
+
8377
+ // For Node v0.10 support. Remove this eventually.
8378
+ function isSlowBuffer (obj) {
8379
+ return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0))
8380
+ }
8381
+
6189
8382
  /**
6190
8383
  * Convert a data object to FormData
6191
8384
  * @param {Object} obj
@@ -6734,7 +8927,7 @@ function getDefaultAdapter() {
6734
8927
  if (typeof XMLHttpRequest !== 'undefined') {
6735
8928
  // For browsers use XHR adapter
6736
8929
  adapter = xhr;
6737
- } else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') {
8930
+ } else if (typeof browser$1 !== 'undefined' && Object.prototype.toString.call(browser$1) === '[object process]') {
6738
8931
  // For node use HTTP adapter
6739
8932
  adapter = xhr;
6740
8933
  }
@@ -7511,7 +9704,7 @@ var axios = axios_1;
7511
9704
 
7512
9705
  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(r){var t=String(r).replace(/=+$/,"");if(t.length%4==1)throw new e("'atob' failed: The string to be decoded is not correctly encoded.");for(var n,o,a=0,i=0,c="";o=t.charAt(i++);~o&&(n=a%4?64*n+o:o,a++%4)?c+=String.fromCharCode(255&n>>(-2*a&6)):0)o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(o);return c};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,r){var t=r.charCodeAt(0).toString(16).toUpperCase();return t.length<2&&(t="0"+t),"%"+t})))}(t)}catch(e){return r(t)}}function n$1(e){this.message=e;}function o$1(e,r){if("string"!=typeof e)throw new n$1("Invalid token specified");var o=!0===(r=r||{}).header?0:1;try{return JSON.parse(t(e.split(".")[o]))}catch(e){throw new n$1("Invalid token specified: "+e.message)}}n$1.prototype=new Error,n$1.prototype.name="InvalidTokenError";
7513
9706
 
7514
- let s=function(e,t,a){return alert(e)},n=function(e,t){return s(e,l.error,t)},l={error:"error",success:"success",info:"info"};var o={fire:function(e,t,a){return s(e,t,a)},setNotifier:function(e){s=e,salla.event.emit("twilight::notifier.changed");},error:n,success:function(e,t){return s(e,l.success,t)},info:function(e,t){return s(e,l.info,t)},sallaInitiated:function(){let e=window.location.href.match(/([\?\&]danger=)[^&]+/g);e&&(window.history.replaceState(null,document.title,window.location.pathname),salla.event.once("twilight::notifier.changed",(()=>{e.forEach((e=>{n(decodeURI(e.replace("?danger=","").replace("&danger=","")));}));})));},types:l};class d{constructor(e,t){return this.api=e,this.event=t,new Proxy(this,{get:function(a,r){return "event"===r?t:"api"===r?e:e&&e[r]||a[r]}})}}String.prototype.toStudlyCase=function(){return this.trim().replace(/([^a-zA-Z\d].)/g,(function(e){return e.toUpperCase().replace(/[^a-zA-Z\d]/g,"")}))},String.prototype.toDatasetName=function(){return this.startsWith("data-")?this.substr(5).toStudlyCase():this.toStudlyCase()},String.prototype.toSelector=function(){return this.trim().startsWith(".")||this.trim().startsWith("#")?this:"#"+this},String.prototype.replaceArray=function(e,t){for(var a,r=this,i=0;i<e.length;i++)a=new RegExp(e[i],"g"),r=r.replace(a,t[i]);return r},String.prototype.rtrim=function(e){return void 0===e&&(e="\\s"),this.replace(new RegExp("["+e+"]*$"),"")},String.prototype.ltrim=function(e){return void 0===e&&(e="\\s"),this.replace(new RegExp("^["+e+"]*"),"")},String.prototype.digitsOnly=function(){return Salla.helpers.digitsOnly(this)},Element.prototype.matches||(Element.prototype.matches=Element.prototype.msMatchesSelector),Element.prototype.closest||(Element.prototype.closest=function(e){for(var t=this;t;){if(t.matches(e))return t;t=t.parentElement;}}),Element.prototype.getElementSallaData=function(e,...t){if(!this.getAttribute)return;if(this.hasAttribute("data-json"))try{return JSON.parse(this.getAttribute("data-json"))}catch(e){}let a=this.getAttribute("data-function");if(a&&window[a])return "function"==typeof window[a]?this.getFilteredData(window[a].call(this,...t)):this.getFilteredData(window[a]);let r=this.hasAttribute("data-form-selector")?document.querySelector(this.dataset.formSelector):void 0;if(r="FORM"===this.tagName?this:r||this.closest("form")||this.closest("[salla-form-data]")||this,r&&"FORM"===r.tagName)return this.getFilteredData(new FormData(r),null,r);let i=r.querySelectorAll("[name]");if(!i.length)return this.getFilteredData();let s=Object.assign({},this.dataset);return i.forEach((e=>{if(!["checkbox","radio"].includes(e.type)||e.checked)try{let t=Salla.helpers.inputData(e.name,e.value,s);s[t.name]=t.value;}catch(t){Salla.log(e.name+" can't be send");}})),this.getFilteredData(s)},Element.prototype.canEventFireHook=function(e){return !!this.hasAttribute&&this.hasAttribute(Salla.api.hooksPrefix+e.type)},Element.prototype.hasAttributeStartsWith=function(e,t){e=e.toLowerCase();for(var a=0;a<this.attributes.length;a++){let r=this.attributes[a].name.toLowerCase();if(0===r.indexOf(e))return !t||r}return !1},HTMLFormElement.prototype.getAjaxFormData=function(e){var t=this.querySelectorAll('input[type="file"]');t.forEach((e=>{e.files.length||e.setAttribute("disabled","");}));var a=new FormData(this);return t.forEach((e=>{e.files.length||e.removeAttribute("disabled");})),{formData:this.getFilteredData(a,e),url:this.getAttribute("action"),method:this.getAttribute("method")||"post",events:{success:this.dataset.onSuccess,fail:this.dataset.onFail}}},Element.prototype.getFilteredData=function(e=null,t=null,a=null){return e=e||a?.dataset||this.dataset,a&&this.name&&void 0!==this.value&&(e=function(e,t,a){e instanceof FormData?e.append(t,a):e[t]=a;return e}(e,this.name,this.value)),["filterBeforeSubmit","filterBeforeSend"].forEach((r=>{let i=a?.dataset[r]||this.dataset[r];if(i){var s=window[i];if("function"==typeof s){if(!s(e,a||this,t)&&e)throw `Data failed to be pass verify function window.${i}(formData, element, event)!`;return s(e,a||this,t)}Salla.log("window."+i+"() not found!");}})),e},HTMLAnchorElement.prototype.getAjaxFormData=function(e){return {formData:this.getFilteredData(null,e),url:this.getAttribute("href"),method:this.dataset.type||"get",events:{success:this.dataset.onSuccess,fail:this.dataset.onFail}}};class c{constructor(){this.events={},this.namespace="";let e=/function (.{1,})\(/.exec(this.constructor.toString());this.className=(e&&e.length>1?e[1]:"").toLowerCase();}after_init(){this.createDynamicFunctions();}createDynamicFunctions(){Object.keys(this.events).forEach((e=>{this.createDynamicEventFuns(e),this.createDynamicListenerFuns(e);}));}createDynamicEventFuns(e){if(this[e])return;let t=this;this[e]=function(...a){return t.dispatch(e,...a)};}createDynamicListenerFuns(e){let t="on"+e.charAt(0).toUpperCase()+e.slice(1);if(this[t])return;let a=this;this[t]=function(t){return a.on(e,(async(...e)=>t(...e)))};}getEventName(e){return e=this.events[e]||e,!this.namespace||e.includes("::")?e:this.namespace+Salla.event.delimiter+e}dispatch(e,...t){return Salla.event.emitAsync(this.getEventName(e),...t)}on(e,t){return Salla.event.addListener(this.getEventName(e),t)}once(e,t){return Salla.event.once(this.getEventName(e),t)}}function u(e){e&&e.sallaInitiated&&!e.initiated&&(e.sallaInitiated(),e.initiated=!0);}Salla.event.auth=new class extends c{constructor(){super(),this.namespace="auth",this.events={login:"login",logout:"logout",codeSent:"code.sent",codeNotSent:"code.not-sent",verified:"verified",verificationFailed:"verification.failed",loggedIn:"logged.in",registered:"registered",registrationFailed:"registration.failed",loggedOut:"logged.out",failedLogout:"failed.logout",refreshFailed:"refresh.failed",tokenFetched:"token.fetched"},this.after_init();}login(e){return e?(e.type&&this.setTypeActionOnVerified(e.type),this.next_event=e.next_event||null,this.dispatch("login",...arguments)):(this.next_event=null,this.dispatch("login",...arguments))}loggedIn(e){return Salla.profile.info().finally((()=>this.dispatch("loggedIn",e)))}setTypeActionOnVerified(e){this.type_action_on_verified=e;}getTypeActionOnVerified(){return this.type_action_on_verified||"redirect"}},Salla.event.cart=new class extends c{constructor(){super(),this.namespace="cart",this.events={latestFetched:"latest.fetched",latestFailed:"latest.failed",updated:"updated",itemUpdated:"item.updated",itemUpdatedFailed:"item.updated.failed",itemAdded:"item.added",itemAddedFailed:"item.added.failed",itemDeleted:"item.deleted",itemDeletedFailed:"item.deleted.failed",submitted:"submitted",submitFailed:"submit.failed",imageDeleted:"image.deleted",imageNotDeleted:"image.not.deleted",detailsFetched:"details.fetched",detailsNotFetched:"details.not.fetched",successReset:"success.reset",priceQuoteSucceeded:"price-quote.succeeded",priceQuoteFailed:"price-quote.failed",couponAdded:"coupon.added",couponDeleted:"coupon.deleted",couponAdditionFailed:"coupon.addition.failed",couponDeletionFailed:"coupon.deletion.failed",quickOrderSettingFetched:"quick-order.fetched",quickOrderSettingFailed:"quick-order.failed",quickOrderSucceeded:"quick-order.succeeded",quickOrderFailed:"quick-order.failed"},this.after_init();}updated(e){return Salla.cookie.set("fresh_summary",1),e&&"object"==typeof e?(e.offer&&salla.product.event.offerExisted(e.offer),e.redirect&&(salla.log("The current cart is purchased!"),salla.cart.api.reset()),e.cart?(salla.storage.set("cart.summary",{total:e.cart.total,sub_total:e.cart.sub_total,discount:e.cart.discount,real_shipping_cost:e.cart.real_shipping_cost,count:e.cart.count,shipping_cost:e.cart.free_shipping_bar?.has_free_shipping?0:e.cart.real_shipping_cost}),this.dispatch("updated",e.cart)):void salla.log("Failed to get the cart summary!")):(Salla.logger.info("Cart summary not an object!",e),this.dispatch("updated"))}latestFetched(e){return this.updated(e.data),this.dispatch("latestFetched",e)}itemAdded(e,t){return this.updated(e.data),this.dispatch("itemAdded",e,t)}itemDeleted(e,t){return this.updated(e.data),this.dispatch("itemDeleted",e,t)}itemUpdated(e,t){return this.updated(e.data),this.dispatch("itemUpdated",e,t)}couponAdded(e,t){return this.updated(e.data),this.dispatch("couponAdded",e,t)}couponDeleted(e,t){return this.updated(e.data),this.dispatch("couponDeleted",e,t)}},Salla.event.order=new class extends c{constructor(){super(),this.namespace="order",this.events={canceled:"canceled",notCanceled:"not.canceled",orderCreated:"order.created",orderCreationFailed:"order.creation.failed",invoiceSent:"invoice.sent",invoiceNotSent:"invoice.not.sent"},this.after_init();}},Salla.event.scope=new class extends c{constructor(){super(),this.namespace="scope",this.events={fetched:"fetched",notFetched:"not.fetched",productAvailabilityFetched:"product-availability.fetched",productAvailabilityNotFetched:"product-availability.not.fetched",changeSucceeded:"changed",changeFailed:"not.changed"},this.after_init();}},Salla.event.rating=new class extends c{constructor(){super(),this.namespace="rating",this.events={orderNotFetched:"order.not.fetched",orderFetched:"order.fetched",storeRated:"store.rated",storeFailed:"store.failed",productsRated:"products.rated",productsFailed:"products.failed",shippingRated:"shipping.rated",shippingFailed:"shipping.failed"},this.after_init();}},Salla.event.comment=new class extends c{constructor(){super(),this.namespace="comment",this.events={added:"added",additionFailed:"addition.failed"},this.after_init();}},Salla.event.loyalty=new class extends c{constructor(){super(),this.namespace="loyalty",this.events={exchangeSucceeded:"exchange.succeeded",exchangeFailed:"exchange.failed",programFetched:"program.fetched",programNotFetched:"program.not.fetched",resetSucceeded:"exchange-reset.succeeded",resetFailed:"exchange-reset.failed"},this.after_init();}},Salla.event.product=new class extends c{constructor(){super(),this.namespace="product",this.events={priceUpdated:"price.updated",priceUpdateFailed:"price.updated.failed",availabilitySubscribed:"availability.subscribed",availabilitySubscribeFailed:"availability.subscribe.failed",categoriesFetched:"categories.fetched",categoriesFailed:"categories.failed",searchFailed:"search.failed",searchResults:"search.results",offerExisted:"offer.existed",fetchOffersFailed:"fetch.offers.failed",offersFetched:"offers.fetched",sizeGuideFetched:"size-guide.fetched",SizeGuideFetchFailed:"size-guide.failed",giftFetched:"gift.fetched",giftFetchFailed:"gift.failed",detailFetched:"detail.fetched",detailFetchFailed:"detail.failed",addGiftToCartSucceeded:"gift.add-to-cart.succeeded",addGiftToCartFailed:"gift.add-to-cart.failed",giftImageUploadSucceeded:"gift.image-upload.succeeded",giftImageUploadFailed:"gift.image-upload.failed"},this.after_init();}},Salla.event.profile=new class extends c{constructor(){super(),this.namespace="profile",this.events={updated:"updated",updateFailed:"update.failed",verificationCodeSent:"verification.code.sent",updateContactsFailed:"update.contacts.failed",verified:"verified",unverified:"unverified",infoFetched:"info.fetched",infoNotFetched:"info.not.fetched",settingsUpdated:"settings.updated",updateSettingsFailed:"update.settings.failed",deleted:"deleted",notDeleted:"not.deleted"},this.after_init();}},Salla.event.currency=new class extends c{constructor(){super(),this.namespace="currency",this.events={changed:"changed",failed:"failed",fetched:"fetched",failedToFetch:"failed.to.fetch"},this.after_init();}},Salla.event.document=new class extends c{constructor(){super(),this.namespace="document",this.events={click:"click",change:"change",submit:"submit",keyup:"keyup",leaving:"leaving",request:"request",requestFailed:"request.failed"},this.after_init();}onClick(e,t){this.fireCallableFuns("click",e,t);}onChange(e,t){this.fireCallableFuns("change",e,t);}onSubmit(e,t){this.fireCallableFuns("submit",e,t);}onKeyup(e,t){this.fireCallableFuns("keyup",e,t);}fireCallableFuns(e,t,a){this.on(e,(e=>{"function"!=typeof t?"function"==typeof a&&e.target.matches(t)&&a(e):t(e);}));}fireEvent(e,t,...a){return this.fireEventForElements(e,t,!1,...a)}fireEventForAll(e,t,...a){return this.fireEventForElements(e,t,!0,...a)}fireEventForElements(e,t,a,...r){if("string"==typeof e){if(a)return document.querySelectorAll(e).forEach((e=>this.fireEventForElements(e,t,!1,...r)));e=document.querySelector(e);}if(!e)return void salla.log("Failed To get element to fire event: "+t);const i=new CustomEvent(t,...r);return e.dispatchEvent(i)}},Salla.event.wishlist=new class extends c{constructor(){super(),this.namespace="wishlist",this.events={added:"added",removed:"removed",additionFailed:"addition.failed",removingFailed:"removing.failed"},this.after_init();}},Salla.event.infiniteScroll=new class extends c{constructor(){super(),this.namespace="infiniteScroll",this.events={scrollThreshold:"scroll.threshold",request:"request",load:"load",append:"append",error:"error",last:"last",history:"history"},this.after_init();}},Salla.event.booking=new class extends c{constructor(){super(),this.namespace="booking",this.events={added:"added",additionFailed:"addition.failed"},this.after_init();}},Salla.event.on("twilight::initiated",(()=>{Object.keys(Salla).forEach((e=>{"object"==typeof(e=Salla[e])&&(u(e),Object.keys(e).forEach((t=>{u(e[t]);})));}));})),Salla.config.default_properties={debug:"undefined"!=typeof process&&"development"==="production",token:null,fastRequests:!0,canLeave:!0,store:{api:"https://api.salla.dev/store/v1/"},currencies:{SAR:{code:"SAR",name:"ريال سعودي",symbol:"ر.س",amount:1,country_code:"sa"}}},Salla.config.merge(Salla.config.default_properties),Salla.config.triedToGetCurrencies_=!1,Salla.config.triedToGetLanguages_=!1,Salla.config.isUser=()=>"user"===Salla.config.get("user.type"),Salla.config.isGuest=()=>!Salla.config.isUser(),Salla.config.languages=async()=>{if(Salla.config.triedToGetLanguages_)return Salla.config.get("languages");Salla.config.triedToGetLanguages_=!0;let e=!0,t=[];return (await salla.document.api.request("languages",null,"get"))?.data?.map((a=>{e&&(t=[],e=!1),a.code=a.code||a.iso_code,a.url=salla.url.get(a.code),a.is_rtl=a.is_rtl||a.rtl,t.push(a);})),Salla.config.set("languages",t),t},Salla.config.currencies=async()=>{if(Salla.config.triedToGetCurrencies_)return Salla.config.get("currencies");Salla.config.triedToGetCurrencies_=!0;let e=!0,t={};return (await salla.currency.api.list())?.data?.map((a=>{e&&(t={},e=!1),a.country_code=a.code.substr(0,2).toLowerCase(),t[a.code]=a;})),Salla.config.set("currencies",t),t},Salla.config.currency=e=>(e=e||Salla.config.get("user.currency_code"),Salla.config.get("currencies."+e)||Object.values(Salla.config.get("currencies"))[0]);class h{constructor(){this.endpoints={},this.webEndpoints=[],this.namespace="BaseApi",this.endpointsMethods={},this.endpointsHeaders={};let e=/function (.{1,})\(/.exec(this.constructor.toString());this.className=(e&&e.length>1?e[1]:"").toLowerCase(),this.debounce={request:void 0,time:300,enabled:!0,exclude:[]};}after_init(){}normalRequest(e,t,a=null){let r=Array.isArray(e),i=r?this.getUrl(...e):this.getUrl(e);e=r?e[0]:e,a=a||this.endpointsMethods[e]||"post";let s=this.endpointsHeaders[e];if("get"===a&&t instanceof FormData){let e={};Array.from(t.entries()).forEach((function(t){e[t[0]]=t[1];})),t={params:e};}return s&&"get"===a&&(t=t?Object.assign(t,s):s),this.webEndpoints.includes(e)?i=salla.url.get(i):"http"!==i.substring(0,4)&&(i=salla.url.api(i)),Salla.api.request(i,t,a,{headers:s})}request(e,t,a=null){return !salla.api.isFastRequestsAllowed()&&this.debounce.enabled?(this.debounce.request||(this.debounce.request=salla.helpers.debounce(this.normalRequest.bind(this),this.debounce.time)),this.debounce.request(e,t,a)):this.normalRequest(e,t,a)}getUrl(e){let t=this.endpoints[e]||e;const a=/{[^{}]+}/i;for(let e=1;e<arguments.length;e++)t=t.replace(a,arguments[e]);return t}event(){return salla.event[this.className]}}class p extends h{constructor(){super(),this.namespace="cart",this.endpoints={latest:"cart/latest",details:"cart/{cart}",quickAdd:"cart/{cart}/item/{product}/quick-add",addItem:"cart/{cart}/item/{product}/add",deleteItem:"cart/{cart}/item/{item}",updateItem:"cart/{cart}/item/{item}",deleteImage:"cart/{cart}/image/{image}",uploadImage:"cart/{cart}/image",status:"cart/{cart}/status",addCoupon:"cart/{id}/coupon",deleteCoupon:"cart/{id}/coupon",getQuickOrderSettings:"checkout/quick-checkout",createQuickOrder:"checkout/quick-checkout",priceQuote:"cart/{cartId}/price-quote"},this.endpointsMethods={latest:"get",details:"get",status:"get",updateItem:"post",deleteItem:"delete",deleteImage:"delete",deleteCoupon:"put",getQuickOrderSettings:"get"},this.webEndpoints=["latest"],this.latestCart=null,this.after_init(),salla.event.on("request::initiated",(()=>this.getCurrentCartId()));}async getCurrentCartId(){if(salla.cart.api.latestCart)return salla.cart.api.latestCart.cart.id;let e=salla.storage.get("cart.id");if(e)return e;let t=await this.latest();return salla.cart.api.latestCart=t.data,salla.cart.api.latestCart.cart.id}getUploadImageEndpoint(e){return salla.url.api(this.getUrl("uploadImage",e||salla.storage.get("cart.id")))}latest(){return this.request("latest",{params:{source:""}}).then((e=>(salla.storage.set("cart",e.data.cart),salla.event.cart.latestFetched(e),e))).catch((e=>{throw salla.storage.set("cart",""),salla.event.cart.latestFailed(e),e}))}async details(){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,t){return this.addItem({id:e,quantity:t,endpoint:"quickAdd"})}async addItem(e){let t=this.getCartPayload(e);if(!t.id){let e='There is no product "id"!';return salla.cart.event.itemAddedFailed(e),salla.api.errorPromise(e)}let a=salla.form.getPossibleValue(t.payload,["endpoint"]);a&&["addItem","quickAdd"].includes(a)||(a=salla.form.getPossibleValue(t.payload,["quantity","donating_amount"])?"addItem":"quickAdd");let r=await this.getCurrentCartId();return this.request([a,r,t.id],t.payload).then((function(e){return salla.cart.event.itemAdded(e,t.id),e})).catch((function(e){throw salla.cart.event.itemAddedFailed(e,t.id),e}))}async deleteItem(e){let t=this.getCartPayload(e);if(!t.id){let e='There is no "id"!';return salla.cart.event.itemDeletedFailed(e),salla.api.errorPromise(e)}let a=await this.getCurrentCartId();return this.request(["deleteItem",a,t.id]).then((function(e){return salla.cart.event.itemDeleted(e,t.id),e})).catch((function(e){throw salla.cart.event.itemDeletedFailed(e,t.id),e}))}async updateItem(e){let t=this.getCartPayload(e);if(!t.id){let e='There is no "id"!';return salla.cart.event.itemUpdatedFailed(e),salla.api.errorPromise(e)}let a=await this.getCurrentCartId();return "Object"===t.payload.constructor?.name?t.payload._method="PUT":t.payload.append("_method","PUT"),this.request(["updateItem",a,t.id],t.payload).then((function(e){return salla.cart.event.itemUpdated(e,t.id),e})).catch((function(e){throw salla.cart.event.itemUpdatedFailed(e,t.id),e}))}async deleteImage(e){if(!(e=salla.form.getPossibleValue(e,["id","image_id","photo_id"]))){let e='There is no "id"!';return salla.cart.event.imageNotDeleted(e),salla.api.errorPromise(e)}let t=await this.getCurrentCartId();return this.request(["deleteImage",t,e]).then((function(t){return salla.cart.event.imageDeleted(t,e),t})).catch((function(t){throw salla.cart.event.imageNotDeleted(t,e),t}))}async status(e){return this.request(["status",e||await this.getCurrentCartId()],{params:{has_apple_pay:!!window.ApplePaySession}})}async submit(){this.status(await this.getCurrentCartId()).then((e=>{let t=e.data.next_step.to;if(!["checkout","refresh","login"].includes(t)){let e="Can't find next_step );";throw salla.cart.event.submitFailed(e),e}if(salla.cart.event.submitted(e),"login"===t)return salla.auth.setCanRedirect(!1),salla.event.dispatch("login::open"),void salla.auth.event.onLoggedIn((e=>{salla.event.dispatch("login::close"),this.submit();}));"checkout"===t?window.location.href=e.data.next_step.url+(window.ApplePaySession?"?has_apple_pay=true":""):window.location.reload();})).catch((function(e){throw salla.cart.event.submitFailed(e),e}));}getCartPayload(e){let t=e?.data||("object"==typeof e?e:void 0);return e=t?salla.form.getPossibleValue(t,["prod_id","product_id","item_id","id"]):e,t="object"==typeof t?t:void 0,{id:e,payload:t}}normalRequest(e,t,a=null){return super.normalRequest(e,t,a).catch((e=>{throw 403===e?.response?.status&&(salla.cart.api.reset(),salla.error(salla.lang.get("pages.checkout.try_again"))),e}))}reset(){salla.api.cart.latestCart=null,salla.storage.remove("cart"),salla.cart.event.successReset();}async addCoupon(e){if(e=e.data||e,!(e=salla.form.getPossibleValue(e,["coupon"]))){let e=new Error('There is no "Coupon Code"!');return e.name="EmptyCoupon",salla.event.cart.couponAdditionFailed(e),salla.api.errorPromise(e)}let t=await salla.cart.api.getCurrentCartId();return this.request(["addCoupon",t],{coupon:e}).then((function(e){return salla.event.cart.couponAdded(e,t),e})).catch((function(e){throw salla.event.cart.couponAdditionFailed(e,t),e}))}async deleteCoupon(){let e=await salla.cart.api.getCurrentCartId();return this.request(["deleteCoupon",e],{}).then((function(t){return salla.event.cart.couponDeleted(t,e),t})).catch((function(t){throw salla.event.cart.couponDeletionFailed(t,e),t}))}getQuickOrderSettings(){return this.request("getQuickOrderSettings").then((e=>(salla.event.cart.quickOrderSettingFetched(e),e))).catch((e=>{throw salla.event.cart.quickOrderSettingFailed(e),e}))}createQuickOrder(e){return this.request("createQuickOrder",e).then((e=>(salla.event.cart.quickOrderSucceeded(e),e))).catch((e=>{throw salla.event.cart.quickOrderFailed(e),e}))}async priceQuote(e){return salla.config.isGuest()?(salla.auth.api.setAfterLoginEvent("cart::priceQuote",e),void salla.event.dispatch("login::open")):this.request(["priceQuote",e||await this.getCurrentCartId()]).then((e=>(salla.cart.api.reset(),salla.event.cart.priceQuoteSucceeded(e).then((()=>(setTimeout((()=>window.location.href=salla.url.get("/")),1e3),e)))))).catch((e=>salla.event.cart.priceQuoteFailed(e).then((()=>{throw 404===e.error?.code&&window.location.reload(),e}))))}}class g extends h{constructor(){super(),this.namespace="loyalty",this.endpoints={getProgram:"loyalty",exchange:"loyalty/exchange",reset:"loyalty/exchange"},this.endpointsMethods={getProgram:"get",reset:"put"},this.after_init();}getProgram(){return this.request("getProgram").then((e=>(salla.loyalty.event.programFetched(e),e))).catch((e=>{throw salla.loyalty.event.programNotFetched(e),e}))}async exchange(e,t=null){if(!(e=salla.form.getPossibleValue(e,["id","loyalty_prize_id","prize_id"]))){let e="Unable to find cart id. Please provide one.";return salla.loyalty.event.exchangeFailed(e),salla.api.errorPromise(e)}if(!(t=t||await salla.cart.getCurrentCartId())){let e="Unable to find cart id. Please provide one.";return salla.loyalty.event.exchangeFailed(e),salla.api.errorPromise(e)}return this.request("exchange",{loyalty_prize_id:e,cart_id:t}).then((function(t){return salla.loyalty.event.exchangeSucceeded(t,e),t})).catch((function(t){throw salla.loyalty.event.exchangeFailed(t,e),t}))}async reset(e=null){if(!(e=e||await salla.cart.getCurrentCartId())){let e="Unable to find cart id. Please provide one.";return salla.loyalty.event.resetFailed(e),salla.api.errorPromise(e)}return this.request("reset",{cart_id:e}).then((e=>(salla.loyalty.event.resetSucceeded(e),e))).catch((e=>{throw salla.loyalty.event.resetFailed(e),e}))}}class f extends h{constructor(){super(),this.namespace="auth",this.canRedirect_=!0,this.afterLoginEvent={event:null,payload:null},this.endpoints={login:"auth/{type}/send_verification",resend:"auth/resend_verification",verify:"auth/{type}/verify",register:"auth/register",logout:"logout",refresh:"auth/refresh"},this.webEndpoints=["logout","auth/jwt","refresh"],this.endpointsMethods={logout:"get"},this.after_init();}setAfterLoginEvent(e,t){salla.api.auth.afterLoginEvent={event:e,payload:t};}setCanRedirect(e){salla.api.auth.canRedirect_=e;}canRedirect(){return salla.api.auth.canRedirect_&&!salla.api.auth.afterLoginEvent.event}login(e){e?.data&&(e=e.data);let t=salla.form.getPossibleValue(e,["type"]);if(!["email","mobile"].includes(t)){let e="Login type should be in: [email, mobile]";return salla.auth.event.codeNotSent(e),salla.api.errorPromise(e)}return this.request(["login",t],e).then((function(e){return salla.auth.event.codeSent(e,t),e})).catch((function(e){throw salla.auth.event.codeNotSent(e,t),e}))}async verify(e,t=!0){let a=salla.form.getPossibleValue(e,["type"]);if(!a){let e="Failed to know what's login type!";return salla.auth.event.verificationFailed(e),salla.api.errorPromise(e)}t=!1!==salla.form.getPossibleValue(e,["supportWebAuth"])&&t,salla.auth.event.next_event&&(e.next_event=salla.auth.event.next_event);let r=await salla.auth.api.request(["verify",a],e);if(200!==r?.status)return salla.auth.event.verificationFailed(r,a),salla.api.errorPromise(r);let i="authenticated"===r.data?.case;return i&&salla.auth.event.tokenFetched(r.data.token),t&&await salla.auth.api.request("auth/jwt"),i&&salla.auth.event.loggedIn(r).then((()=>salla.auth.api.afterUserLogin())),salla.auth.event.verified(r,a),salla.api.successPromise(r)}resend(e){let t;return (e=e.data||e).type=e.type||"mobile","mobile"!==e.type||e.phone&&e.country_code?"email"!==e.type||e.email?this.request("resend",e).then((function(t){return salla.auth.event.codeSent(t,e),t})).catch((function(t){throw salla.auth.event.codeNotSent(t,e),t})):(salla.auth.event.codeNotSent(t="There is no email!",e),salla.api.errorPromise(t)):(salla.auth.event.codeNotSent(t="There is no phone or country_code!",e),salla.api.errorPromise(t))}register(e){let t;return e.data&&(t=e.element,e=e.data),salla.auth.event.next_event&&(e.next_event=salla.auth.event.next_event),this.request("register",e).then((async function(e){return salla.auth.event.registered.call(t,e),"authenticated"===e.data?.case&&(salla.auth.event.tokenFetched(e.data.token),await salla.auth.request("auth/jwt"),salla.auth.event.loggedIn(e),salla.auth.api.afterUserLogin()),e})).catch((function(e){throw salla.auth.event.registrationFailed.call(t,e),e}))}logout(){return salla.storage.clearAll(),salla.cookie.clearAll(),salla.auth.event.loggedOut().then((()=>{let e=salla.url.get("logout");console.log(`Going to ${e}, to do any thing before this action use: salla.auth.even.onLoggedOut(()=>{...})`),location.href=e;}))}refresh(){return this.request("refresh").then((function(e){return salla.auth.event.tokenFetched(e.data.token),e})).catch((function(e){throw salla.auth.event.refreshFailed(e),e}))}afterUserLogin(){this.afterLoginEvent.event&&salla.event.emit(this.afterLoginEvent.event,this.afterLoginEvent.payload);}}class m extends h{constructor(){super(),this.namespace="order",this.endpoints={cancel:"orders/cancel/{id}",createCartFromOrder:"reorder/{id}",sendInvoice:"orders/send/{id}"},this.endpointsMethods={createCartFromOrder:"get"},this.after_init();}show(e){let t=salla.form.getPossibleValue(e?.data||e,["id","order_id"]);salla.event.dispatch("mobile::order.placed",{order_id:t}),location.href=salla.form.getPossibleValue(e?.data||e,["url"]);}cancel(e){return e=e||Salla.config.get("page.id"),this.request(["cancel",e],{params:{has_apple_pay:!!window.ApplePaySession}}).then((function(t){return salla.event.order.canceled(t,e),t})).catch((function(t){throw salla.event.order.notCanceled(t,e),t}))}createCartFromOrder(e){return e=e||salla.config.get("page.id"),this.request(["createCartFromOrder",e]).then((function(t){return salla.cart.reset(),salla.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=salla.form.getPossibleValue(e,["id"])||salla.config.get("page.id");if(!t||isNaN(t)){let e="There is no id!";return salla.order.event.invoiceNotSent(e),salla.api.errorPromise(e)}return this.request(["sendInvoice",t],e).then((e=>(salla.event.order.invoiceSent(e,t),e))).catch((e=>{throw salla.event.order.invoiceNotSent(e,t),e}))}}class v extends h{constructor(){super(),this.namespace="product",this.previousQuery="",this.endpoints={get:"products/{id}/details",getPrice:"products/{id}/price",availabilitySubscribe:"products/{id}/availability-notify",search:"products/search",detail:"products/{product_id}/details",categories:"products/categories/{?id}",offers:"products/{product_id}/specialoffer",getSizeGuides:"products/{prod_id}/size-guides",giftDetail:"products/{product_id}/buy-as-gift",giftToCart:"products/{product_id}/buy-as-gift",giftImage:"products/buy-as-gift/image"},this.endpointsMethods={detail:"get",giftDetail:"get"},this.after_init();}get(e,t=[]){if(!Array.isArray(t)){let e="withItems should be array.";return salla.api.errorPromise(e)}if(!e){let e="productId is not passed.";return salla.api.errorPromise(e)}return this.request(["get",e],{params:{with:t}}).then((function(e){return e})).catch((function(e){throw e}))}getPrice(e){let t=e.data||e,a=salla.form.getPossibleValue(t,["id","prod_id","product_id"]);return this.request(["getPrice",a],"object"==typeof t?t:void 0).then((function(e){return salla.product.event.priceUpdated(e,a),e})).catch((function(e){throw salla.product.event.priceUpdateFailed(e,a),e}))}categories(e){return this.request(["categories",e||""],null,"get").then((function(e){return salla.product.event.categoriesFetched(e),e})).catch((function(e){throw salla.product.event.categoriesFailed(e),e}))}availabilitySubscribe(e){let t=e.data||e;return e=salla.form.getPossibleValue(t,["id","prod_id"]),this.request(["availabilitySubscribe",e],"object"==typeof t?t:void 0).then((function(t){return salla.product.event.availabilitySubscribed(t,e),t})).catch((function(t){throw salla.product.event.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),salla.api.errorPromise(e)}if(e===salla.api.product.previousQuery){let e="Query is same as previous one!";return salla.product.event.searchFailed(e),salla.api.product.previousQuery=null,salla.api.errorPromise(e)}return salla.api.product.previousQuery=e,this.request("search",t,"get").then((function(t){return salla.product.event.searchResults(t,e),t})).catch((function(t){throw salla.product.event.searchFailed(t,e),t}))}offers(e){if(!(e=salla.form.getPossibleValue(e?.data|e,["product_id","id"]))){let e='There is no "product_id"!';return salla.offer.event.fetchDetailsFailed(e),salla.api.errorPromise(e)}return this.request(["offers",e]).then((function(t){return salla.product.event.offersFetched(t,e),t})).catch((function(t){throw salla.product.event.fetchOffersFailed(t,e),t}))}getSizeGuides(e){return this.request(`products/${e}/size-guides`,null,"get").then((t=>(salla.product.event.sizeGuideFetched(t,e),t))).catch((t=>{throw salla.product.event.sizeGuideFetchFailed(t,e),t}))}getGiftDetails(e){return this.request(["giftDetail",e]).then((t=>(salla.product.event.giftFetched(t,e),t))).catch((t=>{throw salla.product.event.giftFetchFailed(t,e),t}))}getDetails(e,t=[]){if(!Array.isArray(t)){let e="withItems should be array.";return salla.product.event.detailFetchFailed(e),salla.api.errorPromise(e)}if(!e){let e="productId is not passed.";return salla.product.event.detailFetchFailed(e),salla.api.errorPromise(e)}return this.request(["detail",e],{params:{with:t}}).then((function(t){return salla.product.event.detailFetched(t,e),t})).catch((function(t){throw salla.product.event.detailFetchFailed(t,e),t}))}addGiftToCart(e,t,a=!1){return this.request(["giftToCart",e],t).then((t=>(salla.product.event.addGiftToCartSucceeded(t,e),a&&(window.location.href=t.redirect),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 y extends h{constructor(){super(),this.namespace="profile",this.endpoints={info:"auth/user",update:"profile/update",updateContacts:"profile/contacts/update",updateSettings:"profile/settings",verify:"profile/verify",delete:"profile"},this.endpointsMethods={delete:"delete"},this.after_init();}info(){return this.request("info",null,"get").then((e=>{let t={id:e.data.id,type:"user",email:e.data.email,mobile:e.data.phone.code+e.data.phone.number,country_code:e.data.phone.country,language_code:e.data.language,currency_code:e.data.currency,notifications:e.data.notifications,pending_orders:e.data.pending_orders,avatar:e.data.avatar,first_name:e.data.first_name,last_name:e.data.last_name,fetched_at:Date.now()};return salla.config.set("user",t),salla.storage.set("user",t),salla.profile.event.infoFetched(e),e})).catch((e=>{throw salla.profile.event.infoNotFetched(e),e}))}update(e){return this.request("update",e).then((e=>(salla.profile.event.updated(e),e))).catch((e=>{throw salla.event.profile.updateFailed(e),e}))}updateContacts(e){return this.request("updateContacts",e).then((e=>(salla.profile.event.verificationCodeSent(e),e))).catch((e=>{throw salla.event.profile.updateContactsFailed(e),e}))}verify(e){return this.request("verify",e).then((e=>(salla.profile.event.verified(e),e))).catch((e=>{throw salla.event.profile.unVerified(e),e}))}updateSettings(e){return this.request("updateSettings",e).then((e=>(salla.event.profile.settingsUpdated(e),e))).catch((e=>{throw salla.event.profile.updateSettingsFailed(e),e}))}delete(){return this.request("delete").then((e=>(salla.storage.clearAll(),salla.cookie.clearAll(),salla.event.profile.deleted(e),window.location.href=salla.url.get("logout"),e))).catch((e=>{throw salla.event.profile.notDeleted(e),e}))}}class w extends h{constructor(){super(),this.namespace="comment",this.endpoints={add:"{type}/{id}/comments"},this.after_init();}add(e){e?.data&&(e=e.data);let t,a=salla.form.getPossibleValue(e,["id"]),r=salla.form.getPossibleValue(e,["type"]),i=salla.form.getPossibleValue(e,["comment"]);return a?r&&["products","pages","product","page"].includes(r)?i?(r+=["product","page"].includes(r)?"s":"",this.request(["add",r,a],{comment:i}).then((function(e){return salla.event.comment.added(e,a),e})).catch((function(e){throw salla.event.comment.additionFailed(e,a),e}))):(salla.event.comment.additionFailed(t="can't find comment content!"),salla.api.errorPromise(t)):(salla.event.comment.additionFailed(t="Failed to get type one of:(products, product, page, pages)!"),salla.api.errorPromise(t)):(salla.event.comment.additionFailed(t="Failed to get id!"),salla.api.errorPromise(t))}}class b extends h{constructor(){super(),this.namespace="currency",this.endpoints={change:"/",list:"currencies"},this.endpointsMethods={change:"get",list:"get"},this.webEndpoints=["change"],this.after_init();}change(e){if(!(e=salla.form.getPossibleValue(e.data||e,["currency","code"]))){let e="Can't find currency code!";return salla.currency.event.failed(e),salla.api.errorPromise(e)}return this.request("change",{params:{change_currency:"",currency:e}}).then((function(t){return salla.cookie.set("fresh_summary",1),salla.storage.set("cart",""),salla.currency.event.changed(t,e),t})).catch((function(t){throw salla.currency.event.failed(t,e),t}))}list(){return this.request("list").then((function(e){return salla.currency.event.fetched(e),e})).catch((function(e){throw salla.currency.event.failedToFetch(e),e}))}}class F extends h{constructor(){super(),this.namespace="document";}}class S extends h{constructor(){super(),this.namespace="rating",this.endpoints={store:"rating/store",products:"rating/products",shipping:"rating/shipping",order:"rating/{order_id}"},this.endpointsMethods={order:"get"},this.after_init();}order(e){let t="object"==typeof e?e:{},a=salla.form.getPossibleValue(e?.data||e,["order_id","id"]);if(!a){let e='There is no "order_id"!';return salla.event.rating.orderNotFetched(e),salla.api.errorPromise(e)}return this.request(["order",a],t).then((function(e){return salla.event.rating.orderFetched(e,a),e})).catch((function(e){throw salla.event.rating.orderNotFetched(e,a),e}))}store(e){if(!(e=e.data||e)){let e='There is no "data"!';return salla.event.rating.storeFailed(e),salla.api.errorPromise(e)}return this.request("store",e).then((function(t){return salla.event.rating.storeRated(t,e),t})).catch((function(t){throw salla.event.rating.storeFailed(t,e),t}))}products(e){if(!(e=e.data||e)){let e='There is no "data"!';return salla.event.rating.productsFailed(e),salla.api.errorPromise(e)}return this.request("products",e).then((function(t){return salla.event.rating.productsRated(t,e),t})).catch((function(t){throw salla.event.rating.productsFailed(t,e),t}))}shipping(e){if(!(e=e.data||e)){let e='There is no "data"!';return salla.event.rating.shippingFailed(e),salla.api.errorPromise(e)}return this.request("shipping",e).then((function(t){return salla.event.rating.shippingRated(t,e),t})).catch((function(t){throw salla.event.rating.shippingFailed(t,e),t}))}}class _ extends h{constructor(){super(),this.namespace="wishlist",this.endpoints={add:"products/favorites/{id}",remove:"products/favorites/{id}"},this.endpointsMethods={remove:"delete"},this.after_init();}toggle(e){return salla.storage.get("salla::wishlist",[]).includes(e)?this.remove(e):this.add(e)}add(e){let t;return salla.config.isGuest()?(salla.wishlist.event.additionFailed(t=salla.lang.get("common.messages.must_login")),salla.error(t),salla.api.errorPromise(t)):(e=salla.form.getPossibleValue(e?.data||e,["product_id","id"]))?this.request(["add",e]).then((t=>(this.updateWishlistStorage(e),salla.wishlist.event.added(t,e),t))).catch((function(t){throw salla.wishlist.event.additionFailed(t,e),t})):(salla.wishlist.event.additionFailed(t="Failed to get product id!"),salla.api.errorPromise(t))}remove(e){let t;return salla.config.isGuest()?(salla.wishlist.event.additionFailed(t=salla.lang.get("common.messages.must_login")),salla.error(t),salla.api.errorPromise(t)):(e=salla.form.getPossibleValue(e?.data||e,["product_id","id"]))?this.request(["remove",e]).then((t=>(this.updateWishlistStorage(e,!1),salla.wishlist.event.removed(t,e),t))).catch((function(t){throw salla.wishlist.event.removingFailed(t,e),t})):(salla.wishlist.event.removingFailed(t="Failed to get id!"),salla.api.errorPromise(t))}updateWishlistStorage(e,t=!0){let a=salla.storage.get("salla::wishlist",[]);t?a.push(e):a.splice(a.indexOf(e),1),salla.storage.set("salla::wishlist",a);}}class q extends h{constructor(){super(),this.namespace="scopes",this.endpoints={get:"scopes",change:"scopes",getProductAvailability:"scopes/availability?product_id={id}"},this.after_init();}get(){return this.request("scopes",null,"get").then((e=>(salla.scope.event.fetched(e),e))).catch((e=>{throw salla.scope.event.notFetched(e),e}))}change(e){return this.request("scopes",e).then((e=>(salla.scope.event.changeSucceeded(e),e))).catch((e=>{throw salla.scope.event.changeFailed(e),e}))}getProductAvailability(e=null){return this.request(`scopes/availability?product_id=${e}`,null,"get").then((t=>(salla.scope.event.productAvailabilityFetched(t,e),t))).catch((e=>{throw salla.scope.event.productAvailabilityNotFetched(e),resp}))}}class A extends h{constructor(){super(),this.namespace="booking",this.endpoints={add:"cart/booking/product/{id}"},this.endpointsMethods={add:"get"};}async add(e,t=!0){if(!e){let e="Please provide product id.";return salla.booking.event.additionFailed(e),salla.api.errorPromise(e)}return this.request(["add",e]).then((function(e){return salla.booking.event.added(e),t&&"booking"===e.data.redirect.to&&(window.location.href=e.data.redirect.url),e})).catch((function(e){throw salla.booking.event.additionFailed(e),e}))}}class E{constructor(t){"ready"!==f$1.status?t?(f$1.config.merge(t),t?.events&&f$1.event.dispatchEvents(t?.events),t._token&&salla.api.setHeader("X-CSRF-TOKEN",t._token),this.injectMaintenanceAlert(),this.injectThemePreviewAlert(),this.injectEditAlert(),t?.user?.language_code&&salla.lang.setLocale(t?.user?.language_code),salla.lang.loadStoreTranslations(),this.setSallaReady(t)):this.setSallaReady(t):salla.log("Trying to re-initiate Salla, while its status === 'ready'!");}injectMaintenanceAlert(){salla.config.get("maintenance")&&(document.querySelector(".store-notify")?salla.logger.warn(".store-notify element Existed before!"):salla.lang.onLoaded((()=>{const 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 a=t.getAjaxFormData(e),r=a.method?a.method.toLowerCase():void 0;salla.api.request(a.url,a.formData,r).then((e=>(e.data&&e.request&&(e=e.data),salla.api.handleAfterResponseActions(e),this.callAjaxEvent(a.events.success,e,a.formData),e))).catch((e=>{throw salla.api.handleErrorResponse(e),this.callAjaxEvent(a.events.fail,e,a.formData),e}));}callAjaxEvent(e,t,a){if(e){if(a instanceof FormData){const e={};Array.from(a.entries()).forEach((function(t){e[t[0]]=t[1];})),a=e;}window[e]?window[e](t,a):salla.event.dispatch(e,t,a);}}setSallaReady(t){f$1.status="ready",f$1.event.dispatch("twilight::initiated",t),window.dispatchEvent(new CustomEvent("twilight::initiated",{detail:t}));}}f$1.status="loading",f$1.notify=o,f$1.lang=new class extends lang{constructor(e){(e=e||{}).messages=e.messages||window.translations,e.locale=e.locale||(window.locale||navigator.language||navigator.userLanguage||"ar").split("-")[0],e.fallback=e.fallback||e.locale,super(e),this.translationsLoaded=!1;}onLoaded(e){if(this.translationsLoaded)return e();Salla.event.once("languages::translations.loaded",e);}loadStoreTranslations(){if(this.messages)return void window.addEventListener("load",(e=>{salla.event.dispatch("languages::translations.loaded"),salla.logger.info("The messages of transactions is already loaded");}));if(!salla.url.get(""))return void this.loadScript("https://cdn.salla.network/js/translations.js",!1);let e=salla.config.get("theme.translations_hash",salla.config.get("store.id","twilight"));this.loadScript(salla.url.get(`languages/assets/${e}.js`));}setMessages(e){super.setMessages(e),salla.event.dispatch("languages::translations.loaded"),this.translationsLoaded=!0;}loadScript(e,t=!0){let a=document.createElement("script");a.src=e,a.onload=()=>{if(window.translations)return this.setMessages(window.translations);a.onerror();},a.onerror=()=>{if(t)return salla.logger.warn("Failed to load Translations for store, lets try load it from CDN"),this.loadScript("https://cdn.salla.network/js/translations.js",!1);salla.logger.error("Failed to load Translations, check your network logs for more details\nor: salla.lang.setMessages({....}), see https://docs.salla.dev for more information's.");},document.head.appendChild(a);}get(e,t,a){return window.translations&&(e="trans."+e),super.get(e,t,a)}set(e,t){return salla.helpers.setNested(this.messages[this.getLocale()+".trans"],e,t),this}},f$1.form=new class{async submit(e,t=null){let a=t;if("SubmitEvent"===t?.constructor?.name||"submit"===t?.type){if(t.preventDefault(),"FORM"!==t.target?.tagName)return Salla.logger.warn("Failed find the target element for submit action. make sure you submit a form element"),new Promise((()=>{throw "Failed find the target element for submit action. make sure you submit a form element"}));"SALLA-BUTTON"===t?.submitter?.parentElement?.tagName&&t.submitter.parentElement.load(),a=t.target.getElementSallaData(),salla.log("Data from element",a);}if(/^https?:\/\/(?:www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)$/gm.test(e))return salla.api.normalRequest(e,a,"post").finally((()=>{loaderSupported&&t?.submitter?.parentElement.stop();}));let r=e.split("."),i=r.splice(-1);return await salla.call(r.join("."))[i](a).finally((()=>t?.submitter?.parentElement?.stop())).catch((e=>{throw salla.logger.warn(e),e}))}onSubmit(e,t){return salla.form.submit(e,t),!1}onChange(e,t){return t?.currentTarget?"FORM"!==t?.currentTarget?.tagName||t.currentTarget.checkValidity()?(salla.form.submit(e,t.currentTarget.getElementSallaData()),!0):(salla.logger.warn(`Trying to trigger '${e}' without filling required fields!`),!1):(salla.logger.warn(`Trying to trigger '${e}' without event!`),!1)}getPossibleValue(e,t,a=!1){if(!e)return;if("object"!=typeof e)return e;let r;for(let a=0;a<t.length&&!(r=e[t[a]])&&!("undefined"!=typeof FormData&&e instanceof FormData&&(r=e.get(t[a])));a++);return r=r||e,"object"!=typeof r||a?r:void 0}},f$1.helpers.app=new class{toggleClassIf(e,t,a,r){return document.querySelectorAll(e).forEach((e=>this.toggleElementClassIf(e,t,a,r))),this}toggleElementClassIf(e,t,a,r){t=Array.isArray(t)?t:t.split(" "),a=Array.isArray(a)?a:a.split(" ");let i=r(e);return e?.classList.remove(...i?a:t),e?.classList.add(...i?t:a),this}isValidEmail(e){return /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(String(e).toLowerCase())}element(e){return "object"==typeof e?e:document.querySelector(e)}watchElement(e,t){return this[e]=this.element(t),this}watchElements(e){return Object.entries(e).forEach((e=>this.watchElement(e[0],e[1]))),this}on(e,t,a,r={}){return "object"==typeof t?(this.element(t).addEventListener(e,a,r),this):(document.querySelectorAll(t).forEach((t=>t.addEventListener(e,a,r))),this)}onClick(e,t){return this.on("click",e,t)}onKeyUp(e,t){return this.on("keyup",e,t)}onEnter(e,t){return this.onKeyUp(e,(e=>13===e.keyCode&&t(e))),this}all(e,t){return document.querySelectorAll(e).forEach(t),this}hideElement(e){return this.element(e).style.display="none",this}showElement(e,t="block"){return this.element(e).style.display=t,this}removeClass(e,t){return this.element(e).classList.remove(...Array.from(arguments).slice(1)),this}addClass(e,t){return this.element(e).classList.add(...Array.from(arguments).slice(1)),this}debounce(e,...t){return this.debounce_||(this.debounce_=Salla.helpers.debounce(((e,...t)=>e(...t)),500)),this.debounce_(e,...t)}},f$1.infiniteScroll=new class extends d{constructor(e,t){super(e,t),this.options={path:".infinite-scroll-btn",history:"push",status:".infinite-scroll-status",append:".list-block"},this.fetchOptions={headers:{"S-INFINITE-SCROLL":!0}},this.instances=[];}initiate(e,a,r){r=this.getCustomOptions(a,r);let i="string"!=typeof e?e:document.querySelector(e),s=r.path;if(!i||!s||"string"==typeof s&&!document.querySelector(s))return void Salla.logger.warn(i?"Path Option (a link that has next page link) Not Existed!":"Container For InfiniteScroll not Existed!");let n=new js(i,r);return n.on("scrollThreshold",Salla.infiniteScroll.event.scrollThreshold),n.on("request",Salla.infiniteScroll.event.request),n.on("load",Salla.infiniteScroll.event.load),n.on("append",Salla.infiniteScroll.event.append),n.on("error",Salla.infiniteScroll.event.error),n.on("last",Salla.infiniteScroll.event.last),n.on("history",Salla.infiniteScroll.event.history),this.instances.push(n),n}getCustomOptions(e,t){return (t="object"==typeof e&&e||t||this.options).fetchOptions=this.fetchOptions,t.path=t.path||this.options.path,t.button=t.button||t.path,t.status=t.status||this.options.status,t.hasOwnProperty("history")||(t.history=this.options.history),t.nextPage=t.nextPage||t.next_page,t.append="string"==typeof e&&e||t.append||this.options.append,t}}(void 0,salla.event.infiniteScroll),f$1.api=new class extends class{constructor(){salla.event.on("twilight::initiated",(e=>this.initiateRequest(e))),salla.event.on("profile::info.fetched",(e=>this.setCurrencyAndLanguage(e))),salla.event.on("auth::token.fetched",(e=>{salla.storage.set("token",e),this.setToken(e),salla.cart.api.reset();})),this.notifier_handler_disabled=!1,this.axios=axios.create({headers:{common:{"X-Requested-With":"XMLHttpRequest","S-SOURCE":"twilight","S-APP-VERSION":"v2.0.0","S-APP-OS":"browser"}}});}getHeaders(){return this.axios.defaults.headers.common}setHeaders(e){return Object.entries(e).forEach((e=>this.setHeader(e[0],e[1]))),this}setHeader(e,t){return salla.infiniteScroll.fetchOptions.headers[e]=this.axios.defaults.headers.common[e]=t,this}async withoutNotifier(e){return this.notifier_handler_disabled=!0,await e().finally((()=>{this.notifier_handler_disabled=!1;}))}initiateRequest(e){this.axios.defaults.baseURL=Salla.config.get("store.api",Salla.config.get("store.url")),this.setHeaders({"Store-Identifier":Salla.config.get("store.id"),currency:e.user?.currency_code||"SAR","accept-language":salla.lang.getLocale(),"s-user-id":e.user?.id});let t=salla.storage.get("scope");t&&this.setHeaders({"s-scope-type":t.type,"s-scope-id":t.id}),this.injectTokenToTheRequests(e);}injectTokenToTheRequests(e){let t=salla.storage.get("token"),a=Salla.config.isGuest(),r=salla.storage.get("cart"),s=e.user?.id,n=salla.storage.get("user.id");if(n&&n!==s&&salla.storage.remove("user"),r&&(r.user_id!==s||r.store_id!==e.store?.id))return salla.log("cart",{user_id:r.user_id,store_id:r.store_id}),salla.log("current",{user_id:s,store_id:e.store?.id}),salla.log("Auth:: The cart is not belong to current "+(r.user_id!==s?"user":"store")+"!"),void salla.cart.api.reset();if(a&&!t)return;if(a&&t)return salla.log("Auth:: Token without user!"),salla.storage.remove("token"),void salla.cart.api.reset();if(!t)return salla.cart.api.reset(),void salla.auth.api.refresh();let l=o$1(t);return Date.now()/1e3>l.exp?(salla.log("Auth:: An expired token!"),salla.storage.remove("token"),salla.cart.api.reset(),void salla.auth.api.refresh()):l.sub!==s?(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()):(this.setToken(t),void salla.event.emit("request::initiated"))}setToken(e){return this.setHeader("Authorization","Bearer "+e)}setCurrencyAndLanguage(e){return this.setHeaders({currency:e.data.currency,"accept-language":e.data.language})}request(e,t,a="get",r={}){let i={endPoint:e,payload:t,method:a,options:r},s="undefined"!=typeof event?event.currentTarget:null,n=!1;return "SALLA-BUTTON"===s?.tagName&&(n=!0),n&&s?.load(),this.axios[i.method](i.endPoint,i.payload,i.options).then((e=>(n&&s?.stop(),e.data&&e.request&&(e=e.data),this.handleAfterResponseActions(e),e))).catch((e=>{throw n&&s?.stop(),salla.event.document.requestFailed(i,e),this.handleErrorResponse(e),e}))}handleAfterResponseActions(e){if(!e)return;let{data:t,googleTags:a=null}=e,r=t&&t.googleTags?t.googleTags:a;dataLayer&&r&&dataLayer.push(r),this.fireEventsForResponse(e),this.showAlert(e),this.renderSections(e);}fireEventsForResponse(e){let t=e?.events||e.data?.events||e.error?.events;"string"==typeof t&&(t=JSON.parse(t)),t&&Object.keys(t).forEach((e=>salla.event.dispatch(e,t[e])));}handleErrorResponse(e){if(e.response&&e.response.data)return e.response.data.error&&e.response.data.error.fields&&!this.notifier_handler_disabled?this.handleInvalidFields(e):this.handleAfterResponseActions(e.response.data)}showAlert(e){if(e&&!this.notifier_handler_disabled)return e.case&&e.msg?salla.notify.fire(e.msg,e.case,e):e.hasOwnProperty("success")&&e.data?.message?salla.notify.fire(e.data?.message,e.success?salla.notify.types.success:salla.notify.types.error,e):e.error&&e.error.message&&"FORBIDDEN"!==e.error.message?salla.error(e.error.message,e):void 0}handleInvalidFields(e){let t=e.response.data.error.fields,a=[];Object.keys(t).forEach((e=>{let r=t[e];Array.isArray(r)?r.forEach((e=>a.push(e))):a.push(r);}));let r=(a.length>1?"* ":"")+a.join("\n* ");salla.error(r,e);}isFastRequestsAllowed(){return Salla.config.get("fastRequests")}promise(e,t=!0){return new Promise(((a,r)=>t?a(e):r(e)))}errorPromise(e){return this.promise(e,!1)}successPromise(e){return this.promise(e,!0)}renderSections(e){e.sections&&Object.keys(e.sections).forEach((t=>{document.querySelectorAll(t.toSelector()).forEach((function(a){a.innerHTML=e.sections[t];}));}));}}{constructor(){super(),this.auth=new f,this.cart=new p,this.loyalty=new g,this.order=new m,this.rating=new S,this.product=new v,this.profile=new y,this.comment=new w,this.currency=new b,this.document=new F,this.wishlist=new _,this.scope=new q,this.booking=new A;}},f$1.cart=new d(f$1.api.cart,f$1.event.cart),f$1.auth=new d(f$1.api.auth,f$1.event.auth),f$1.order=new d(f$1.api.order,f$1.event.order),f$1.scope=new d(f$1.api.scope,f$1.event.scope),f$1.rating=new d(f$1.api.rating,f$1.event.rating),f$1.comment=new d(f$1.api.comment,f$1.event.comment),f$1.loyalty=new d(f$1.api.loyalty,f$1.event.loyalty),f$1.product=new d(f$1.api.product,f$1.event.product),f$1.profile=new d(f$1.api.profile,f$1.event.profile),f$1.currency=new d(f$1.api.currency,f$1.event.currency),f$1.document=new d(f$1.api.document,f$1.event.document),f$1.wishlist=new d(f$1.api.wishlist,f$1.event.wishlist),f$1.booking=new d(f$1.api.booking,f$1.event.booking),f$1.call=t=>{let a=f$1,r=t.split(".");for(;r.length&&(a=a[r.shift()]););return a},f$1.init=e=>new E(e),salla.event.once("twilight::init",salla.init),salla.event.once("twilight::api",(e=>{let t=e?.events;t&&salla.event.dispatchEvents(t);})),f$1.success=f$1.notify.success,f$1.error=f$1.notify.error,f$1.versions.twilight="[VI]{version}[/VI]",f$1.onInitiated=e=>salla.event.once("twilight::initiated",e),f$1.onReady=f$1.onReady||function(t){"ready"!==salla.status?f$1.onInitiated(t):t(salla.config.all());},window.dispatchEvent(new CustomEvent("salla::created"));
9707
+ let s=function(e,t,a){return alert(e)},n=function(e,t){return s(e,l.error,t)},l={error:"error",success:"success",info:"info"};var o={fire:function(e,t,a){return s(e,t,a)},setNotifier:function(e){s=e,salla.event.emit("twilight::notifier.changed");},error:n,success:function(e,t){return s(e,l.success,t)},info:function(e,t){return s(e,l.info,t)},sallaInitiated:function(){let e=window.location.href.match(/([\?\&]danger=)[^&]+/g);e&&(window.history.replaceState(null,document.title,window.location.pathname),salla.event.once("twilight::notifier.changed",(()=>{e.forEach((e=>{n(decodeURI(e.replace("?danger=","").replace("&danger=","")));}));})));},types:l};class d{constructor(e,t){return this.api=e,this.event=t,new Proxy(this,{get:function(a,r){return "event"===r?t:"api"===r?e:e&&e[r]||a[r]}})}}String.prototype.toStudlyCase=function(){return this.trim().replace(/([^a-zA-Z\d].)/g,(function(e){return e.toUpperCase().replace(/[^a-zA-Z\d]/g,"")}))},String.prototype.toDatasetName=function(){return this.startsWith("data-")?this.substr(5).toStudlyCase():this.toStudlyCase()},String.prototype.toSelector=function(){return this.trim().startsWith(".")||this.trim().startsWith("#")?this:"#"+this},String.prototype.replaceArray=function(e,t){for(var a,r=this,i=0;i<e.length;i++)a=new RegExp(e[i],"g"),r=r.replace(a,t[i]);return r},String.prototype.rtrim=function(e){return void 0===e&&(e="\\s"),this.replace(new RegExp("["+e+"]*$"),"")},String.prototype.ltrim=function(e){return void 0===e&&(e="\\s"),this.replace(new RegExp("^["+e+"]*"),"")},String.prototype.digitsOnly=function(){return Salla.helpers.digitsOnly(this)},Element.prototype.matches||(Element.prototype.matches=Element.prototype.msMatchesSelector),Element.prototype.closest||(Element.prototype.closest=function(e){for(var t=this;t;){if(t.matches(e))return t;t=t.parentElement;}}),Element.prototype.getElementSallaData=function(e,...t){if(!this.getAttribute)return;if(this.hasAttribute("data-json"))try{return JSON.parse(this.getAttribute("data-json"))}catch(e){}let a=this.getAttribute("data-function");if(a&&window[a])return "function"==typeof window[a]?this.getFilteredData(window[a].call(this,...t)):this.getFilteredData(window[a]);let r=this.hasAttribute("data-form-selector")?document.querySelector(this.dataset.formSelector):void 0;if(r="FORM"===this.tagName?this:r||this.closest("form")||this.closest("[salla-form-data]")||this,r&&"FORM"===r.tagName)return this.getFilteredData(new FormData(r),null,r);let i=r.querySelectorAll("[name]");if(!i.length)return this.getFilteredData();let s=Object.assign({},this.dataset);return i.forEach((e=>{if(!["checkbox","radio"].includes(e.type)||e.checked)try{let t=Salla.helpers.inputData(e.name,e.value,s);s[t.name]=t.value;}catch(t){Salla.log(e.name+" can't be send");}})),this.getFilteredData(s)},Element.prototype.canEventFireHook=function(e){return !!this.hasAttribute&&this.hasAttribute(Salla.api.hooksPrefix+e.type)},Element.prototype.hasAttributeStartsWith=function(e,t){e=e.toLowerCase();for(var a=0;a<this.attributes.length;a++){let r=this.attributes[a].name.toLowerCase();if(0===r.indexOf(e))return !t||r}return !1},HTMLFormElement.prototype.getAjaxFormData=function(e){var t=this.querySelectorAll('input[type="file"]');t.forEach((e=>{e.files.length||e.setAttribute("disabled","");}));var a=new FormData(this);return t.forEach((e=>{e.files.length||e.removeAttribute("disabled");})),{formData:this.getFilteredData(a,e),url:this.getAttribute("action"),method:this.getAttribute("method")||"post",events:{success:this.dataset.onSuccess,fail:this.dataset.onFail}}},Element.prototype.getFilteredData=function(e=null,t=null,a=null){return e=e||a?.dataset||this.dataset,a&&this.name&&void 0!==this.value&&(e=function(e,t,a){e instanceof FormData?e.append(t,a):e[t]=a;return e}(e,this.name,this.value)),["filterBeforeSubmit","filterBeforeSend"].forEach((r=>{let i=a?.dataset[r]||this.dataset[r];if(i){var s=window[i];if("function"==typeof s){if(!s(e,a||this,t)&&e)throw `Data failed to be pass verify function window.${i}(formData, element, event)!`;return s(e,a||this,t)}Salla.log("window."+i+"() not found!");}})),e},HTMLAnchorElement.prototype.getAjaxFormData=function(e){return {formData:this.getFilteredData(null,e),url:this.getAttribute("href"),method:this.dataset.type||"get",events:{success:this.dataset.onSuccess,fail:this.dataset.onFail}}};class c{constructor(){this.events={},this.namespace="";let e=/function (.{1,})\(/.exec(this.constructor.toString());this.className=(e&&e.length>1?e[1]:"").toLowerCase();}after_init(){this.createDynamicFunctions();}createDynamicFunctions(){Object.keys(this.events).forEach((e=>{this.createDynamicEventFuns(e),this.createDynamicListenerFuns(e);}));}createDynamicEventFuns(e){if(this[e])return;let t=this;this[e]=function(...a){return t.dispatch(e,...a)};}createDynamicListenerFuns(e){let t="on"+e.charAt(0).toUpperCase()+e.slice(1);if(this[t])return;let a=this;this[t]=function(t){return a.on(e,(async(...e)=>t(...e)))};}getEventName(e){return e=this.events[e]||e,!this.namespace||e.includes("::")?e:this.namespace+Salla.event.delimiter+e}dispatch(e,...t){return Salla.event.emitAsync(this.getEventName(e),...t)}on(e,t){return Salla.event.addListener(this.getEventName(e),t)}once(e,t){return Salla.event.once(this.getEventName(e),t)}}function u(e){e&&e.sallaInitiated&&!e.initiated&&(e.sallaInitiated(),e.initiated=!0);}Salla.event.auth=new class extends c{constructor(){super(),this.namespace="auth",this.events={login:"login",logout:"logout",codeSent:"code.sent",codeNotSent:"code.not-sent",verified:"verified",verificationFailed:"verification.failed",loggedIn:"logged.in",registered:"registered",registrationFailed:"registration.failed",loggedOut:"logged.out",failedLogout:"failed.logout",refreshFailed:"refresh.failed",tokenFetched:"token.fetched"},this.after_init();}login(e){return e?(e.type&&this.setTypeActionOnVerified(e.type),this.next_event=e.next_event||null,this.dispatch("login",...arguments)):(this.next_event=null,this.dispatch("login",...arguments))}loggedIn(e){return Salla.profile.info().finally((()=>this.dispatch("loggedIn",e)))}setTypeActionOnVerified(e){this.type_action_on_verified=e;}getTypeActionOnVerified(){return this.type_action_on_verified||"redirect"}},Salla.event.cart=new class extends c{constructor(){super(),this.namespace="cart",this.events={latestFetched:"latest.fetched",latestFailed:"latest.failed",updated:"updated",itemUpdated:"item.updated",itemUpdatedFailed:"item.updated.failed",itemAdded:"item.added",itemAddedFailed:"item.added.failed",itemDeleted:"item.deleted",itemDeletedFailed:"item.deleted.failed",submitted:"submitted",submitFailed:"submit.failed",imageDeleted:"image.deleted",imageNotDeleted:"image.not.deleted",detailsFetched:"details.fetched",detailsNotFetched:"details.not.fetched",successReset:"success.reset",priceQuoteSucceeded:"price-quote.succeeded",priceQuoteFailed:"price-quote.failed",couponAdded:"coupon.added",couponDeleted:"coupon.deleted",couponAdditionFailed:"coupon.addition.failed",couponDeletionFailed:"coupon.deletion.failed",quickOrderSettingFetched:"quick-order.fetched",quickOrderSettingFailed:"quick-order.failed",quickOrderSucceeded:"quick-order.succeeded",quickOrderFailed:"quick-order.failed"},this.after_init();}updated(e){return Salla.cookie.set("fresh_summary",1),e&&"object"==typeof e?(e.offer&&salla.product.event.offerExisted(e.offer),e.redirect&&(salla.log("The current cart is purchased!"),salla.cart.api.reset()),e.cart?(salla.storage.set("cart.summary",{total:e.cart.total,sub_total:e.cart.sub_total,discount:e.cart.discount,real_shipping_cost:e.cart.real_shipping_cost,count:e.cart.count,shipping_cost:e.cart.free_shipping_bar?.has_free_shipping?0:e.cart.real_shipping_cost}),this.dispatch("updated",e.cart)):void salla.log("Failed to get the cart summary!")):(Salla.logger.info("Cart summary not an object!",e),this.dispatch("updated"))}latestFetched(e){return this.updated(e.data),this.dispatch("latestFetched",e)}itemAdded(e,t){return this.updated(e.data),this.dispatch("itemAdded",e,t)}itemDeleted(e,t){return this.updated(e.data),this.dispatch("itemDeleted",e,t)}itemUpdated(e,t){return this.updated(e.data),this.dispatch("itemUpdated",e,t)}couponAdded(e,t){return this.updated(e.data),this.dispatch("couponAdded",e,t)}couponDeleted(e,t){return this.updated(e.data),this.dispatch("couponDeleted",e,t)}},Salla.event.order=new class extends c{constructor(){super(),this.namespace="order",this.events={canceled:"canceled",notCanceled:"not.canceled",orderCreated:"order.created",orderCreationFailed:"order.creation.failed",invoiceSent:"invoice.sent",invoiceNotSent:"invoice.not.sent"},this.after_init();}},Salla.event.scope=new class extends c{constructor(){super(),this.namespace="scope",this.events={fetched:"fetched",notFetched:"not.fetched",productAvailabilityFetched:"product-availability.fetched",productAvailabilityNotFetched:"product-availability.not.fetched",changeSucceeded:"changed",changeFailed:"not.changed"},this.after_init();}},Salla.event.rating=new class extends c{constructor(){super(),this.namespace="rating",this.events={orderNotFetched:"order.not.fetched",orderFetched:"order.fetched",storeRated:"store.rated",storeFailed:"store.failed",productsRated:"products.rated",productsFailed:"products.failed",shippingRated:"shipping.rated",shippingFailed:"shipping.failed"},this.after_init();}},Salla.event.comment=new class extends c{constructor(){super(),this.namespace="comment",this.events={added:"added",additionFailed:"addition.failed"},this.after_init();}},Salla.event.loyalty=new class extends c{constructor(){super(),this.namespace="loyalty",this.events={exchangeSucceeded:"exchange.succeeded",exchangeFailed:"exchange.failed",programFetched:"program.fetched",programNotFetched:"program.not.fetched",resetSucceeded:"exchange-reset.succeeded",resetFailed:"exchange-reset.failed"},this.after_init();}},Salla.event.product=new class extends c{constructor(){super(),this.namespace="product",this.events={priceUpdated:"price.updated",priceUpdateFailed:"price.updated.failed",availabilitySubscribed:"availability.subscribed",availabilitySubscribeFailed:"availability.subscribe.failed",categoriesFetched:"categories.fetched",categoriesFailed:"categories.failed",searchFailed:"search.failed",searchResults:"search.results",offerExisted:"offer.existed",fetchOffersFailed:"fetch.offers.failed",offersFetched:"offers.fetched",sizeGuideFetched:"size-guide.fetched",SizeGuideFetchFailed:"size-guide.failed",giftFetched:"gift.fetched",giftFetchFailed:"gift.failed",detailFetched:"detail.fetched",detailFetchFailed:"detail.failed",addGiftToCartSucceeded:"gift.add-to-cart.succeeded",addGiftToCartFailed:"gift.add-to-cart.failed",giftImageUploadSucceeded:"gift.image-upload.succeeded",giftImageUploadFailed:"gift.image-upload.failed"},this.after_init();}},Salla.event.profile=new class extends c{constructor(){super(),this.namespace="profile",this.events={updated:"updated",updateFailed:"update.failed",verificationCodeSent:"verification.code.sent",updateContactsFailed:"update.contacts.failed",verified:"verified",unverified:"unverified",infoFetched:"info.fetched",infoNotFetched:"info.not.fetched",settingsUpdated:"settings.updated",updateSettingsFailed:"update.settings.failed",deleted:"deleted",notDeleted:"not.deleted"},this.after_init();}},Salla.event.currency=new class extends c{constructor(){super(),this.namespace="currency",this.events={changed:"changed",failed:"failed",fetched:"fetched",failedToFetch:"failed.to.fetch"},this.after_init();}},Salla.event.document=new class extends c{constructor(){super(),this.namespace="document",this.events={click:"click",change:"change",submit:"submit",keyup:"keyup",leaving:"leaving",request:"request",requestFailed:"request.failed"},this.after_init();}onClick(e,t){this.fireCallableFuns("click",e,t);}onChange(e,t){this.fireCallableFuns("change",e,t);}onSubmit(e,t){this.fireCallableFuns("submit",e,t);}onKeyup(e,t){this.fireCallableFuns("keyup",e,t);}fireCallableFuns(e,t,a){this.on(e,(e=>{"function"!=typeof t?"function"==typeof a&&e.target.matches(t)&&a(e):t(e);}));}fireEvent(e,t,...a){return this.fireEventForElements(e,t,!1,...a)}fireEventForAll(e,t,...a){return this.fireEventForElements(e,t,!0,...a)}fireEventForElements(e,t,a,...r){if("string"==typeof e){if(a)return document.querySelectorAll(e).forEach((e=>this.fireEventForElements(e,t,!1,...r)));e=document.querySelector(e);}if(!e)return void salla.log("Failed To get element to fire event: "+t);const i=new CustomEvent(t,...r);return e.dispatchEvent(i)}},Salla.event.wishlist=new class extends c{constructor(){super(),this.namespace="wishlist",this.events={added:"added",removed:"removed",additionFailed:"addition.failed",removingFailed:"removing.failed"},this.after_init();}},Salla.event.infiniteScroll=new class extends c{constructor(){super(),this.namespace="infiniteScroll",this.events={scrollThreshold:"scroll.threshold",request:"request",load:"load",append:"append",error:"error",last:"last",history:"history"},this.after_init();}},Salla.event.booking=new class extends c{constructor(){super(),this.namespace="booking",this.events={added:"added",additionFailed:"addition.failed"},this.after_init();}},Salla.event.on("twilight::initiated",(()=>{Object.keys(Salla).forEach((e=>{"object"==typeof(e=Salla[e])&&(u(e),Object.keys(e).forEach((t=>{u(e[t]);})));}));})),Salla.config.default_properties={debug:"undefined"!=typeof browser$1&&"development"==="production",token:null,fastRequests:!0,canLeave:!0,store:{api:"https://api.salla.dev/store/v1/"},currencies:{SAR:{code:"SAR",name:"ريال سعودي",symbol:"ر.س",amount:1,country_code:"sa"}}},Salla.config.merge(Salla.config.default_properties),Salla.config.triedToGetCurrencies_=!1,Salla.config.triedToGetLanguages_=!1,Salla.config.isUser=()=>"user"===Salla.config.get("user.type"),Salla.config.isGuest=()=>!Salla.config.isUser(),Salla.config.languages=async()=>{if(Salla.config.triedToGetLanguages_)return Salla.config.get("languages");Salla.config.triedToGetLanguages_=!0;let e=!0,t=[];return (await salla.document.api.request("languages",null,"get"))?.data?.map((a=>{e&&(t=[],e=!1),a.code=a.code||a.iso_code,a.url=salla.url.get(a.code),a.is_rtl=a.is_rtl||a.rtl,t.push(a);})),Salla.config.set("languages",t),t},Salla.config.currencies=async()=>{if(Salla.config.triedToGetCurrencies_)return Salla.config.get("currencies");Salla.config.triedToGetCurrencies_=!0;let e=!0,t={};return (await salla.currency.api.list())?.data?.map((a=>{e&&(t={},e=!1),a.country_code=a.code.substr(0,2).toLowerCase(),t[a.code]=a;})),Salla.config.set("currencies",t),t},Salla.config.currency=e=>(e=e||Salla.config.get("user.currency_code"),Salla.config.get("currencies."+e)||Object.values(Salla.config.get("currencies"))[0]);class h{constructor(){this.endpoints={},this.webEndpoints=[],this.namespace="BaseApi",this.endpointsMethods={},this.endpointsHeaders={};let e=/function (.{1,})\(/.exec(this.constructor.toString());this.className=(e&&e.length>1?e[1]:"").toLowerCase(),this.debounce={request:void 0,time:300,enabled:!0,exclude:[]};}after_init(){}normalRequest(e,t,a=null){let r=Array.isArray(e),i=r?this.getUrl(...e):this.getUrl(e);e=r?e[0]:e,a=a||this.endpointsMethods[e]||"post";let s=this.endpointsHeaders[e];if("get"===a&&t instanceof FormData){let e={};Array.from(t.entries()).forEach((function(t){e[t[0]]=t[1];})),t={params:e};}return s&&"get"===a&&(t=t?Object.assign(t,s):s),this.webEndpoints.includes(e)?i=salla.url.get(i):"http"!==i.substring(0,4)&&(i=salla.url.api(i)),Salla.api.request(i,t,a,{headers:s})}request(e,t,a=null){return !salla.api.isFastRequestsAllowed()&&this.debounce.enabled?(this.debounce.request||(this.debounce.request=salla.helpers.debounce(this.normalRequest.bind(this),this.debounce.time)),this.debounce.request(e,t,a)):this.normalRequest(e,t,a)}getUrl(e){let t=this.endpoints[e]||e;const a=/{[^{}]+}/i;for(let e=1;e<arguments.length;e++)t=t.replace(a,arguments[e]);return t}event(){return salla.event[this.className]}}class p extends h{constructor(){super(),this.namespace="cart",this.endpoints={latest:"cart/latest",details:"cart/{cart}",quickAdd:"cart/{cart}/item/{product}/quick-add",addItem:"cart/{cart}/item/{product}/add",deleteItem:"cart/{cart}/item/{item}",updateItem:"cart/{cart}/item/{item}",deleteImage:"cart/{cart}/image/{image}",uploadImage:"cart/{cart}/image",status:"cart/{cart}/status",addCoupon:"cart/{id}/coupon",deleteCoupon:"cart/{id}/coupon",getQuickOrderSettings:"checkout/quick-checkout",createQuickOrder:"checkout/quick-checkout",priceQuote:"cart/{cartId}/price-quote"},this.endpointsMethods={latest:"get",details:"get",status:"get",updateItem:"post",deleteItem:"delete",deleteImage:"delete",deleteCoupon:"put",getQuickOrderSettings:"get"},this.webEndpoints=["latest"],this.latestCart=null,this.after_init(),salla.event.on("request::initiated",(()=>this.getCurrentCartId()));}async getCurrentCartId(){if(salla.cart.api.latestCart)return salla.cart.api.latestCart.cart.id;let e=salla.storage.get("cart.id");if(e)return e;let t=await this.latest();return salla.cart.api.latestCart=t.data,salla.cart.api.latestCart.cart.id}getUploadImageEndpoint(e){return salla.url.api(this.getUrl("uploadImage",e||salla.storage.get("cart.id")))}latest(){return this.request("latest",{params:{source:""}}).then((e=>(salla.storage.set("cart",e.data.cart),salla.event.cart.latestFetched(e),e))).catch((e=>{throw salla.storage.set("cart",""),salla.event.cart.latestFailed(e),e}))}async details(){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,t){return this.addItem({id:e,quantity:t,endpoint:"quickAdd"})}async addItem(e){let t=this.getCartPayload(e);if(!t.id){let e='There is no product "id"!';return salla.cart.event.itemAddedFailed(e),salla.api.errorPromise(e)}let a=salla.form.getPossibleValue(t.payload,["endpoint"]);a&&["addItem","quickAdd"].includes(a)||(a=salla.form.getPossibleValue(t.payload,["quantity","donating_amount"])?"addItem":"quickAdd");let r=await this.getCurrentCartId();return this.request([a,r,t.id],t.payload).then((function(e){return salla.cart.event.itemAdded(e,t.id),e})).catch((function(e){throw salla.cart.event.itemAddedFailed(e,t.id),e}))}async deleteItem(e){let t=this.getCartPayload(e);if(!t.id){let e='There is no "id"!';return salla.cart.event.itemDeletedFailed(e),salla.api.errorPromise(e)}let a=await this.getCurrentCartId();return this.request(["deleteItem",a,t.id]).then((function(e){return salla.cart.event.itemDeleted(e,t.id),e})).catch((function(e){throw salla.cart.event.itemDeletedFailed(e,t.id),e}))}async updateItem(e){let t=this.getCartPayload(e);if(!t.id){let e='There is no "id"!';return salla.cart.event.itemUpdatedFailed(e),salla.api.errorPromise(e)}let a=await this.getCurrentCartId();return "Object"===t.payload.constructor?.name?t.payload._method="PUT":t.payload.append("_method","PUT"),this.request(["updateItem",a,t.id],t.payload).then((function(e){return salla.cart.event.itemUpdated(e,t.id),e})).catch((function(e){throw salla.cart.event.itemUpdatedFailed(e,t.id),e}))}async deleteImage(e){if(!(e=salla.form.getPossibleValue(e,["id","image_id","photo_id"]))){let e='There is no "id"!';return salla.cart.event.imageNotDeleted(e),salla.api.errorPromise(e)}let t=await this.getCurrentCartId();return this.request(["deleteImage",t,e]).then((function(t){return salla.cart.event.imageDeleted(t,e),t})).catch((function(t){throw salla.cart.event.imageNotDeleted(t,e),t}))}async status(e){return this.request(["status",e||await this.getCurrentCartId()],{params:{has_apple_pay:!!window.ApplePaySession}})}async submit(){this.status(await this.getCurrentCartId()).then((e=>{let t=e.data.next_step.to;if(!["checkout","refresh","login"].includes(t)){let e="Can't find next_step );";throw salla.cart.event.submitFailed(e),e}if(salla.cart.event.submitted(e),"login"===t)return salla.auth.setCanRedirect(!1),salla.event.dispatch("login::open"),void salla.auth.event.onLoggedIn((e=>{salla.event.dispatch("login::close"),this.submit();}));"checkout"===t?window.location.href=e.data.next_step.url+(window.ApplePaySession?"?has_apple_pay=true":""):window.location.reload();})).catch((function(e){throw salla.cart.event.submitFailed(e),e}));}getCartPayload(e){let t=e?.data||("object"==typeof e?e:void 0);return e=t?salla.form.getPossibleValue(t,["prod_id","product_id","item_id","id"]):e,t="object"==typeof t?t:void 0,{id:e,payload:t}}normalRequest(e,t,a=null){return super.normalRequest(e,t,a).catch((e=>{throw 403===e?.response?.status&&(salla.cart.api.reset(),salla.error(salla.lang.get("pages.checkout.try_again"))),e}))}reset(){salla.api.cart.latestCart=null,salla.storage.remove("cart"),salla.cart.event.successReset();}async addCoupon(e){if(e=e.data||e,!(e=salla.form.getPossibleValue(e,["coupon"]))){let e=new Error('There is no "Coupon Code"!');return e.name="EmptyCoupon",salla.event.cart.couponAdditionFailed(e),salla.api.errorPromise(e)}let t=await salla.cart.api.getCurrentCartId();return this.request(["addCoupon",t],{coupon:e}).then((function(e){return salla.event.cart.couponAdded(e,t),e})).catch((function(e){throw salla.event.cart.couponAdditionFailed(e,t),e}))}async deleteCoupon(){let e=await salla.cart.api.getCurrentCartId();return this.request(["deleteCoupon",e],{}).then((function(t){return salla.event.cart.couponDeleted(t,e),t})).catch((function(t){throw salla.event.cart.couponDeletionFailed(t,e),t}))}getQuickOrderSettings(){return this.request("getQuickOrderSettings").then((e=>(salla.event.cart.quickOrderSettingFetched(e),e))).catch((e=>{throw salla.event.cart.quickOrderSettingFailed(e),e}))}createQuickOrder(e){return this.request("createQuickOrder",e).then((e=>(salla.event.cart.quickOrderSucceeded(e),e))).catch((e=>{throw salla.event.cart.quickOrderFailed(e),e}))}async priceQuote(e){return salla.config.isGuest()?(salla.auth.api.setAfterLoginEvent("cart::priceQuote",e),void salla.event.dispatch("login::open")):this.request(["priceQuote",e||await this.getCurrentCartId()]).then((e=>(salla.cart.api.reset(),salla.event.cart.priceQuoteSucceeded(e).then((()=>(setTimeout((()=>window.location.href=salla.url.get("/")),1e3),e)))))).catch((e=>salla.event.cart.priceQuoteFailed(e).then((()=>{throw 404===e.error?.code&&window.location.reload(),e}))))}}class g extends h{constructor(){super(),this.namespace="loyalty",this.endpoints={getProgram:"loyalty",exchange:"loyalty/exchange",reset:"loyalty/exchange"},this.endpointsMethods={getProgram:"get",reset:"put"},this.after_init();}getProgram(){return this.request("getProgram").then((e=>(salla.loyalty.event.programFetched(e),e))).catch((e=>{throw salla.loyalty.event.programNotFetched(e),e}))}async exchange(e,t=null){if(!(e=salla.form.getPossibleValue(e,["id","loyalty_prize_id","prize_id"]))){let e="Unable to find cart id. Please provide one.";return salla.loyalty.event.exchangeFailed(e),salla.api.errorPromise(e)}if(!(t=t||await salla.cart.getCurrentCartId())){let e="Unable to find cart id. Please provide one.";return salla.loyalty.event.exchangeFailed(e),salla.api.errorPromise(e)}return this.request("exchange",{loyalty_prize_id:e,cart_id:t}).then((function(t){return salla.loyalty.event.exchangeSucceeded(t,e),t})).catch((function(t){throw salla.loyalty.event.exchangeFailed(t,e),t}))}async reset(e=null){if(!(e=e||await salla.cart.getCurrentCartId())){let e="Unable to find cart id. Please provide one.";return salla.loyalty.event.resetFailed(e),salla.api.errorPromise(e)}return this.request("reset",{cart_id:e}).then((e=>(salla.loyalty.event.resetSucceeded(e),e))).catch((e=>{throw salla.loyalty.event.resetFailed(e),e}))}}class f extends h{constructor(){super(),this.namespace="auth",this.canRedirect_=!0,this.afterLoginEvent={event:null,payload:null},this.endpoints={login:"auth/{type}/send_verification",resend:"auth/resend_verification",verify:"auth/{type}/verify",register:"auth/register",logout:"logout",refresh:"auth/refresh"},this.webEndpoints=["logout","auth/jwt","refresh"],this.endpointsMethods={logout:"get"},this.after_init();}setAfterLoginEvent(e,t){salla.api.auth.afterLoginEvent={event:e,payload:t};}setCanRedirect(e){salla.api.auth.canRedirect_=e;}canRedirect(){return salla.api.auth.canRedirect_&&!salla.api.auth.afterLoginEvent.event}login(e){e?.data&&(e=e.data);let t=salla.form.getPossibleValue(e,["type"]);if(!["email","mobile"].includes(t)){let e="Login type should be in: [email, mobile]";return salla.auth.event.codeNotSent(e),salla.api.errorPromise(e)}return this.request(["login",t],e).then((function(e){return salla.auth.event.codeSent(e,t),e})).catch((function(e){throw salla.auth.event.codeNotSent(e,t),e}))}async verify(e,t=!0){let a=salla.form.getPossibleValue(e,["type"]);if(!a){let e="Failed to know what's login type!";return salla.auth.event.verificationFailed(e),salla.api.errorPromise(e)}t=!1!==salla.form.getPossibleValue(e,["supportWebAuth"])&&t,salla.auth.event.next_event&&(e.next_event=salla.auth.event.next_event);let r=await salla.auth.api.request(["verify",a],e);if(200!==r?.status)return salla.auth.event.verificationFailed(r,a),salla.api.errorPromise(r);let i="authenticated"===r.data?.case;return i&&salla.auth.event.tokenFetched(r.data.token),t&&await salla.auth.api.request("auth/jwt"),i&&salla.auth.event.loggedIn(r).then((()=>salla.auth.api.afterUserLogin())),salla.auth.event.verified(r,a),salla.api.successPromise(r)}resend(e){let t;return (e=e.data||e).type=e.type||"mobile","mobile"!==e.type||e.phone&&e.country_code?"email"!==e.type||e.email?this.request("resend",e).then((function(t){return salla.auth.event.codeSent(t,e),t})).catch((function(t){throw salla.auth.event.codeNotSent(t,e),t})):(salla.auth.event.codeNotSent(t="There is no email!",e),salla.api.errorPromise(t)):(salla.auth.event.codeNotSent(t="There is no phone or country_code!",e),salla.api.errorPromise(t))}register(e){let t;return e.data&&(t=e.element,e=e.data),salla.auth.event.next_event&&(e.next_event=salla.auth.event.next_event),this.request("register",e).then((async function(e){return salla.auth.event.registered.call(t,e),"authenticated"===e.data?.case&&(salla.auth.event.tokenFetched(e.data.token),await salla.auth.request("auth/jwt"),salla.auth.event.loggedIn(e),salla.auth.api.afterUserLogin()),e})).catch((function(e){throw salla.auth.event.registrationFailed.call(t,e),e}))}logout(){return salla.storage.clearAll(),salla.cookie.clearAll(),salla.auth.event.loggedOut().then((()=>{let e=salla.url.get("logout");console.log(`Going to ${e}, to do any thing before this action use: salla.auth.even.onLoggedOut(()=>{...})`),location.href=e;}))}refresh(){return this.request("refresh").then((function(e){return salla.auth.event.tokenFetched(e.data.token),e})).catch((function(e){throw salla.auth.event.refreshFailed(e),e}))}afterUserLogin(){this.afterLoginEvent.event&&salla.event.emit(this.afterLoginEvent.event,this.afterLoginEvent.payload);}}class m extends h{constructor(){super(),this.namespace="order",this.endpoints={cancel:"orders/cancel/{id}",createCartFromOrder:"reorder/{id}",sendInvoice:"orders/send/{id}"},this.endpointsMethods={createCartFromOrder:"get"},this.after_init();}show(e){let t=salla.form.getPossibleValue(e?.data||e,["id","order_id"]);salla.event.dispatch("mobile::order.placed",{order_id:t}),location.href=salla.form.getPossibleValue(e?.data||e,["url"]);}cancel(e){return e=e||Salla.config.get("page.id"),this.request(["cancel",e],{params:{has_apple_pay:!!window.ApplePaySession}}).then((function(t){return salla.event.order.canceled(t,e),t})).catch((function(t){throw salla.event.order.notCanceled(t,e),t}))}createCartFromOrder(e){return e=e||salla.config.get("page.id"),this.request(["createCartFromOrder",e]).then((function(t){return salla.cart.reset(),salla.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=salla.form.getPossibleValue(e,["id"])||salla.config.get("page.id");if(!t||isNaN(t)){let e="There is no id!";return salla.order.event.invoiceNotSent(e),salla.api.errorPromise(e)}return this.request(["sendInvoice",t],e).then((e=>(salla.event.order.invoiceSent(e,t),e))).catch((e=>{throw salla.event.order.invoiceNotSent(e,t),e}))}}class v extends h{constructor(){super(),this.namespace="product",this.previousQuery="",this.endpoints={get:"products/{id}/details",getPrice:"products/{id}/price",availabilitySubscribe:"products/{id}/availability-notify",search:"products/search",detail:"products/{product_id}/details",categories:"products/categories/{?id}",offers:"products/{product_id}/specialoffer",getSizeGuides:"products/{prod_id}/size-guides",giftDetail:"products/{product_id}/buy-as-gift",giftToCart:"products/{product_id}/buy-as-gift",giftImage:"products/buy-as-gift/image"},this.endpointsMethods={detail:"get",giftDetail:"get"},this.after_init();}get(e,t=[]){if(!Array.isArray(t)){let e="withItems should be array.";return salla.api.errorPromise(e)}if(!e){let e="productId is not passed.";return salla.api.errorPromise(e)}return this.request(["get",e],{params:{with:t}}).then((function(e){return e})).catch((function(e){throw e}))}getPrice(e){let t=e.data||e,a=salla.form.getPossibleValue(t,["id","prod_id","product_id"]);return this.request(["getPrice",a],"object"==typeof t?t:void 0).then((function(e){return salla.product.event.priceUpdated(e,a),e})).catch((function(e){throw salla.product.event.priceUpdateFailed(e,a),e}))}categories(e){return this.request(["categories",e||""],null,"get").then((function(e){return salla.product.event.categoriesFetched(e),e})).catch((function(e){throw salla.product.event.categoriesFailed(e),e}))}availabilitySubscribe(e){let t=e.data||e;return e=salla.form.getPossibleValue(t,["id","prod_id"]),this.request(["availabilitySubscribe",e],"object"==typeof t?t:void 0).then((function(t){return salla.product.event.availabilitySubscribed(t,e),t})).catch((function(t){throw salla.product.event.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),salla.api.errorPromise(e)}if(e===salla.api.product.previousQuery){let e="Query is same as previous one!";return salla.product.event.searchFailed(e),salla.api.product.previousQuery=null,salla.api.errorPromise(e)}return salla.api.product.previousQuery=e,this.request("search",t,"get").then((function(t){return salla.product.event.searchResults(t,e),t})).catch((function(t){throw salla.product.event.searchFailed(t,e),t}))}offers(e){if(!(e=salla.form.getPossibleValue(e?.data|e,["product_id","id"]))){let e='There is no "product_id"!';return salla.offer.event.fetchDetailsFailed(e),salla.api.errorPromise(e)}return this.request(["offers",e]).then((function(t){return salla.product.event.offersFetched(t,e),t})).catch((function(t){throw salla.product.event.fetchOffersFailed(t,e),t}))}getSizeGuides(e){return this.request(`products/${e}/size-guides`,null,"get").then((t=>(salla.product.event.sizeGuideFetched(t,e),t))).catch((t=>{throw salla.product.event.sizeGuideFetchFailed(t,e),t}))}getGiftDetails(e){return this.request(["giftDetail",e]).then((t=>(salla.product.event.giftFetched(t,e),t))).catch((t=>{throw salla.product.event.giftFetchFailed(t,e),t}))}getDetails(e,t=[]){if(!Array.isArray(t)){let e="withItems should be array.";return salla.product.event.detailFetchFailed(e),salla.api.errorPromise(e)}if(!e){let e="productId is not passed.";return salla.product.event.detailFetchFailed(e),salla.api.errorPromise(e)}return this.request(["detail",e],{params:{with:t}}).then((function(t){return salla.product.event.detailFetched(t,e),t})).catch((function(t){throw salla.product.event.detailFetchFailed(t,e),t}))}addGiftToCart(e,t,a=!1){return this.request(["giftToCart",e],t).then((t=>(salla.product.event.addGiftToCartSucceeded(t,e),a&&(window.location.href=t.redirect),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 y extends h{constructor(){super(),this.namespace="profile",this.endpoints={info:"auth/user",update:"profile/update",updateContacts:"profile/contacts/update",updateSettings:"profile/settings",verify:"profile/verify",delete:"profile"},this.endpointsMethods={delete:"delete"},this.after_init();}info(){return this.request("info",null,"get").then((e=>{let t={id:e.data.id,type:"user",email:e.data.email,mobile:e.data.phone.code+e.data.phone.number,country_code:e.data.phone.country,language_code:e.data.language,currency_code:e.data.currency,notifications:e.data.notifications,pending_orders:e.data.pending_orders,avatar:e.data.avatar,first_name:e.data.first_name,last_name:e.data.last_name,fetched_at:Date.now()};return salla.config.set("user",t),salla.storage.set("user",t),salla.profile.event.infoFetched(e),e})).catch((e=>{throw salla.profile.event.infoNotFetched(e),e}))}update(e){return this.request("update",e).then((e=>(salla.profile.event.updated(e),e))).catch((e=>{throw salla.event.profile.updateFailed(e),e}))}updateContacts(e){return this.request("updateContacts",e).then((e=>(salla.profile.event.verificationCodeSent(e),e))).catch((e=>{throw salla.event.profile.updateContactsFailed(e),e}))}verify(e){return this.request("verify",e).then((e=>(salla.profile.event.verified(e),e))).catch((e=>{throw salla.event.profile.unVerified(e),e}))}updateSettings(e){return this.request("updateSettings",e).then((e=>(salla.event.profile.settingsUpdated(e),e))).catch((e=>{throw salla.event.profile.updateSettingsFailed(e),e}))}delete(){return this.request("delete").then((e=>(salla.storage.clearAll(),salla.cookie.clearAll(),salla.event.profile.deleted(e),window.location.href=salla.url.get("logout"),e))).catch((e=>{throw salla.event.profile.notDeleted(e),e}))}}class w extends h{constructor(){super(),this.namespace="comment",this.endpoints={add:"{type}/{id}/comments"},this.after_init();}add(e){e?.data&&(e=e.data);let t,a=salla.form.getPossibleValue(e,["id"]),r=salla.form.getPossibleValue(e,["type"]),i=salla.form.getPossibleValue(e,["comment"]);return a?r&&["products","pages","product","page"].includes(r)?i?(r+=["product","page"].includes(r)?"s":"",this.request(["add",r,a],{comment:i}).then((function(e){return salla.event.comment.added(e,a),e})).catch((function(e){throw salla.event.comment.additionFailed(e,a),e}))):(salla.event.comment.additionFailed(t="can't find comment content!"),salla.api.errorPromise(t)):(salla.event.comment.additionFailed(t="Failed to get type one of:(products, product, page, pages)!"),salla.api.errorPromise(t)):(salla.event.comment.additionFailed(t="Failed to get id!"),salla.api.errorPromise(t))}}class b extends h{constructor(){super(),this.namespace="currency",this.endpoints={change:"/",list:"currencies"},this.endpointsMethods={change:"get",list:"get"},this.webEndpoints=["change"],this.after_init();}change(e){if(!(e=salla.form.getPossibleValue(e.data||e,["currency","code"]))){let e="Can't find currency code!";return salla.currency.event.failed(e),salla.api.errorPromise(e)}return this.request("change",{params:{change_currency:"",currency:e}}).then((function(t){return salla.cookie.set("fresh_summary",1),salla.storage.set("cart",""),salla.currency.event.changed(t,e),t})).catch((function(t){throw salla.currency.event.failed(t,e),t}))}list(){return this.request("list").then((function(e){return salla.currency.event.fetched(e),e})).catch((function(e){throw salla.currency.event.failedToFetch(e),e}))}}class F extends h{constructor(){super(),this.namespace="document";}}class S extends h{constructor(){super(),this.namespace="rating",this.endpoints={store:"rating/store",products:"rating/products",shipping:"rating/shipping",order:"rating/{order_id}"},this.endpointsMethods={order:"get"},this.after_init();}order(e){let t="object"==typeof e?e:{},a=salla.form.getPossibleValue(e?.data||e,["order_id","id"]);if(!a){let e='There is no "order_id"!';return salla.event.rating.orderNotFetched(e),salla.api.errorPromise(e)}return this.request(["order",a],t).then((function(e){return salla.event.rating.orderFetched(e,a),e})).catch((function(e){throw salla.event.rating.orderNotFetched(e,a),e}))}store(e){if(!(e=e.data||e)){let e='There is no "data"!';return salla.event.rating.storeFailed(e),salla.api.errorPromise(e)}return this.request("store",e).then((function(t){return salla.event.rating.storeRated(t,e),t})).catch((function(t){throw salla.event.rating.storeFailed(t,e),t}))}products(e){if(!(e=e.data||e)){let e='There is no "data"!';return salla.event.rating.productsFailed(e),salla.api.errorPromise(e)}return this.request("products",e).then((function(t){return salla.event.rating.productsRated(t,e),t})).catch((function(t){throw salla.event.rating.productsFailed(t,e),t}))}shipping(e){if(!(e=e.data||e)){let e='There is no "data"!';return salla.event.rating.shippingFailed(e),salla.api.errorPromise(e)}return this.request("shipping",e).then((function(t){return salla.event.rating.shippingRated(t,e),t})).catch((function(t){throw salla.event.rating.shippingFailed(t,e),t}))}}class _ extends h{constructor(){super(),this.namespace="wishlist",this.endpoints={add:"products/favorites/{id}",remove:"products/favorites/{id}"},this.endpointsMethods={remove:"delete"},this.after_init();}toggle(e){return salla.storage.get("salla::wishlist",[]).includes(e)?this.remove(e):this.add(e)}add(e){let t;return salla.config.isGuest()?(salla.wishlist.event.additionFailed(t=salla.lang.get("common.messages.must_login")),salla.error(t),salla.api.errorPromise(t)):(e=salla.form.getPossibleValue(e?.data||e,["product_id","id"]))?this.request(["add",e]).then((t=>(this.updateWishlistStorage(e),salla.wishlist.event.added(t,e),t))).catch((function(t){throw salla.wishlist.event.additionFailed(t,e),t})):(salla.wishlist.event.additionFailed(t="Failed to get product id!"),salla.api.errorPromise(t))}remove(e){let t;return salla.config.isGuest()?(salla.wishlist.event.additionFailed(t=salla.lang.get("common.messages.must_login")),salla.error(t),salla.api.errorPromise(t)):(e=salla.form.getPossibleValue(e?.data||e,["product_id","id"]))?this.request(["remove",e]).then((t=>(this.updateWishlistStorage(e,!1),salla.wishlist.event.removed(t,e),t))).catch((function(t){throw salla.wishlist.event.removingFailed(t,e),t})):(salla.wishlist.event.removingFailed(t="Failed to get id!"),salla.api.errorPromise(t))}updateWishlistStorage(e,t=!0){let a=salla.storage.get("salla::wishlist",[]);t?a.push(e):a.splice(a.indexOf(e),1),salla.storage.set("salla::wishlist",a);}}class q extends h{constructor(){super(),this.namespace="scopes",this.endpoints={get:"scopes",change:"scopes",getProductAvailability:"scopes/availability?product_id={id}"},this.after_init();}get(){return this.request("scopes",null,"get").then((e=>(salla.scope.event.fetched(e),e))).catch((e=>{throw salla.scope.event.notFetched(e),e}))}change(e){return this.request("scopes",e).then((e=>(salla.scope.event.changeSucceeded(e),e))).catch((e=>{throw salla.scope.event.changeFailed(e),e}))}getProductAvailability(e=null){return this.request(`scopes/availability?product_id=${e}`,null,"get").then((t=>(salla.scope.event.productAvailabilityFetched(t,e),t))).catch((e=>{throw salla.scope.event.productAvailabilityNotFetched(e),resp}))}}class A extends h{constructor(){super(),this.namespace="booking",this.endpoints={add:"cart/booking/product/{id}"},this.endpointsMethods={add:"get"};}async add(e,t=!0){if(!e){let e="Please provide product id.";return salla.booking.event.additionFailed(e),salla.api.errorPromise(e)}return this.request(["add",e]).then((function(e){return salla.booking.event.added(e),t&&"booking"===e.data.redirect.to&&(window.location.href=e.data.redirect.url),e})).catch((function(e){throw salla.booking.event.additionFailed(e),e}))}}class E{constructor(t){"ready"!==f$1.status?t?(f$1.config.merge(t),t?.events&&f$1.event.dispatchEvents(t?.events),t._token&&salla.api.setHeader("X-CSRF-TOKEN",t._token),this.injectMaintenanceAlert(),this.injectThemePreviewAlert(),this.injectEditAlert(),t?.user?.language_code&&salla.lang.setLocale(t?.user?.language_code),salla.lang.loadStoreTranslations(),this.setSallaReady(t)):this.setSallaReady(t):salla.log("Trying to re-initiate Salla, while its status === 'ready'!");}injectMaintenanceAlert(){salla.config.get("maintenance")&&(document.querySelector(".store-notify")?salla.logger.warn(".store-notify element Existed before!"):salla.lang.onLoaded((()=>{const 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 a=t.getAjaxFormData(e),r=a.method?a.method.toLowerCase():void 0;salla.api.request(a.url,a.formData,r).then((e=>(e.data&&e.request&&(e=e.data),salla.api.handleAfterResponseActions(e),this.callAjaxEvent(a.events.success,e,a.formData),e))).catch((e=>{throw salla.api.handleErrorResponse(e),this.callAjaxEvent(a.events.fail,e,a.formData),e}));}callAjaxEvent(e,t,a){if(e){if(a instanceof FormData){const e={};Array.from(a.entries()).forEach((function(t){e[t[0]]=t[1];})),a=e;}window[e]?window[e](t,a):salla.event.dispatch(e,t,a);}}setSallaReady(t){f$1.status="ready",f$1.event.dispatch("twilight::initiated",t),window.dispatchEvent(new CustomEvent("twilight::initiated",{detail:t}));}}f$1.status="loading",f$1.notify=o,f$1.lang=new class extends lang{constructor(e){(e=e||{}).messages=e.messages||window.translations,e.locale=e.locale||(window.locale||navigator.language||navigator.userLanguage||"ar").split("-")[0],e.fallback=e.fallback||e.locale,super(e),this.translationsLoaded=!1;}onLoaded(e){if(this.translationsLoaded)return e();Salla.event.once("languages::translations.loaded",e);}loadStoreTranslations(){if(this.messages)return void window.addEventListener("load",(e=>{salla.event.dispatch("languages::translations.loaded"),salla.logger.info("The messages of transactions is already loaded");}));if(!salla.url.get(""))return void this.loadScript("https://cdn.salla.network/js/translations.js",!1);let e=salla.config.get("theme.translations_hash",salla.config.get("store.id","twilight"));this.loadScript(salla.url.get(`languages/assets/${e}.js`));}setMessages(e){super.setMessages(e),salla.event.dispatch("languages::translations.loaded"),this.translationsLoaded=!0;}loadScript(e,t=!0){let a=document.createElement("script");a.src=e,a.onload=()=>{if(window.translations)return this.setMessages(window.translations);a.onerror();},a.onerror=()=>{if(t)return salla.logger.warn("Failed to load Translations for store, lets try load it from CDN"),this.loadScript("https://cdn.salla.network/js/translations.js",!1);salla.logger.error("Failed to load Translations, check your network logs for more details\nor: salla.lang.setMessages({....}), see https://docs.salla.dev for more information's.");},document.head.appendChild(a);}get(e,t,a){return window.translations&&(e="trans."+e),super.get(e,t,a)}set(e,t){return salla.helpers.setNested(this.messages[this.getLocale()+".trans"],e,t),this}},f$1.form=new class{async submit(e,t=null){let a=t;if("SubmitEvent"===t?.constructor?.name||"submit"===t?.type){if(t.preventDefault(),"FORM"!==t.target?.tagName)return Salla.logger.warn("Failed find the target element for submit action. make sure you submit a form element"),new Promise((()=>{throw "Failed find the target element for submit action. make sure you submit a form element"}));"SALLA-BUTTON"===t?.submitter?.parentElement?.tagName&&t.submitter.parentElement.load(),a=t.target.getElementSallaData(),salla.log("Data from element",a);}if(/^https?:\/\/(?:www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)$/gm.test(e))return salla.api.normalRequest(e,a,"post").finally((()=>{loaderSupported&&t?.submitter?.parentElement.stop();}));let r=e.split("."),i=r.splice(-1);return await salla.call(r.join("."))[i](a).finally((()=>t?.submitter?.parentElement?.stop())).catch((e=>{throw salla.logger.warn(e),e}))}onSubmit(e,t){return salla.form.submit(e,t),!1}onChange(e,t){return t?.currentTarget?"FORM"!==t?.currentTarget?.tagName||t.currentTarget.checkValidity()?(salla.form.submit(e,t.currentTarget.getElementSallaData()),!0):(salla.logger.warn(`Trying to trigger '${e}' without filling required fields!`),!1):(salla.logger.warn(`Trying to trigger '${e}' without event!`),!1)}getPossibleValue(e,t,a=!1){if(!e)return;if("object"!=typeof e)return e;let r;for(let a=0;a<t.length&&!(r=e[t[a]])&&!("undefined"!=typeof FormData&&e instanceof FormData&&(r=e.get(t[a])));a++);return r=r||e,"object"!=typeof r||a?r:void 0}},f$1.helpers.app=new class{toggleClassIf(e,t,a,r){return document.querySelectorAll(e).forEach((e=>this.toggleElementClassIf(e,t,a,r))),this}toggleElementClassIf(e,t,a,r){t=Array.isArray(t)?t:t.split(" "),a=Array.isArray(a)?a:a.split(" ");let i=r(e);return e?.classList.remove(...i?a:t),e?.classList.add(...i?t:a),this}isValidEmail(e){return /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(String(e).toLowerCase())}element(e){return "object"==typeof e?e:document.querySelector(e)}watchElement(e,t){return this[e]=this.element(t),this}watchElements(e){return Object.entries(e).forEach((e=>this.watchElement(e[0],e[1]))),this}on(e,t,a,r={}){return "object"==typeof t?(this.element(t).addEventListener(e,a,r),this):(document.querySelectorAll(t).forEach((t=>t.addEventListener(e,a,r))),this)}onClick(e,t){return this.on("click",e,t)}onKeyUp(e,t){return this.on("keyup",e,t)}onEnter(e,t){return this.onKeyUp(e,(e=>13===e.keyCode&&t(e))),this}all(e,t){return document.querySelectorAll(e).forEach(t),this}hideElement(e){return this.element(e).style.display="none",this}showElement(e,t="block"){return this.element(e).style.display=t,this}removeClass(e,t){return this.element(e).classList.remove(...Array.from(arguments).slice(1)),this}addClass(e,t){return this.element(e).classList.add(...Array.from(arguments).slice(1)),this}debounce(e,...t){return this.debounce_||(this.debounce_=Salla.helpers.debounce(((e,...t)=>e(...t)),500)),this.debounce_(e,...t)}},f$1.infiniteScroll=new class extends d{constructor(e,t){super(e,t),this.options={path:".infinite-scroll-btn",history:"push",status:".infinite-scroll-status",append:".list-block"},this.fetchOptions={headers:{"S-INFINITE-SCROLL":!0}},this.instances=[];}initiate(e,a,r){r=this.getCustomOptions(a,r);let i="string"!=typeof e?e:document.querySelector(e),s=r.path;if(!i||!s||"string"==typeof s&&!document.querySelector(s))return void Salla.logger.warn(i?"Path Option (a link that has next page link) Not Existed!":"Container For InfiniteScroll not Existed!");let n=new js(i,r);return n.on("scrollThreshold",Salla.infiniteScroll.event.scrollThreshold),n.on("request",Salla.infiniteScroll.event.request),n.on("load",Salla.infiniteScroll.event.load),n.on("append",Salla.infiniteScroll.event.append),n.on("error",Salla.infiniteScroll.event.error),n.on("last",Salla.infiniteScroll.event.last),n.on("history",Salla.infiniteScroll.event.history),this.instances.push(n),n}getCustomOptions(e,t){return (t="object"==typeof e&&e||t||this.options).fetchOptions=this.fetchOptions,t.path=t.path||this.options.path,t.button=t.button||t.path,t.status=t.status||this.options.status,t.hasOwnProperty("history")||(t.history=this.options.history),t.nextPage=t.nextPage||t.next_page,t.append="string"==typeof e&&e||t.append||this.options.append,t}}(void 0,salla.event.infiniteScroll),f$1.api=new class extends class{constructor(){salla.event.on("twilight::initiated",(e=>this.initiateRequest(e))),salla.event.on("profile::info.fetched",(e=>this.setCurrencyAndLanguage(e))),salla.event.on("auth::token.fetched",(e=>{salla.storage.set("token",e),this.setToken(e),salla.cart.api.reset();})),this.notifier_handler_disabled=!1,this.axios=axios.create({headers:{common:{"X-Requested-With":"XMLHttpRequest","S-SOURCE":"twilight","S-APP-VERSION":"v2.0.0","S-APP-OS":"browser"}}});}getHeaders(){return this.axios.defaults.headers.common}setHeaders(e){return Object.entries(e).forEach((e=>this.setHeader(e[0],e[1]))),this}setHeader(e,t){return salla.infiniteScroll.fetchOptions.headers[e]=this.axios.defaults.headers.common[e]=t,this}async withoutNotifier(e){return this.notifier_handler_disabled=!0,await e().finally((()=>{this.notifier_handler_disabled=!1;}))}initiateRequest(e){this.axios.defaults.baseURL=Salla.config.get("store.api",Salla.config.get("store.url")),this.setHeaders({"Store-Identifier":Salla.config.get("store.id"),currency:e.user?.currency_code||"SAR","accept-language":salla.lang.getLocale(),"s-user-id":e.user?.id});let t=salla.storage.get("scope");t&&this.setHeaders({"s-scope-type":t.type,"s-scope-id":t.id}),this.injectTokenToTheRequests(e);}injectTokenToTheRequests(e){let t=salla.storage.get("token"),a=Salla.config.isGuest(),r=salla.storage.get("cart"),s=e.user?.id,n=salla.storage.get("user.id");if(n&&n!==s&&salla.storage.remove("user"),r&&(r.user_id!==s||r.store_id!==e.store?.id))return salla.log("cart",{user_id:r.user_id,store_id:r.store_id}),salla.log("current",{user_id:s,store_id:e.store?.id}),salla.log("Auth:: The cart is not belong to current "+(r.user_id!==s?"user":"store")+"!"),void salla.cart.api.reset();if(a&&!t)return;if(a&&t)return salla.log("Auth:: Token without user!"),salla.storage.remove("token"),void salla.cart.api.reset();if(!t)return salla.cart.api.reset(),void salla.auth.api.refresh();let l=o$1(t);return Date.now()/1e3>l.exp?(salla.log("Auth:: An expired token!"),salla.storage.remove("token"),salla.cart.api.reset(),void salla.auth.api.refresh()):l.sub!==s?(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()):(this.setToken(t),void salla.event.emit("request::initiated"))}setToken(e){return this.setHeader("Authorization","Bearer "+e)}setCurrencyAndLanguage(e){return this.setHeaders({currency:e.data.currency,"accept-language":e.data.language})}request(e,t,a="get",r={}){let i={endPoint:e,payload:t,method:a,options:r},s="undefined"!=typeof event?event.currentTarget:null,n=!1;return "SALLA-BUTTON"===s?.tagName&&(n=!0),n&&s?.load(),this.axios[i.method](i.endPoint,i.payload,i.options).then((e=>(n&&s?.stop(),e.data&&e.request&&(e=e.data),this.handleAfterResponseActions(e),e))).catch((e=>{throw n&&s?.stop(),salla.event.document.requestFailed(i,e),this.handleErrorResponse(e),e}))}handleAfterResponseActions(e){if(!e)return;let{data:t,googleTags:a=null}=e,r=t&&t.googleTags?t.googleTags:a;dataLayer&&r&&dataLayer.push(r),this.fireEventsForResponse(e),this.showAlert(e),this.renderSections(e);}fireEventsForResponse(e){let t=e?.events||e.data?.events||e.error?.events;"string"==typeof t&&(t=JSON.parse(t)),t&&Object.keys(t).forEach((e=>salla.event.dispatch(e,t[e])));}handleErrorResponse(e){if(e.response&&e.response.data)return e.response.data.error&&e.response.data.error.fields&&!this.notifier_handler_disabled?this.handleInvalidFields(e):this.handleAfterResponseActions(e.response.data)}showAlert(e){if(e&&!this.notifier_handler_disabled)return e.case&&e.msg?salla.notify.fire(e.msg,e.case,e):e.hasOwnProperty("success")&&e.data?.message?salla.notify.fire(e.data?.message,e.success?salla.notify.types.success:salla.notify.types.error,e):e.error&&e.error.message&&"FORBIDDEN"!==e.error.message?salla.error(e.error.message,e):void 0}handleInvalidFields(e){let t=e.response.data.error.fields,a=[];Object.keys(t).forEach((e=>{let r=t[e];Array.isArray(r)?r.forEach((e=>a.push(e))):a.push(r);}));let r=(a.length>1?"* ":"")+a.join("\n* ");salla.error(r,e);}isFastRequestsAllowed(){return Salla.config.get("fastRequests")}promise(e,t=!0){return new Promise(((a,r)=>t?a(e):r(e)))}errorPromise(e){return this.promise(e,!1)}successPromise(e){return this.promise(e,!0)}renderSections(e){e.sections&&Object.keys(e.sections).forEach((t=>{document.querySelectorAll(t.toSelector()).forEach((function(a){a.innerHTML=e.sections[t];}));}));}}{constructor(){super(),this.auth=new f,this.cart=new p,this.loyalty=new g,this.order=new m,this.rating=new S,this.product=new v,this.profile=new y,this.comment=new w,this.currency=new b,this.document=new F,this.wishlist=new _,this.scope=new q,this.booking=new A;}},f$1.cart=new d(f$1.api.cart,f$1.event.cart),f$1.auth=new d(f$1.api.auth,f$1.event.auth),f$1.order=new d(f$1.api.order,f$1.event.order),f$1.scope=new d(f$1.api.scope,f$1.event.scope),f$1.rating=new d(f$1.api.rating,f$1.event.rating),f$1.comment=new d(f$1.api.comment,f$1.event.comment),f$1.loyalty=new d(f$1.api.loyalty,f$1.event.loyalty),f$1.product=new d(f$1.api.product,f$1.event.product),f$1.profile=new d(f$1.api.profile,f$1.event.profile),f$1.currency=new d(f$1.api.currency,f$1.event.currency),f$1.document=new d(f$1.api.document,f$1.event.document),f$1.wishlist=new d(f$1.api.wishlist,f$1.event.wishlist),f$1.booking=new d(f$1.api.booking,f$1.event.booking),f$1.call=t=>{let a=f$1,r=t.split(".");for(;r.length&&(a=a[r.shift()]););return a},f$1.init=e=>new E(e),salla.event.once("twilight::init",salla.init),salla.event.once("twilight::api",(e=>{let t=e?.events;t&&salla.event.dispatchEvents(t);})),f$1.success=f$1.notify.success,f$1.error=f$1.notify.error,f$1.versions.twilight="[VI]{version}[/VI]",f$1.onInitiated=e=>salla.event.once("twilight::initiated",e),f$1.onReady=f$1.onReady||function(t){"ready"!==salla.status?f$1.onInitiated(t):t(salla.config.all());},window.dispatchEvent(new CustomEvent("salla::created"));
7515
9708
 
7516
9709
  var lazyload_min = createCommonjsModule(function (module, exports) {
7517
9710
  !function(n,t){module.exports=t();}(commonjsGlobal,(function(){function n(){return n=Object.assign||function(n){for(var t=1;t<arguments.length;t++){var e=arguments[t];for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(n[i]=e[i]);}return n},n.apply(this,arguments)}var t="undefined"!=typeof window,e=t&&!("onscroll"in window)||"undefined"!=typeof navigator&&/(gle|ing|ro)bot|crawl|spider/i.test(navigator.userAgent),i=t&&"IntersectionObserver"in window,o=t&&"classList"in document.createElement("p"),a=t&&window.devicePixelRatio>1,r={elements_selector:".lazy",container:e||t?document:null,threshold:300,thresholds:null,data_src:"src",data_srcset:"srcset",data_sizes:"sizes",data_bg:"bg",data_bg_hidpi:"bg-hidpi",data_bg_multi:"bg-multi",data_bg_multi_hidpi:"bg-multi-hidpi",data_bg_set:"bg-set",data_poster:"poster",class_applied:"applied",class_loading:"loading",class_loaded:"loaded",class_error:"error",class_entered:"entered",class_exited:"exited",unobserve_completed:!0,unobserve_entered:!1,cancel_on_exit:!0,callback_enter:null,callback_exit:null,callback_applied:null,callback_loading:null,callback_loaded:null,callback_error:null,callback_finish:null,callback_cancel:null,use_native:!1,restore_on_error:!1},c=function(t){return n({},r,t)},l=function(n,t){var e,i="LazyLoad::Initialized",o=new n(t);try{e=new CustomEvent(i,{detail:{instance:o}});}catch(n){(e=document.createEvent("CustomEvent")).initCustomEvent(i,!1,!1,{instance:o});}window.dispatchEvent(e);},u="src",s="srcset",d="sizes",f="poster",_="llOriginalAttrs",g="data",v="loading",b="loaded",m="applied",p="error",h="native",E="data-",I="ll-status",y=function(n,t){return n.getAttribute(E+t)},k=function(n){return y(n,I)},w=function(n,t){return function(n,t,e){var i="data-ll-status";null!==e?n.setAttribute(i,e):n.removeAttribute(i);}(n,0,t)},A=function(n){return w(n,null)},L=function(n){return null===k(n)},O=function(n){return k(n)===h},x=[v,b,m,p],C=function(n,t,e,i){n&&(void 0===i?void 0===e?n(t):n(t,e):n(t,e,i));},N=function(n,t){o?n.classList.add(t):n.className+=(n.className?" ":"")+t;},M=function(n,t){o?n.classList.remove(t):n.className=n.className.replace(new RegExp("(^|\\s+)"+t+"(\\s+|$)")," ").replace(/^\s+/,"").replace(/\s+$/,"");},z=function(n){return n.llTempImage},T=function(n,t){if(t){var e=t._observer;e&&e.unobserve(n);}},R=function(n,t){n&&(n.loadingCount+=t);},G=function(n,t){n&&(n.toLoadCount=t);},j=function(n){for(var t,e=[],i=0;t=n.children[i];i+=1)"SOURCE"===t.tagName&&e.push(t);return e},D=function(n,t){var e=n.parentNode;e&&"PICTURE"===e.tagName&&j(e).forEach(t);},H=function(n,t){j(n).forEach(t);},V=[u],F=[u,f],B=[u,s,d],J=[g],P=function(n){return !!n[_]},S=function(n){return n[_]},U=function(n){return delete n[_]},$=function(n,t){if(!P(n)){var e={};t.forEach((function(t){e[t]=n.getAttribute(t);})),n[_]=e;}},q=function(n,t){if(P(n)){var e=S(n);t.forEach((function(t){!function(n,t,e){e?n.setAttribute(t,e):n.removeAttribute(t);}(n,t,e[t]);}));}},K=function(n,t,e){N(n,t.class_applied),w(n,m),e&&(t.unobserve_completed&&T(n,t),C(t.callback_applied,n,e));},Q=function(n,t,e){N(n,t.class_loading),w(n,v),e&&(R(e,1),C(t.callback_loading,n,e));},W=function(n,t,e){e&&n.setAttribute(t,e);},X=function(n,t){W(n,d,y(n,t.data_sizes)),W(n,s,y(n,t.data_srcset)),W(n,u,y(n,t.data_src));},Y={IMG:function(n,t){D(n,(function(n){$(n,B),X(n,t);})),$(n,B),X(n,t);},IFRAME:function(n,t){$(n,V),W(n,u,y(n,t.data_src));},VIDEO:function(n,t){H(n,(function(n){$(n,V),W(n,u,y(n,t.data_src));})),$(n,F),W(n,f,y(n,t.data_poster)),W(n,u,y(n,t.data_src)),n.load();},OBJECT:function(n,t){$(n,J),W(n,g,y(n,t.data_src));}},Z=["IMG","IFRAME","VIDEO","OBJECT"],nn=function(n,t){!t||function(n){return n.loadingCount>0}(t)||function(n){return n.toLoadCount>0}(t)||C(n.callback_finish,t);},tn=function(n,t,e){n.addEventListener(t,e),n.llEvLisnrs[t]=e;},en=function(n,t,e){n.removeEventListener(t,e);},on=function(n){return !!n.llEvLisnrs},an=function(n){if(on(n)){var t=n.llEvLisnrs;for(var e in t){var i=t[e];en(n,e,i);}delete n.llEvLisnrs;}},rn=function(n,t,e){!function(n){delete n.llTempImage;}(n),R(e,-1),function(n){n&&(n.toLoadCount-=1);}(e),M(n,t.class_loading),t.unobserve_completed&&T(n,e);},cn=function(n,t,e){var i=z(n)||n;on(i)||function(n,t,e){on(n)||(n.llEvLisnrs={});var i="VIDEO"===n.tagName?"loadeddata":"load";tn(n,i,t),tn(n,"error",e);}(i,(function(o){!function(n,t,e,i){var o=O(t);rn(t,e,i),N(t,e.class_loaded),w(t,b),C(e.callback_loaded,t,i),o||nn(e,i);}(0,n,t,e),an(i);}),(function(o){!function(n,t,e,i){var o=O(t);rn(t,e,i),N(t,e.class_error),w(t,p),C(e.callback_error,t,i),e.restore_on_error&&q(t,B),o||nn(e,i);}(0,n,t,e),an(i);}));},ln=function(n,t,e){!function(n){return Z.indexOf(n.tagName)>-1}(n)?function(n,t,e){!function(n){n.llTempImage=document.createElement("IMG");}(n),cn(n,t,e),function(n){P(n)||(n[_]={backgroundImage:n.style.backgroundImage});}(n),function(n,t,e){var i=y(n,t.data_bg),o=y(n,t.data_bg_hidpi),r=a&&o?o:i;r&&(n.style.backgroundImage='url("'.concat(r,'")'),z(n).setAttribute(u,r),Q(n,t,e));}(n,t,e),function(n,t,e){var i=y(n,t.data_bg_multi),o=y(n,t.data_bg_multi_hidpi),r=a&&o?o:i;r&&(n.style.backgroundImage=r,K(n,t,e));}(n,t,e),function(n,t,e){var i=y(n,t.data_bg_set);if(i){var o=i.split("|"),a=o.map((function(n){return "image-set(".concat(n,")")}));n.style.backgroundImage=a.join(),""===n.style.backgroundImage&&(a=o.map((function(n){return "-webkit-image-set(".concat(n,")")})),n.style.backgroundImage=a.join()),K(n,t,e);}}(n,t,e);}(n,t,e):function(n,t,e){cn(n,t,e),function(n,t,e){var i=Y[n.tagName];i&&(i(n,t),Q(n,t,e));}(n,t,e);}(n,t,e);},un=function(n){n.removeAttribute(u),n.removeAttribute(s),n.removeAttribute(d);},sn=function(n){D(n,(function(n){q(n,B);})),q(n,B);},dn={IMG:sn,IFRAME:function(n){q(n,V);},VIDEO:function(n){H(n,(function(n){q(n,V);})),q(n,F),n.load();},OBJECT:function(n){q(n,J);}},fn=function(n,t){(function(n){var t=dn[n.tagName];t?t(n):function(n){if(P(n)){var t=S(n);n.style.backgroundImage=t.backgroundImage;}}(n);})(n),function(n,t){L(n)||O(n)||(M(n,t.class_entered),M(n,t.class_exited),M(n,t.class_applied),M(n,t.class_loading),M(n,t.class_loaded),M(n,t.class_error));}(n,t),A(n),U(n);},_n=["IMG","IFRAME","VIDEO"],gn=function(n){return n.use_native&&"loading"in HTMLImageElement.prototype},vn=function(n,t,e){n.forEach((function(n){return function(n){return n.isIntersecting||n.intersectionRatio>0}(n)?function(n,t,e,i){var o=function(n){return x.indexOf(k(n))>=0}(n);w(n,"entered"),N(n,e.class_entered),M(n,e.class_exited),function(n,t,e){t.unobserve_entered&&T(n,e);}(n,e,i),C(e.callback_enter,n,t,i),o||ln(n,e,i);}(n.target,n,t,e):function(n,t,e,i){L(n)||(N(n,e.class_exited),function(n,t,e,i){e.cancel_on_exit&&function(n){return k(n)===v}(n)&&"IMG"===n.tagName&&(an(n),function(n){D(n,(function(n){un(n);})),un(n);}(n),sn(n),M(n,e.class_loading),R(i,-1),A(n),C(e.callback_cancel,n,t,i));}(n,t,e,i),C(e.callback_exit,n,t,i));}(n.target,n,t,e)}));},bn=function(n){return Array.prototype.slice.call(n)},mn=function(n){return n.container.querySelectorAll(n.elements_selector)},pn=function(n){return function(n){return k(n)===p}(n)},hn=function(n,t){return function(n){return bn(n).filter(L)}(n||mn(t))},En=function(n,e){var o=c(n);this._settings=o,this.loadingCount=0,function(n,t){i&&!gn(n)&&(t._observer=new IntersectionObserver((function(e){vn(e,n,t);}),function(n){return {root:n.container===document?null:n.container,rootMargin:n.thresholds||n.threshold+"px"}}(n)));}(o,this),function(n,e){t&&(e._onlineHandler=function(){!function(n,t){var e;(e=mn(n),bn(e).filter(pn)).forEach((function(t){M(t,n.class_error),A(t);})),t.update();}(n,e);},window.addEventListener("online",e._onlineHandler));}(o,this),this.update(e);};return En.prototype={update:function(n){var t,o,a=this._settings,r=hn(n,a);G(this,r.length),!e&&i?gn(a)?function(n,t,e){n.forEach((function(n){-1!==_n.indexOf(n.tagName)&&function(n,t,e){n.setAttribute("loading","lazy"),cn(n,t,e),function(n,t){var e=Y[n.tagName];e&&e(n,t);}(n,t),w(n,h);}(n,t,e);})),G(e,0);}(r,a,this):(o=r,function(n){n.disconnect();}(t=this._observer),function(n,t){t.forEach((function(t){n.observe(t);}));}(t,o)):this.loadAll(r);},destroy:function(){this._observer&&this._observer.disconnect(),t&&window.removeEventListener("online",this._onlineHandler),mn(this._settings).forEach((function(n){U(n);})),delete this._observer,delete this._settings,delete this._onlineHandler,delete this.loadingCount,delete this.toLoadCount;},loadAll:function(n){var t=this,e=this._settings;hn(n,e).forEach((function(n){T(n,t),ln(n,e,t);}));},restoreAll:function(){var n=this._settings;mn(n).forEach((function(t){fn(t,n);}));}},En.load=function(n,t){var e=c(t);ln(n,e);},En.resetStatus=function(n){A(n);},t&&function(n,t){if(t)if(t.length)for(var e,i=0;e=t[i];i+=1)l(n,e);else l(n,t);}(En,window.lazyLoadOptions),En}));