choco-one-click-payment 1.1.61 → 1.1.62

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.esm.js CHANGED
@@ -963,10 +963,10 @@ function Dr() {
963
963
  token: me
964
964
  }
965
965
  }, Ne = a._getSub(s);
966
- Ne !== null && a._call(gt).then(function(ne) {
967
- a._subRefreshResponse(s, a._decoder.decodeCommandResult(a._methodType.SUB_REFRESH, ne.result)), ne.next && ne.next();
968
- }, function(ne) {
969
- a._subRefreshError(s, ne.error), ne.next && ne.next();
966
+ Ne !== null && a._call(gt).then(function(re) {
967
+ a._subRefreshResponse(s, a._decoder.decodeCommandResult(a._methodType.SUB_REFRESH, re.result)), re.next && re.next();
968
+ }, function(re) {
969
+ a._subRefreshError(s, re.error), re.next && re.next();
970
970
  });
971
971
  }
972
972
  }
@@ -1482,8 +1482,8 @@ function Dr() {
1482
1482
  }
1483
1483
  var Ne = {};
1484
1484
  if (x.data.channels)
1485
- for (var ne in x.data.channels) {
1486
- var yt = x.data.channels[ne];
1485
+ for (var re in x.data.channels) {
1486
+ var yt = x.data.channels[re];
1487
1487
  yt.channel && (Ne[yt.channel] = yt.token);
1488
1488
  }
1489
1489
  var Gt = !1;
@@ -3107,14 +3107,14 @@ function po(e) {
3107
3107
  } catch {
3108
3108
  }
3109
3109
  }
3110
- var re;
3110
+ var oe;
3111
3111
  (function(e) {
3112
3112
  e[e.PENDING = 0] = "PENDING";
3113
3113
  const n = 1;
3114
3114
  e[e.RESOLVED = n] = "RESOLVED";
3115
3115
  const r = 2;
3116
3116
  e[e.REJECTED = r] = "REJECTED";
3117
- })(re || (re = {}));
3117
+ })(oe || (oe = {}));
3118
3118
  function pe(e) {
3119
3119
  return new W((t) => {
3120
3120
  t(e);
@@ -3127,7 +3127,7 @@ function $e(e) {
3127
3127
  }
3128
3128
  class W {
3129
3129
  constructor(t) {
3130
- W.prototype.__init.call(this), W.prototype.__init2.call(this), W.prototype.__init3.call(this), W.prototype.__init4.call(this), this._state = re.PENDING, this._handlers = [];
3130
+ W.prototype.__init.call(this), W.prototype.__init2.call(this), W.prototype.__init3.call(this), W.prototype.__init4.call(this), this._state = oe.PENDING, this._handlers = [];
3131
3131
  try {
3132
3132
  t(this._resolve, this._reject);
3133
3133
  } catch (n) {
@@ -3189,19 +3189,19 @@ class W {
3189
3189
  /** JSDoc */
3190
3190
  __init() {
3191
3191
  this._resolve = (t) => {
3192
- this._setResult(re.RESOLVED, t);
3192
+ this._setResult(oe.RESOLVED, t);
3193
3193
  };
3194
3194
  }
3195
3195
  /** JSDoc */
3196
3196
  __init2() {
3197
3197
  this._reject = (t) => {
3198
- this._setResult(re.REJECTED, t);
3198
+ this._setResult(oe.REJECTED, t);
3199
3199
  };
3200
3200
  }
3201
3201
  /** JSDoc */
3202
3202
  __init3() {
3203
3203
  this._setResult = (t, n) => {
3204
- if (this._state === re.PENDING) {
3204
+ if (this._state === oe.PENDING) {
3205
3205
  if (lt(n)) {
3206
3206
  n.then(this._resolve, this._reject);
3207
3207
  return;
@@ -3213,11 +3213,11 @@ class W {
3213
3213
  /** JSDoc */
3214
3214
  __init4() {
3215
3215
  this._executeHandlers = () => {
3216
- if (this._state === re.PENDING)
3216
+ if (this._state === oe.PENDING)
3217
3217
  return;
3218
3218
  const t = this._handlers.slice();
3219
3219
  this._handlers = [], t.forEach((n) => {
3220
- n[0] || (this._state === re.RESOLVED && n[1](this._value), this._state === re.REJECTED && n[2](this._value), n[0] = !0);
3220
+ n[0] || (this._state === oe.RESOLVED && n[1](this._value), this._state === oe.REJECTED && n[2](this._value), n[0] = !0);
3221
3221
  });
3222
3222
  };
3223
3223
  }
@@ -3942,7 +3942,7 @@ function ns() {
3942
3942
  }
3943
3943
  return [n, r];
3944
3944
  }
3945
- function oe(e, t = 100, n = 1 / 0) {
3945
+ function se(e, t = 100, n = 1 / 0) {
3946
3946
  try {
3947
3947
  return wt("", e, t, n);
3948
3948
  } catch (r) {
@@ -3950,7 +3950,7 @@ function oe(e, t = 100, n = 1 / 0) {
3950
3950
  }
3951
3951
  }
3952
3952
  function ar(e, t = 3, n = 100 * 1024) {
3953
- const r = oe(e, t);
3953
+ const r = se(e, t);
3954
3954
  return is(r) > n ? ar(e, t - 1, n) : r;
3955
3955
  }
3956
3956
  function wt(e, t, n = 1 / 0, r = 1 / 0, o = ns()) {
@@ -4066,7 +4066,7 @@ ${JSON.stringify(c)}
4066
4066
  try {
4067
4067
  l = JSON.stringify(u);
4068
4068
  } catch {
4069
- l = JSON.stringify(oe(u));
4069
+ l = JSON.stringify(se(u));
4070
4070
  }
4071
4071
  o(l);
4072
4072
  }
@@ -4323,26 +4323,26 @@ function ks(e, t, n) {
4323
4323
  breadcrumbs: e.breadcrumbs.map((o) => ({
4324
4324
  ...o,
4325
4325
  ...o.data && {
4326
- data: oe(o.data, t, n)
4326
+ data: se(o.data, t, n)
4327
4327
  }
4328
4328
  }))
4329
4329
  },
4330
4330
  ...e.user && {
4331
- user: oe(e.user, t, n)
4331
+ user: se(e.user, t, n)
4332
4332
  },
4333
4333
  ...e.contexts && {
4334
- contexts: oe(e.contexts, t, n)
4334
+ contexts: se(e.contexts, t, n)
4335
4335
  },
4336
4336
  ...e.extra && {
4337
- extra: oe(e.extra, t, n)
4337
+ extra: se(e.extra, t, n)
4338
4338
  }
4339
4339
  };
4340
- return e.contexts && e.contexts.trace && r.contexts && (r.contexts.trace = e.contexts.trace, e.contexts.trace.data && (r.contexts.trace.data = oe(e.contexts.trace.data, t, n))), e.spans && (r.spans = e.spans.map((o) => ({
4340
+ return e.contexts && e.contexts.trace && r.contexts && (r.contexts.trace = e.contexts.trace, e.contexts.trace.data && (r.contexts.trace.data = se(e.contexts.trace.data, t, n))), e.spans && (r.spans = e.spans.map((o) => ({
4341
4341
  ...o,
4342
4342
  ...o.data && {
4343
- data: oe(o.data, t, n)
4343
+ data: se(o.data, t, n)
4344
4344
  }
4345
- }))), e.contexts && e.contexts.flags && r.contexts && (r.contexts.flags = oe(e.contexts.flags, 3, n)), r;
4345
+ }))), e.contexts && e.contexts.flags && r.contexts && (r.contexts.flags = se(e.contexts.flags, 3, n)), r;
4346
4346
  }
4347
4347
  function Ps(e, t) {
4348
4348
  if (!t)
@@ -5313,12 +5313,12 @@ function wi(e) {
5313
5313
  transport: pi,
5314
5314
  stackParser: ki,
5315
5315
  integrations: [],
5316
- release: "1.1.61",
5316
+ release: "1.1.62",
5317
5317
  environment: e.environment || "production"
5318
5318
  }), n = new ue();
5319
5319
  n.setClient(t), n.setTags(e), t.init(), Nt = n;
5320
5320
  }
5321
- function se(e, t) {
5321
+ function ne(e, t) {
5322
5322
  Nt && Nt.captureException(
5323
5323
  e,
5324
5324
  t ? { captureContext: { extra: t } } : void 0
@@ -6267,7 +6267,7 @@ async function ua(e) {
6267
6267
  const l = (u == null ? void 0 : u.id) ?? ((n = u == null ? void 0 : u.data) == null ? void 0 : n.id);
6268
6268
  return l && ye(e, String(l)), u;
6269
6269
  } catch (u) {
6270
- throw K(e), se(u, { paymentMethod: "balance" }), e.config.onError({
6270
+ throw K(e), ne(u, { paymentMethod: "balance" }), e.config.onError({
6271
6271
  attributes: { message: e._resolveErrorMessage(u) }
6272
6272
  }), u;
6273
6273
  }
@@ -6307,7 +6307,7 @@ async function ua(e) {
6307
6307
  }
6308
6308
  return u;
6309
6309
  } catch (u) {
6310
- throw K(e), se(u, { paymentMethod: ((c = e.selectedPaymentMethod) == null ? void 0 : c.type) || "card" }), e.config.onError({ message: e._resolveErrorMessage(u) }), u;
6310
+ throw K(e), ne(u, { paymentMethod: ((c = e.selectedPaymentMethod) == null ? void 0 : c.type) || "card" }), e.config.onError({ message: e._resolveErrorMessage(u) }), u;
6311
6311
  }
6312
6312
  }
6313
6313
  async function Fn(e) {
@@ -6333,7 +6333,7 @@ async function la(e, t) {
6333
6333
  t
6334
6334
  );
6335
6335
  } catch (n) {
6336
- e.waitingForNewCardAction = !1, e._clearNewCardActionTimeout(), K(e), se(n, { paymentMethod: "new_card" }), e.config.onError({
6336
+ e.waitingForNewCardAction = !1, e._clearNewCardActionTimeout(), K(e), ne(n, { paymentMethod: "new_card" }), e.config.onError({
6337
6337
  attributes: { message: e._resolveErrorMessage(n) }
6338
6338
  }), console.error("New card payment error:", n);
6339
6339
  }
@@ -6381,7 +6381,7 @@ async function Aa(e, t) {
6381
6381
  const f = ((u = (c = l == null ? void 0 : l.data) == null ? void 0 : c.attributes) == null ? void 0 : u.session) || l, y = JSON.parse(atob(f));
6382
6382
  o.completeMerchantValidation(y), be = !0;
6383
6383
  } catch (l) {
6384
- console.error("Apple Pay session error:", l), se(l, { paymentMethod: "apple_pay", phase: "merchant_validation" }), K(e), Je = !0, o.abort(), e.config.onError({ attributes: { message: e.t("errorApplePayInit") } });
6384
+ console.error("Apple Pay session error:", l), ne(l, { paymentMethod: "apple_pay", phase: "merchant_validation" }), K(e), Je = !0, o.abort(), e.config.onError({ attributes: { message: e.t("errorApplePayInit") } });
6385
6385
  }
6386
6386
  }, o.onpaymentauthorized = async (i) => {
6387
6387
  var c;
@@ -6401,7 +6401,7 @@ async function Aa(e, t) {
6401
6401
  const l = (u == null ? void 0 : u.id) ?? ((c = u == null ? void 0 : u.data) == null ? void 0 : c.id);
6402
6402
  l && !e._orderStatusResolved && ye(e, String(l));
6403
6403
  } catch (u) {
6404
- console.error("Apple Pay payment error:", u), se(u, { paymentMethod: "apple_pay", phase: "payment_authorized" }), o.completePayment(n.STATUS_FAILURE), ke = null, be = !1, K(e), e.config.onError({
6404
+ console.error("Apple Pay payment error:", u), ne(u, { paymentMethod: "apple_pay", phase: "payment_authorized" }), o.completePayment(n.STATUS_FAILURE), ke = null, be = !1, K(e), e.config.onError({
6405
6405
  attributes: {
6406
6406
  message: e._resolveErrorMessage(u, "errorApplePayPayment")
6407
6407
  }
@@ -6508,7 +6508,7 @@ async function da(e, t) {
6508
6508
  ), I = (M == null ? void 0 : M.id) ?? ((q = M == null ? void 0 : M.data) == null ? void 0 : q.id);
6509
6509
  I && ye(e, String(I));
6510
6510
  } catch (D) {
6511
- K(e), D.statusCode === "CANCELED" ? e.config.onCancel() : (se(D, { paymentMethod: "google_pay" }), e.config.onError({
6511
+ K(e), D.statusCode === "CANCELED" ? e.config.onCancel() : (ne(D, { paymentMethod: "google_pay" }), e.config.onError({
6512
6512
  attributes: {
6513
6513
  message: e._resolveErrorMessage(D, "errorGooglePayPayment")
6514
6514
  }
@@ -6536,7 +6536,7 @@ async function fa(e, t, n) {
6536
6536
  ), u = (c == null ? void 0 : c.id) ?? ((r = c == null ? void 0 : c.data) == null ? void 0 : r.id);
6537
6537
  u && ye(e, String(u));
6538
6538
  } catch (o) {
6539
- K(e), o.statusCode === "CANCELED" ? e.config.onCancel() : (se(o, { paymentMethod: "google_pay_native" }), e.config.onError({
6539
+ K(e), o.statusCode === "CANCELED" ? e.config.onCancel() : (ne(o, { paymentMethod: "google_pay_native" }), e.config.onError({
6540
6540
  attributes: {
6541
6541
  message: e._resolveErrorMessage(o, "errorGooglePayPayment")
6542
6542
  }
@@ -6845,6 +6845,30 @@ class Ee {
6845
6845
  throw t;
6846
6846
  }
6847
6847
  }
6848
+ /**
6849
+ * Загружает токен + контекст оплаты с бесшовным авто-ретраем для флейки/оборванной
6850
+ * сети. Всё это время пользователь видит только скелетон загрузки и о сбоях не знает —
6851
+ * при восстановлении связи виджет догрузится сам, без ошибок и кнопок «Повторить».
6852
+ * Возвращает true при успехе. Только если все попытки исчерпаны — сообщает хосту
6853
+ * через onError (последний fallback) и возвращает false.
6854
+ */
6855
+ async _acquireCheckoutContextWithBackoff() {
6856
+ const t = [500, 1500, 3e3, 5e3, 8e3];
6857
+ for (let n = 0; ; n++) {
6858
+ if (this._destroyed) return !1;
6859
+ try {
6860
+ return this.accessToken || await this._obtainTokenByRefreshOrTrackId(), this._destroyed ? !1 : (await this._fetchCheckoutContextWithRetry(), !0);
6861
+ } catch (r) {
6862
+ if (this._destroyed) return !1;
6863
+ if (n >= t.length)
6864
+ return this.config.onError({ attributes: { message: r.message } }), ne(r, { phase: "init_context", attempts: n + 1 }), !1;
6865
+ await this._delay(t[n]);
6866
+ }
6867
+ }
6868
+ }
6869
+ _delay(t) {
6870
+ return new Promise((n) => setTimeout(n, t));
6871
+ }
6848
6872
  async _fetchCoupons() {
6849
6873
  try {
6850
6874
  const t = await Kr(this.apiUrl, this._getApiConfig()), r = (Array.isArray(t) ? t : Array.isArray(t == null ? void 0 : t.data) ? t.data : []).filter((o) => Number(o.reward_amount) > 0).sort((o, i) => o.sort_weight - i.sort_weight);
@@ -6874,25 +6898,17 @@ class Ee {
6874
6898
  return this.config.onError({ attributes: { message: this.t("errorMissingTrackClient") } }), !1;
6875
6899
  if (this.accessToken = this._getAuthStorageValue("webPayToken"), !this.config.trackId && !this.accessToken)
6876
6900
  return this.paymentMethodDisabled = !0, this._render(), !0;
6877
- if (!this.accessToken && (await this._obtainTokenByRefreshOrTrackId(), this._destroyed))
6878
- return !1;
6879
- try {
6880
- await this._fetchCheckoutContextWithRetry();
6881
- } catch (o) {
6882
- const i = o;
6883
- return this.config.onError({ attributes: { message: i.message } }), !1;
6884
- }
6885
- if (this._destroyed || (await this._fetchCoupons(), this._emitCouponSuppressingCashback(), this._destroyed)) return !1;
6886
- const r = on(
6901
+ if (!await this._acquireCheckoutContextWithBackoff() || this._destroyed || (await this._fetchCoupons(), this._emitCouponSuppressingCashback(), this._destroyed)) return !1;
6902
+ const o = on(
6887
6903
  (n = (t = this.checkoutContext) == null ? void 0 : t.data) == null ? void 0 : n.socket_connections,
6888
- (o) => Un(this, o)
6904
+ (i) => Un(this, i)
6889
6905
  );
6890
- return r && (this.centrifuge = r.centrifuge), Qe(this), this.selectedPaymentMethod = Bt(
6906
+ return o && (this.centrifuge = o.centrifuge), Qe(this), this.selectedPaymentMethod = Bt(
6891
6907
  this.checkoutContext.data,
6892
6908
  this._getKaspiOptions()
6893
6909
  ), this._emitPaymentMethodSelected(), this._render(), !0;
6894
6910
  } catch (r) {
6895
- return console.error(`${this.t("errorWidgetInit")}:`, r), se(r, { phase: "init" }), this.config.onError({ attributes: { message: r.message } }), !1;
6911
+ return console.error(`${this.t("errorWidgetInit")}:`, r), ne(r, { phase: "init" }), this.config.onError({ attributes: { message: r.message } }), !1;
6896
6912
  }
6897
6913
  }
6898
6914
  close() {
@@ -7028,7 +7044,7 @@ class Ee {
7028
7044
  this._getKaspiOptions()
7029
7045
  ), this._emitPaymentMethodSelected(), this.paymentMethodDisabled = !1, this._render(), !0;
7030
7046
  } catch (o) {
7031
- return console.error(`${this.t("errorWidgetInit")}:`, o), se(o, { phase: "updateTrackId" }), this.config.onError({ attributes: { message: o.message } }), !1;
7047
+ return console.error(`${this.t("errorWidgetInit")}:`, o), ne(o, { phase: "updateTrackId" }), this.config.onError({ attributes: { message: o.message } }), !1;
7032
7048
  }
7033
7049
  }
7034
7050
  async onConfirmPay(t) {
package/dist/index.js CHANGED
@@ -1,11 +1,11 @@
1
1
  (function(){"use strict";try{if(typeof document<"u"){var e=document.createElement("style");e.appendChild(document.createTextNode('.choco-one-click-widget{position:fixed;top:0;left:0;right:0;bottom:0;z-index:999999;font-family:Sirius,sans-serif;--choco-widget-accent-color: #2F2F2F;pointer-events:none}.choco-one-click-widget--embedded{position:static;top:auto;left:auto;right:auto;bottom:auto;z-index:auto;pointer-events:auto;min-height:1px}.choco-one-click-widget--embedded .choco-widget-bottom-bar{position:static;box-shadow:none;border-radius:24px}.choco-one-click-widget--embedded .choco-widget-payment-sheet{position:fixed}.choco-one-click-widget *{box-sizing:border-box;font-family:Sirius,sans-serif}.choco-one-click-widget .choco-widget-bottom-bar{opacity:0;transform:translateY(16px)}.choco-one-click-widget .choco-widget-balance-section,.choco-one-click-widget .choco-widget-payment-info{opacity:0;transform:translateY(8px)}.choco-one-click-widget--visible .choco-widget-bottom-bar,.choco-one-click-widget--visible .choco-widget-balance-section,.choco-one-click-widget--visible .choco-widget-payment-info{opacity:1;transform:translateY(0)}.choco-widget-bottom-bar{position:absolute;bottom:0;left:0;right:0;background:#fff;border-radius:24px 24px 0 0;padding:16px;box-shadow:0 -4px 20px #0000001a;transition:transform .24s cubic-bezier(.4,0,.2,1),opacity .2s ease;pointer-events:auto}.choco-widget-payment-info{display:flex;flex-direction:column;gap:12px;align-items:stretch;transition:transform .22s ease,opacity .2s ease}.choco-widget-payment-info-main{display:flex;gap:12px;align-items:center}.choco-widget-payment-method{gap:12px;background:#f1f2f7;border-radius:16px;padding:5px 8px;cursor:pointer;transition:background .2s ease;border:none;font-family:inherit;text-align:left;width:100%;position:relative;height:46px}.choco-widget-payment-method:disabled{cursor:not-allowed;pointer-events:none;opacity:.5}.choco-widget-payment-method.google_pay,.choco-widget-payment-method.apple_pay{max-width:140px}.choco-widget-method-icon-placeholder{font-size:24px}.choco-widget-method-details{flex:1}.choco-widget-method-label{font-size:14px;color:#000}.choco-widget-method-value{font-size:14px;font-weight:600;color:#000;display:flex;align-items:center;gap:4px}.choco-widget-method-icon-wrapper svg{display:block;width:100%;max-width:29px;max-height:18px;margin-top:2px}.choco-widget-method-icon-wrapper:empty{display:none}.choco-widget-method-icon-wrapper.google_pay svg{height:17px;max-width:35px;border:1px solid #3C4043;padding:3px 4px 2px;border-radius:8px}.choco-widget-method-name{font-size:14px;font-weight:700}.choco-widget-method-name.google_pay,.choco-widget-method-name.apple_pay{display:none}.choco-widget-method-chevron{position:absolute;right:5px;top:0;bottom:0;margin:auto 0;width:24px;height:24px}.choco-widget-freedom-card-btn{width:100%;height:46px;padding:0 13px;background:linear-gradient(to right,#17678d,#00ca82);border:none;border-radius:16px;font-size:16px;font-weight:700;font-family:inherit;color:#fff;cursor:pointer}.choco-widget-freedom-card-btn:disabled{opacity:.5;pointer-events:none}.choco-widget-pay-button{background:var(--choco-widget-accent-color);color:#fff;border:none;border-radius:16px;height:46px;padding:0 16px;font-size:16px;font-weight:600;cursor:pointer;transition:all .2s ease;white-space:nowrap;width:100%;overflow:hidden}.choco-widget-pay-button--loading{cursor:not-allowed;pointer-events:none;position:relative}.choco-widget-pay-button--loading:before{content:"";display:block;width:16px;height:16px;border:2px solid #ffffff;border-top:2px solid transparent;border-radius:50%;animation:choco-spin 1s linear infinite;position:absolute;left:0;right:0;margin:0 auto;z-index:2}.choco-widget-pay-button--loading:after{content:"";display:block;width:100%;height:100%;background:#2f2f2f;position:absolute;left:0;top:0}.choco-widget-pay-button:disabled{opacity:.5;pointer-events:none}.choco-widget-pay-button--hidden{display:none}.choco-widget-google-pay-amount{min-width:124px;height:46px;display:flex;flex-direction:column;justify-content:center;text-align:right;width:100%}.choco-widget-google-pay-amount--hidden{display:none}.choco-widget-google-pay-amount-label{font-size:20px;font-weight:700;line-height:24px;color:#1d1d1d}.choco-widget-google-pay-amount-value{font-size:14px;line-height:18px;color:#1d1d1d;white-space:nowrap;opacity:.5}.choco-widget-google-pay-amount-value--hidden{display:none}.choco-widget-google-pay-amount-value-number{text-decoration:line-through}.choco-widget-google-pay-row--hidden{display:none}.choco-widget-wallet-blocked{pointer-events:none;opacity:.6}.choco-widget-google-pay-button-slot{width:100%}.choco-widget-google-pay-button-slot>button{width:100%!important;height:52px;min-height:52px;border-radius:12px!important;font-size:16px!important}.choco-widget-apple-pay-row--hidden{display:none}.choco-widget-apple-pay-button-slot{width:100%}.choco-widget-apple-pay-button-wrapper{position:relative;width:100%;height:52px}.choco-widget-apple-pay-button{width:100%;height:52px;min-height:52px;border:0;border-radius:12px;cursor:pointer;background:#000;color:#fff;font-size:16px;display:flex;align-items:center;justify-content:center;gap:8px;padding:0 16px}.choco-widget-apple-pay-button--native{position:absolute;top:0;right:0;bottom:0;left:0;width:100%;height:52px;opacity:.01;z-index:2}.choco-widget-apple-pay-button-overlay{position:absolute;top:0;right:0;bottom:0;left:0;display:flex;align-items:center;justify-content:center;gap:8px;background:#000;border-radius:12px;pointer-events:none;z-index:1}.choco-widget-apple-pay-button-text{font-size:16px;line-height:20px;font-weight:600;color:#fff}.choco-widget-apple-pay-button-icon{display:inline-flex;align-items:center;justify-content:center}.choco-widget-payment-sheet{position:absolute;bottom:0;left:0;right:0;top:0;background:#00000080;display:flex;align-items:flex-end;opacity:0;pointer-events:none;transition:opacity .3s ease}.choco-widget-payment-sheet--open{opacity:1;pointer-events:auto}.choco-widget-payment-sheet--open .choco-widget-sheet-content{transform:translateY(0)}.choco-widget-sheet-content{background:#fff;border-radius:24px 24px 0 0;width:100%;max-height:70vh;overflow-y:auto;transform:translateY(100%);transition:transform .3s cubic-bezier(.4,0,.2,1);padding:8px 16px 16px;position:relative;will-change:transform}.choco-widget-sheet-content--dragging{transition:none}.choco-widget-sheet-grabber{flex-shrink:0;display:flex;align-items:center;justify-content:center;cursor:grab;touch-action:none;margin-bottom:8px;-webkit-user-select:none;user-select:none}.choco-widget-sheet-grabber:active{cursor:grabbing}.choco-widget-sheet-grabber:before{content:"";width:72px;height:6px;background:#e5e5e7;border-radius:42px}.choco-widget-sheet-content{-webkit-overflow-scrolling:touch;overscroll-behavior:contain}.choco-widget-sheet-header{display:flex;align-items:center;justify-content:space-between;margin-bottom:8px;position:relative}.choco-widget-sheet-title{font-size:20px;font-weight:700;color:#000;margin:0;flex:1;text-align:center}.choco-widget-payment-sheet--edit .choco-widget-sheet-title{padding-left:30px}.choco-widget-payment-sheet--no-cards .choco-widget-sheet-title{padding-right:30px}.choco-widget-payment-sheet--delete-confirm .choco-widget-sheet-title{padding:0}.choco-widget-sheet-button{background:none;border:none;width:32px;height:32px;border-radius:50%;display:flex;align-items:center;justify-content:center;cursor:pointer;padding:0}.choco-widget-sheet-button svg{color:#000}.choco-widget-sheet-delete-confirm{display:none;padding-top:16px}.choco-widget-payment-sheet--delete-confirm .choco-widget-payment-methods,.choco-widget-payment-sheet--delete-confirm .choco-widget-cashback-section{display:none!important}.choco-widget-payment-sheet--delete-confirm .choco-widget-sheet-delete-confirm{display:block}.choco-widget-sheet-delete-confirm-text{margin:0 0 24px;font-size:16px;line-height:1.4;color:#242424;text-align:center}.choco-widget-sheet-delete-confirm-actions{display:flex;gap:12px}.choco-widget-delete-confirm-btn{flex:1;padding:14px 20px;font-size:16px;font-weight:600;font-family:inherit;border-radius:16px;border:none;cursor:pointer;transition:background .2s ease,opacity .2s ease}.choco-widget-delete-confirm-btn--cancel{background:#f1f2f7;color:#242424}.choco-widget-delete-confirm-btn--delete{background:var(--choco-widget-accent-color);color:#fff}.choco-widget-delete-confirm-btn--loading{cursor:not-allowed;pointer-events:none;position:relative}.choco-widget-sheet-delete-confirm-actions.choco-widget-sheet-delete-confirm-actions--loading .choco-widget-delete-confirm-btn{pointer-events:none;cursor:not-allowed;opacity:.7}.choco-widget-delete-confirm-btn--delete.choco-widget-delete-confirm-btn--loading:before{content:"";display:block;width:16px;height:16px;border:2px solid #ffffff;border-top:2px solid transparent;border-radius:50%;animation:choco-spin 1s linear infinite;position:absolute;left:0;right:0;margin:0 auto;z-index:2}.choco-widget-delete-confirm-btn--delete.choco-widget-delete-confirm-btn--loading:after{content:"";display:block;width:100%;height:100%;background:#cc3434;position:absolute;left:0;top:0;border-radius:16px}.choco-widget-add-card-sheet{align-items:stretch}.choco-widget-add-card-sheet .choco-widget-add-card-sheet-content{max-height:none;height:100%;display:flex;flex-direction:column;transform:none;border-radius:0;padding:0}.choco-widget-add-card-sheet--open .choco-widget-add-card-sheet-content{transform:none}.choco-widget-add-card-sheet .choco-widget-sheet-header{flex-shrink:0;margin-bottom:0;padding:12px 0;border-bottom:1px solid #eee}.choco-widget-add-card-iframe-wrapper{flex:1;min-height:0;background:#fff}.choco-widget-add-card-iframe{width:100%;height:100%;border:none;display:block}.choco-widget-balance-section{margin-bottom:12px;padding:12px 8px;background:#f1f2f7;border-radius:12px;transition:transform .22s ease,opacity .2s ease}.choco-widget-balance-section.disabled{opacity:.5;pointer-events:none}.choco-widget-balance-toggle{display:flex;align-items:center;justify-content:space-between;margin-bottom:8px;padding:4px 0}.choco-widget-balance-toggle:last-child{margin-bottom:0}.choco-widget-balance-toggle--disabled{opacity:.5;pointer-events:none}.choco-widget-balance-info{display:flex;align-items:center;gap:12px}.choco-widget-balance-text{display:flex;flex-direction:column}.choco-widget-balance-label-wrapper{display:flex;align-items:center;gap:8px}.choco-widget-balance-label{font-size:16px;font-weight:500}.choco-widget-balance-sublabel{font-size:12px;color:#767485;margin-top:2px}.choco-widget-balance-icon{width:22px;height:22px}.choco-widget-balance-amount{font-size:16px;font-weight:500;color:#000;white-space:nowrap}.choco-widget-toggle{position:relative;display:inline-block;width:42px;height:26px}.choco-widget-toggle input{opacity:0;width:0;height:0}.choco-widget-toggle-slider{position:absolute;cursor:pointer;top:0;left:0;right:0;bottom:0;background-color:#d4d3df;transition:.3s;border-radius:28px}.choco-widget-toggle-slider:before{position:absolute;content:"";height:22px;width:22px;left:2px;bottom:0;top:0;margin:auto;background-color:#fff;transition:.3s;border-radius:50%}.choco-widget-toggle input:checked+.choco-widget-toggle-slider{background-color:var(--choco-widget-accent-color)}.choco-widget-toggle input:checked+.choco-widget-toggle-slider:before{transform:translate(16px)}.choco-widget-cashback-section{margin-top:20px;padding-top:20px;border-top:1px solid #f0f0f0}.choco-widget-cashback-info{display:flex;align-items:center;gap:8px;padding:12px 16px;background:#fff5ee;border-radius:12px;font-size:14px;color:#ff6b00}.choco-widget-cashback-icon{font-size:20px}.choco-widget-cashback-text strong{font-weight:700}.choco-widget-payment-methods{display:flex;flex-direction:column;gap:8px}.choco-widget-method-item{display:flex;align-items:center;gap:12px;padding:10px 0;cursor:pointer;transition:all .2s ease;border:2px solid transparent;width:100%;border:0;background:none;text-align:left;font-family:inherit;font-size:inherit}.choco-widget-method-item-icon-wrapper{width:37px}.choco-widget-method-item-icon-wrapper svg{display:block;width:100%;max-width:29px;height:29px;margin:0 auto}.choco-widget-method-item-icon-wrapper.google_pay{outline:1px solid #3C4043;padding:3px 5px 2px;border-radius:15px}.choco-widget-method-item-icon-wrapper.google_pay svg{height:15px;max-width:29px}.choco-widget-method-item-label{flex:1;font-size:16px;color:#000}.choco-widget-method-item-check,.choco-widget-method-item-trash-btn{flex-shrink:0;display:flex;align-items:center;justify-content:center;padding:6px;margin:-6px 0 -6px 6px;background:none;border:none;cursor:pointer;border-radius:8px;-webkit-tap-highlight-color:transparent}.choco-widget-method-item-check{height:30px;width:30px}.choco-widget-method-item-trash-btn:hover{background:#cc343414}.choco-widget-method-item-trash{flex-shrink:0;width:20px;height:20px}.choco-widget-bottom-bar-prerender{position:absolute;bottom:0;left:0;right:0;background:#fff;border-radius:24px 24px 0 0;box-shadow:0 -4px 20px #0000001a;transition:transform .3s cubic-bezier(.4,0,.2,1);height:78px}.choco-widget-payment-loading{width:30px;height:30px;animation:choco-spin 1s linear infinite;border:3px solid var(--choco-widget-accent-color);border-top:3px solid transparent;border-radius:50%;position:absolute;top:0;bottom:0;left:0;right:0;margin:auto}@keyframes choco-spin{to{transform:rotate(360deg)}}@keyframes choco-fade-in{0%{opacity:0;transform:translate(-50%,-50%) scale(.9)}to{opacity:1;transform:translate(-50%,-50%) scale(1)}}@media(max-width:768px){.choco-widget-bottom-bar{padding:16px 16px 20px}.choco-widget-sheet-content{max-height:80vh}.choco-widget-sheet-title{font-size:18px}.choco-widget-method-item-label{font-size:17px}}@media(max-width:768px)and (min-height:812px){.choco-widget-bottom-bar,.choco-widget-sheet-content{padding-bottom:calc(20px + env(safe-area-inset-bottom,20px))}}@supports (padding: env(safe-area-inset-bottom)){.choco-widget-bottom-bar{padding-bottom:calc(16px + env(safe-area-inset-bottom))}.choco-widget-sheet-content{padding-bottom:calc(20px + env(safe-area-inset-bottom))}}')),document.head.appendChild(e)}}catch(o){console.error("vite-plugin-css-injected-by-js",o)}})();
2
- (function(Qe,ke){typeof exports=="object"&&typeof module<"u"?module.exports=ke():typeof define=="function"&&define.amd?define(ke):(Qe=typeof globalThis<"u"?globalThis:Qe||self,Qe.ChocoOneClickWidget=ke())})(this,(function(){"use strict";const Qe={ru:{paymentMethod:"Способ оплаты",selectMethod:"Выберите метод",pay:"Оплатить",login:"Войти",paymentSuccess:"Оплата прошла успешно!",paymentError:"Ошибка оплаты",paymentMethods:"Способ оплаты",newCard:"Оплата новой картой",balance:"Списать баланс",bonus:"Списать бонусы",bonusText:"Можно оплатить до {amount}%",cashback:"Кешбэк",willGet:"Получите",total:"Итого",instead:"вместо",coupon:"Списать купон",couponSuppressesCashback:"При применении купона бонусы не начисляются",couponUntil:"до {date}",addCard:"Добавление карты",editCards:"Редактировать карты",cardDeleted:"Карта успешно удалена",confirmDeleteCard:"Вы действительно хотите удалить карту?",cancel:"Отмена",delete:"Удалить",back:"Назад",errorMissingTrackClient:"Укажите trackId и clientId",errorNoServerResponseRetry:"Нет ответа от сервера, попробуйте заново",errorNoServerResponse:"Нет ответа от сервера",errorPaymentMethodNotSelected:"Метод оплаты не выбран",errorApplePayUnsupported:"Apple Pay не поддерживается в этом браузере",errorApplePayInit:"Ошибка инициализации Apple Pay",errorApplePayPayment:"Ошибка оплаты через Apple Pay",errorApplePayInterrupted:"Пожалуйста, подтвердите оплату после полной загрузки окна Apple Pay",errorGooglePayUnsupported:"Google Pay не поддерживается в этом браузере",errorGooglePaySettingsUnavailable:"Настройки Google Pay недоступны",errorGooglePayPayment:"Ошибка оплаты через Google Pay",errorActionUrlMissing:"action_url отсутствует в событии order.action_required",errorWidgetInit:"Ошибка инициализации виджета",errorPaymentProcess:"Ошибка оплаты"},en:{paymentMethod:"Payment method",selectMethod:"Select method",pay:"Pay",login:"Sign in",paymentSuccess:"Payment successful!",paymentError:"Payment error",paymentMethods:"Payment method",newCard:"Pay with new card",balance:"Use balance",bonus:"Use bonuses",bonusText:"You can pay up to {amount}%",cashback:"Cashback",willGet:"You will get",total:"Total",instead:"instead",coupon:"Apply coupon",couponSuppressesCashback:"Bonuses are not credited when the coupon is applied",couponUntil:"until {date}",addCard:"Add card",editCards:"Edit cards",cardDeleted:"Card successfully deleted",confirmDeleteCard:"Are you sure you want to delete this card?",cancel:"Cancel",delete:"Delete",back:"Back",errorMissingTrackClient:"Provide trackId and clientId",errorNoServerResponseRetry:"No response from server, please try again",errorNoServerResponse:"No response from server",errorPaymentMethodNotSelected:"Payment method is not selected",errorApplePayUnsupported:"Apple Pay is not supported in this browser",errorApplePayInit:"Apple Pay initialization error",errorApplePayPayment:"Apple Pay payment error",errorApplePayInterrupted:"Please confirm payment after the Apple Pay sheet fully loads",errorGooglePayUnsupported:"Google Pay is not supported in this browser",errorGooglePaySettingsUnavailable:"Google Pay settings are unavailable",errorGooglePayPayment:"Google Pay payment error",errorActionUrlMissing:"action_url is missing in order.action_required event",errorWidgetInit:"Widget initialization error",errorPaymentProcess:"Payment error"},kk:{paymentMethod:"Төлем әдісі",selectMethod:"Әдісті таңдаңыз",pay:"Төлеу",login:"Кіру",paymentSuccess:"Төлем сәтті өтті!",paymentError:"Төлем қатесі",paymentMethods:"Төлем әдісі",newCard:"Жаңа картамен төлеу",balance:"Балансты пайдалану",bonus:"Бонусдарды пайдалану",bonusText:"{amount}%-ге дейін төлеуге болады",cashback:"Кэшбэк",willGet:"Аласыз",total:"Барлығы",instead:"орнына",coupon:"Купонды пайдалану",couponSuppressesCashback:"Купон қолданылғанда бонустар есептелмейді",couponUntil:"{date} дейін",addCard:"Картаны қосу",editCards:"Карталарды өңдеу",cardDeleted:"Карта жойылды",confirmDeleteCard:"Картаны жойғыңыз келетініне сенімдісіз бе?",cancel:"Болдырмау",delete:"Жою",back:"Артқа",errorMissingTrackClient:"trackId пен clientId көрсетіңіз",errorNoServerResponseRetry:"Серверден жауап жоқ, қайтадан көріңіз",errorNoServerResponse:"Серверден жауап жоқ",errorPaymentMethodNotSelected:"Төлем әдісі таңдалмаған",errorApplePayUnsupported:"Бұл браузерде Apple Pay қолдау көрсетілмейді",errorApplePayInit:"Apple Pay инициализация қатесі",errorApplePayPayment:"Apple Pay арқылы төлем қатесі",errorApplePayInterrupted:"Өтінеміз, төлемді Apple Pay терезесі толық жүктелгеннен кейін растаңыз",errorGooglePayUnsupported:"Бұл браузерде Google Pay қолдау көрсетілмейді",errorGooglePaySettingsUnavailable:"Google Pay баптаулары қолжетімсіз",errorGooglePayPayment:"Google Pay арқылы төлем қатесі",errorActionUrlMissing:"order.action_required оқиғасында action_url жоқ",errorWidgetInit:"Виджетті инициализациялау қатесі",errorPaymentProcess:"Төлем қатесі"},ka:{paymentMethod:"გადახდის მეთოდი",selectMethod:"აირჩიეთ მეთოდი",pay:"გადახდა",login:"შესვლა",paymentSuccess:"გადახდა წარმატებით შესრულდა!",paymentError:"გადახდის შეცდომა",paymentMethods:"გადახდის მეთოდი",newCard:"ახალი ბარათით გადახდა",balance:"ბალანსის გამოყენება",bonus:"ბონუსების გამოყენება",bonusText:"{amount}%-ზე გადახდა შესაძლებელია",cashback:"ქეშბექი",willGet:"მიიღებთ",total:"ჯამი",instead:"ნაცვლად",coupon:"კუპონის გამოყენება",couponSuppressesCashback:"კუპონის გამოყენებისას ბონუსები არ დაირიცხება",couponUntil:"{date}-მდე",addCard:"ბარათის დამატება",editCards:"ბარათების რედაქტირება",cardDeleted:"ბარათი წაშლილია",confirmDeleteCard:"დარწმუნებული ხართ, რომ გსურთ ამ ბარათის წაშლა?",cancel:"გაუქმება",delete:"წაშლა",back:"უკან",errorMissingTrackClient:"მიუთითეთ trackId და clientId",errorNoServerResponseRetry:"სერვერის პასუხი არ არის, სცადეთ თავიდან",errorNoServerResponse:"სერვერის პასუხი არ არის",errorPaymentMethodNotSelected:"გადახდის მეთოდი არ არის არჩეული",errorApplePayUnsupported:"ამ ბრაუზერში Apple Pay არ არის მხარდაჭერილი",errorApplePayInit:"Apple Pay-ის ინიციალიზაციის შეცდომა",errorApplePayPayment:"Apple Pay-ით გადახდის შეცდომა",errorApplePayInterrupted:"გთხოვთ, დაადასტუროთ გადახდა Apple Pay-ის ფანჯრის სრულად ჩატვირთვის შემდეგ",errorGooglePayUnsupported:"ამ ბრაუზერში Google Pay არ არის მხარდაჭერილი",errorGooglePaySettingsUnavailable:"Google Pay-ის პარამეტრები მიუწვდომელია",errorGooglePayPayment:"Google Pay-ით გადახდის შეცდომა",errorActionUrlMissing:"order.action_required მოვლენაში action_url არ არის",errorWidgetInit:"ვიჯეტის ინიციალიზაციის შეცდომა",errorPaymentProcess:"გადახდის შეცდომა"}},ke={KZT:"₸",GEL:"₾"};function kr(e){return e==="production"?"https://api-proxy.choco.kz":"https://api-proxy.chocodev.kz"}let Me;const Pr=new Uint8Array(16);function wr(){if(!Me&&(Me=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!Me))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Me(Pr)}const F=[];for(let e=0;e<256;++e)F.push((e+256).toString(16).slice(1));function Tr(e,t=0){return F[e[t+0]]+F[e[t+1]]+F[e[t+2]]+F[e[t+3]]+"-"+F[e[t+4]]+F[e[t+5]]+"-"+F[e[t+6]]+F[e[t+7]]+"-"+F[e[t+8]]+F[e[t+9]]+"-"+F[e[t+10]]+F[e[t+11]]+F[e[t+12]]+F[e[t+13]]+F[e[t+14]]+F[e[t+15]]}const Yt={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function xe(e,t,n){if(Yt.randomUUID&&!e)return Yt.randomUUID();e=e||{};const r=e.random||(e.rng||wr)();return r[6]=r[6]&15|64,r[8]=r[8]&63|128,Tr(r)}const Vt="choco_device_id";function Z(e,t="ru",n="KZT"){const r=Number(e),o=t==="ru"?"ru-RU":"en-US";return`${r.toLocaleString(o)} ${ke[n]}`}function Zt(){let e=localStorage.getItem(Vt);return e||(e=xe(),localStorage.setItem(Vt,e)),e}function Ue(){if(typeof window>"u")return!1;const e=window.safari!==void 0,t=window.navigator.userAgent||"",n=!!t.match(/iPad/i)||!!t.match(/iPhone/i),r=!!t.match(/WebKit/i),o=n&&r&&!t.match(/CriOS/i);return e||o}function $t(){if(typeof navigator>"u")return 0;const e=navigator.userAgent||"",t=e.indexOf("OS");return(e.indexOf("iPhone")>-1||e.indexOf("iPad")>-1)&&t>-1?Number(e.substring(t+3,t+6).replace("_",".")):0}function mt(){var i;if(typeof navigator>"u")return"unknown";const e=(navigator.userAgent||navigator.vendor||"").toLowerCase(),t=(navigator.platform||"").toLowerCase(),n=(((i=navigator.userAgentData)==null?void 0:i.platform)||"").toLowerCase(),r=`${e} ${t} ${n}`;return/iphone|ipad|ipod/.test(r)||r.includes("macintosh")&&typeof document<"u"&&"ontouchend"in document?"ios":r.includes("android")?"android":r.includes("windows")?"windows":r.includes("mac")?"macos":"other"}function Fe(){if(typeof navigator>"u")return!1;const e=navigator.userAgentData;return e!=null&&e.platform&&["iOS","iPadOS"].includes(e.platform)||mt()==="ios"?!0:(navigator.userAgent||"").includes("Macintosh")&&typeof document<"u"&&"ontouchend"in document}function Xe(e){if(typeof sessionStorage>"u")return!1;const t=e==="apple_pay"?"disableApplePay":e==="google_pay"?"disableGooglePay":null;return t?sessionStorage.getItem(t)==="true":!1}function Rr(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var He={exports:{}},Lr=He.exports,en;function Or(){return en||(en=1,(function(e,t){(function(r,o){e.exports=o()})(Lr,function(){return(function(){var n={382:(function(c,u,l){Object.defineProperty(u,"__esModule",{value:!0}),u.Centrifuge=void 0;var f=v(l(187)),y=v(l(471)),m=l(147),C=l(853);function v(g){return g&&g.__esModule?g:{default:g}}function B(g){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?B=function(b){return typeof b}:B=function(b){return b&&typeof Symbol=="function"&&b.constructor===Symbol&&b!==Symbol.prototype?"symbol":typeof b},B(g)}function Q(g,p){if(!(g instanceof p))throw new TypeError("Cannot call a class as a function")}function S(g,p){for(var b=0;b<p.length;b++){var d=p[b];d.enumerable=d.enumerable||!1,d.configurable=!0,"value"in d&&(d.writable=!0),Object.defineProperty(g,d.key,d)}}function P(g,p,b){return p&&S(g.prototype,p),g}function k(g,p){if(typeof p!="function"&&p!==null)throw new TypeError("Super expression must either be null or a function");g.prototype=Object.create(p&&p.prototype,{constructor:{value:g,writable:!0,configurable:!0}}),p&&L(g,p)}function L(g,p){return L=Object.setPrototypeOf||function(d,s){return d.__proto__=s,d},L(g,p)}function R(g){var p=G();return function(){var d=K(g),s;if(p){var a=K(this).constructor;s=Reflect.construct(d,arguments,a)}else s=d.apply(this,arguments);return z(this,s)}}function z(g,p){if(p&&(B(p)==="object"||typeof p=="function"))return p;if(p!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return D(g)}function D(g){if(g===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return g}function G(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}function K(g){return K=Object.setPrototypeOf?Object.getPrototypeOf:function(b){return b.__proto__||Object.getPrototypeOf(b)},K(g)}var J="timeout",M="connection closed",I=(function(g){k(b,g);var p=R(b);function b(d,s){var a;return Q(this,b),a=p.call(this),a._url=d,a._websocket=null,a._sockjs=null,a._isSockjs=!1,a._xmlhttprequest=null,a._binary=!1,a._methodType=null,a._pushType=null,a._encoder=null,a._decoder=null,a._status="disconnected",a._reconnect=!0,a._reconnecting=!1,a._transport=null,a._transportName=null,a._transportClosed=!0,a._messageId=0,a._clientID=null,a._refreshRequired=!1,a._subs={},a._serverSubs={},a._lastSeq={},a._lastGen={},a._lastOffset={},a._lastEpoch={},a._messages=[],a._isBatching=!1,a._isSubscribeBatching=!1,a._privateChannels={},a._numRefreshFailed=0,a._refreshTimeout=null,a._pingTimeout=null,a._pongTimeout=null,a._subRefreshTimeouts={},a._retries=0,a._callbacks={},a._latency=null,a._latencyStart=null,a._connectData=null,a._token=null,a._xhrID=0,a._xhrs={},a._dispatchPromise=Promise.resolve(),a._protocol="",a._config={protocol:"",debug:!1,name:"js",version:"",websocket:null,sockjs:null,xmlhttprequest:null,minRetry:1e3,maxRetry:2e4,timeout:5e3,ping:!0,pingInterval:25e3,pongWaitTimeout:5e3,privateChannelPrefix:"$",onTransportClose:null,sockjsServer:null,sockjsTimeout:null,sockjsTransports:["websocket","xdr-streaming","xhr-streaming","eventsource","iframe-eventsource","iframe-htmlfile","xdr-polling","xhr-polling","iframe-xhr-polling","jsonp-polling"],refreshEndpoint:"/centrifuge/refresh",refreshHeaders:{},refreshParams:{},refreshData:{},refreshAttempts:null,refreshInterval:1e3,onRefreshFailed:null,onRefresh:null,subscribeEndpoint:"/centrifuge/subscribe",subscribeHeaders:{},subscribeParams:{},subRefreshInterval:1e3,onPrivateSubscribe:null,disableWithCredentials:!1},a._configure(s),a}return P(b,[{key:"setToken",value:function(s){this._token=s}},{key:"setConnectData",value:function(s){this._connectData=s}},{key:"setRefreshHeaders",value:function(s){this._config.refreshHeaders=s}},{key:"setRefreshParams",value:function(s){this._config.refreshParams=s}},{key:"setRefreshData",value:function(s){this._config.refreshData=s}},{key:"setSubscribeHeaders",value:function(s){this._config.subscribeHeaders=s}},{key:"setSubscribeParams",value:function(s){this._config.subscribeParams=s}},{key:"_ajax",value:function(s,a,A,h,E){var _=this,T="";this._debug("sending AJAX request to",s,"with data",JSON.stringify(h));var w;this._xmlhttprequest!==null?w=new this._xmlhttprequest:w=l.g.XMLHttpRequest?new l.g.XMLHttpRequest:new l.g.ActiveXObject("Microsoft.XMLHTTP");for(var O in a)a.hasOwnProperty(O)&&(T.length>0&&(T+="&"),T+=encodeURIComponent(O)+"="+encodeURIComponent(a[O]));T.length>0&&(T="?"+T),w.open("POST",s+T,!0),"withCredentials"in w&&(w.withCredentials=!this._config.disableWithCredentials),w.setRequestHeader("X-Requested-With","XMLHttpRequest"),w.setRequestHeader("Content-Type","application/json");for(var X in A)A.hasOwnProperty(X)&&w.setRequestHeader(X,A[X]);return w.onreadystatechange=function(){if(w.readyState===4)if(w.status===200){var H,x=!1;try{H=JSON.parse(w.responseText),x=!0}catch{E({error:"Invalid JSON. Data was: "+w.responseText,status:200,data:null})}x&&E({data:H,status:200})}else _._log("wrong status code in AJAX response",w.status),E({status:w.status,data:null})},setTimeout(function(){return w.send(JSON.stringify(h))},20),w}},{key:"_log",value:function(){(0,C.log)("info",arguments)}},{key:"_debug",value:function(){this._config.debug===!0&&(0,C.log)("debug",arguments)}},{key:"_websocketSupported",value:function(){return this._config.websocket!==null?!0:!(typeof WebSocket!="function"&&(typeof WebSocket>"u"?"undefined":B(WebSocket))!=="object")}},{key:"_setFormat",value:function(s){if(!this._formatOverride(s)){if(s==="protobuf")throw new Error("not implemented by JSON only Centrifuge client – use client with Protobuf");this._binary=!1,this._methodType=m.JsonMethodType,this._pushType=m.JsonPushType,this._encoder=new m.JsonEncoder,this._decoder=new m.JsonDecoder}}},{key:"_formatOverride",value:function(s){return!1}},{key:"_configure",value:function(s){if(!("Promise"in l.g))throw new Error("Promise polyfill required");if((0,C.extend)(this._config,s||{}),this._debug("centrifuge config",this._config),!this._url)throw new Error("url required");var a=(0,C.startsWith)(this._url,"ws")&&this._url.indexOf("format=protobuf")>-1;if(a||this._config.protocol==="protobuf")this._setFormat("protobuf"),this._protocol="protobuf";else{if(this._config.protocol!==""&&this._config.protocol!=="json")throw new Error("unsupported protocol "+this._config.protocol);this._setFormat("json")}if((0,C.startsWith)(this._url,"http"))if(this._debug("client will try to connect to SockJS endpoint"),this._config.sockjs!==null)this._debug("SockJS explicitly provided in options"),this._sockjs=this._config.sockjs;else{if(typeof l.g.SockJS>"u")throw new Error("SockJS not found, use ws:// in url or include SockJS");this._debug("use globally defined SockJS"),this._sockjs=l.g.SockJS}else this._debug("client will connect to websocket endpoint");this._xmlhttprequest=this._config.xmlhttprequest}},{key:"_setStatus",value:function(s){this._status!==s&&(this._debug("Status",this._status,"->",s),this._status=s)}},{key:"_isDisconnected",value:function(){return this._status==="disconnected"}},{key:"_isConnecting",value:function(){return this._status==="connecting"}},{key:"_isConnected",value:function(){return this._status==="connected"}},{key:"_nextMessageId",value:function(){return++this._messageId}},{key:"_resetRetry",value:function(){this._debug("reset retries count to 0"),this._retries=0}},{key:"_getRetryInterval",value:function(){var s=(0,C.backoff)(this._retries,this._config.minRetry,this._config.maxRetry);return this._retries+=1,s}},{key:"_abortInflightXHRs",value:function(){for(var s in this._xhrs){try{this._xhrs[s].abort()}catch(a){this._debug("error aborting xhr",a)}delete this._xhrs[s]}}},{key:"_clearConnectedState",value:function(s){this._clientID=null,this._stopPing();for(var a in this._callbacks)if(this._callbacks.hasOwnProperty(a)){var A=this._callbacks[a];clearTimeout(A.timeout);var h=A.errback;if(!h)continue;h({error:this._createErrorObject("disconnected")})}this._callbacks={};for(var E in this._subs)if(this._subs.hasOwnProperty(E)){var _=this._subs[E];s?(_._isSuccess()&&(_._triggerUnsubscribe(),_._recover=!0),_._shouldResubscribe()&&_._setSubscribing()):_._setUnsubscribed()}this._abortInflightXHRs(),this._refreshTimeout!==null&&(clearTimeout(this._refreshTimeout),this._refreshTimeout=null);for(var T in this._subRefreshTimeouts)this._subRefreshTimeouts.hasOwnProperty(T)&&this._subRefreshTimeouts[T]&&this._clearSubRefreshTimeout(T);this._subRefreshTimeouts={},this._reconnect||(this._subs={})}},{key:"_isTransportOpen",value:function(){return this._isSockjs?this._transport&&this._transport.transport&&this._transport.transport.readyState===this._transport.transport.OPEN:this._transport&&this._transport.readyState===this._transport.OPEN}},{key:"_transportSend",value:function(s){if(!s.length)return!0;if(!this._isTransportOpen()){for(var a in s){var A=a.id;if(A in this._callbacks){var h=this._callbacks[A];clearTimeout(this._callbacks[A].timeout),delete this._callbacks[A];var E=h.errback;E({error:this._createErrorObject(M,0)})}}return!1}return this._transport.send(this._encoder.encodeCommands(s)),!0}},{key:"_getSubProtocol",value:function(){return this._protocol?"centrifuge-"+this._protocol:""}},{key:"_setupTransport",value:function(){var s=this;if(this._isSockjs=!1,this._sockjs!==null){var a={transports:this._config.sockjsTransports};this._config.sockjsServer!==null&&(a.server=this._config.sockjsServer),this._config.sockjsTimeout!==null&&(a.timeout=this._config.sockjsTimeout),this._isSockjs=!0,this._transport=new this._sockjs(this._url,null,a)}else{if(!this._websocketSupported())throw this._debug("No Websocket support and no SockJS configured, can not connect"),new Error("No Websocket support and no SockJS configured, can not connect");this._config.websocket!==null?this._websocket=this._config.websocket:this._websocket=WebSocket;var A=this._getSubProtocol();A!==""?this._transport=new this._websocket(this._url,A):this._transport=new this._websocket(this._url),this._binary===!0&&(this._transport.binaryType="arraybuffer")}this._transport.onopen=function(){s._transportClosed=!1,s._isSockjs?(s._transportName="sockjs-"+s._transport.transport,s._transport.onheartbeat=function(){return s._restartPing()}):s._transportName="websocket";var h={};(s._token||s._connectData||s._config.name||s._config.version)&&(h.params={}),s._token&&(h.params.token=s._token),s._connectData&&(h.params.data=s._connectData),s._config.name&&(h.params.name=s._config.name),s._config.version&&(h.params.version=s._config.version);var E={},_=!1;for(var T in s._serverSubs)if(s._serverSubs.hasOwnProperty(T)&&s._serverSubs[T].recoverable){_=!0;var w={recover:!0};s._serverSubs[T].seq||s._serverSubs[T].gen?(s._serverSubs[T].seq&&(w.seq=s._serverSubs[T].seq),s._serverSubs[T].gen&&(w.gen=s._serverSubs[T].gen)):s._serverSubs[T].offset&&(w.offset=s._serverSubs[T].offset),s._serverSubs[T].epoch&&(w.epoch=s._serverSubs[T].epoch),E[T]=w}_&&(h.params||(h.params={}),h.params.subs=E),s._latencyStart=new Date,s._call(h).then(function(O){s._connectResponse(s._decoder.decodeCommandResult(s._methodType.CONNECT,O.result),_),O.next&&O.next()},function(O){var X=O.error;X.code===109&&(s._refreshRequired=!0),s._disconnect("connect error",!0),O.next&&O.next()})},this._transport.onerror=function(h){s._debug("transport level error",h)},this._transport.onclose=function(h){s._transportClosed=!0;var E=M,_=!0;if(h&&"reason"in h&&h.reason)try{var T=JSON.parse(h.reason);s._debug("reason is an advice object",T),E=T.reason,_=T.reconnect}catch{E=h.reason,s._debug("reason is a plain string",E)}if(s._config.onTransportClose!==null&&s._config.onTransportClose({event:h,reason:E,reconnect:_}),s._disconnect(E,_),s._reconnect===!0){s._reconnecting=!0;var w=s._getRetryInterval();s._debug("reconnect after "+w+" milliseconds"),setTimeout(function(){s._reconnect===!0&&(s._refreshRequired?s._refresh():s._connect())},w)}},this._transport.onmessage=function(h){s._dataReceived(h.data)}}},{key:"rpc",value:function(s){return this._rpc("",s)}},{key:"namedRPC",value:function(s,a){return this._rpc(s,a)}},{key:"_rpc",value:function(s,a){var A={data:a};s!==""&&(A.method=s);var h={method:this._methodType.RPC,params:A};return this._methodCall(h,function(E){return E})}},{key:"send",value:function(s){var a={method:this._methodType.SEND,params:{data:s}};if(!this.isConnected())return Promise.reject(this._createErrorObject(M,0));var A=this._transportSend([a]);return A?Promise.resolve({}):Promise.reject(this._createErrorObject(M,0))}},{key:"_getHistoryParams",value:function(s,a){var A={channel:s};return a!==void 0&&(a.since&&(A.since={offset:a.since.offset},a.since.epoch&&(A.since.epoch=a.since.epoch)),a.limit!==void 0&&(A.limit=a.limit),a.reverse===!0&&(A.reverse=!0)),A}},{key:"_methodCall",value:function(s,a){var A=this;return this.isConnected()?new Promise(function(h,E){A._call(s).then(function(_){h(a(A._decoder.decodeCommandResult(s.method,_.result))),_.next&&_.next()},function(_){E(_.error),_.next&&_.next()})}):Promise.reject(this._createErrorObject(M,0))}},{key:"publish",value:function(s,a){var A={method:this._methodType.PUBLISH,params:{channel:s,data:a}};return this._methodCall(A,function(){return{}})}},{key:"history",value:function(s,a){var A=this._getHistoryParams(s,a),h={method:this._methodType.HISTORY,params:A};return this._methodCall(h,function(E){return{publications:E.publications,epoch:E.epoch||"",offset:E.offset||0}})}},{key:"presence",value:function(s){var a={method:this._methodType.PRESENCE,params:{channel:s}};return this._methodCall(a,function(A){return{presence:A.presence}})}},{key:"presenceStats",value:function(s){var a={method:this._methodType.PRESENCE_STATS,params:{channel:s}};return this._methodCall(a,function(A){return{num_users:A.num_users,num_clients:A.num_clients}})}},{key:"_dataReceived",value:function(s){var a=this,A=this._decoder.decodeReplies(s);this._dispatchPromise=this._dispatchPromise.then(function(){var h;a._dispatchPromise=new Promise(function(E){h=E}),a._dispatchSynchronized(A,h)}),this._restartPing()}},{key:"_dispatchSynchronized",value:function(s,a){var A=this,h=Promise.resolve(),E=function(w){s.hasOwnProperty(w)&&(h=h.then(function(){return A._dispatchReply(s[w])}))};for(var _ in s)E(_);h=h.then(function(){a()})}},{key:"_dispatchReply",value:function(s){var a,A=new Promise(function(E){a=E});if(s==null)return this._debug("dispatch: got undefined or null reply"),a(),A;var h=s.id;return h&&h>0?this._handleReply(s,a):this._handlePush(s.result,a),A}},{key:"_call",value:function(s){var a=this;return new Promise(function(A,h){var E=a._addMessage(s);a._registerCall(E,A,h)})}},{key:"_connect",value:function(){if(this.isConnected()){this._debug("connect called when already connected");return}this._status!=="connecting"&&(this._debug("start connecting"),this._setStatus("connecting"),this._clientID=null,this._reconnect=!0,this._setupTransport())}},{key:"_disconnect",value:function(s,a){var A=a||!1;if(A===!1&&(this._reconnect=!1),this._isDisconnected()){A||this._clearConnectedState(A);return}if(this._clearConnectedState(A),this._debug("disconnected:",s,a),this._setStatus("disconnected"),this._refreshTimeout&&(clearTimeout(this._refreshTimeout),this._refreshTimeout=null),this._reconnecting===!1){for(var h in this._serverSubs)this._serverSubs.hasOwnProperty(h)&&this.emit("unsubscribe",{channel:h});this.emit("disconnect",{reason:s,reconnect:A})}A===!1&&(this._subs={},this._serverSubs={}),this._transportClosed||this._transport.close()}},{key:"_refreshFailed",value:function(){this._numRefreshFailed=0,this._isDisconnected()||this._disconnect("refresh failed",!1),this._config.onRefreshFailed!==null&&this._config.onRefreshFailed()}},{key:"_refresh",value:function(){var s=this;if(this._debug("refresh token"),this._config.refreshAttempts===0){this._debug("refresh attempts set to 0, do not send refresh request at all"),this._refreshFailed();return}this._refreshTimeout!==null&&(clearTimeout(this._refreshTimeout),this._refreshTimeout=null);var a=this._clientID,A=this._newXHRID(),h=function(w){if(A in s._xhrs&&delete s._xhrs[A],s._clientID===a){if(w.error||w.status!==200){if(w.error?s._debug("error refreshing connection token",w.error):s._debug("error refreshing connection token: wrong status code",w.status),s._numRefreshFailed++,s._refreshTimeout!==null&&(clearTimeout(s._refreshTimeout),s._refreshTimeout=null),s._config.refreshAttempts!==null&&s._numRefreshFailed>=s._config.refreshAttempts){s._refreshFailed();return}var O=Math.round(Math.random()*1e3*Math.max(s._numRefreshFailed,20)),X=s._config.refreshInterval+O;s._refreshTimeout=setTimeout(function(){return s._refresh()},X);return}if(s._numRefreshFailed=0,s._token=w.data.token,!s._token){s._refreshFailed();return}if(s._isDisconnected()&&s._reconnect)s._debug("token refreshed, connect from scratch"),s._connect();else{s._debug("send refreshed token");var H={method:s._methodType.REFRESH,params:{token:s._token}};s._call(H).then(function(x){s._refreshResponse(s._decoder.decodeCommandResult(s._methodType.REFRESH,x.result)),x.next&&x.next()},function(x){s._refreshError(x.error),x.next&&x.next()})}}};if(this._config.onRefresh!==null){var E={};this._config.onRefresh(E,h)}else{var _=this._ajax(this._config.refreshEndpoint,this._config.refreshParams,this._config.refreshHeaders,this._config.refreshData,h);this._xhrs[A]=_}}},{key:"_refreshError",value:function(s){var a=this;this._debug("refresh error",s),this._refreshTimeout&&(clearTimeout(this._refreshTimeout),this._refreshTimeout=null);var A=this._config.refreshInterval+Math.round(Math.random()*1e3);this._refreshTimeout=setTimeout(function(){return a._refresh()},A)}},{key:"_refreshResponse",value:function(s){var a=this;this._refreshTimeout&&(clearTimeout(this._refreshTimeout),this._refreshTimeout=null),s.expires&&(this._clientID=s.client,this._refreshTimeout=setTimeout(function(){return a._refresh()},this._getTTLMilliseconds(s.ttl)))}},{key:"_newXHRID",value:function(){return this._xhrID++,this._xhrID}},{key:"_subRefresh",value:function(s){var a=this;if(this._debug("refresh subscription token for channel",s),this._subRefreshTimeouts[s]!==void 0)this._clearSubRefreshTimeout(s);else return;var A=this._clientID,h=this._newXHRID(),E=function(O){if(h in a._xhrs&&delete a._xhrs[h],!(O.error||O.status!==200||a._clientID!==A)){var X={};if(O.data.channels)for(var H in O.data.channels){var x=O.data.channels[H];x.channel&&(X[x.channel]=x.token)}var Se=X[s];if(Se){var zt={method:a._methodType.SUB_REFRESH,params:{channel:s,token:Se}},yt=a._getSub(s);yt!==null&&a._call(zt).then(function(ie){a._subRefreshResponse(s,a._decoder.decodeCommandResult(a._methodType.SUB_REFRESH,ie.result)),ie.next&&ie.next()},function(ie){a._subRefreshError(s,ie.error),ie.next&&ie.next()})}}},_={client:this._clientID,channels:[s]};if(this._config.onPrivateSubscribe!==null)this._config.onPrivateSubscribe({data:_},E);else{var T=this._ajax(this._config.subscribeEndpoint,this._config.subscribeParams,this._config.subscribeHeaders,_,E);this._xhrs[h]=T}}},{key:"_clearSubRefreshTimeout",value:function(s){this._subRefreshTimeouts[s]!==void 0&&(clearTimeout(this._subRefreshTimeouts[s]),delete this._subRefreshTimeouts[s])}},{key:"_subRefreshError",value:function(s,a){var A=this;this._debug("subscription refresh error",s,a),this._clearSubRefreshTimeout(s);var h=this._getSub(s);if(h!==null){var E=Math.round(Math.random()*1e3),_=setTimeout(function(){return A._subRefresh(s)},this._config.subRefreshInterval+E);this._subRefreshTimeouts[s]=_}}},{key:"_subRefreshResponse",value:function(s,a){var A=this;this._debug("subscription refresh success",s),this._clearSubRefreshTimeout(s);var h=this._getSub(s);if(h!==null&&a.expires===!0){var E=setTimeout(function(){return A._subRefresh(s)},this._getTTLMilliseconds(a.ttl));this._subRefreshTimeouts[s]=E}}},{key:"_subscribe",value:function(s,a){var A=this;this._debug("subscribing on",s.channel);var h=s.channel;if(h in this._subs||(this._subs[h]=s),!this.isConnected()){s._setNew();return}s._setSubscribing(a);var E={method:this._methodType.SUBSCRIBE,params:{channel:h}};if(s._subscribeData&&(E.params.data=s._subscribeData),(0,C.startsWith)(h,this._config.privateChannelPrefix))this._isSubscribeBatching?this._privateChannels[h]=!0:(this.startSubscribeBatching(),this._subscribe(s),this.stopSubscribeBatching());else{var _=s._needRecover();if(_===!0){E.params.recover=!0;var T=this._getLastSeq(h),w=this._getLastGen(h);if(T||w)T&&(E.params.seq=T),w&&(E.params.gen=w);else{var O=this._getLastOffset(h);O&&(E.params.offset=O)}var X=this._getLastEpoch(h);X&&(E.params.epoch=X)}this._call(E).then(function(H){A._subscribeResponse(h,_,A._decoder.decodeCommandResult(A._methodType.SUBSCRIBE,H.result)),H.next&&H.next()},function(H){A._subscribeError(h,H.error),H.next&&H.next()})}}},{key:"_unsubscribe",value:function(s){delete this._subs[s.channel],delete this._lastOffset[s.channel],delete this._lastSeq[s.channel],delete this._lastGen[s.channel],this.isConnected()&&this._addMessage({method:this._methodType.UNSUBSCRIBE,params:{channel:s.channel}})}},{key:"_getTTLMilliseconds",value:function(s){return Math.min(s*1e3,2147483647)}},{key:"getSub",value:function(s){return this._getSub(s)}},{key:"_getSub",value:function(s){var a=this._subs[s];return a||null}},{key:"_isServerSub",value:function(s){return this._serverSubs[s]!==void 0}},{key:"_connectResponse",value:function(s,a){var A=this,h=this._reconnecting;if(this._reconnecting=!1,this._resetRetry(),this._refreshRequired=!1,!this.isConnected()){this._latencyStart!==null&&(this._latency=new Date().getTime()-this._latencyStart.getTime(),this._latencyStart=null),this._clientID=s.client,this._setStatus("connected"),this._refreshTimeout&&clearTimeout(this._refreshTimeout),s.expires&&(this._refreshTimeout=setTimeout(function(){return A._refresh()},this._getTTLMilliseconds(s.ttl))),this.startBatching(),this.startSubscribeBatching();for(var E in this._subs)if(this._subs.hasOwnProperty(E)){var _=this._subs[E];_._shouldResubscribe()&&this._subscribe(_,h)}this.stopSubscribeBatching(),this.stopBatching(),this._startPing();var T={client:s.client,transport:this._transportName,latency:this._latency};s.data&&(T.data=s.data),this.emit("connect",T),s.subs&&this._processServerSubs(s.subs)}}},{key:"_processServerSubs",value:function(s){for(var a in s)if(s.hasOwnProperty(a)){var A=s[a],h=this._serverSubs[a]!==void 0,E={channel:a,isResubscribe:h};E=this._expandSubscribeContext(E,A),this.emit("subscribe",E)}for(var _ in s)if(s.hasOwnProperty(_)){var T=s[_];if(T.recovered){var w=T.publications;if(w&&w.length>0){w.length>1&&(!w[0].offset||w[0].offset>w[1].offset)&&(w=w.reverse());for(var O in w)w.hasOwnProperty(O)&&this._handlePublication(_,w[O])}}this._serverSubs[_]={seq:T.seq,gen:T.gen,offset:T.offset,epoch:T.epoch,recoverable:T.recoverable}}}},{key:"_stopPing",value:function(){this._pongTimeout!==null&&(clearTimeout(this._pongTimeout),this._pongTimeout=null),this._pingTimeout!==null&&(clearTimeout(this._pingTimeout),this._pingTimeout=null)}},{key:"_startPing",value:function(){var s=this;this._config.ping!==!0||this._config.pingInterval<=0||this.isConnected()&&(this._pingTimeout=setTimeout(function(){if(!s.isConnected()){s._stopPing();return}s.ping(),s._pongTimeout=setTimeout(function(){s._disconnect("no ping",!0)},s._config.pongWaitTimeout)},this._config.pingInterval))}},{key:"_restartPing",value:function(){this._stopPing(),this._startPing()}},{key:"_subscribeError",value:function(s,a){var A=this._getSub(s);if(A&&A._isSubscribing()){if(a.code===0&&a.message===J){this._disconnect("timeout",!0);return}A._setSubscribeError(a)}}},{key:"_expandSubscribeContext",value:function(s,a){var A=!1;"recovered"in a&&(A=a.recovered),s.recovered=A;var h=!1;"positioned"in a&&(h=a.positioned);var E="";"epoch"in a&&(E=a.epoch);var _=0;return"offset"in a&&(_=a.offset),h&&(s.streamPosition={offset:_,epoch:E}),a.data&&(s.data=a.data),s}},{key:"_subscribeResponse",value:function(s,a,A){var h=this,E=this._getSub(s);if(E&&E._isSubscribing()){E._setSubscribeSuccess(A);var _=A.publications;if(_&&_.length>0){_.length>=2&&!_[0].offset&&!_[1].offset&&(_=_.reverse());for(var T in _)_.hasOwnProperty(T)&&this._handlePublication(s,_[T])}if(A.recoverable&&(!a||!A.recovered)&&(this._lastSeq[s]=A.seq||0,this._lastGen[s]=A.gen||0,this._lastOffset[s]=A.offset||0),this._lastEpoch[s]=A.epoch||"",A.recoverable&&(E._recoverable=!0),A.expires===!0){var w=setTimeout(function(){return h._subRefresh(s)},this._getTTLMilliseconds(A.ttl));this._subRefreshTimeouts[s]=w}}}},{key:"_handleReply",value:function(s,a){var A=s.id,h=s.result;if(!(A in this._callbacks)){a();return}var E=this._callbacks[A];if(clearTimeout(this._callbacks[A].timeout),delete this._callbacks[A],(0,C.errorExists)(s)){var T=E.errback;if(!T){a();return}var w=s.error;T({error:w,next:a})}else{var _=E.callback;if(!_)return;_({result:h,next:a})}}},{key:"_handleJoin",value:function(s,a){var A={info:a.info},h=this._getSub(s);if(!h){this._isServerSub(s)&&(A.channel=s,this.emit("join",A));return}h.emit("join",A)}},{key:"_handleLeave",value:function(s,a){var A={info:a.info},h=this._getSub(s);if(!h){this._isServerSub(s)&&(A.channel=s,this.emit("leave",A));return}h.emit("leave",A)}},{key:"_handleUnsub",value:function(s,a){var A={},h=this._getSub(s);if(!h){this._isServerSub(s)&&(delete this._serverSubs[s],A.channel=s,this.emit("unsubscribe",A));return}h.unsubscribe(),a.resubscribe===!0&&h.subscribe()}},{key:"_handleSub",value:function(s,a){this._serverSubs[s]={seq:a.seq,gen:a.gen,offset:a.offset,epoch:a.epoch,recoverable:a.recoverable};var A={channel:s,isResubscribe:!1};A=this._expandSubscribeContext(A,a),this.emit("subscribe",A)}},{key:"_handlePublication",value:function(s,a){var A=this._getSub(s),h={data:a.data,seq:a.seq,gen:a.gen,offset:a.offset};if(a.info&&(h.info=a.info),!A){this._isServerSub(s)&&(a.seq!==void 0&&(this._serverSubs[s].seq=a.seq),a.gen!==void 0&&(this._serverSubs[s].gen=a.gen),a.offset!==void 0&&(this._serverSubs[s].offset=a.offset),h.channel=s,this.emit("publish",h));return}a.seq!==void 0&&(this._lastSeq[s]=a.seq),a.gen!==void 0&&(this._lastGen[s]=a.gen),a.offset!==void 0&&(this._lastOffset[s]=a.offset),A.emit("publish",h)}},{key:"_handleMessage",value:function(s){this.emit("message",s.data)}},{key:"_handlePush",value:function(s,a){var A=this._decoder.decodePush(s),h=0;"type"in A&&(h=A.type);var E=A.channel;if(h===this._pushType.PUBLICATION){var _=this._decoder.decodePushData(this._pushType.PUBLICATION,A.data);this._handlePublication(E,_)}else if(h===this._pushType.MESSAGE){var T=this._decoder.decodePushData(this._pushType.MESSAGE,A.data);this._handleMessage(T)}else if(h===this._pushType.JOIN){var w=this._decoder.decodePushData(this._pushType.JOIN,A.data);this._handleJoin(E,w)}else if(h===this._pushType.LEAVE){var O=this._decoder.decodePushData(this._pushType.LEAVE,A.data);this._handleLeave(E,O)}else if(h===this._pushType.UNSUBSCRIBE){var X=this._decoder.decodePushData(this._pushType.UNSUBSCRIBE,A.data);this._handleUnsub(E,X)}else if(h===this._pushType.SUBSCRIBE){var H=this._decoder.decodePushData(this._pushType.UNSUBSCRIBE,A.data);this._handleSub(E,H)}a()}},{key:"_flush",value:function(){var s=this._messages.slice(0);this._messages=[],this._transportSend(s)}},{key:"_ping",value:function(){var s=this,a={method:this._methodType.PING};this._call(a).then(function(A){s._pingResponse(s._decoder.decodeCommandResult(s._methodType.PING,A.result)),A.next&&A.next()},function(A){s._debug("ping error",A.error),A.next&&A.next()})}},{key:"_pingResponse",value:function(s){this.isConnected()&&(this._stopPing(),this._startPing())}},{key:"_getLastSeq",value:function(s){var a=this._lastSeq[s];return a||0}},{key:"_getLastOffset",value:function(s){var a=this._lastOffset[s];return a||0}},{key:"_getLastGen",value:function(s){var a=this._lastGen[s];return a||0}},{key:"_getLastEpoch",value:function(s){var a=this._lastEpoch[s];return a||""}},{key:"_createErrorObject",value:function(s,a){var A={message:s,code:a||0};return A}},{key:"_registerCall",value:function(s,a,A){var h=this;this._callbacks[s]={callback:a,errback:A,timeout:null},this._callbacks[s].timeout=setTimeout(function(){delete h._callbacks[s],(0,C.isFunction)(A)&&A({error:h._createErrorObject(J)})},this._config.timeout)}},{key:"_addMessage",value:function(s){var a=this._nextMessageId();return s.id=a,this._isBatching===!0?this._messages.push(s):this._transportSend([s]),a}},{key:"isConnected",value:function(){return this._isConnected()}},{key:"connect",value:function(){this._connect()}},{key:"disconnect",value:function(){this._disconnect("client",!1)}},{key:"ping",value:function(){return this._ping()}},{key:"startBatching",value:function(){this._isBatching=!0}},{key:"stopBatching",value:function(){this._isBatching=!1,this._flush()}},{key:"startSubscribeBatching",value:function(){this._isSubscribeBatching=!0}},{key:"stopSubscribeBatching",value:function(){var s=this;this._isSubscribeBatching=!1;var a=this._privateChannels;this._privateChannels={};var A=[];for(var h in a)if(a.hasOwnProperty(h)){var E=this._getSub(h);if(!E)continue;A.push(h)}if(A.length===0){this._debug("no private channels found, no need to make request");return}var _={client:this._clientID,channels:A},T=this._clientID,w=this._newXHRID(),O=function(x){if(w in s._xhrs&&delete s._xhrs[w],s._clientID===T){if(x.error||x.status!==200){s._debug("authorization request failed");for(var Se in A)if(A.hasOwnProperty(Se)){var zt=A[Se];s._subscribeError(zt,s._createErrorObject("authorization request failed"))}return}var yt={};if(x.data.channels)for(var ie in x.data.channels){var Kt=x.data.channels[ie];Kt.channel&&(yt[Kt.channel]=Kt.token)}var Er=!1;s._isBatching||(s.startBatching(),Er=!0);for(var vr in A)if(A.hasOwnProperty(vr)){var sa=(function(){var te=A[vr],Ir=yt[te];if(Ir){var _e={method:s._methodType.SUBSCRIBE,params:{channel:te,token:Ir}},Br=s._getSub(te);if(Br===null)return"continue";var Sr=Br._needRecover();if(Sr===!0){_e.params.recover=!0;var Gt=s._getLastSeq(te),Wt=s._getLastGen(te);if(Gt||Wt)Gt&&(_e.params.seq=Gt),Wt&&(_e.params.gen=Wt);else{var _r=s._getLastOffset(te);_r&&(_e.params.offset=_r)}var Qr=s._getLastEpoch(te);Qr&&(_e.params.epoch=Qr)}s._call(_e).then(function(me){s._subscribeResponse(te,Sr,s._decoder.decodeCommandResult(s._methodType.SUBSCRIBE,me.result)),me.next&&me.next()},function(me){s._subscribeError(te,me.error),me.next&&me.next()})}else return s._subscribeError(te,s._createErrorObject("permission denied",103)),"continue"})();if(sa==="continue")continue}Er&&s.stopBatching()}};if(this._config.onPrivateSubscribe!==null)this._config.onPrivateSubscribe({data:_},O);else{var X=this._ajax(this._config.subscribeEndpoint,this._config.subscribeParams,this._config.subscribeHeaders,_,O);this._xhrs[w]=X}}},{key:"_setSubscribeSince",value:function(s,a){this._lastOffset[s.channel]=a.offset,this._lastEpoch[s.channel]=a.epoch,s._setNeedRecover(!0)}},{key:"subscribe",value:function(s,a,A){var h=this._getSub(s);if(h!==null)return h._setEvents(a),h._isUnsubscribed()&&h.subscribe(A),h;var E=new y.default(this,s,a);return this._subs[s]=E,E.subscribe(A),E}}]),b})(f.default);u.Centrifuge=I}),579:(function(c,u,l){Object.defineProperty(u,"__esModule",{value:!0}),u.default=void 0;var f=l(382),y=f.Centrifuge;u.default=y,c.exports=u.default}),147:(function(c,u){Object.defineProperty(u,"__esModule",{value:!0}),u.JsonPushType=u.JsonMethodType=u.JsonEncoder=u.JsonDecoder=void 0;function l(Q,S){if(!(Q instanceof S))throw new TypeError("Cannot call a class as a function")}function f(Q,S){for(var P=0;P<S.length;P++){var k=S[P];k.enumerable=k.enumerable||!1,k.configurable=!0,"value"in k&&(k.writable=!0),Object.defineProperty(Q,k.key,k)}}function y(Q,S,P){return S&&f(Q.prototype,S),Q}var m={CONNECT:0,SUBSCRIBE:1,UNSUBSCRIBE:2,PUBLISH:3,PRESENCE:4,PRESENCE_STATS:5,HISTORY:6,PING:7,SEND:8,RPC:9,REFRESH:10,SUB_REFRESH:11};u.JsonMethodType=m;var C={PUBLICATION:0,JOIN:1,LEAVE:2,UNSUBSCRIBE:3,MESSAGE:4,SUBSCRIBE:5};u.JsonPushType=C;var v=(function(){function Q(){l(this,Q)}return y(Q,[{key:"encodeCommands",value:function(P){return P.map(function(k){return JSON.stringify(k)}).join(`
2
+ (function(Qe,ke){typeof exports=="object"&&typeof module<"u"?module.exports=ke():typeof define=="function"&&define.amd?define(ke):(Qe=typeof globalThis<"u"?globalThis:Qe||self,Qe.ChocoOneClickWidget=ke())})(this,(function(){"use strict";const Qe={ru:{paymentMethod:"Способ оплаты",selectMethod:"Выберите метод",pay:"Оплатить",login:"Войти",paymentSuccess:"Оплата прошла успешно!",paymentError:"Ошибка оплаты",paymentMethods:"Способ оплаты",newCard:"Оплата новой картой",balance:"Списать баланс",bonus:"Списать бонусы",bonusText:"Можно оплатить до {amount}%",cashback:"Кешбэк",willGet:"Получите",total:"Итого",instead:"вместо",coupon:"Списать купон",couponSuppressesCashback:"При применении купона бонусы не начисляются",couponUntil:"до {date}",addCard:"Добавление карты",editCards:"Редактировать карты",cardDeleted:"Карта успешно удалена",confirmDeleteCard:"Вы действительно хотите удалить карту?",cancel:"Отмена",delete:"Удалить",back:"Назад",errorMissingTrackClient:"Укажите trackId и clientId",errorNoServerResponseRetry:"Нет ответа от сервера, попробуйте заново",errorNoServerResponse:"Нет ответа от сервера",errorPaymentMethodNotSelected:"Метод оплаты не выбран",errorApplePayUnsupported:"Apple Pay не поддерживается в этом браузере",errorApplePayInit:"Ошибка инициализации Apple Pay",errorApplePayPayment:"Ошибка оплаты через Apple Pay",errorApplePayInterrupted:"Пожалуйста, подтвердите оплату после полной загрузки окна Apple Pay",errorGooglePayUnsupported:"Google Pay не поддерживается в этом браузере",errorGooglePaySettingsUnavailable:"Настройки Google Pay недоступны",errorGooglePayPayment:"Ошибка оплаты через Google Pay",errorActionUrlMissing:"action_url отсутствует в событии order.action_required",errorWidgetInit:"Ошибка инициализации виджета",errorPaymentProcess:"Ошибка оплаты"},en:{paymentMethod:"Payment method",selectMethod:"Select method",pay:"Pay",login:"Sign in",paymentSuccess:"Payment successful!",paymentError:"Payment error",paymentMethods:"Payment method",newCard:"Pay with new card",balance:"Use balance",bonus:"Use bonuses",bonusText:"You can pay up to {amount}%",cashback:"Cashback",willGet:"You will get",total:"Total",instead:"instead",coupon:"Apply coupon",couponSuppressesCashback:"Bonuses are not credited when the coupon is applied",couponUntil:"until {date}",addCard:"Add card",editCards:"Edit cards",cardDeleted:"Card successfully deleted",confirmDeleteCard:"Are you sure you want to delete this card?",cancel:"Cancel",delete:"Delete",back:"Back",errorMissingTrackClient:"Provide trackId and clientId",errorNoServerResponseRetry:"No response from server, please try again",errorNoServerResponse:"No response from server",errorPaymentMethodNotSelected:"Payment method is not selected",errorApplePayUnsupported:"Apple Pay is not supported in this browser",errorApplePayInit:"Apple Pay initialization error",errorApplePayPayment:"Apple Pay payment error",errorApplePayInterrupted:"Please confirm payment after the Apple Pay sheet fully loads",errorGooglePayUnsupported:"Google Pay is not supported in this browser",errorGooglePaySettingsUnavailable:"Google Pay settings are unavailable",errorGooglePayPayment:"Google Pay payment error",errorActionUrlMissing:"action_url is missing in order.action_required event",errorWidgetInit:"Widget initialization error",errorPaymentProcess:"Payment error"},kk:{paymentMethod:"Төлем әдісі",selectMethod:"Әдісті таңдаңыз",pay:"Төлеу",login:"Кіру",paymentSuccess:"Төлем сәтті өтті!",paymentError:"Төлем қатесі",paymentMethods:"Төлем әдісі",newCard:"Жаңа картамен төлеу",balance:"Балансты пайдалану",bonus:"Бонусдарды пайдалану",bonusText:"{amount}%-ге дейін төлеуге болады",cashback:"Кэшбэк",willGet:"Аласыз",total:"Барлығы",instead:"орнына",coupon:"Купонды пайдалану",couponSuppressesCashback:"Купон қолданылғанда бонустар есептелмейді",couponUntil:"{date} дейін",addCard:"Картаны қосу",editCards:"Карталарды өңдеу",cardDeleted:"Карта жойылды",confirmDeleteCard:"Картаны жойғыңыз келетініне сенімдісіз бе?",cancel:"Болдырмау",delete:"Жою",back:"Артқа",errorMissingTrackClient:"trackId пен clientId көрсетіңіз",errorNoServerResponseRetry:"Серверден жауап жоқ, қайтадан көріңіз",errorNoServerResponse:"Серверден жауап жоқ",errorPaymentMethodNotSelected:"Төлем әдісі таңдалмаған",errorApplePayUnsupported:"Бұл браузерде Apple Pay қолдау көрсетілмейді",errorApplePayInit:"Apple Pay инициализация қатесі",errorApplePayPayment:"Apple Pay арқылы төлем қатесі",errorApplePayInterrupted:"Өтінеміз, төлемді Apple Pay терезесі толық жүктелгеннен кейін растаңыз",errorGooglePayUnsupported:"Бұл браузерде Google Pay қолдау көрсетілмейді",errorGooglePaySettingsUnavailable:"Google Pay баптаулары қолжетімсіз",errorGooglePayPayment:"Google Pay арқылы төлем қатесі",errorActionUrlMissing:"order.action_required оқиғасында action_url жоқ",errorWidgetInit:"Виджетті инициализациялау қатесі",errorPaymentProcess:"Төлем қатесі"},ka:{paymentMethod:"გადახდის მეთოდი",selectMethod:"აირჩიეთ მეთოდი",pay:"გადახდა",login:"შესვლა",paymentSuccess:"გადახდა წარმატებით შესრულდა!",paymentError:"გადახდის შეცდომა",paymentMethods:"გადახდის მეთოდი",newCard:"ახალი ბარათით გადახდა",balance:"ბალანსის გამოყენება",bonus:"ბონუსების გამოყენება",bonusText:"{amount}%-ზე გადახდა შესაძლებელია",cashback:"ქეშბექი",willGet:"მიიღებთ",total:"ჯამი",instead:"ნაცვლად",coupon:"კუპონის გამოყენება",couponSuppressesCashback:"კუპონის გამოყენებისას ბონუსები არ დაირიცხება",couponUntil:"{date}-მდე",addCard:"ბარათის დამატება",editCards:"ბარათების რედაქტირება",cardDeleted:"ბარათი წაშლილია",confirmDeleteCard:"დარწმუნებული ხართ, რომ გსურთ ამ ბარათის წაშლა?",cancel:"გაუქმება",delete:"წაშლა",back:"უკან",errorMissingTrackClient:"მიუთითეთ trackId და clientId",errorNoServerResponseRetry:"სერვერის პასუხი არ არის, სცადეთ თავიდან",errorNoServerResponse:"სერვერის პასუხი არ არის",errorPaymentMethodNotSelected:"გადახდის მეთოდი არ არის არჩეული",errorApplePayUnsupported:"ამ ბრაუზერში Apple Pay არ არის მხარდაჭერილი",errorApplePayInit:"Apple Pay-ის ინიციალიზაციის შეცდომა",errorApplePayPayment:"Apple Pay-ით გადახდის შეცდომა",errorApplePayInterrupted:"გთხოვთ, დაადასტუროთ გადახდა Apple Pay-ის ფანჯრის სრულად ჩატვირთვის შემდეგ",errorGooglePayUnsupported:"ამ ბრაუზერში Google Pay არ არის მხარდაჭერილი",errorGooglePaySettingsUnavailable:"Google Pay-ის პარამეტრები მიუწვდომელია",errorGooglePayPayment:"Google Pay-ით გადახდის შეცდომა",errorActionUrlMissing:"order.action_required მოვლენაში action_url არ არის",errorWidgetInit:"ვიჯეტის ინიციალიზაციის შეცდომა",errorPaymentProcess:"გადახდის შეცდომა"}},ke={KZT:"₸",GEL:"₾"};function kr(e){return e==="production"?"https://api-proxy.choco.kz":"https://api-proxy.chocodev.kz"}let Me;const Pr=new Uint8Array(16);function wr(){if(!Me&&(Me=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!Me))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Me(Pr)}const F=[];for(let e=0;e<256;++e)F.push((e+256).toString(16).slice(1));function Tr(e,t=0){return F[e[t+0]]+F[e[t+1]]+F[e[t+2]]+F[e[t+3]]+"-"+F[e[t+4]]+F[e[t+5]]+"-"+F[e[t+6]]+F[e[t+7]]+"-"+F[e[t+8]]+F[e[t+9]]+"-"+F[e[t+10]]+F[e[t+11]]+F[e[t+12]]+F[e[t+13]]+F[e[t+14]]+F[e[t+15]]}const Yt={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function xe(e,t,n){if(Yt.randomUUID&&!e)return Yt.randomUUID();e=e||{};const r=e.random||(e.rng||wr)();return r[6]=r[6]&15|64,r[8]=r[8]&63|128,Tr(r)}const Vt="choco_device_id";function Z(e,t="ru",n="KZT"){const r=Number(e),o=t==="ru"?"ru-RU":"en-US";return`${r.toLocaleString(o)} ${ke[n]}`}function Zt(){let e=localStorage.getItem(Vt);return e||(e=xe(),localStorage.setItem(Vt,e)),e}function Ue(){if(typeof window>"u")return!1;const e=window.safari!==void 0,t=window.navigator.userAgent||"",n=!!t.match(/iPad/i)||!!t.match(/iPhone/i),r=!!t.match(/WebKit/i),o=n&&r&&!t.match(/CriOS/i);return e||o}function $t(){if(typeof navigator>"u")return 0;const e=navigator.userAgent||"",t=e.indexOf("OS");return(e.indexOf("iPhone")>-1||e.indexOf("iPad")>-1)&&t>-1?Number(e.substring(t+3,t+6).replace("_",".")):0}function mt(){var i;if(typeof navigator>"u")return"unknown";const e=(navigator.userAgent||navigator.vendor||"").toLowerCase(),t=(navigator.platform||"").toLowerCase(),n=(((i=navigator.userAgentData)==null?void 0:i.platform)||"").toLowerCase(),r=`${e} ${t} ${n}`;return/iphone|ipad|ipod/.test(r)||r.includes("macintosh")&&typeof document<"u"&&"ontouchend"in document?"ios":r.includes("android")?"android":r.includes("windows")?"windows":r.includes("mac")?"macos":"other"}function Fe(){if(typeof navigator>"u")return!1;const e=navigator.userAgentData;return e!=null&&e.platform&&["iOS","iPadOS"].includes(e.platform)||mt()==="ios"?!0:(navigator.userAgent||"").includes("Macintosh")&&typeof document<"u"&&"ontouchend"in document}function Xe(e){if(typeof sessionStorage>"u")return!1;const t=e==="apple_pay"?"disableApplePay":e==="google_pay"?"disableGooglePay":null;return t?sessionStorage.getItem(t)==="true":!1}function Rr(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var He={exports:{}},Lr=He.exports,en;function Or(){return en||(en=1,(function(e,t){(function(r,o){e.exports=o()})(Lr,function(){return(function(){var n={382:(function(c,u,l){Object.defineProperty(u,"__esModule",{value:!0}),u.Centrifuge=void 0;var f=v(l(187)),y=v(l(471)),m=l(147),C=l(853);function v(g){return g&&g.__esModule?g:{default:g}}function B(g){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?B=function(b){return typeof b}:B=function(b){return b&&typeof Symbol=="function"&&b.constructor===Symbol&&b!==Symbol.prototype?"symbol":typeof b},B(g)}function Q(g,p){if(!(g instanceof p))throw new TypeError("Cannot call a class as a function")}function S(g,p){for(var b=0;b<p.length;b++){var d=p[b];d.enumerable=d.enumerable||!1,d.configurable=!0,"value"in d&&(d.writable=!0),Object.defineProperty(g,d.key,d)}}function P(g,p,b){return p&&S(g.prototype,p),g}function k(g,p){if(typeof p!="function"&&p!==null)throw new TypeError("Super expression must either be null or a function");g.prototype=Object.create(p&&p.prototype,{constructor:{value:g,writable:!0,configurable:!0}}),p&&L(g,p)}function L(g,p){return L=Object.setPrototypeOf||function(d,s){return d.__proto__=s,d},L(g,p)}function R(g){var p=G();return function(){var d=K(g),s;if(p){var a=K(this).constructor;s=Reflect.construct(d,arguments,a)}else s=d.apply(this,arguments);return z(this,s)}}function z(g,p){if(p&&(B(p)==="object"||typeof p=="function"))return p;if(p!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return D(g)}function D(g){if(g===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return g}function G(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}function K(g){return K=Object.setPrototypeOf?Object.getPrototypeOf:function(b){return b.__proto__||Object.getPrototypeOf(b)},K(g)}var J="timeout",M="connection closed",I=(function(g){k(b,g);var p=R(b);function b(d,s){var a;return Q(this,b),a=p.call(this),a._url=d,a._websocket=null,a._sockjs=null,a._isSockjs=!1,a._xmlhttprequest=null,a._binary=!1,a._methodType=null,a._pushType=null,a._encoder=null,a._decoder=null,a._status="disconnected",a._reconnect=!0,a._reconnecting=!1,a._transport=null,a._transportName=null,a._transportClosed=!0,a._messageId=0,a._clientID=null,a._refreshRequired=!1,a._subs={},a._serverSubs={},a._lastSeq={},a._lastGen={},a._lastOffset={},a._lastEpoch={},a._messages=[],a._isBatching=!1,a._isSubscribeBatching=!1,a._privateChannels={},a._numRefreshFailed=0,a._refreshTimeout=null,a._pingTimeout=null,a._pongTimeout=null,a._subRefreshTimeouts={},a._retries=0,a._callbacks={},a._latency=null,a._latencyStart=null,a._connectData=null,a._token=null,a._xhrID=0,a._xhrs={},a._dispatchPromise=Promise.resolve(),a._protocol="",a._config={protocol:"",debug:!1,name:"js",version:"",websocket:null,sockjs:null,xmlhttprequest:null,minRetry:1e3,maxRetry:2e4,timeout:5e3,ping:!0,pingInterval:25e3,pongWaitTimeout:5e3,privateChannelPrefix:"$",onTransportClose:null,sockjsServer:null,sockjsTimeout:null,sockjsTransports:["websocket","xdr-streaming","xhr-streaming","eventsource","iframe-eventsource","iframe-htmlfile","xdr-polling","xhr-polling","iframe-xhr-polling","jsonp-polling"],refreshEndpoint:"/centrifuge/refresh",refreshHeaders:{},refreshParams:{},refreshData:{},refreshAttempts:null,refreshInterval:1e3,onRefreshFailed:null,onRefresh:null,subscribeEndpoint:"/centrifuge/subscribe",subscribeHeaders:{},subscribeParams:{},subRefreshInterval:1e3,onPrivateSubscribe:null,disableWithCredentials:!1},a._configure(s),a}return P(b,[{key:"setToken",value:function(s){this._token=s}},{key:"setConnectData",value:function(s){this._connectData=s}},{key:"setRefreshHeaders",value:function(s){this._config.refreshHeaders=s}},{key:"setRefreshParams",value:function(s){this._config.refreshParams=s}},{key:"setRefreshData",value:function(s){this._config.refreshData=s}},{key:"setSubscribeHeaders",value:function(s){this._config.subscribeHeaders=s}},{key:"setSubscribeParams",value:function(s){this._config.subscribeParams=s}},{key:"_ajax",value:function(s,a,A,h,E){var _=this,T="";this._debug("sending AJAX request to",s,"with data",JSON.stringify(h));var w;this._xmlhttprequest!==null?w=new this._xmlhttprequest:w=l.g.XMLHttpRequest?new l.g.XMLHttpRequest:new l.g.ActiveXObject("Microsoft.XMLHTTP");for(var O in a)a.hasOwnProperty(O)&&(T.length>0&&(T+="&"),T+=encodeURIComponent(O)+"="+encodeURIComponent(a[O]));T.length>0&&(T="?"+T),w.open("POST",s+T,!0),"withCredentials"in w&&(w.withCredentials=!this._config.disableWithCredentials),w.setRequestHeader("X-Requested-With","XMLHttpRequest"),w.setRequestHeader("Content-Type","application/json");for(var X in A)A.hasOwnProperty(X)&&w.setRequestHeader(X,A[X]);return w.onreadystatechange=function(){if(w.readyState===4)if(w.status===200){var H,x=!1;try{H=JSON.parse(w.responseText),x=!0}catch{E({error:"Invalid JSON. Data was: "+w.responseText,status:200,data:null})}x&&E({data:H,status:200})}else _._log("wrong status code in AJAX response",w.status),E({status:w.status,data:null})},setTimeout(function(){return w.send(JSON.stringify(h))},20),w}},{key:"_log",value:function(){(0,C.log)("info",arguments)}},{key:"_debug",value:function(){this._config.debug===!0&&(0,C.log)("debug",arguments)}},{key:"_websocketSupported",value:function(){return this._config.websocket!==null?!0:!(typeof WebSocket!="function"&&(typeof WebSocket>"u"?"undefined":B(WebSocket))!=="object")}},{key:"_setFormat",value:function(s){if(!this._formatOverride(s)){if(s==="protobuf")throw new Error("not implemented by JSON only Centrifuge client – use client with Protobuf");this._binary=!1,this._methodType=m.JsonMethodType,this._pushType=m.JsonPushType,this._encoder=new m.JsonEncoder,this._decoder=new m.JsonDecoder}}},{key:"_formatOverride",value:function(s){return!1}},{key:"_configure",value:function(s){if(!("Promise"in l.g))throw new Error("Promise polyfill required");if((0,C.extend)(this._config,s||{}),this._debug("centrifuge config",this._config),!this._url)throw new Error("url required");var a=(0,C.startsWith)(this._url,"ws")&&this._url.indexOf("format=protobuf")>-1;if(a||this._config.protocol==="protobuf")this._setFormat("protobuf"),this._protocol="protobuf";else{if(this._config.protocol!==""&&this._config.protocol!=="json")throw new Error("unsupported protocol "+this._config.protocol);this._setFormat("json")}if((0,C.startsWith)(this._url,"http"))if(this._debug("client will try to connect to SockJS endpoint"),this._config.sockjs!==null)this._debug("SockJS explicitly provided in options"),this._sockjs=this._config.sockjs;else{if(typeof l.g.SockJS>"u")throw new Error("SockJS not found, use ws:// in url or include SockJS");this._debug("use globally defined SockJS"),this._sockjs=l.g.SockJS}else this._debug("client will connect to websocket endpoint");this._xmlhttprequest=this._config.xmlhttprequest}},{key:"_setStatus",value:function(s){this._status!==s&&(this._debug("Status",this._status,"->",s),this._status=s)}},{key:"_isDisconnected",value:function(){return this._status==="disconnected"}},{key:"_isConnecting",value:function(){return this._status==="connecting"}},{key:"_isConnected",value:function(){return this._status==="connected"}},{key:"_nextMessageId",value:function(){return++this._messageId}},{key:"_resetRetry",value:function(){this._debug("reset retries count to 0"),this._retries=0}},{key:"_getRetryInterval",value:function(){var s=(0,C.backoff)(this._retries,this._config.minRetry,this._config.maxRetry);return this._retries+=1,s}},{key:"_abortInflightXHRs",value:function(){for(var s in this._xhrs){try{this._xhrs[s].abort()}catch(a){this._debug("error aborting xhr",a)}delete this._xhrs[s]}}},{key:"_clearConnectedState",value:function(s){this._clientID=null,this._stopPing();for(var a in this._callbacks)if(this._callbacks.hasOwnProperty(a)){var A=this._callbacks[a];clearTimeout(A.timeout);var h=A.errback;if(!h)continue;h({error:this._createErrorObject("disconnected")})}this._callbacks={};for(var E in this._subs)if(this._subs.hasOwnProperty(E)){var _=this._subs[E];s?(_._isSuccess()&&(_._triggerUnsubscribe(),_._recover=!0),_._shouldResubscribe()&&_._setSubscribing()):_._setUnsubscribed()}this._abortInflightXHRs(),this._refreshTimeout!==null&&(clearTimeout(this._refreshTimeout),this._refreshTimeout=null);for(var T in this._subRefreshTimeouts)this._subRefreshTimeouts.hasOwnProperty(T)&&this._subRefreshTimeouts[T]&&this._clearSubRefreshTimeout(T);this._subRefreshTimeouts={},this._reconnect||(this._subs={})}},{key:"_isTransportOpen",value:function(){return this._isSockjs?this._transport&&this._transport.transport&&this._transport.transport.readyState===this._transport.transport.OPEN:this._transport&&this._transport.readyState===this._transport.OPEN}},{key:"_transportSend",value:function(s){if(!s.length)return!0;if(!this._isTransportOpen()){for(var a in s){var A=a.id;if(A in this._callbacks){var h=this._callbacks[A];clearTimeout(this._callbacks[A].timeout),delete this._callbacks[A];var E=h.errback;E({error:this._createErrorObject(M,0)})}}return!1}return this._transport.send(this._encoder.encodeCommands(s)),!0}},{key:"_getSubProtocol",value:function(){return this._protocol?"centrifuge-"+this._protocol:""}},{key:"_setupTransport",value:function(){var s=this;if(this._isSockjs=!1,this._sockjs!==null){var a={transports:this._config.sockjsTransports};this._config.sockjsServer!==null&&(a.server=this._config.sockjsServer),this._config.sockjsTimeout!==null&&(a.timeout=this._config.sockjsTimeout),this._isSockjs=!0,this._transport=new this._sockjs(this._url,null,a)}else{if(!this._websocketSupported())throw this._debug("No Websocket support and no SockJS configured, can not connect"),new Error("No Websocket support and no SockJS configured, can not connect");this._config.websocket!==null?this._websocket=this._config.websocket:this._websocket=WebSocket;var A=this._getSubProtocol();A!==""?this._transport=new this._websocket(this._url,A):this._transport=new this._websocket(this._url),this._binary===!0&&(this._transport.binaryType="arraybuffer")}this._transport.onopen=function(){s._transportClosed=!1,s._isSockjs?(s._transportName="sockjs-"+s._transport.transport,s._transport.onheartbeat=function(){return s._restartPing()}):s._transportName="websocket";var h={};(s._token||s._connectData||s._config.name||s._config.version)&&(h.params={}),s._token&&(h.params.token=s._token),s._connectData&&(h.params.data=s._connectData),s._config.name&&(h.params.name=s._config.name),s._config.version&&(h.params.version=s._config.version);var E={},_=!1;for(var T in s._serverSubs)if(s._serverSubs.hasOwnProperty(T)&&s._serverSubs[T].recoverable){_=!0;var w={recover:!0};s._serverSubs[T].seq||s._serverSubs[T].gen?(s._serverSubs[T].seq&&(w.seq=s._serverSubs[T].seq),s._serverSubs[T].gen&&(w.gen=s._serverSubs[T].gen)):s._serverSubs[T].offset&&(w.offset=s._serverSubs[T].offset),s._serverSubs[T].epoch&&(w.epoch=s._serverSubs[T].epoch),E[T]=w}_&&(h.params||(h.params={}),h.params.subs=E),s._latencyStart=new Date,s._call(h).then(function(O){s._connectResponse(s._decoder.decodeCommandResult(s._methodType.CONNECT,O.result),_),O.next&&O.next()},function(O){var X=O.error;X.code===109&&(s._refreshRequired=!0),s._disconnect("connect error",!0),O.next&&O.next()})},this._transport.onerror=function(h){s._debug("transport level error",h)},this._transport.onclose=function(h){s._transportClosed=!0;var E=M,_=!0;if(h&&"reason"in h&&h.reason)try{var T=JSON.parse(h.reason);s._debug("reason is an advice object",T),E=T.reason,_=T.reconnect}catch{E=h.reason,s._debug("reason is a plain string",E)}if(s._config.onTransportClose!==null&&s._config.onTransportClose({event:h,reason:E,reconnect:_}),s._disconnect(E,_),s._reconnect===!0){s._reconnecting=!0;var w=s._getRetryInterval();s._debug("reconnect after "+w+" milliseconds"),setTimeout(function(){s._reconnect===!0&&(s._refreshRequired?s._refresh():s._connect())},w)}},this._transport.onmessage=function(h){s._dataReceived(h.data)}}},{key:"rpc",value:function(s){return this._rpc("",s)}},{key:"namedRPC",value:function(s,a){return this._rpc(s,a)}},{key:"_rpc",value:function(s,a){var A={data:a};s!==""&&(A.method=s);var h={method:this._methodType.RPC,params:A};return this._methodCall(h,function(E){return E})}},{key:"send",value:function(s){var a={method:this._methodType.SEND,params:{data:s}};if(!this.isConnected())return Promise.reject(this._createErrorObject(M,0));var A=this._transportSend([a]);return A?Promise.resolve({}):Promise.reject(this._createErrorObject(M,0))}},{key:"_getHistoryParams",value:function(s,a){var A={channel:s};return a!==void 0&&(a.since&&(A.since={offset:a.since.offset},a.since.epoch&&(A.since.epoch=a.since.epoch)),a.limit!==void 0&&(A.limit=a.limit),a.reverse===!0&&(A.reverse=!0)),A}},{key:"_methodCall",value:function(s,a){var A=this;return this.isConnected()?new Promise(function(h,E){A._call(s).then(function(_){h(a(A._decoder.decodeCommandResult(s.method,_.result))),_.next&&_.next()},function(_){E(_.error),_.next&&_.next()})}):Promise.reject(this._createErrorObject(M,0))}},{key:"publish",value:function(s,a){var A={method:this._methodType.PUBLISH,params:{channel:s,data:a}};return this._methodCall(A,function(){return{}})}},{key:"history",value:function(s,a){var A=this._getHistoryParams(s,a),h={method:this._methodType.HISTORY,params:A};return this._methodCall(h,function(E){return{publications:E.publications,epoch:E.epoch||"",offset:E.offset||0}})}},{key:"presence",value:function(s){var a={method:this._methodType.PRESENCE,params:{channel:s}};return this._methodCall(a,function(A){return{presence:A.presence}})}},{key:"presenceStats",value:function(s){var a={method:this._methodType.PRESENCE_STATS,params:{channel:s}};return this._methodCall(a,function(A){return{num_users:A.num_users,num_clients:A.num_clients}})}},{key:"_dataReceived",value:function(s){var a=this,A=this._decoder.decodeReplies(s);this._dispatchPromise=this._dispatchPromise.then(function(){var h;a._dispatchPromise=new Promise(function(E){h=E}),a._dispatchSynchronized(A,h)}),this._restartPing()}},{key:"_dispatchSynchronized",value:function(s,a){var A=this,h=Promise.resolve(),E=function(w){s.hasOwnProperty(w)&&(h=h.then(function(){return A._dispatchReply(s[w])}))};for(var _ in s)E(_);h=h.then(function(){a()})}},{key:"_dispatchReply",value:function(s){var a,A=new Promise(function(E){a=E});if(s==null)return this._debug("dispatch: got undefined or null reply"),a(),A;var h=s.id;return h&&h>0?this._handleReply(s,a):this._handlePush(s.result,a),A}},{key:"_call",value:function(s){var a=this;return new Promise(function(A,h){var E=a._addMessage(s);a._registerCall(E,A,h)})}},{key:"_connect",value:function(){if(this.isConnected()){this._debug("connect called when already connected");return}this._status!=="connecting"&&(this._debug("start connecting"),this._setStatus("connecting"),this._clientID=null,this._reconnect=!0,this._setupTransport())}},{key:"_disconnect",value:function(s,a){var A=a||!1;if(A===!1&&(this._reconnect=!1),this._isDisconnected()){A||this._clearConnectedState(A);return}if(this._clearConnectedState(A),this._debug("disconnected:",s,a),this._setStatus("disconnected"),this._refreshTimeout&&(clearTimeout(this._refreshTimeout),this._refreshTimeout=null),this._reconnecting===!1){for(var h in this._serverSubs)this._serverSubs.hasOwnProperty(h)&&this.emit("unsubscribe",{channel:h});this.emit("disconnect",{reason:s,reconnect:A})}A===!1&&(this._subs={},this._serverSubs={}),this._transportClosed||this._transport.close()}},{key:"_refreshFailed",value:function(){this._numRefreshFailed=0,this._isDisconnected()||this._disconnect("refresh failed",!1),this._config.onRefreshFailed!==null&&this._config.onRefreshFailed()}},{key:"_refresh",value:function(){var s=this;if(this._debug("refresh token"),this._config.refreshAttempts===0){this._debug("refresh attempts set to 0, do not send refresh request at all"),this._refreshFailed();return}this._refreshTimeout!==null&&(clearTimeout(this._refreshTimeout),this._refreshTimeout=null);var a=this._clientID,A=this._newXHRID(),h=function(w){if(A in s._xhrs&&delete s._xhrs[A],s._clientID===a){if(w.error||w.status!==200){if(w.error?s._debug("error refreshing connection token",w.error):s._debug("error refreshing connection token: wrong status code",w.status),s._numRefreshFailed++,s._refreshTimeout!==null&&(clearTimeout(s._refreshTimeout),s._refreshTimeout=null),s._config.refreshAttempts!==null&&s._numRefreshFailed>=s._config.refreshAttempts){s._refreshFailed();return}var O=Math.round(Math.random()*1e3*Math.max(s._numRefreshFailed,20)),X=s._config.refreshInterval+O;s._refreshTimeout=setTimeout(function(){return s._refresh()},X);return}if(s._numRefreshFailed=0,s._token=w.data.token,!s._token){s._refreshFailed();return}if(s._isDisconnected()&&s._reconnect)s._debug("token refreshed, connect from scratch"),s._connect();else{s._debug("send refreshed token");var H={method:s._methodType.REFRESH,params:{token:s._token}};s._call(H).then(function(x){s._refreshResponse(s._decoder.decodeCommandResult(s._methodType.REFRESH,x.result)),x.next&&x.next()},function(x){s._refreshError(x.error),x.next&&x.next()})}}};if(this._config.onRefresh!==null){var E={};this._config.onRefresh(E,h)}else{var _=this._ajax(this._config.refreshEndpoint,this._config.refreshParams,this._config.refreshHeaders,this._config.refreshData,h);this._xhrs[A]=_}}},{key:"_refreshError",value:function(s){var a=this;this._debug("refresh error",s),this._refreshTimeout&&(clearTimeout(this._refreshTimeout),this._refreshTimeout=null);var A=this._config.refreshInterval+Math.round(Math.random()*1e3);this._refreshTimeout=setTimeout(function(){return a._refresh()},A)}},{key:"_refreshResponse",value:function(s){var a=this;this._refreshTimeout&&(clearTimeout(this._refreshTimeout),this._refreshTimeout=null),s.expires&&(this._clientID=s.client,this._refreshTimeout=setTimeout(function(){return a._refresh()},this._getTTLMilliseconds(s.ttl)))}},{key:"_newXHRID",value:function(){return this._xhrID++,this._xhrID}},{key:"_subRefresh",value:function(s){var a=this;if(this._debug("refresh subscription token for channel",s),this._subRefreshTimeouts[s]!==void 0)this._clearSubRefreshTimeout(s);else return;var A=this._clientID,h=this._newXHRID(),E=function(O){if(h in a._xhrs&&delete a._xhrs[h],!(O.error||O.status!==200||a._clientID!==A)){var X={};if(O.data.channels)for(var H in O.data.channels){var x=O.data.channels[H];x.channel&&(X[x.channel]=x.token)}var Se=X[s];if(Se){var zt={method:a._methodType.SUB_REFRESH,params:{channel:s,token:Se}},yt=a._getSub(s);yt!==null&&a._call(zt).then(function(ie){a._subRefreshResponse(s,a._decoder.decodeCommandResult(a._methodType.SUB_REFRESH,ie.result)),ie.next&&ie.next()},function(ie){a._subRefreshError(s,ie.error),ie.next&&ie.next()})}}},_={client:this._clientID,channels:[s]};if(this._config.onPrivateSubscribe!==null)this._config.onPrivateSubscribe({data:_},E);else{var T=this._ajax(this._config.subscribeEndpoint,this._config.subscribeParams,this._config.subscribeHeaders,_,E);this._xhrs[h]=T}}},{key:"_clearSubRefreshTimeout",value:function(s){this._subRefreshTimeouts[s]!==void 0&&(clearTimeout(this._subRefreshTimeouts[s]),delete this._subRefreshTimeouts[s])}},{key:"_subRefreshError",value:function(s,a){var A=this;this._debug("subscription refresh error",s,a),this._clearSubRefreshTimeout(s);var h=this._getSub(s);if(h!==null){var E=Math.round(Math.random()*1e3),_=setTimeout(function(){return A._subRefresh(s)},this._config.subRefreshInterval+E);this._subRefreshTimeouts[s]=_}}},{key:"_subRefreshResponse",value:function(s,a){var A=this;this._debug("subscription refresh success",s),this._clearSubRefreshTimeout(s);var h=this._getSub(s);if(h!==null&&a.expires===!0){var E=setTimeout(function(){return A._subRefresh(s)},this._getTTLMilliseconds(a.ttl));this._subRefreshTimeouts[s]=E}}},{key:"_subscribe",value:function(s,a){var A=this;this._debug("subscribing on",s.channel);var h=s.channel;if(h in this._subs||(this._subs[h]=s),!this.isConnected()){s._setNew();return}s._setSubscribing(a);var E={method:this._methodType.SUBSCRIBE,params:{channel:h}};if(s._subscribeData&&(E.params.data=s._subscribeData),(0,C.startsWith)(h,this._config.privateChannelPrefix))this._isSubscribeBatching?this._privateChannels[h]=!0:(this.startSubscribeBatching(),this._subscribe(s),this.stopSubscribeBatching());else{var _=s._needRecover();if(_===!0){E.params.recover=!0;var T=this._getLastSeq(h),w=this._getLastGen(h);if(T||w)T&&(E.params.seq=T),w&&(E.params.gen=w);else{var O=this._getLastOffset(h);O&&(E.params.offset=O)}var X=this._getLastEpoch(h);X&&(E.params.epoch=X)}this._call(E).then(function(H){A._subscribeResponse(h,_,A._decoder.decodeCommandResult(A._methodType.SUBSCRIBE,H.result)),H.next&&H.next()},function(H){A._subscribeError(h,H.error),H.next&&H.next()})}}},{key:"_unsubscribe",value:function(s){delete this._subs[s.channel],delete this._lastOffset[s.channel],delete this._lastSeq[s.channel],delete this._lastGen[s.channel],this.isConnected()&&this._addMessage({method:this._methodType.UNSUBSCRIBE,params:{channel:s.channel}})}},{key:"_getTTLMilliseconds",value:function(s){return Math.min(s*1e3,2147483647)}},{key:"getSub",value:function(s){return this._getSub(s)}},{key:"_getSub",value:function(s){var a=this._subs[s];return a||null}},{key:"_isServerSub",value:function(s){return this._serverSubs[s]!==void 0}},{key:"_connectResponse",value:function(s,a){var A=this,h=this._reconnecting;if(this._reconnecting=!1,this._resetRetry(),this._refreshRequired=!1,!this.isConnected()){this._latencyStart!==null&&(this._latency=new Date().getTime()-this._latencyStart.getTime(),this._latencyStart=null),this._clientID=s.client,this._setStatus("connected"),this._refreshTimeout&&clearTimeout(this._refreshTimeout),s.expires&&(this._refreshTimeout=setTimeout(function(){return A._refresh()},this._getTTLMilliseconds(s.ttl))),this.startBatching(),this.startSubscribeBatching();for(var E in this._subs)if(this._subs.hasOwnProperty(E)){var _=this._subs[E];_._shouldResubscribe()&&this._subscribe(_,h)}this.stopSubscribeBatching(),this.stopBatching(),this._startPing();var T={client:s.client,transport:this._transportName,latency:this._latency};s.data&&(T.data=s.data),this.emit("connect",T),s.subs&&this._processServerSubs(s.subs)}}},{key:"_processServerSubs",value:function(s){for(var a in s)if(s.hasOwnProperty(a)){var A=s[a],h=this._serverSubs[a]!==void 0,E={channel:a,isResubscribe:h};E=this._expandSubscribeContext(E,A),this.emit("subscribe",E)}for(var _ in s)if(s.hasOwnProperty(_)){var T=s[_];if(T.recovered){var w=T.publications;if(w&&w.length>0){w.length>1&&(!w[0].offset||w[0].offset>w[1].offset)&&(w=w.reverse());for(var O in w)w.hasOwnProperty(O)&&this._handlePublication(_,w[O])}}this._serverSubs[_]={seq:T.seq,gen:T.gen,offset:T.offset,epoch:T.epoch,recoverable:T.recoverable}}}},{key:"_stopPing",value:function(){this._pongTimeout!==null&&(clearTimeout(this._pongTimeout),this._pongTimeout=null),this._pingTimeout!==null&&(clearTimeout(this._pingTimeout),this._pingTimeout=null)}},{key:"_startPing",value:function(){var s=this;this._config.ping!==!0||this._config.pingInterval<=0||this.isConnected()&&(this._pingTimeout=setTimeout(function(){if(!s.isConnected()){s._stopPing();return}s.ping(),s._pongTimeout=setTimeout(function(){s._disconnect("no ping",!0)},s._config.pongWaitTimeout)},this._config.pingInterval))}},{key:"_restartPing",value:function(){this._stopPing(),this._startPing()}},{key:"_subscribeError",value:function(s,a){var A=this._getSub(s);if(A&&A._isSubscribing()){if(a.code===0&&a.message===J){this._disconnect("timeout",!0);return}A._setSubscribeError(a)}}},{key:"_expandSubscribeContext",value:function(s,a){var A=!1;"recovered"in a&&(A=a.recovered),s.recovered=A;var h=!1;"positioned"in a&&(h=a.positioned);var E="";"epoch"in a&&(E=a.epoch);var _=0;return"offset"in a&&(_=a.offset),h&&(s.streamPosition={offset:_,epoch:E}),a.data&&(s.data=a.data),s}},{key:"_subscribeResponse",value:function(s,a,A){var h=this,E=this._getSub(s);if(E&&E._isSubscribing()){E._setSubscribeSuccess(A);var _=A.publications;if(_&&_.length>0){_.length>=2&&!_[0].offset&&!_[1].offset&&(_=_.reverse());for(var T in _)_.hasOwnProperty(T)&&this._handlePublication(s,_[T])}if(A.recoverable&&(!a||!A.recovered)&&(this._lastSeq[s]=A.seq||0,this._lastGen[s]=A.gen||0,this._lastOffset[s]=A.offset||0),this._lastEpoch[s]=A.epoch||"",A.recoverable&&(E._recoverable=!0),A.expires===!0){var w=setTimeout(function(){return h._subRefresh(s)},this._getTTLMilliseconds(A.ttl));this._subRefreshTimeouts[s]=w}}}},{key:"_handleReply",value:function(s,a){var A=s.id,h=s.result;if(!(A in this._callbacks)){a();return}var E=this._callbacks[A];if(clearTimeout(this._callbacks[A].timeout),delete this._callbacks[A],(0,C.errorExists)(s)){var T=E.errback;if(!T){a();return}var w=s.error;T({error:w,next:a})}else{var _=E.callback;if(!_)return;_({result:h,next:a})}}},{key:"_handleJoin",value:function(s,a){var A={info:a.info},h=this._getSub(s);if(!h){this._isServerSub(s)&&(A.channel=s,this.emit("join",A));return}h.emit("join",A)}},{key:"_handleLeave",value:function(s,a){var A={info:a.info},h=this._getSub(s);if(!h){this._isServerSub(s)&&(A.channel=s,this.emit("leave",A));return}h.emit("leave",A)}},{key:"_handleUnsub",value:function(s,a){var A={},h=this._getSub(s);if(!h){this._isServerSub(s)&&(delete this._serverSubs[s],A.channel=s,this.emit("unsubscribe",A));return}h.unsubscribe(),a.resubscribe===!0&&h.subscribe()}},{key:"_handleSub",value:function(s,a){this._serverSubs[s]={seq:a.seq,gen:a.gen,offset:a.offset,epoch:a.epoch,recoverable:a.recoverable};var A={channel:s,isResubscribe:!1};A=this._expandSubscribeContext(A,a),this.emit("subscribe",A)}},{key:"_handlePublication",value:function(s,a){var A=this._getSub(s),h={data:a.data,seq:a.seq,gen:a.gen,offset:a.offset};if(a.info&&(h.info=a.info),!A){this._isServerSub(s)&&(a.seq!==void 0&&(this._serverSubs[s].seq=a.seq),a.gen!==void 0&&(this._serverSubs[s].gen=a.gen),a.offset!==void 0&&(this._serverSubs[s].offset=a.offset),h.channel=s,this.emit("publish",h));return}a.seq!==void 0&&(this._lastSeq[s]=a.seq),a.gen!==void 0&&(this._lastGen[s]=a.gen),a.offset!==void 0&&(this._lastOffset[s]=a.offset),A.emit("publish",h)}},{key:"_handleMessage",value:function(s){this.emit("message",s.data)}},{key:"_handlePush",value:function(s,a){var A=this._decoder.decodePush(s),h=0;"type"in A&&(h=A.type);var E=A.channel;if(h===this._pushType.PUBLICATION){var _=this._decoder.decodePushData(this._pushType.PUBLICATION,A.data);this._handlePublication(E,_)}else if(h===this._pushType.MESSAGE){var T=this._decoder.decodePushData(this._pushType.MESSAGE,A.data);this._handleMessage(T)}else if(h===this._pushType.JOIN){var w=this._decoder.decodePushData(this._pushType.JOIN,A.data);this._handleJoin(E,w)}else if(h===this._pushType.LEAVE){var O=this._decoder.decodePushData(this._pushType.LEAVE,A.data);this._handleLeave(E,O)}else if(h===this._pushType.UNSUBSCRIBE){var X=this._decoder.decodePushData(this._pushType.UNSUBSCRIBE,A.data);this._handleUnsub(E,X)}else if(h===this._pushType.SUBSCRIBE){var H=this._decoder.decodePushData(this._pushType.UNSUBSCRIBE,A.data);this._handleSub(E,H)}a()}},{key:"_flush",value:function(){var s=this._messages.slice(0);this._messages=[],this._transportSend(s)}},{key:"_ping",value:function(){var s=this,a={method:this._methodType.PING};this._call(a).then(function(A){s._pingResponse(s._decoder.decodeCommandResult(s._methodType.PING,A.result)),A.next&&A.next()},function(A){s._debug("ping error",A.error),A.next&&A.next()})}},{key:"_pingResponse",value:function(s){this.isConnected()&&(this._stopPing(),this._startPing())}},{key:"_getLastSeq",value:function(s){var a=this._lastSeq[s];return a||0}},{key:"_getLastOffset",value:function(s){var a=this._lastOffset[s];return a||0}},{key:"_getLastGen",value:function(s){var a=this._lastGen[s];return a||0}},{key:"_getLastEpoch",value:function(s){var a=this._lastEpoch[s];return a||""}},{key:"_createErrorObject",value:function(s,a){var A={message:s,code:a||0};return A}},{key:"_registerCall",value:function(s,a,A){var h=this;this._callbacks[s]={callback:a,errback:A,timeout:null},this._callbacks[s].timeout=setTimeout(function(){delete h._callbacks[s],(0,C.isFunction)(A)&&A({error:h._createErrorObject(J)})},this._config.timeout)}},{key:"_addMessage",value:function(s){var a=this._nextMessageId();return s.id=a,this._isBatching===!0?this._messages.push(s):this._transportSend([s]),a}},{key:"isConnected",value:function(){return this._isConnected()}},{key:"connect",value:function(){this._connect()}},{key:"disconnect",value:function(){this._disconnect("client",!1)}},{key:"ping",value:function(){return this._ping()}},{key:"startBatching",value:function(){this._isBatching=!0}},{key:"stopBatching",value:function(){this._isBatching=!1,this._flush()}},{key:"startSubscribeBatching",value:function(){this._isSubscribeBatching=!0}},{key:"stopSubscribeBatching",value:function(){var s=this;this._isSubscribeBatching=!1;var a=this._privateChannels;this._privateChannels={};var A=[];for(var h in a)if(a.hasOwnProperty(h)){var E=this._getSub(h);if(!E)continue;A.push(h)}if(A.length===0){this._debug("no private channels found, no need to make request");return}var _={client:this._clientID,channels:A},T=this._clientID,w=this._newXHRID(),O=function(x){if(w in s._xhrs&&delete s._xhrs[w],s._clientID===T){if(x.error||x.status!==200){s._debug("authorization request failed");for(var Se in A)if(A.hasOwnProperty(Se)){var zt=A[Se];s._subscribeError(zt,s._createErrorObject("authorization request failed"))}return}var yt={};if(x.data.channels)for(var ie in x.data.channels){var Kt=x.data.channels[ie];Kt.channel&&(yt[Kt.channel]=Kt.token)}var Er=!1;s._isBatching||(s.startBatching(),Er=!0);for(var vr in A)if(A.hasOwnProperty(vr)){var sa=(function(){var ne=A[vr],Ir=yt[ne];if(Ir){var _e={method:s._methodType.SUBSCRIBE,params:{channel:ne,token:Ir}},Br=s._getSub(ne);if(Br===null)return"continue";var Sr=Br._needRecover();if(Sr===!0){_e.params.recover=!0;var Gt=s._getLastSeq(ne),Wt=s._getLastGen(ne);if(Gt||Wt)Gt&&(_e.params.seq=Gt),Wt&&(_e.params.gen=Wt);else{var _r=s._getLastOffset(ne);_r&&(_e.params.offset=_r)}var Qr=s._getLastEpoch(ne);Qr&&(_e.params.epoch=Qr)}s._call(_e).then(function(me){s._subscribeResponse(ne,Sr,s._decoder.decodeCommandResult(s._methodType.SUBSCRIBE,me.result)),me.next&&me.next()},function(me){s._subscribeError(ne,me.error),me.next&&me.next()})}else return s._subscribeError(ne,s._createErrorObject("permission denied",103)),"continue"})();if(sa==="continue")continue}Er&&s.stopBatching()}};if(this._config.onPrivateSubscribe!==null)this._config.onPrivateSubscribe({data:_},O);else{var X=this._ajax(this._config.subscribeEndpoint,this._config.subscribeParams,this._config.subscribeHeaders,_,O);this._xhrs[w]=X}}},{key:"_setSubscribeSince",value:function(s,a){this._lastOffset[s.channel]=a.offset,this._lastEpoch[s.channel]=a.epoch,s._setNeedRecover(!0)}},{key:"subscribe",value:function(s,a,A){var h=this._getSub(s);if(h!==null)return h._setEvents(a),h._isUnsubscribed()&&h.subscribe(A),h;var E=new y.default(this,s,a);return this._subs[s]=E,E.subscribe(A),E}}]),b})(f.default);u.Centrifuge=I}),579:(function(c,u,l){Object.defineProperty(u,"__esModule",{value:!0}),u.default=void 0;var f=l(382),y=f.Centrifuge;u.default=y,c.exports=u.default}),147:(function(c,u){Object.defineProperty(u,"__esModule",{value:!0}),u.JsonPushType=u.JsonMethodType=u.JsonEncoder=u.JsonDecoder=void 0;function l(Q,S){if(!(Q instanceof S))throw new TypeError("Cannot call a class as a function")}function f(Q,S){for(var P=0;P<S.length;P++){var k=S[P];k.enumerable=k.enumerable||!1,k.configurable=!0,"value"in k&&(k.writable=!0),Object.defineProperty(Q,k.key,k)}}function y(Q,S,P){return S&&f(Q.prototype,S),Q}var m={CONNECT:0,SUBSCRIBE:1,UNSUBSCRIBE:2,PUBLISH:3,PRESENCE:4,PRESENCE_STATS:5,HISTORY:6,PING:7,SEND:8,RPC:9,REFRESH:10,SUB_REFRESH:11};u.JsonMethodType=m;var C={PUBLICATION:0,JOIN:1,LEAVE:2,UNSUBSCRIBE:3,MESSAGE:4,SUBSCRIBE:5};u.JsonPushType=C;var v=(function(){function Q(){l(this,Q)}return y(Q,[{key:"encodeCommands",value:function(P){return P.map(function(k){return JSON.stringify(k)}).join(`
3
3
  `)}}]),Q})();u.JsonEncoder=v;var B=(function(){function Q(){l(this,Q)}return y(Q,[{key:"decodeReplies",value:function(P){return P.split(`
4
- `).filter(function(k){return k!==""}).map(function(k){return JSON.parse(k)})}},{key:"decodeCommandResult",value:function(P,k){return k}},{key:"decodePush",value:function(P){return P}},{key:"decodePushData",value:function(P,k){return k}}]),Q})();u.JsonDecoder=B}),471:(function(c,u,l){function f(p){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?f=function(d){return typeof d}:f=function(d){return d&&typeof Symbol=="function"&&d.constructor===Symbol&&d!==Symbol.prototype?"symbol":typeof d},f(p)}Object.defineProperty(u,"__esModule",{value:!0}),u.default=void 0;var y=C(l(187)),m=l(853);function C(p){return p&&p.__esModule?p:{default:p}}function v(p,b){if(!(p instanceof b))throw new TypeError("Cannot call a class as a function")}function B(p,b){for(var d=0;d<b.length;d++){var s=b[d];s.enumerable=s.enumerable||!1,s.configurable=!0,"value"in s&&(s.writable=!0),Object.defineProperty(p,s.key,s)}}function Q(p,b,d){return b&&B(p.prototype,b),p}function S(p,b){if(typeof b!="function"&&b!==null)throw new TypeError("Super expression must either be null or a function");p.prototype=Object.create(b&&b.prototype,{constructor:{value:p,writable:!0,configurable:!0}}),b&&P(p,b)}function P(p,b){return P=Object.setPrototypeOf||function(s,a){return s.__proto__=a,s},P(p,b)}function k(p){var b=z();return function(){var s=D(p),a;if(b){var A=D(this).constructor;a=Reflect.construct(s,arguments,A)}else a=s.apply(this,arguments);return L(this,a)}}function L(p,b){if(b&&(f(b)==="object"||typeof b=="function"))return b;if(b!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return R(p)}function R(p){if(p===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return p}function z(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}function D(p){return D=Object.setPrototypeOf?Object.getPrototypeOf:function(d){return d.__proto__||Object.getPrototypeOf(d)},D(p)}var G=0,K=1,J=2,M=3,I=4,g=(function(p){S(d,p);var b=k(d);function d(s,a,A){var h;return v(this,d),h=b.call(this),h.channel=a,h._centrifuge=s,h._status=G,h._error=null,h._isResubscribe=!1,h._ready=!1,h._subscriptionPromise=null,h._noResubscribe=!1,h._recoverable=!1,h._recover=!1,h._setEvents(A),h._initializePromise(),h._promises={},h._promiseId=0,h._subscribeData=null,h.on("error",function(E){this._centrifuge._debug("subscription error",E)}),h}return Q(d,[{key:"_nextPromiseId",value:function(){return++this._promiseId}},{key:"_initializePromise",value:function(){var a=this;this._ready=!1,this._subscriptionPromise=new Promise(function(A,h){a._resolve=function(E){a._ready=!0,A(E)},a._reject=function(E){a._ready=!0,h(E)}}).then(function(){},function(){})}},{key:"_setNeedRecover",value:function(a){this._recoverable=a,this._recover=a}},{key:"_needRecover",value:function(){return this._recoverable===!0&&this._recover===!0}},{key:"_setEvents",value:function(a){if(a){if((0,m.isFunction)(a))this.on("publish",a);else if(Object.prototype.toString.call(a)===Object.prototype.toString.call({}))for(var A=["publish","join","leave","unsubscribe","subscribe","error"],h=0,E=A.length;h<E;h++){var _=A[h];_ in a&&this.on(_,a[_])}}}},{key:"_isNew",value:function(){return this._status===G}},{key:"_isUnsubscribed",value:function(){return this._status===I}},{key:"_isSubscribing",value:function(){return this._status===K}},{key:"_isReady",value:function(){return this._status===J||this._status===M}},{key:"_isSuccess",value:function(){return this._status===J}},{key:"_isError",value:function(){return this._status===M}},{key:"_setNew",value:function(){this._status=G}},{key:"_setSubscribing",value:function(a){this._isResubscribe=a||!1,this._ready===!0&&this._initializePromise(),this._status=K}},{key:"_setSubscribeSuccess",value:function(a){if(this._status!==J){this._status=J;var A=this._getSubscribeSuccessContext(a);this._recover=!1,this.emit("subscribe",A),this._resolve(A);for(var h in this._promises)clearTimeout(this._promises[h].timeout),this._promises[h].resolve(),delete this._promises[h]}}},{key:"_setSubscribeError",value:function(a){if(this._status!==M){this._status=M,this._error=a;var A=this._getSubscribeErrorContext();this.emit("error",A),this._reject(A);for(var h in this._promises)clearTimeout(this._promises[h].timeout),this._promises[h].reject(a),delete this._promises[h]}}},{key:"_triggerUnsubscribe",value:function(){this.emit("unsubscribe",{channel:this.channel})}},{key:"_setUnsubscribed",value:function(a){if(this._centrifuge._clearSubRefreshTimeout(this.channel),this._status!==I){var A=this._status===J;this._status=I,a===!0&&(this._recover=!1,this._noResubscribe=!0,delete this._centrifuge._lastSeq[this.channel],delete this._centrifuge._lastGen[this.channel],delete this._centrifuge._lastEpoch[this.channel]),A&&this._triggerUnsubscribe()}}},{key:"_shouldResubscribe",value:function(){return!this._noResubscribe}},{key:"_getSubscribeSuccessContext",value:function(a){var A={channel:this.channel,isResubscribe:this._isResubscribe};return a&&(A=this._centrifuge._expandSubscribeContext(A,a)),A}},{key:"_getSubscribeErrorContext",value:function(){var a=this._error;return a.channel=this.channel,a.isResubscribe=this._isResubscribe,a}},{key:"_setSubscribeData",value:function(a){this._subscribeData=a}},{key:"ready",value:function(a,A){this._ready&&(this._isSuccess()?a(this._getSubscribeSuccessContext()):A(this._getSubscribeErrorContext()))}},{key:"subscribe",value:function(a){this._status!==J&&(a&&a.since&&this._centrifuge._setSubscribeSince(this,a.since),a&&a.data&&this._setSubscribeData(a.data),this._noResubscribe=!1,this._centrifuge._subscribe(this))}},{key:"unsubscribe",value:function(){this._setUnsubscribed(!0),this._centrifuge._unsubscribe(this)}},{key:"_methodCall",value:function(){var a=this;if(this._isSuccess())return Promise.resolve();if(this._isError())return Promise.reject(this._error);var A=new Promise(function(h,E){var _=setTimeout(function(){E({code:0,message:"timeout"})},a._centrifuge._config.timeout);a._promises[a._nextPromiseId()]={timeout:_,resolve:h,reject:E}});return A}},{key:"publish",value:function(a){var A=this;return this._methodCall().then(function(){return A._centrifuge.publish(A.channel,a)})}},{key:"presence",value:function(){var a=this;return this._methodCall().then(function(){return a._centrifuge.presence(a.channel)})}},{key:"presenceStats",value:function(){var a=this;return this._methodCall().then(function(){return a._centrifuge.presenceStats(a.channel)})}},{key:"history",value:function(a){var A=this;return this._methodCall().then(function(){return A._centrifuge.history(A.channel,a)})}}]),d})(y.default);u.default=g,c.exports=u.default}),853:(function(c,u,l){Object.defineProperty(u,"__esModule",{value:!0}),u.backoff=C,u.errorExists=v,u.extend=B,u.isFunction=y,u.log=m,u.startsWith=f;function f(Q,S){return Q.lastIndexOf(S,0)===0}function y(Q){return Q==null?!1:typeof Q=="function"}function m(Q,S){if(l.g.console){var P=l.g.console[Q];y(P)&&P.apply(l.g.console,S)}}function C(Q,S,P){var k=.5*Math.random(),L=Math.min(P,S*Math.pow(2,Q+1));return Math.floor((1-k)*L)}function v(Q){return"error"in Q&&Q.error!==null}function B(Q,S){for(var P in S)S.hasOwnProperty(P)&&(Q[P]=S[P]);return Q}}),187:(function(c){var u=typeof Reflect=="object"?Reflect:null,l=u&&typeof u.apply=="function"?u.apply:function(g,p,b){return Function.prototype.apply.call(g,p,b)},f;u&&typeof u.ownKeys=="function"?f=u.ownKeys:Object.getOwnPropertySymbols?f=function(g){return Object.getOwnPropertyNames(g).concat(Object.getOwnPropertySymbols(g))}:f=function(g){return Object.getOwnPropertyNames(g)};function y(I){console&&console.warn&&console.warn(I)}var m=Number.isNaN||function(g){return g!==g};function C(){C.init.call(this)}c.exports=C,c.exports.once=K,C.EventEmitter=C,C.prototype._events=void 0,C.prototype._eventsCount=0,C.prototype._maxListeners=void 0;var v=10;function B(I){if(typeof I!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof I)}Object.defineProperty(C,"defaultMaxListeners",{enumerable:!0,get:function(){return v},set:function(I){if(typeof I!="number"||I<0||m(I))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+I+".");v=I}}),C.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},C.prototype.setMaxListeners=function(g){if(typeof g!="number"||g<0||m(g))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+g+".");return this._maxListeners=g,this};function Q(I){return I._maxListeners===void 0?C.defaultMaxListeners:I._maxListeners}C.prototype.getMaxListeners=function(){return Q(this)},C.prototype.emit=function(g){for(var p=[],b=1;b<arguments.length;b++)p.push(arguments[b]);var d=g==="error",s=this._events;if(s!==void 0)d=d&&s.error===void 0;else if(!d)return!1;if(d){var a;if(p.length>0&&(a=p[0]),a instanceof Error)throw a;var A=new Error("Unhandled error."+(a?" ("+a.message+")":""));throw A.context=a,A}var h=s[g];if(h===void 0)return!1;if(typeof h=="function")l(h,this,p);else for(var E=h.length,_=z(h,E),b=0;b<E;++b)l(_[b],this,p);return!0};function S(I,g,p,b){var d,s,a;if(B(p),s=I._events,s===void 0?(s=I._events=Object.create(null),I._eventsCount=0):(s.newListener!==void 0&&(I.emit("newListener",g,p.listener?p.listener:p),s=I._events),a=s[g]),a===void 0)a=s[g]=p,++I._eventsCount;else if(typeof a=="function"?a=s[g]=b?[p,a]:[a,p]:b?a.unshift(p):a.push(p),d=Q(I),d>0&&a.length>d&&!a.warned){a.warned=!0;var A=new Error("Possible EventEmitter memory leak detected. "+a.length+" "+String(g)+" listeners added. Use emitter.setMaxListeners() to increase limit");A.name="MaxListenersExceededWarning",A.emitter=I,A.type=g,A.count=a.length,y(A)}return I}C.prototype.addListener=function(g,p){return S(this,g,p,!1)},C.prototype.on=C.prototype.addListener,C.prototype.prependListener=function(g,p){return S(this,g,p,!0)};function P(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function k(I,g,p){var b={fired:!1,wrapFn:void 0,target:I,type:g,listener:p},d=P.bind(b);return d.listener=p,b.wrapFn=d,d}C.prototype.once=function(g,p){return B(p),this.on(g,k(this,g,p)),this},C.prototype.prependOnceListener=function(g,p){return B(p),this.prependListener(g,k(this,g,p)),this},C.prototype.removeListener=function(g,p){var b,d,s,a,A;if(B(p),d=this._events,d===void 0)return this;if(b=d[g],b===void 0)return this;if(b===p||b.listener===p)--this._eventsCount===0?this._events=Object.create(null):(delete d[g],d.removeListener&&this.emit("removeListener",g,b.listener||p));else if(typeof b!="function"){for(s=-1,a=b.length-1;a>=0;a--)if(b[a]===p||b[a].listener===p){A=b[a].listener,s=a;break}if(s<0)return this;s===0?b.shift():D(b,s),b.length===1&&(d[g]=b[0]),d.removeListener!==void 0&&this.emit("removeListener",g,A||p)}return this},C.prototype.off=C.prototype.removeListener,C.prototype.removeAllListeners=function(g){var p,b,d;if(b=this._events,b===void 0)return this;if(b.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):b[g]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete b[g]),this;if(arguments.length===0){var s=Object.keys(b),a;for(d=0;d<s.length;++d)a=s[d],a!=="removeListener"&&this.removeAllListeners(a);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(p=b[g],typeof p=="function")this.removeListener(g,p);else if(p!==void 0)for(d=p.length-1;d>=0;d--)this.removeListener(g,p[d]);return this};function L(I,g,p){var b=I._events;if(b===void 0)return[];var d=b[g];return d===void 0?[]:typeof d=="function"?p?[d.listener||d]:[d]:p?G(d):z(d,d.length)}C.prototype.listeners=function(g){return L(this,g,!0)},C.prototype.rawListeners=function(g){return L(this,g,!1)},C.listenerCount=function(I,g){return typeof I.listenerCount=="function"?I.listenerCount(g):R.call(I,g)},C.prototype.listenerCount=R;function R(I){var g=this._events;if(g!==void 0){var p=g[I];if(typeof p=="function")return 1;if(p!==void 0)return p.length}return 0}C.prototype.eventNames=function(){return this._eventsCount>0?f(this._events):[]};function z(I,g){for(var p=new Array(g),b=0;b<g;++b)p[b]=I[b];return p}function D(I,g){for(;g+1<I.length;g++)I[g]=I[g+1];I.pop()}function G(I){for(var g=new Array(I.length),p=0;p<g.length;++p)g[p]=I[p].listener||I[p];return g}function K(I,g){return new Promise(function(p,b){function d(a){I.removeListener(g,s),b(a)}function s(){typeof I.removeListener=="function"&&I.removeListener("error",d),p([].slice.call(arguments))}M(I,g,s,{once:!0}),g!=="error"&&J(I,d,{once:!0})})}function J(I,g,p){typeof I.on=="function"&&M(I,"error",g,p)}function M(I,g,p,b){if(typeof I.on=="function")b.once?I.once(g,p):I.on(g,p);else if(typeof I.addEventListener=="function")I.addEventListener(g,function d(s){b.once&&I.removeEventListener(g,d),p(s)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof I)}})},r={};function o(c){var u=r[c];if(u!==void 0)return u.exports;var l=r[c]={exports:{}};return n[c](l,l.exports,o),l.exports}(function(){o.g=(function(){if(typeof globalThis=="object")return globalThis;try{return this||new Function("return this")()}catch{if(typeof window=="object")return window}})()})();var i=o(579);return i})()})})(He)),He.exports}var Nr=Or();const Dr=Rr(Nr);let je=null;function tn(e,t){if(!(e!=null&&e.client_url)||!(e!=null&&e.token)||!(e!=null&&e.channel))return console.error("[Centrifuge] Invalid socket_connections"),null;const{client_url:n,token:r,channel:o}=e;if(o.includes("#")||console.warn("[Centrifuge] Channel should contain #user_id"),je){try{console.log("[Centrifuge] Disconnecting previous instance..."),je.disconnect()}catch(c){console.error("[Centrifuge] Error while disconnecting previous instance:",c)}je=null}console.log("[Centrifuge] Creating new instance:",n);const i=new Dr(n);return i.setToken(r),i.on("connect",c=>{console.log("[Centrifuge] Connected",c),console.log("[Centrifuge] Subscribing to channel:",o);const u=i.subscribe(o);u.on("publish",l=>{console.log("[Centrifuge] Publish event received:",l);const f=Mr(l);f&&t(f)}),u.on("subscribe",l=>{console.log("[Centrifuge] ✅ Channel subscribed successfully:",o,l)}),u.on("error",l=>{console.error("[Centrifuge] ❌ Subscription error:",l)}),u.on("unsubscribe",l=>{console.log("[Centrifuge] Channel unsubscribed:",l)})}),i.on("disconnect",c=>console.log("[Centrifuge] Disconnected",c)),i.on("error",c=>console.error("[Centrifuge] Error",c)),console.log("[Centrifuge] Calling connect()..."),i.connect(),je=i,{centrifuge:i}}function Mr(e){var n,r,o;if(console.log("[Centrifuge] Raw message received:",JSON.stringify(e)),!(e!=null&&e.data))return console.warn("[Centrifuge] Empty or invalid response"),null;let t=e.data;return(n=t.data)!=null&&n.type?t=t.data:(o=(r=t.data)==null?void 0:r.data)!=null&&o.type&&(t=t.data.data),console.log("[Centrifuge] Parsed message:",t),t.type?t:(console.warn("[Centrifuge] Message has no type:",t),null)}function Je(e){return/^4[0-9]/.test(e)?"visa":/^5[1-5]/.test(e)||/^2[2-7]/.test(e)?"mastercard":"card"}const Ae={iconType:"kaspi_pay",label:"Kaspi.kz",type:"kaspi_pay"},nn={iconType:"apple_pay",label:"Apple Pay",type:"apple_pay"},rn={iconType:"google_pay",label:"Google Pay",type:"google_pay"};function $(e){return e==="enabled"||e===!0}function on(e){if(!e)return null;let t=String(e).trim().toLowerCase();return t.startsWith("payment_method_")&&(t=t.replace("payment_method_","")),t==="kaspi"?"kaspi_pay":t==="apple"?"apple_pay":t==="google"?"google_pay":t==="newcard"?"new_card":t==="card"?"card":["kaspi_pay","apple_pay","google_pay","new_card"].includes(t)?t:null}function xr(e){var i,c,u;const t=e,n=((i=t==null?void 0:t.context)==null?void 0:i.last_payment_method)??(t==null?void 0:t.last_payment_method)??((c=t==null?void 0:t.attributes)==null?void 0:c.last_payment_method);if(!n)return null;if(typeof n=="string")return{type:on(n),cardId:null};if(typeof n!="object")return null;const r=n.type??n.payment_method??n.method,o=n.card_id??n.cardId??n.id??((u=n.card)==null?void 0:u.id)??null;return{type:on(r),cardId:o!=null?String(o):null}}function Ur(e,t,n={}){var S,P,k,L;const r=[],o=(S=e==null?void 0:e.kaspi)==null?void 0:S.data,i=((P=e==null?void 0:e.cards_v2)==null?void 0:P.data)||[],c=((L=(k=e==null?void 0:e.payment_methods)==null?void 0:k.data)==null?void 0:L.attributes)||{},u=$(c.payment_method_kaspi),l=$(c.payment_method_card),f=typeof window<"u"&&window.self===window.top,m=mt()==="ios",C=!!(n!=null&&n.onlyKaspiAvailable),v=!!(n!=null&&n.disableKaspi);return o!=null&&o.isKaspiOnly&&u&&!v?[Ae]:C?o!=null&&o.isAvailable&&u&&!v?[Ae]:[]:($(c.payment_method_apple_pay)&&!Xe("apple_pay")&&(Ue()&&f||Fe()||m||$t()===16)&&r.push(nn),o!=null&&o.isAvailable&&u&&!v&&r.push(Ae),l&&i.filter(R=>!R.isExpired).forEach(R=>{r.push({iconType:Je(R.attributes.mask),type:"card",cardId:R.id,label:`•••• ${R.attributes.mask.slice(-4)}`,cardType:R.type,isDefault:R.attributes.isDefault})}),$(c.payment_method_google_pay)&&!Xe("google_pay")&&!(n!=null&&n.disableGooglePay)&&!Ue()&&!Fe()&&r.push(rn),$(c.payment_method_new_card)&&r.push({iconType:"new_card",type:"new_card",label:t?t("newCard"):"Оплата новой картой"}),r)}function Ct(e,t={}){var Q,S,P,k;const n=(Q=e==null?void 0:e.kaspi)==null?void 0:Q.data,r=((S=e==null?void 0:e.cards_v2)==null?void 0:S.data)||[],o=((k=(P=e==null?void 0:e.payment_methods)==null?void 0:P.data)==null?void 0:k.attributes)||{},i=$(o.payment_method_kaspi),c=$(o.payment_method_card),u=!!(t!=null&&t.disableKaspi),l=typeof window<"u"&&window.self===window.top,y=mt()==="ios",m=$(o.payment_method_apple_pay)&&!Xe("apple_pay")&&(Ue()&&l||Fe()||y||$t()===16),C=$(o.payment_method_google_pay)&&!Xe("google_pay")&&!(t!=null&&t.disableGooglePay)&&!Ue()&&!Fe();if(n!=null&&n.isKaspiOnly&&i&&!u||t!=null&&t.onlyKaspiAvailable&&(n!=null&&n.isAvailable)&&i&&!u)return Ae;const v=xr(e);if((v==null?void 0:v.type)==="kaspi_pay"&&(n!=null&&n.isAvailable)&&i&&!u)return Ae;if((v==null?void 0:v.type)==="apple_pay"&&m)return nn;if((v==null?void 0:v.type)==="google_pay"&&C)return rn;if((v==null?void 0:v.type)==="new_card"&&$(o.payment_method_new_card))return{iconType:"new_card",type:"new_card",label:"Оплата новой картой"};if((v==null?void 0:v.type)==="card"&&c){const L=v.cardId!=null?r.find(R=>!R.isExpired&&String(R.id)===v.cardId):null;if(L)return{iconType:Je(L.attributes.mask),type:"card",cardId:L.id,label:`•••• ${L.attributes.mask.slice(-4)}`,cardType:L.type}}if(c){const L=r.find(R=>{var z;return((z=R.attributes)==null?void 0:z.isDefault)&&!R.isExpired});if(L)return{iconType:Je(L.attributes.mask),type:"card",cardId:L.id,label:`•••• ${L.attributes.mask.slice(-4)}`,cardType:L.type}}if(n!=null&&n.isAvailable&&i&&!u)return Ae;const B=c?r.find(L=>!L.isExpired):null;return B?{iconType:Je(B.attributes.mask),type:"card",cardId:B.id,label:`••••${B.attributes.mask.slice(-4)}`,cardType:B.type}:null}function bt(e){if(typeof localStorage>"u")return null;try{return localStorage.getItem(e)}catch{return null}}function qe(e,t){if(!(typeof localStorage>"u"))try{localStorage.setItem(e,t)}catch{}}function Ce(e){if(!(typeof localStorage>"u"))try{localStorage.removeItem(e)}catch{}}function ne(e){return e?{"X-Country":e}:{}}async function Fr(e,t){var n;try{const r=await e.json(),o=(n=r==null?void 0:r.errors)==null?void 0:n[0];return(o==null?void 0:o.title)||(o==null?void 0:o.detail)||(r==null?void 0:r.message)||(r==null?void 0:r.error)||t}catch{return`HTTP ${e.status}: ${e.statusText}`}}async function ae(e,t){const n=await Fr(e,t);throw Object.assign(new Error(n),{status:e.status})}function ze(e,t,n={}){const r=Number.isFinite(n.checkoutAmount)&&n.checkoutAmount>=0?Number(n.checkoutAmount):e.amount,o=!!n.forceBalanceMethod,i=!!n.useBalance,c=n.voucher;return{checkoutAmount:r,checkoutPaymentMethod:o?{type:"balance"}:t,useBalanceFlag:i,voucher:c}}function Ke(e,t,n,r,o){return{preorder_id:e.preorderId,terminal_id:e.terminalId,merchant_order_id:e.merchantOrderId,money:{amount:String(n),currency:e.currency},payment_method:t,...e.backlink&&{backlink:e.backlink},...r&&{use_balance:!0},...o&&{voucher:o},...e.isFridge&&{is_fridge:!0}}}async function Ge(e,t,n,r,o){const i=await fetch(`${e}/orders/v1/checkout`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t.accessToken}`,"X-Idempotency-Key":t.idempotencyKey??xe(),"X-Device-Id":n,"X-OS":"WEB",...ne(t.country)},body:JSON.stringify(r)});return i.ok||await ae(i,o),i.json()}async function sn(e,t,n,r){var f,y,m,C,v,B;const o=await fetch(`${e}/api/v2/oauth2/tokens`,{method:"POST",headers:{"Content-Type":"application/json","X-Idempotency-Key":xe(),"X-Fingerprint":Zt(),...ne(r)},body:JSON.stringify({client_id:t,grant_type:"authorization_track_id",track_id:n})});o.ok||await ae(o,"Не удалось авторизоваться через track_id");const i=await o.json(),c=(i==null?void 0:i.access_token)??((y=(f=i==null?void 0:i.data)==null?void 0:f.attributes)==null?void 0:y.access_token),u=(i==null?void 0:i.refresh_token)??((C=(m=i==null?void 0:i.data)==null?void 0:m.attributes)==null?void 0:C.refresh_token)??null,l=Number((i==null?void 0:i.expires_in)??((B=(v=i==null?void 0:i.data)==null?void 0:v.attributes)==null?void 0:B.expires_in));if(!c)throw new Error("В ответе отсутствует access_token");return{access_token:c,refresh_token:u,expires_in:Number.isFinite(l)&&l>0?l:null}}async function Xr(e,t,n,r){var f,y,m,C,v,B;const o=await fetch(`${e}/api/v2/oauth2/tokens`,{method:"POST",headers:{"Content-Type":"application/json",...ne(r)},body:JSON.stringify({client_id:t,grant_type:"refresh_token",refresh_token:n})});o.ok||await ae(o,"Не удалось обновить токен по refresh_token");const i=await o.json(),c=(i==null?void 0:i.access_token)??((y=(f=i==null?void 0:i.data)==null?void 0:f.attributes)==null?void 0:y.access_token),u=(i==null?void 0:i.refresh_token)??((C=(m=i==null?void 0:i.data)==null?void 0:m.attributes)==null?void 0:C.refresh_token)??null,l=Number((i==null?void 0:i.expires_in)??((B=(v=i==null?void 0:i.data)==null?void 0:v.attributes)==null?void 0:B.expires_in));if(!c)throw new Error("В ответе отсутствует access_token");return{access_token:c,refresh_token:u,expires_in:Number.isFinite(l)&&l>0?l:null}}async function Et(e,t){const n=await fetch(`${e}/orders/v1/checkout/context`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t.accessToken}`,"X-Idempotency-Key":xe(),...ne(t.country)},body:JSON.stringify({terminal_id:t.terminalId,include:["cards","payment_methods","balance","cashback"],money:{amount:String(t.amount),currency:t.currency}})});return n.ok||await ae(n,"Ошибка получения контекста оплаты"),n.json()}async function Hr(e,t,n){const r=await fetch(`${e}/payment-gateway/v1/cards/${n}`,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t.accessToken}`,...ne(t.country)}});return r.ok||await ae(r,"Не удалось удалить карту"),r.json().catch(()=>({}))}async function jr(e,t,n){const r=await fetch(`${e}/payment-gateway/v1/cards/${n}/mark_as_default`,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t.accessToken}`,...ne(t.country)}});return r.ok||await ae(r,"Не удалось отметить карту как основную"),r.json().catch(()=>({}))}async function an(e,t,n){const r=await fetch(`${e}/orders/v1/orders/${n}/status`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t.accessToken}`,...ne(t.country)}});if(!r.ok)throw Object.assign(new Error(`Ошибка проверки статуса заказа: ${r.status} ${r.statusText}`),{status:r.status});const o=await r.json(),i=(o==null?void 0:o.data)??o;return{data:{status:i==null?void 0:i.status,payload:(i==null?void 0:i.payload)??{}}}}async function cn(e,t,n,r,o={}){const{checkoutAmount:i,checkoutPaymentMethod:c,useBalanceFlag:u,voucher:l}=ze(t,{type:r.type,...r.cardId&&{card_id:r.cardId}},o);return Ge(e,t,n,Ke(t,c,i,u,l),"Ошибка создания заказа")}async function Jr(e,t,n,r={}){const{checkoutAmount:o,checkoutPaymentMethod:i,useBalanceFlag:c,voucher:u}=ze(t,{type:"new_card"},r);return Ge(e,t,n,Ke(t,i,o,c,u),"Ошибка создания заказа для новой карты")}async function qr(e,t){const n=await fetch(`${e}/loyalty/v6/coupons/by_terminal/${t.terminalId}/at_payment?order_pay_amount=${t.amount}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t.accessToken}`,...ne(t.country)}});return n.ok||await ae(n,"Ошибка получения купонов"),n.json()}async function un(e,t,n){const r=window.location.hostname,o={validationUrl:n,domainName:r};t.merchantName&&(o.merchantName=t.merchantName);const i=await fetch(`${e}/payment-gateway/v1/apple/session`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/vnd.api+json",Authorization:`Bearer ${t.accessToken}`,...ne(t.country)},body:JSON.stringify(o)});return i.ok||await ae(i,"Ошибка получения Apple Pay сессии"),i.json()}async function zr(e,t,n,r,o={}){const{checkoutAmount:i,checkoutPaymentMethod:c,useBalanceFlag:u,voucher:l}=ze(t,{type:"apple_pay",data:r},o);return Ge(e,t,n,Ke(t,c,i,u,l),"Ошибка создания заказа с Apple Pay")}async function ln(e,t,n,r,o={}){const{checkoutAmount:i,checkoutPaymentMethod:c,useBalanceFlag:u,voucher:l}=ze(t,{type:"google_pay",data:r},o);return Ge(e,t,n,Ke(t,c,i,u,l),"Ошибка создания заказа с Google Pay")}function Kr(e){const t=typeof e.color=="string"?e.color.trim():"",n=t&&/^[0-9a-fA-F]{3}([0-9a-fA-F]{3})?$/.test(t)?`#${t}`:t,r=e.bonuses,o=r&&typeof r=="object"&&Number.isFinite(r.amount)&&Number.isFinite(r.percent)?{availableBonus:Number.isFinite(r.availableBonus)?Number(r.availableBonus):0,amount:Number(r.amount),percent:Number(r.percent)}:null;return{preorderId:e.preorderId,trackId:e.trackId,clientId:e.clientId,projectId:e.projectId,terminalId:e.terminalId,merchantOrderId:e.merchantOrderId,amount:e.amount,currency:e.currency||"KZT",environment:e.environment||"production",backlink:e.backlink,onSuccess:e.onSuccess||(()=>{}),onAppliedBonus:e.onAppliedBonus||(()=>{}),onCouponSuppressingCashback:e.onCouponSuppressingCashback||(()=>{}),onError:e.onError||(()=>{}),onCancel:e.onCancel||(()=>{}),onCardDeleted:typeof e.onCardDeleted=="function"?e.onCardDeleted:null,onConfirmPay:typeof e.onConfirmPay=="function"?e.onConfirmPay:null,onPaymentMethodSelected:typeof e.onPaymentMethodSelected=="function"?e.onPaymentMethodSelected:null,onKaspiLink:typeof e.onKaspiLink=="function"?e.onKaspiLink:null,onPayWithGooglePay:typeof e.onPayWithGooglePay=="function"?e.onPayWithGooglePay:null,onUserEvent:typeof e.onUserEvent=="function"?e.onUserEvent:null,onBeforeCheckout:typeof e.onBeforeCheckout=="function"?e.onBeforeCheckout:null,onFreedomLink:typeof e.onFreedomLink=="function"?e.onFreedomLink:null,onRequestNewTrackId:typeof e.onRequestNewTrackId=="function"?e.onRequestNewTrackId:null,idempotencyKey:e.idempotencyKey,country:typeof e.country=="string"&&e.country.trim()||void 0,merchantName:typeof e.merchantName=="string"&&Array.from(e.merchantName.trim()).slice(0,35).join("")||void 0,locale:e.locale||"ru",containerSelector:typeof e.containerSelector=="string"?e.containerSelector.trim():"",color:n||"#2F2F2F",onlyKaspiAvailable:!!e.onlyKaspiAvailable,disableKaspi:!!e.disableKaspi,disableGooglePay:!!e.disableGooglePay,disableUseBalance:!!e.disableUseBalance,isNativeAndroid:!!e.isNativeAndroid,isFridge:!!e.isFridge,bonuses:o}}const U=typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__,de="8.55.2",j=globalThis;function We(e,t,n){const r=n||j,o=r.__SENTRY__=r.__SENTRY__||{},i=o[de]=o[de]||{};return i[e]||(i[e]=t())}const vt=typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__,Gr="Sentry Logger ",An=["debug","info","warn","error","log","assert","trace"],dn={};function Ye(e){if(!("console"in j))return e();const t=j.console,n={},r=Object.keys(dn);r.forEach(o=>{const i=dn[o];n[o]=t[o],t[o]=i});try{return e()}finally{r.forEach(o=>{t[o]=n[o]})}}function Wr(){let e=!1;const t={enable:()=>{e=!0},disable:()=>{e=!1},isEnabled:()=>e};return vt?An.forEach(n=>{t[n]=(...r)=>{e&&Ye(()=>{j.console[n](`${Gr}[${n}]:`,...r)})}}):An.forEach(n=>{t[n]=()=>{}}),t}const N=We("logger",Wr),fn=50,be="?",hn=/\(error: (.*)\)/,pn=/captureMessage|captureException/;function Yr(...e){const t=e.sort((n,r)=>n[0]-r[0]).map(n=>n[1]);return(n,r=0,o=0)=>{const i=[],c=n.split(`
5
- `);for(let u=r;u<c.length;u++){const l=c[u];if(l.length>1024)continue;const f=hn.test(l)?l.replace(hn,"$1"):l;if(!f.match(/\S*Error: /)){for(const y of t){const m=y(f);if(m){i.push(m);break}}if(i.length>=fn+o)break}}return Vr(i.slice(o))}}function Vr(e){if(!e.length)return[];const t=Array.from(e);return/sentryWrapped/.test(Ve(t).function||"")&&t.pop(),t.reverse(),pn.test(Ve(t).function||"")&&(t.pop(),pn.test(Ve(t).function||"")&&t.pop()),t.slice(0,fn).map(n=>({...n,filename:n.filename||Ve(t).filename,function:n.function||be}))}function Ve(e){return e[e.length-1]||{}}const It="<anonymous>";function Zr(e){try{return!e||typeof e!="function"?It:e.name||It}catch{return It}}function Bt(){return St(j),j}function St(e){const t=e.__SENTRY__=e.__SENTRY__||{};return t.version=t.version||de,t[de]=t[de]||{}}const gn=Object.prototype.toString;function yn(e){switch(gn.call(e)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object WebAssembly.Exception]":return!0;default:return et(e,Error)}}function Pe(e,t){return gn.call(e)===`[object ${t}]`}function mn(e){return Pe(e,"ErrorEvent")}function Cn(e){return Pe(e,"DOMError")}function $r(e){return Pe(e,"DOMException")}function bn(e){return Pe(e,"String")}function _t(e){return typeof e=="object"&&e!==null&&"__sentry_template_string__"in e&&"__sentry_template_values__"in e}function eo(e){return e===null||_t(e)||typeof e!="object"&&typeof e!="function"}function Ee(e){return Pe(e,"Object")}function Ze(e){return typeof Event<"u"&&et(e,Event)}function to(e){return typeof Element<"u"&&et(e,Element)}function $e(e){return!!(e&&e.then&&typeof e.then=="function")}function no(e){return Ee(e)&&"nativeEvent"in e&&"preventDefault"in e&&"stopPropagation"in e}function et(e,t){try{return e instanceof t}catch{return!1}}function ro(e){return!!(typeof e=="object"&&e!==null&&(e.__isVue||e._isVue))}const oo=j,so=80;function io(e,t={}){if(!e)return"<unknown>";try{let n=e;const r=5,o=[];let i=0,c=0;const u=" > ",l=u.length;let f;const y=Array.isArray(t)?t:t.keyAttrs,m=!Array.isArray(t)&&t.maxStringLength||so;for(;n&&i++<r&&(f=ao(n,y),!(f==="html"||i>1&&c+o.length*l+f.length>=m));)o.push(f),c+=f.length,n=n.parentNode;return o.reverse().join(u)}catch{return"<unknown>"}}function ao(e,t){const n=e,r=[];if(!n||!n.tagName)return"";if(oo.HTMLElement&&n instanceof HTMLElement&&n.dataset){if(n.dataset.sentryComponent)return n.dataset.sentryComponent;if(n.dataset.sentryElement)return n.dataset.sentryElement}r.push(n.tagName.toLowerCase());const o=t&&t.length?t.filter(c=>n.getAttribute(c)).map(c=>[c,n.getAttribute(c)]):null;if(o&&o.length)o.forEach(c=>{r.push(`[${c[0]}="${c[1]}"]`)});else{n.id&&r.push(`#${n.id}`);const c=n.className;if(c&&bn(c)){const u=c.split(/\s+/);for(const l of u)r.push(`.${l}`)}}const i=["aria-label","type","name","title","alt"];for(const c of i){const u=n.getAttribute(c);u&&r.push(`[${c}="${u}"]`)}return r.join("")}function we(e,t=0){return typeof e!="string"||t===0||e.length<=t?e:`${e.slice(0,t)}...`}function En(e,t,n){try{Object.defineProperty(e,t,{value:n,writable:!0,configurable:!0})}catch{vt&&N.log(`Failed to add non-enumerable property "${t}" to object`,e)}}function vn(e){if(yn(e))return{message:e.message,name:e.name,stack:e.stack,...Bn(e)};if(Ze(e)){const t={type:e.type,target:In(e.target),currentTarget:In(e.currentTarget),...Bn(e)};return typeof CustomEvent<"u"&&et(e,CustomEvent)&&(t.detail=e.detail),t}else return e}function In(e){try{return to(e)?io(e):Object.prototype.toString.call(e)}catch{return"<unknown>"}}function Bn(e){if(typeof e=="object"&&e!==null){const t={};for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t}else return{}}function co(e,t=40){const n=Object.keys(vn(e));n.sort();const r=n[0];if(!r)return"[object has no keys]";if(r.length>=t)return we(r,t);for(let o=n.length;o>0;o--){const i=n.slice(0,o).join(", ");if(!(i.length>t))return o===n.length?i:we(i,t)}return""}function Y(e){return Qt(e,new Map)}function Qt(e,t){if(uo(e)){const n=t.get(e);if(n!==void 0)return n;const r={};t.set(e,r);for(const o of Object.getOwnPropertyNames(e))typeof e[o]<"u"&&(r[o]=Qt(e[o],t));return r}if(Array.isArray(e)){const n=t.get(e);if(n!==void 0)return n;const r=[];return t.set(e,r),e.forEach(o=>{r.push(Qt(o,t))}),r}return e}function uo(e){if(!Ee(e))return!1;try{const t=Object.getPrototypeOf(e).constructor.name;return!t||t==="Object"}catch{return!0}}const Sn=1e3;function tt(){return Date.now()/Sn}function lo(){const{performance:e}=j;if(!e||!e.now)return tt;const t=Date.now()-e.now(),n=e.timeOrigin==null?t:e.timeOrigin;return()=>(n+e.now())/Sn}const _n=lo();(()=>{const{performance:e}=j;if(!e||!e.now)return;const t=3600*1e3,n=e.now(),r=Date.now(),o=e.timeOrigin?Math.abs(e.timeOrigin+n-r):t,i=o<t,c=e.timing&&e.timing.navigationStart,l=typeof c=="number"?Math.abs(c+n-r):t,f=l<t;return i||f?o<=l?e.timeOrigin:c:r})();function ee(){const e=j,t=e.crypto||e.msCrypto;let n=()=>Math.random()*16;try{if(t&&t.randomUUID)return t.randomUUID().replace(/-/g,"");t&&t.getRandomValues&&(n=()=>{const r=new Uint8Array(1);return t.getRandomValues(r),r[0]})}catch{}return("10000000100040008000"+1e11).replace(/[018]/g,r=>(r^(n()&15)>>r/4).toString(16))}function Ao(e){return e.exception&&e.exception.values?e.exception.values[0]:void 0}function Qn(e,t,n){const r=e.exception=e.exception||{},o=r.values=r.values||[],i=o[0]=o[0]||{};i.value||(i.value=t||""),i.type||(i.type="Error")}function Te(e,t){const n=Ao(e);if(!n)return;const r={type:"generic",handled:!0},o=n.mechanism;if(n.mechanism={...r,...o,...t},t&&"data"in t){const i={...o&&o.data,...t.data};n.mechanism.data=i}}function kn(e){if(fo(e))return!0;try{En(e,"__sentry_captured__",!0)}catch{}return!1}function fo(e){try{return e.__sentry_captured__}catch{}}var re;(function(e){e[e.PENDING=0]="PENDING";const n=1;e[e.RESOLVED=n]="RESOLVED";const r=2;e[e.REJECTED=r]="REJECTED"})(re||(re={}));function fe(e){return new W(t=>{t(e)})}function nt(e){return new W((t,n)=>{n(e)})}class W{constructor(t){W.prototype.__init.call(this),W.prototype.__init2.call(this),W.prototype.__init3.call(this),W.prototype.__init4.call(this),this._state=re.PENDING,this._handlers=[];try{t(this._resolve,this._reject)}catch(n){this._reject(n)}}then(t,n){return new W((r,o)=>{this._handlers.push([!1,i=>{if(!t)r(i);else try{r(t(i))}catch(c){o(c)}},i=>{if(!n)o(i);else try{r(n(i))}catch(c){o(c)}}]),this._executeHandlers()})}catch(t){return this.then(n=>n,t)}finally(t){return new W((n,r)=>{let o,i;return this.then(c=>{i=!1,o=c,t&&t()},c=>{i=!0,o=c,t&&t()}).then(()=>{if(i){r(o);return}n(o)})})}__init(){this._resolve=t=>{this._setResult(re.RESOLVED,t)}}__init2(){this._reject=t=>{this._setResult(re.REJECTED,t)}}__init3(){this._setResult=(t,n)=>{if(this._state===re.PENDING){if($e(n)){n.then(this._resolve,this._reject);return}this._state=t,this._value=n,this._executeHandlers()}}}__init4(){this._executeHandlers=()=>{if(this._state===re.PENDING)return;const t=this._handlers.slice();this._handlers=[],t.forEach(n=>{n[0]||(this._state===re.RESOLVED&&n[1](this._value),this._state===re.REJECTED&&n[2](this._value),n[0]=!0)})}}}function kt(e,t={}){if(t.user&&(!e.ipAddress&&t.user.ip_address&&(e.ipAddress=t.user.ip_address),!e.did&&!t.did&&(e.did=t.user.id||t.user.email||t.user.username)),e.timestamp=t.timestamp||_n(),t.abnormal_mechanism&&(e.abnormal_mechanism=t.abnormal_mechanism),t.ignoreDuration&&(e.ignoreDuration=t.ignoreDuration),t.sid&&(e.sid=t.sid.length===32?t.sid:ee()),t.init!==void 0&&(e.init=t.init),!e.did&&t.did&&(e.did=`${t.did}`),typeof t.started=="number"&&(e.started=t.started),e.ignoreDuration)e.duration=void 0;else if(typeof t.duration=="number")e.duration=t.duration;else{const n=e.timestamp-e.started;e.duration=n>=0?n:0}t.release&&(e.release=t.release),t.environment&&(e.environment=t.environment),!e.ipAddress&&t.ipAddress&&(e.ipAddress=t.ipAddress),!e.userAgent&&t.userAgent&&(e.userAgent=t.userAgent),typeof t.errors=="number"&&(e.errors=t.errors),t.status&&(e.status=t.status)}function Pn(){return ee()}function Pt(){return ee().substring(16)}function rt(e,t,n=2){if(!t||typeof t!="object"||n<=0)return t;if(e&&t&&Object.keys(t).length===0)return e;const r={...e};for(const o in t)Object.prototype.hasOwnProperty.call(t,o)&&(r[o]=rt(r[o],t[o],n-1));return r}const wt="_sentrySpan";function wn(e,t){t?En(e,wt,t):delete e[wt]}function Tn(e){return e[wt]}const ho=100;class Tt{constructor(){this._notifyingListeners=!1,this._scopeListeners=[],this._eventProcessors=[],this._breadcrumbs=[],this._attachments=[],this._user={},this._tags={},this._extra={},this._contexts={},this._sdkProcessingMetadata={},this._propagationContext={traceId:Pn(),spanId:Pt()}}clone(){const t=new Tt;return t._breadcrumbs=[...this._breadcrumbs],t._tags={...this._tags},t._extra={...this._extra},t._contexts={...this._contexts},this._contexts.flags&&(t._contexts.flags={values:[...this._contexts.flags.values]}),t._user=this._user,t._level=this._level,t._session=this._session,t._transactionName=this._transactionName,t._fingerprint=this._fingerprint,t._eventProcessors=[...this._eventProcessors],t._requestSession=this._requestSession,t._attachments=[...this._attachments],t._sdkProcessingMetadata={...this._sdkProcessingMetadata},t._propagationContext={...this._propagationContext},t._client=this._client,t._lastEventId=this._lastEventId,wn(t,Tn(this)),t}setClient(t){this._client=t}setLastEventId(t){this._lastEventId=t}getClient(){return this._client}lastEventId(){return this._lastEventId}addScopeListener(t){this._scopeListeners.push(t)}addEventProcessor(t){return this._eventProcessors.push(t),this}setUser(t){return this._user=t||{email:void 0,id:void 0,ip_address:void 0,username:void 0},this._session&&kt(this._session,{user:t}),this._notifyScopeListeners(),this}getUser(){return this._user}getRequestSession(){return this._requestSession}setRequestSession(t){return this._requestSession=t,this}setTags(t){return this._tags={...this._tags,...t},this._notifyScopeListeners(),this}setTag(t,n){return this._tags={...this._tags,[t]:n},this._notifyScopeListeners(),this}setExtras(t){return this._extra={...this._extra,...t},this._notifyScopeListeners(),this}setExtra(t,n){return this._extra={...this._extra,[t]:n},this._notifyScopeListeners(),this}setFingerprint(t){return this._fingerprint=t,this._notifyScopeListeners(),this}setLevel(t){return this._level=t,this._notifyScopeListeners(),this}setTransactionName(t){return this._transactionName=t,this._notifyScopeListeners(),this}setContext(t,n){return n===null?delete this._contexts[t]:this._contexts[t]=n,this._notifyScopeListeners(),this}setSession(t){return t?this._session=t:delete this._session,this._notifyScopeListeners(),this}getSession(){return this._session}update(t){if(!t)return this;const n=typeof t=="function"?t(this):t,[r,o]=n instanceof ce?[n.getScopeData(),n.getRequestSession()]:Ee(n)?[t,t.requestSession]:[],{tags:i,extra:c,user:u,contexts:l,level:f,fingerprint:y=[],propagationContext:m}=r||{};return this._tags={...this._tags,...i},this._extra={...this._extra,...c},this._contexts={...this._contexts,...l},u&&Object.keys(u).length&&(this._user=u),f&&(this._level=f),y.length&&(this._fingerprint=y),m&&(this._propagationContext=m),o&&(this._requestSession=o),this}clear(){return this._breadcrumbs=[],this._tags={},this._extra={},this._user={},this._contexts={},this._level=void 0,this._transactionName=void 0,this._fingerprint=void 0,this._requestSession=void 0,this._session=void 0,wn(this,void 0),this._attachments=[],this.setPropagationContext({traceId:Pn()}),this._notifyScopeListeners(),this}addBreadcrumb(t,n){const r=typeof n=="number"?n:ho;if(r<=0)return this;const o={timestamp:tt(),...t};return this._breadcrumbs.push(o),this._breadcrumbs.length>r&&(this._breadcrumbs=this._breadcrumbs.slice(-r),this._client&&this._client.recordDroppedEvent("buffer_overflow","log_item")),this._notifyScopeListeners(),this}getLastBreadcrumb(){return this._breadcrumbs[this._breadcrumbs.length-1]}clearBreadcrumbs(){return this._breadcrumbs=[],this._notifyScopeListeners(),this}addAttachment(t){return this._attachments.push(t),this}clearAttachments(){return this._attachments=[],this}getScopeData(){return{breadcrumbs:this._breadcrumbs,attachments:this._attachments,contexts:this._contexts,tags:this._tags,extra:this._extra,user:this._user,level:this._level,fingerprint:this._fingerprint||[],eventProcessors:this._eventProcessors,propagationContext:this._propagationContext,sdkProcessingMetadata:this._sdkProcessingMetadata,transactionName:this._transactionName,span:Tn(this)}}setSDKProcessingMetadata(t){return this._sdkProcessingMetadata=rt(this._sdkProcessingMetadata,t,2),this}setPropagationContext(t){return this._propagationContext={spanId:Pt(),...t},this}getPropagationContext(){return this._propagationContext}captureException(t,n){const r=n&&n.event_id?n.event_id:ee();if(!this._client)return N.warn("No client configured on scope - will not capture exception!"),r;const o=new Error("Sentry syntheticException");return this._client.captureException(t,{originalException:t,syntheticException:o,...n,event_id:r},this),r}captureMessage(t,n,r){const o=r&&r.event_id?r.event_id:ee();if(!this._client)return N.warn("No client configured on scope - will not capture message!"),o;const i=new Error(t);return this._client.captureMessage(t,n,{originalException:t,syntheticException:i,...r,event_id:o},this),o}captureEvent(t,n){const r=n&&n.event_id?n.event_id:ee();return this._client?(this._client.captureEvent(t,{...n,event_id:r},this),r):(N.warn("No client configured on scope - will not capture event!"),r)}_notifyScopeListeners(){this._notifyingListeners||(this._notifyingListeners=!0,this._scopeListeners.forEach(t=>{t(this)}),this._notifyingListeners=!1)}}const ce=Tt;function po(){return We("defaultCurrentScope",()=>new ce)}function go(){return We("defaultIsolationScope",()=>new ce)}class yo{constructor(t,n){let r;t?r=t:r=new ce;let o;n?o=n:o=new ce,this._stack=[{scope:r}],this._isolationScope=o}withScope(t){const n=this._pushScope();let r;try{r=t(n)}catch(o){throw this._popScope(),o}return $e(r)?r.then(o=>(this._popScope(),o),o=>{throw this._popScope(),o}):(this._popScope(),r)}getClient(){return this.getStackTop().client}getScope(){return this.getStackTop().scope}getIsolationScope(){return this._isolationScope}getStackTop(){return this._stack[this._stack.length-1]}_pushScope(){const t=this.getScope().clone();return this._stack.push({client:this.getClient(),scope:t}),t}_popScope(){return this._stack.length<=1?!1:!!this._stack.pop()}}function ve(){const e=Bt(),t=St(e);return t.stack=t.stack||new yo(po(),go())}function mo(e){return ve().withScope(e)}function Co(e,t){const n=ve();return n.withScope(()=>(n.getStackTop().scope=e,t(e)))}function Rn(e){return ve().withScope(()=>e(ve().getIsolationScope()))}function bo(){return{withIsolationScope:Rn,withScope:mo,withSetScope:Co,withSetIsolationScope:(e,t)=>Rn(t),getCurrentScope:()=>ve().getScope(),getIsolationScope:()=>ve().getIsolationScope()}}function Ln(e){const t=St(e);return t.acs?t.acs:bo()}function On(){const e=Bt();return Ln(e).getCurrentScope()}function Eo(){const e=Bt();return Ln(e).getIsolationScope()}function vo(){return We("globalScope",()=>new ce)}function Rt(){return On().getClient()}function Io(e){const t=e.getPropagationContext(),{traceId:n,spanId:r,parentSpanId:o}=t;return Y({trace_id:n,span_id:r,parent_span_id:o})}const Bo="_sentryMetrics";function So(e){const t=e[Bo];if(!t)return;const n={};for(const[,[r,o]]of t)(n[r]||(n[r]=[])).push(Y(o));return n}const _o="sentry.source",Qo="sentry.sample_rate",ko="sentry.op",Po="sentry.origin",wo=0,To=1,Ro="sentry-",Lo=/^sentry-/;function Oo(e){const t=No(e);if(!t)return;const n=Object.entries(t).reduce((r,[o,i])=>{if(o.match(Lo)){const c=o.slice(Ro.length);r[c]=i}return r},{});if(Object.keys(n).length>0)return n}function No(e){if(!(!e||!bn(e)&&!Array.isArray(e)))return Array.isArray(e)?e.reduce((t,n)=>{const r=Nn(n);return Object.entries(r).forEach(([o,i])=>{t[o]=i}),t},{}):Nn(e)}function Nn(e){return e.split(",").map(t=>t.split("=").map(n=>decodeURIComponent(n.trim()))).reduce((t,[n,r])=>(n&&r&&(t[n]=r),t),{})}const Do=1;let Dn=!1;function Mo(e){const{spanId:t,traceId:n,isRemote:r}=e.spanContext(),o=r?t:Lt(e).parent_span_id,i=r?Pt():t;return Y({parent_span_id:o,span_id:i,trace_id:n})}function Mn(e){return typeof e=="number"?xn(e):Array.isArray(e)?e[0]+e[1]/1e9:e instanceof Date?xn(e.getTime()):_n()}function xn(e){return e>9999999999?e/1e3:e}function Lt(e){if(Uo(e))return e.getSpanJSON();try{const{spanId:t,traceId:n}=e.spanContext();if(xo(e)){const{attributes:r,startTime:o,name:i,endTime:c,parentSpanId:u,status:l}=e;return Y({span_id:t,trace_id:n,data:r,description:i,parent_span_id:u,start_timestamp:Mn(o),timestamp:Mn(c)||void 0,status:Xo(l),op:r[ko],origin:r[Po],_metrics_summary:So(e)})}return{span_id:t,trace_id:n}}catch{return{}}}function xo(e){const t=e;return!!t.attributes&&!!t.startTime&&!!t.name&&!!t.endTime&&!!t.status}function Uo(e){return typeof e.getSpanJSON=="function"}function Fo(e){const{traceFlags:t}=e.spanContext();return t===Do}function Xo(e){if(!(!e||e.code===wo))return e.code===To?"ok":e.message||"unknown_error"}const Ho="_sentryRootSpan";function Un(e){return e[Ho]||e}function jo(){Dn||(Ye(()=>{console.warn("[Sentry] Deprecation warning: Returning null from `beforeSendSpan` will be disallowed from SDK version 9.0.0 onwards. The callback will only support mutating spans. To drop certain spans, configure the respective integrations directly.")}),Dn=!0)}function Jo(e){if(typeof __SENTRY_TRACING__=="boolean"&&!__SENTRY_TRACING__)return!1;const t=Rt(),n=t&&t.getOptions();return!!n&&(n.enableTracing||"tracesSampleRate"in n||"tracesSampler"in n)}const Fn="production",qo="_frozenDsc";function Xn(e,t){const n=t.getOptions(),{publicKey:r}=t.getDsn()||{},o=Y({environment:n.environment||Fn,release:n.release,public_key:r,trace_id:e});return t.emit("createDsc",o),o}function zo(e,t){const n=t.getPropagationContext();return n.dsc||Xn(n.traceId,e)}function Ko(e){const t=Rt();if(!t)return{};const n=Un(e),r=n[qo];if(r)return r;const o=n.spanContext().traceState,i=o&&o.get("sentry.dsc"),c=i&&Oo(i);if(c)return c;const u=Xn(e.spanContext().traceId,t),l=Lt(n),f=l.data||{},y=f[Qo];y!=null&&(u.sample_rate=`${y}`);const m=f[_o],C=l.description;return m!=="url"&&C&&(u.transaction=C),Jo()&&(u.sampled=String(Fo(n))),t.emit("createDsc",u,n),u}function Go(e){if(typeof e=="boolean")return Number(e);const t=typeof e=="string"?parseFloat(e):e;if(typeof t!="number"||isNaN(t)||t<0||t>1){U&&N.warn(`[Tracing] Given sample rate is invalid. Sample rate must be a boolean or a number between 0 and 1. Got ${JSON.stringify(e)} of type ${JSON.stringify(typeof e)}.`);return}return t}const Wo=/^(?:(\w+):)\/\/(?:(\w+)(?::(\w+)?)?@)([\w.-]+)(?::(\d+))?\/(.+)/;function Yo(e){return e==="http"||e==="https"}function ot(e,t=!1){const{host:n,path:r,pass:o,port:i,projectId:c,protocol:u,publicKey:l}=e;return`${u}://${l}${t&&o?`:${o}`:""}@${n}${i?`:${i}`:""}/${r&&`${r}/`}${c}`}function Vo(e){const t=Wo.exec(e);if(!t){Ye(()=>{console.error(`Invalid Sentry Dsn: ${e}`)});return}const[n,r,o="",i="",c="",u=""]=t.slice(1);let l="",f=u;const y=f.split("/");if(y.length>1&&(l=y.slice(0,-1).join("/"),f=y.pop()),f){const m=f.match(/^\d+/);m&&(f=m[0])}return Hn({host:i,pass:o,path:l,projectId:f,port:c,protocol:n,publicKey:r})}function Hn(e){return{protocol:e.protocol,publicKey:e.publicKey||"",pass:e.pass||"",host:e.host,port:e.port||"",path:e.path||"",projectId:e.projectId}}function Zo(e){if(!vt)return!0;const{port:t,projectId:n,protocol:r}=e;return["protocol","publicKey","host","projectId"].find(c=>e[c]?!1:(N.error(`Invalid Sentry Dsn: ${c} missing`),!0))?!1:n.match(/^\d+$/)?Yo(r)?t&&isNaN(parseInt(t,10))?(N.error(`Invalid Sentry Dsn: Invalid port ${t}`),!1):!0:(N.error(`Invalid Sentry Dsn: Invalid protocol ${r}`),!1):(N.error(`Invalid Sentry Dsn: Invalid projectId ${n}`),!1)}function $o(e){const t=typeof e=="string"?Vo(e):Hn(e);if(!(!t||!Zo(t)))return t}function es(){const e=typeof WeakSet=="function",t=e?new WeakSet:[];function n(o){if(e)return t.has(o)?!0:(t.add(o),!1);for(let i=0;i<t.length;i++)if(t[i]===o)return!0;return t.push(o),!1}function r(o){if(e)t.delete(o);else for(let i=0;i<t.length;i++)if(t[i]===o){t.splice(i,1);break}}return[n,r]}function oe(e,t=100,n=1/0){try{return Ot("",e,t,n)}catch(r){return{ERROR:`**non-serializable** (${r})`}}}function jn(e,t=3,n=100*1024){const r=oe(e,t);return os(r)>n?jn(e,t-1,n):r}function Ot(e,t,n=1/0,r=1/0,o=es()){const[i,c]=o;if(t==null||["boolean","string"].includes(typeof t)||typeof t=="number"&&Number.isFinite(t))return t;const u=ts(e,t);if(!u.startsWith("[object "))return u;if(t.__sentry_skip_normalization__)return t;const l=typeof t.__sentry_override_normalization_depth__=="number"?t.__sentry_override_normalization_depth__:n;if(l===0)return u.replace("object ","");if(i(t))return"[Circular ~]";const f=t;if(f&&typeof f.toJSON=="function")try{const v=f.toJSON();return Ot("",v,l-1,r,o)}catch{}const y=Array.isArray(t)?[]:{};let m=0;const C=vn(t);for(const v in C){if(!Object.prototype.hasOwnProperty.call(C,v))continue;if(m>=r){y[v]="[MaxProperties ~]";break}const B=C[v];y[v]=Ot(v,B,l-1,r,o),m++}return c(t),y}function ts(e,t){try{if(e==="domain"&&t&&typeof t=="object"&&t._events)return"[Domain]";if(e==="domainEmitter")return"[DomainEmitter]";if(typeof global<"u"&&t===global)return"[Global]";if(typeof window<"u"&&t===window)return"[Window]";if(typeof document<"u"&&t===document)return"[Document]";if(ro(t))return"[VueViewModel]";if(no(t))return"[SyntheticEvent]";if(typeof t=="number"&&!Number.isFinite(t))return`[${t}]`;if(typeof t=="function")return`[Function: ${Zr(t)}]`;if(typeof t=="symbol")return`[${String(t)}]`;if(typeof t=="bigint")return`[BigInt: ${String(t)}]`;const n=ns(t);return/^HTML(\w*)Element$/.test(n)?`[HTMLElement: ${n}]`:`[object ${n}]`}catch(n){return`**non-serializable** (${n})`}}function ns(e){const t=Object.getPrototypeOf(e);return t?t.constructor.name:"null prototype"}function rs(e){return~-encodeURI(e).split(/%..|./).length}function os(e){return rs(JSON.stringify(e))}function Re(e,t=[]){return[e,t]}function ss(e,t){const[n,r]=e;return[n,[...r,t]]}function Jn(e,t){const n=e[1];for(const r of n){const o=r[0].type;if(t(r,o))return!0}return!1}function Nt(e){return j.__SENTRY__&&j.__SENTRY__.encodePolyfill?j.__SENTRY__.encodePolyfill(e):new TextEncoder().encode(e)}function is(e){const[t,n]=e;let r=JSON.stringify(t);function o(i){typeof r=="string"?r=typeof i=="string"?r+i:[Nt(r),i]:r.push(typeof i=="string"?Nt(i):i)}for(const i of n){const[c,u]=i;if(o(`
4
+ `).filter(function(k){return k!==""}).map(function(k){return JSON.parse(k)})}},{key:"decodeCommandResult",value:function(P,k){return k}},{key:"decodePush",value:function(P){return P}},{key:"decodePushData",value:function(P,k){return k}}]),Q})();u.JsonDecoder=B}),471:(function(c,u,l){function f(p){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?f=function(d){return typeof d}:f=function(d){return d&&typeof Symbol=="function"&&d.constructor===Symbol&&d!==Symbol.prototype?"symbol":typeof d},f(p)}Object.defineProperty(u,"__esModule",{value:!0}),u.default=void 0;var y=C(l(187)),m=l(853);function C(p){return p&&p.__esModule?p:{default:p}}function v(p,b){if(!(p instanceof b))throw new TypeError("Cannot call a class as a function")}function B(p,b){for(var d=0;d<b.length;d++){var s=b[d];s.enumerable=s.enumerable||!1,s.configurable=!0,"value"in s&&(s.writable=!0),Object.defineProperty(p,s.key,s)}}function Q(p,b,d){return b&&B(p.prototype,b),p}function S(p,b){if(typeof b!="function"&&b!==null)throw new TypeError("Super expression must either be null or a function");p.prototype=Object.create(b&&b.prototype,{constructor:{value:p,writable:!0,configurable:!0}}),b&&P(p,b)}function P(p,b){return P=Object.setPrototypeOf||function(s,a){return s.__proto__=a,s},P(p,b)}function k(p){var b=z();return function(){var s=D(p),a;if(b){var A=D(this).constructor;a=Reflect.construct(s,arguments,A)}else a=s.apply(this,arguments);return L(this,a)}}function L(p,b){if(b&&(f(b)==="object"||typeof b=="function"))return b;if(b!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return R(p)}function R(p){if(p===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return p}function z(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}function D(p){return D=Object.setPrototypeOf?Object.getPrototypeOf:function(d){return d.__proto__||Object.getPrototypeOf(d)},D(p)}var G=0,K=1,J=2,M=3,I=4,g=(function(p){S(d,p);var b=k(d);function d(s,a,A){var h;return v(this,d),h=b.call(this),h.channel=a,h._centrifuge=s,h._status=G,h._error=null,h._isResubscribe=!1,h._ready=!1,h._subscriptionPromise=null,h._noResubscribe=!1,h._recoverable=!1,h._recover=!1,h._setEvents(A),h._initializePromise(),h._promises={},h._promiseId=0,h._subscribeData=null,h.on("error",function(E){this._centrifuge._debug("subscription error",E)}),h}return Q(d,[{key:"_nextPromiseId",value:function(){return++this._promiseId}},{key:"_initializePromise",value:function(){var a=this;this._ready=!1,this._subscriptionPromise=new Promise(function(A,h){a._resolve=function(E){a._ready=!0,A(E)},a._reject=function(E){a._ready=!0,h(E)}}).then(function(){},function(){})}},{key:"_setNeedRecover",value:function(a){this._recoverable=a,this._recover=a}},{key:"_needRecover",value:function(){return this._recoverable===!0&&this._recover===!0}},{key:"_setEvents",value:function(a){if(a){if((0,m.isFunction)(a))this.on("publish",a);else if(Object.prototype.toString.call(a)===Object.prototype.toString.call({}))for(var A=["publish","join","leave","unsubscribe","subscribe","error"],h=0,E=A.length;h<E;h++){var _=A[h];_ in a&&this.on(_,a[_])}}}},{key:"_isNew",value:function(){return this._status===G}},{key:"_isUnsubscribed",value:function(){return this._status===I}},{key:"_isSubscribing",value:function(){return this._status===K}},{key:"_isReady",value:function(){return this._status===J||this._status===M}},{key:"_isSuccess",value:function(){return this._status===J}},{key:"_isError",value:function(){return this._status===M}},{key:"_setNew",value:function(){this._status=G}},{key:"_setSubscribing",value:function(a){this._isResubscribe=a||!1,this._ready===!0&&this._initializePromise(),this._status=K}},{key:"_setSubscribeSuccess",value:function(a){if(this._status!==J){this._status=J;var A=this._getSubscribeSuccessContext(a);this._recover=!1,this.emit("subscribe",A),this._resolve(A);for(var h in this._promises)clearTimeout(this._promises[h].timeout),this._promises[h].resolve(),delete this._promises[h]}}},{key:"_setSubscribeError",value:function(a){if(this._status!==M){this._status=M,this._error=a;var A=this._getSubscribeErrorContext();this.emit("error",A),this._reject(A);for(var h in this._promises)clearTimeout(this._promises[h].timeout),this._promises[h].reject(a),delete this._promises[h]}}},{key:"_triggerUnsubscribe",value:function(){this.emit("unsubscribe",{channel:this.channel})}},{key:"_setUnsubscribed",value:function(a){if(this._centrifuge._clearSubRefreshTimeout(this.channel),this._status!==I){var A=this._status===J;this._status=I,a===!0&&(this._recover=!1,this._noResubscribe=!0,delete this._centrifuge._lastSeq[this.channel],delete this._centrifuge._lastGen[this.channel],delete this._centrifuge._lastEpoch[this.channel]),A&&this._triggerUnsubscribe()}}},{key:"_shouldResubscribe",value:function(){return!this._noResubscribe}},{key:"_getSubscribeSuccessContext",value:function(a){var A={channel:this.channel,isResubscribe:this._isResubscribe};return a&&(A=this._centrifuge._expandSubscribeContext(A,a)),A}},{key:"_getSubscribeErrorContext",value:function(){var a=this._error;return a.channel=this.channel,a.isResubscribe=this._isResubscribe,a}},{key:"_setSubscribeData",value:function(a){this._subscribeData=a}},{key:"ready",value:function(a,A){this._ready&&(this._isSuccess()?a(this._getSubscribeSuccessContext()):A(this._getSubscribeErrorContext()))}},{key:"subscribe",value:function(a){this._status!==J&&(a&&a.since&&this._centrifuge._setSubscribeSince(this,a.since),a&&a.data&&this._setSubscribeData(a.data),this._noResubscribe=!1,this._centrifuge._subscribe(this))}},{key:"unsubscribe",value:function(){this._setUnsubscribed(!0),this._centrifuge._unsubscribe(this)}},{key:"_methodCall",value:function(){var a=this;if(this._isSuccess())return Promise.resolve();if(this._isError())return Promise.reject(this._error);var A=new Promise(function(h,E){var _=setTimeout(function(){E({code:0,message:"timeout"})},a._centrifuge._config.timeout);a._promises[a._nextPromiseId()]={timeout:_,resolve:h,reject:E}});return A}},{key:"publish",value:function(a){var A=this;return this._methodCall().then(function(){return A._centrifuge.publish(A.channel,a)})}},{key:"presence",value:function(){var a=this;return this._methodCall().then(function(){return a._centrifuge.presence(a.channel)})}},{key:"presenceStats",value:function(){var a=this;return this._methodCall().then(function(){return a._centrifuge.presenceStats(a.channel)})}},{key:"history",value:function(a){var A=this;return this._methodCall().then(function(){return A._centrifuge.history(A.channel,a)})}}]),d})(y.default);u.default=g,c.exports=u.default}),853:(function(c,u,l){Object.defineProperty(u,"__esModule",{value:!0}),u.backoff=C,u.errorExists=v,u.extend=B,u.isFunction=y,u.log=m,u.startsWith=f;function f(Q,S){return Q.lastIndexOf(S,0)===0}function y(Q){return Q==null?!1:typeof Q=="function"}function m(Q,S){if(l.g.console){var P=l.g.console[Q];y(P)&&P.apply(l.g.console,S)}}function C(Q,S,P){var k=.5*Math.random(),L=Math.min(P,S*Math.pow(2,Q+1));return Math.floor((1-k)*L)}function v(Q){return"error"in Q&&Q.error!==null}function B(Q,S){for(var P in S)S.hasOwnProperty(P)&&(Q[P]=S[P]);return Q}}),187:(function(c){var u=typeof Reflect=="object"?Reflect:null,l=u&&typeof u.apply=="function"?u.apply:function(g,p,b){return Function.prototype.apply.call(g,p,b)},f;u&&typeof u.ownKeys=="function"?f=u.ownKeys:Object.getOwnPropertySymbols?f=function(g){return Object.getOwnPropertyNames(g).concat(Object.getOwnPropertySymbols(g))}:f=function(g){return Object.getOwnPropertyNames(g)};function y(I){console&&console.warn&&console.warn(I)}var m=Number.isNaN||function(g){return g!==g};function C(){C.init.call(this)}c.exports=C,c.exports.once=K,C.EventEmitter=C,C.prototype._events=void 0,C.prototype._eventsCount=0,C.prototype._maxListeners=void 0;var v=10;function B(I){if(typeof I!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof I)}Object.defineProperty(C,"defaultMaxListeners",{enumerable:!0,get:function(){return v},set:function(I){if(typeof I!="number"||I<0||m(I))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+I+".");v=I}}),C.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},C.prototype.setMaxListeners=function(g){if(typeof g!="number"||g<0||m(g))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+g+".");return this._maxListeners=g,this};function Q(I){return I._maxListeners===void 0?C.defaultMaxListeners:I._maxListeners}C.prototype.getMaxListeners=function(){return Q(this)},C.prototype.emit=function(g){for(var p=[],b=1;b<arguments.length;b++)p.push(arguments[b]);var d=g==="error",s=this._events;if(s!==void 0)d=d&&s.error===void 0;else if(!d)return!1;if(d){var a;if(p.length>0&&(a=p[0]),a instanceof Error)throw a;var A=new Error("Unhandled error."+(a?" ("+a.message+")":""));throw A.context=a,A}var h=s[g];if(h===void 0)return!1;if(typeof h=="function")l(h,this,p);else for(var E=h.length,_=z(h,E),b=0;b<E;++b)l(_[b],this,p);return!0};function S(I,g,p,b){var d,s,a;if(B(p),s=I._events,s===void 0?(s=I._events=Object.create(null),I._eventsCount=0):(s.newListener!==void 0&&(I.emit("newListener",g,p.listener?p.listener:p),s=I._events),a=s[g]),a===void 0)a=s[g]=p,++I._eventsCount;else if(typeof a=="function"?a=s[g]=b?[p,a]:[a,p]:b?a.unshift(p):a.push(p),d=Q(I),d>0&&a.length>d&&!a.warned){a.warned=!0;var A=new Error("Possible EventEmitter memory leak detected. "+a.length+" "+String(g)+" listeners added. Use emitter.setMaxListeners() to increase limit");A.name="MaxListenersExceededWarning",A.emitter=I,A.type=g,A.count=a.length,y(A)}return I}C.prototype.addListener=function(g,p){return S(this,g,p,!1)},C.prototype.on=C.prototype.addListener,C.prototype.prependListener=function(g,p){return S(this,g,p,!0)};function P(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function k(I,g,p){var b={fired:!1,wrapFn:void 0,target:I,type:g,listener:p},d=P.bind(b);return d.listener=p,b.wrapFn=d,d}C.prototype.once=function(g,p){return B(p),this.on(g,k(this,g,p)),this},C.prototype.prependOnceListener=function(g,p){return B(p),this.prependListener(g,k(this,g,p)),this},C.prototype.removeListener=function(g,p){var b,d,s,a,A;if(B(p),d=this._events,d===void 0)return this;if(b=d[g],b===void 0)return this;if(b===p||b.listener===p)--this._eventsCount===0?this._events=Object.create(null):(delete d[g],d.removeListener&&this.emit("removeListener",g,b.listener||p));else if(typeof b!="function"){for(s=-1,a=b.length-1;a>=0;a--)if(b[a]===p||b[a].listener===p){A=b[a].listener,s=a;break}if(s<0)return this;s===0?b.shift():D(b,s),b.length===1&&(d[g]=b[0]),d.removeListener!==void 0&&this.emit("removeListener",g,A||p)}return this},C.prototype.off=C.prototype.removeListener,C.prototype.removeAllListeners=function(g){var p,b,d;if(b=this._events,b===void 0)return this;if(b.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):b[g]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete b[g]),this;if(arguments.length===0){var s=Object.keys(b),a;for(d=0;d<s.length;++d)a=s[d],a!=="removeListener"&&this.removeAllListeners(a);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(p=b[g],typeof p=="function")this.removeListener(g,p);else if(p!==void 0)for(d=p.length-1;d>=0;d--)this.removeListener(g,p[d]);return this};function L(I,g,p){var b=I._events;if(b===void 0)return[];var d=b[g];return d===void 0?[]:typeof d=="function"?p?[d.listener||d]:[d]:p?G(d):z(d,d.length)}C.prototype.listeners=function(g){return L(this,g,!0)},C.prototype.rawListeners=function(g){return L(this,g,!1)},C.listenerCount=function(I,g){return typeof I.listenerCount=="function"?I.listenerCount(g):R.call(I,g)},C.prototype.listenerCount=R;function R(I){var g=this._events;if(g!==void 0){var p=g[I];if(typeof p=="function")return 1;if(p!==void 0)return p.length}return 0}C.prototype.eventNames=function(){return this._eventsCount>0?f(this._events):[]};function z(I,g){for(var p=new Array(g),b=0;b<g;++b)p[b]=I[b];return p}function D(I,g){for(;g+1<I.length;g++)I[g]=I[g+1];I.pop()}function G(I){for(var g=new Array(I.length),p=0;p<g.length;++p)g[p]=I[p].listener||I[p];return g}function K(I,g){return new Promise(function(p,b){function d(a){I.removeListener(g,s),b(a)}function s(){typeof I.removeListener=="function"&&I.removeListener("error",d),p([].slice.call(arguments))}M(I,g,s,{once:!0}),g!=="error"&&J(I,d,{once:!0})})}function J(I,g,p){typeof I.on=="function"&&M(I,"error",g,p)}function M(I,g,p,b){if(typeof I.on=="function")b.once?I.once(g,p):I.on(g,p);else if(typeof I.addEventListener=="function")I.addEventListener(g,function d(s){b.once&&I.removeEventListener(g,d),p(s)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof I)}})},r={};function o(c){var u=r[c];if(u!==void 0)return u.exports;var l=r[c]={exports:{}};return n[c](l,l.exports,o),l.exports}(function(){o.g=(function(){if(typeof globalThis=="object")return globalThis;try{return this||new Function("return this")()}catch{if(typeof window=="object")return window}})()})();var i=o(579);return i})()})})(He)),He.exports}var Nr=Or();const Dr=Rr(Nr);let je=null;function tn(e,t){if(!(e!=null&&e.client_url)||!(e!=null&&e.token)||!(e!=null&&e.channel))return console.error("[Centrifuge] Invalid socket_connections"),null;const{client_url:n,token:r,channel:o}=e;if(o.includes("#")||console.warn("[Centrifuge] Channel should contain #user_id"),je){try{console.log("[Centrifuge] Disconnecting previous instance..."),je.disconnect()}catch(c){console.error("[Centrifuge] Error while disconnecting previous instance:",c)}je=null}console.log("[Centrifuge] Creating new instance:",n);const i=new Dr(n);return i.setToken(r),i.on("connect",c=>{console.log("[Centrifuge] Connected",c),console.log("[Centrifuge] Subscribing to channel:",o);const u=i.subscribe(o);u.on("publish",l=>{console.log("[Centrifuge] Publish event received:",l);const f=Mr(l);f&&t(f)}),u.on("subscribe",l=>{console.log("[Centrifuge] ✅ Channel subscribed successfully:",o,l)}),u.on("error",l=>{console.error("[Centrifuge] ❌ Subscription error:",l)}),u.on("unsubscribe",l=>{console.log("[Centrifuge] Channel unsubscribed:",l)})}),i.on("disconnect",c=>console.log("[Centrifuge] Disconnected",c)),i.on("error",c=>console.error("[Centrifuge] Error",c)),console.log("[Centrifuge] Calling connect()..."),i.connect(),je=i,{centrifuge:i}}function Mr(e){var n,r,o;if(console.log("[Centrifuge] Raw message received:",JSON.stringify(e)),!(e!=null&&e.data))return console.warn("[Centrifuge] Empty or invalid response"),null;let t=e.data;return(n=t.data)!=null&&n.type?t=t.data:(o=(r=t.data)==null?void 0:r.data)!=null&&o.type&&(t=t.data.data),console.log("[Centrifuge] Parsed message:",t),t.type?t:(console.warn("[Centrifuge] Message has no type:",t),null)}function Je(e){return/^4[0-9]/.test(e)?"visa":/^5[1-5]/.test(e)||/^2[2-7]/.test(e)?"mastercard":"card"}const Ae={iconType:"kaspi_pay",label:"Kaspi.kz",type:"kaspi_pay"},nn={iconType:"apple_pay",label:"Apple Pay",type:"apple_pay"},rn={iconType:"google_pay",label:"Google Pay",type:"google_pay"};function $(e){return e==="enabled"||e===!0}function on(e){if(!e)return null;let t=String(e).trim().toLowerCase();return t.startsWith("payment_method_")&&(t=t.replace("payment_method_","")),t==="kaspi"?"kaspi_pay":t==="apple"?"apple_pay":t==="google"?"google_pay":t==="newcard"?"new_card":t==="card"?"card":["kaspi_pay","apple_pay","google_pay","new_card"].includes(t)?t:null}function xr(e){var i,c,u;const t=e,n=((i=t==null?void 0:t.context)==null?void 0:i.last_payment_method)??(t==null?void 0:t.last_payment_method)??((c=t==null?void 0:t.attributes)==null?void 0:c.last_payment_method);if(!n)return null;if(typeof n=="string")return{type:on(n),cardId:null};if(typeof n!="object")return null;const r=n.type??n.payment_method??n.method,o=n.card_id??n.cardId??n.id??((u=n.card)==null?void 0:u.id)??null;return{type:on(r),cardId:o!=null?String(o):null}}function Ur(e,t,n={}){var S,P,k,L;const r=[],o=(S=e==null?void 0:e.kaspi)==null?void 0:S.data,i=((P=e==null?void 0:e.cards_v2)==null?void 0:P.data)||[],c=((L=(k=e==null?void 0:e.payment_methods)==null?void 0:k.data)==null?void 0:L.attributes)||{},u=$(c.payment_method_kaspi),l=$(c.payment_method_card),f=typeof window<"u"&&window.self===window.top,m=mt()==="ios",C=!!(n!=null&&n.onlyKaspiAvailable),v=!!(n!=null&&n.disableKaspi);return o!=null&&o.isKaspiOnly&&u&&!v?[Ae]:C?o!=null&&o.isAvailable&&u&&!v?[Ae]:[]:($(c.payment_method_apple_pay)&&!Xe("apple_pay")&&(Ue()&&f||Fe()||m||$t()===16)&&r.push(nn),o!=null&&o.isAvailable&&u&&!v&&r.push(Ae),l&&i.filter(R=>!R.isExpired).forEach(R=>{r.push({iconType:Je(R.attributes.mask),type:"card",cardId:R.id,label:`•••• ${R.attributes.mask.slice(-4)}`,cardType:R.type,isDefault:R.attributes.isDefault})}),$(c.payment_method_google_pay)&&!Xe("google_pay")&&!(n!=null&&n.disableGooglePay)&&!Ue()&&!Fe()&&r.push(rn),$(c.payment_method_new_card)&&r.push({iconType:"new_card",type:"new_card",label:t?t("newCard"):"Оплата новой картой"}),r)}function Ct(e,t={}){var Q,S,P,k;const n=(Q=e==null?void 0:e.kaspi)==null?void 0:Q.data,r=((S=e==null?void 0:e.cards_v2)==null?void 0:S.data)||[],o=((k=(P=e==null?void 0:e.payment_methods)==null?void 0:P.data)==null?void 0:k.attributes)||{},i=$(o.payment_method_kaspi),c=$(o.payment_method_card),u=!!(t!=null&&t.disableKaspi),l=typeof window<"u"&&window.self===window.top,y=mt()==="ios",m=$(o.payment_method_apple_pay)&&!Xe("apple_pay")&&(Ue()&&l||Fe()||y||$t()===16),C=$(o.payment_method_google_pay)&&!Xe("google_pay")&&!(t!=null&&t.disableGooglePay)&&!Ue()&&!Fe();if(n!=null&&n.isKaspiOnly&&i&&!u||t!=null&&t.onlyKaspiAvailable&&(n!=null&&n.isAvailable)&&i&&!u)return Ae;const v=xr(e);if((v==null?void 0:v.type)==="kaspi_pay"&&(n!=null&&n.isAvailable)&&i&&!u)return Ae;if((v==null?void 0:v.type)==="apple_pay"&&m)return nn;if((v==null?void 0:v.type)==="google_pay"&&C)return rn;if((v==null?void 0:v.type)==="new_card"&&$(o.payment_method_new_card))return{iconType:"new_card",type:"new_card",label:"Оплата новой картой"};if((v==null?void 0:v.type)==="card"&&c){const L=v.cardId!=null?r.find(R=>!R.isExpired&&String(R.id)===v.cardId):null;if(L)return{iconType:Je(L.attributes.mask),type:"card",cardId:L.id,label:`•••• ${L.attributes.mask.slice(-4)}`,cardType:L.type}}if(c){const L=r.find(R=>{var z;return((z=R.attributes)==null?void 0:z.isDefault)&&!R.isExpired});if(L)return{iconType:Je(L.attributes.mask),type:"card",cardId:L.id,label:`•••• ${L.attributes.mask.slice(-4)}`,cardType:L.type}}if(n!=null&&n.isAvailable&&i&&!u)return Ae;const B=c?r.find(L=>!L.isExpired):null;return B?{iconType:Je(B.attributes.mask),type:"card",cardId:B.id,label:`••••${B.attributes.mask.slice(-4)}`,cardType:B.type}:null}function bt(e){if(typeof localStorage>"u")return null;try{return localStorage.getItem(e)}catch{return null}}function qe(e,t){if(!(typeof localStorage>"u"))try{localStorage.setItem(e,t)}catch{}}function Ce(e){if(!(typeof localStorage>"u"))try{localStorage.removeItem(e)}catch{}}function re(e){return e?{"X-Country":e}:{}}async function Fr(e,t){var n;try{const r=await e.json(),o=(n=r==null?void 0:r.errors)==null?void 0:n[0];return(o==null?void 0:o.title)||(o==null?void 0:o.detail)||(r==null?void 0:r.message)||(r==null?void 0:r.error)||t}catch{return`HTTP ${e.status}: ${e.statusText}`}}async function ae(e,t){const n=await Fr(e,t);throw Object.assign(new Error(n),{status:e.status})}function ze(e,t,n={}){const r=Number.isFinite(n.checkoutAmount)&&n.checkoutAmount>=0?Number(n.checkoutAmount):e.amount,o=!!n.forceBalanceMethod,i=!!n.useBalance,c=n.voucher;return{checkoutAmount:r,checkoutPaymentMethod:o?{type:"balance"}:t,useBalanceFlag:i,voucher:c}}function Ke(e,t,n,r,o){return{preorder_id:e.preorderId,terminal_id:e.terminalId,merchant_order_id:e.merchantOrderId,money:{amount:String(n),currency:e.currency},payment_method:t,...e.backlink&&{backlink:e.backlink},...r&&{use_balance:!0},...o&&{voucher:o},...e.isFridge&&{is_fridge:!0}}}async function Ge(e,t,n,r,o){const i=await fetch(`${e}/orders/v1/checkout`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t.accessToken}`,"X-Idempotency-Key":t.idempotencyKey??xe(),"X-Device-Id":n,"X-OS":"WEB",...re(t.country)},body:JSON.stringify(r)});return i.ok||await ae(i,o),i.json()}async function sn(e,t,n,r){var f,y,m,C,v,B;const o=await fetch(`${e}/api/v2/oauth2/tokens`,{method:"POST",headers:{"Content-Type":"application/json","X-Idempotency-Key":xe(),"X-Fingerprint":Zt(),...re(r)},body:JSON.stringify({client_id:t,grant_type:"authorization_track_id",track_id:n})});o.ok||await ae(o,"Не удалось авторизоваться через track_id");const i=await o.json(),c=(i==null?void 0:i.access_token)??((y=(f=i==null?void 0:i.data)==null?void 0:f.attributes)==null?void 0:y.access_token),u=(i==null?void 0:i.refresh_token)??((C=(m=i==null?void 0:i.data)==null?void 0:m.attributes)==null?void 0:C.refresh_token)??null,l=Number((i==null?void 0:i.expires_in)??((B=(v=i==null?void 0:i.data)==null?void 0:v.attributes)==null?void 0:B.expires_in));if(!c)throw new Error("В ответе отсутствует access_token");return{access_token:c,refresh_token:u,expires_in:Number.isFinite(l)&&l>0?l:null}}async function Xr(e,t,n,r){var f,y,m,C,v,B;const o=await fetch(`${e}/api/v2/oauth2/tokens`,{method:"POST",headers:{"Content-Type":"application/json",...re(r)},body:JSON.stringify({client_id:t,grant_type:"refresh_token",refresh_token:n})});o.ok||await ae(o,"Не удалось обновить токен по refresh_token");const i=await o.json(),c=(i==null?void 0:i.access_token)??((y=(f=i==null?void 0:i.data)==null?void 0:f.attributes)==null?void 0:y.access_token),u=(i==null?void 0:i.refresh_token)??((C=(m=i==null?void 0:i.data)==null?void 0:m.attributes)==null?void 0:C.refresh_token)??null,l=Number((i==null?void 0:i.expires_in)??((B=(v=i==null?void 0:i.data)==null?void 0:v.attributes)==null?void 0:B.expires_in));if(!c)throw new Error("В ответе отсутствует access_token");return{access_token:c,refresh_token:u,expires_in:Number.isFinite(l)&&l>0?l:null}}async function Et(e,t){const n=await fetch(`${e}/orders/v1/checkout/context`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t.accessToken}`,"X-Idempotency-Key":xe(),...re(t.country)},body:JSON.stringify({terminal_id:t.terminalId,include:["cards","payment_methods","balance","cashback"],money:{amount:String(t.amount),currency:t.currency}})});return n.ok||await ae(n,"Ошибка получения контекста оплаты"),n.json()}async function Hr(e,t,n){const r=await fetch(`${e}/payment-gateway/v1/cards/${n}`,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t.accessToken}`,...re(t.country)}});return r.ok||await ae(r,"Не удалось удалить карту"),r.json().catch(()=>({}))}async function jr(e,t,n){const r=await fetch(`${e}/payment-gateway/v1/cards/${n}/mark_as_default`,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t.accessToken}`,...re(t.country)}});return r.ok||await ae(r,"Не удалось отметить карту как основную"),r.json().catch(()=>({}))}async function an(e,t,n){const r=await fetch(`${e}/orders/v1/orders/${n}/status`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t.accessToken}`,...re(t.country)}});if(!r.ok)throw Object.assign(new Error(`Ошибка проверки статуса заказа: ${r.status} ${r.statusText}`),{status:r.status});const o=await r.json(),i=(o==null?void 0:o.data)??o;return{data:{status:i==null?void 0:i.status,payload:(i==null?void 0:i.payload)??{}}}}async function cn(e,t,n,r,o={}){const{checkoutAmount:i,checkoutPaymentMethod:c,useBalanceFlag:u,voucher:l}=ze(t,{type:r.type,...r.cardId&&{card_id:r.cardId}},o);return Ge(e,t,n,Ke(t,c,i,u,l),"Ошибка создания заказа")}async function Jr(e,t,n,r={}){const{checkoutAmount:o,checkoutPaymentMethod:i,useBalanceFlag:c,voucher:u}=ze(t,{type:"new_card"},r);return Ge(e,t,n,Ke(t,i,o,c,u),"Ошибка создания заказа для новой карты")}async function qr(e,t){const n=await fetch(`${e}/loyalty/v6/coupons/by_terminal/${t.terminalId}/at_payment?order_pay_amount=${t.amount}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t.accessToken}`,...re(t.country)}});return n.ok||await ae(n,"Ошибка получения купонов"),n.json()}async function un(e,t,n){const r=window.location.hostname,o={validationUrl:n,domainName:r};t.merchantName&&(o.merchantName=t.merchantName);const i=await fetch(`${e}/payment-gateway/v1/apple/session`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/vnd.api+json",Authorization:`Bearer ${t.accessToken}`,...re(t.country)},body:JSON.stringify(o)});return i.ok||await ae(i,"Ошибка получения Apple Pay сессии"),i.json()}async function zr(e,t,n,r,o={}){const{checkoutAmount:i,checkoutPaymentMethod:c,useBalanceFlag:u,voucher:l}=ze(t,{type:"apple_pay",data:r},o);return Ge(e,t,n,Ke(t,c,i,u,l),"Ошибка создания заказа с Apple Pay")}async function ln(e,t,n,r,o={}){const{checkoutAmount:i,checkoutPaymentMethod:c,useBalanceFlag:u,voucher:l}=ze(t,{type:"google_pay",data:r},o);return Ge(e,t,n,Ke(t,c,i,u,l),"Ошибка создания заказа с Google Pay")}function Kr(e){const t=typeof e.color=="string"?e.color.trim():"",n=t&&/^[0-9a-fA-F]{3}([0-9a-fA-F]{3})?$/.test(t)?`#${t}`:t,r=e.bonuses,o=r&&typeof r=="object"&&Number.isFinite(r.amount)&&Number.isFinite(r.percent)?{availableBonus:Number.isFinite(r.availableBonus)?Number(r.availableBonus):0,amount:Number(r.amount),percent:Number(r.percent)}:null;return{preorderId:e.preorderId,trackId:e.trackId,clientId:e.clientId,projectId:e.projectId,terminalId:e.terminalId,merchantOrderId:e.merchantOrderId,amount:e.amount,currency:e.currency||"KZT",environment:e.environment||"production",backlink:e.backlink,onSuccess:e.onSuccess||(()=>{}),onAppliedBonus:e.onAppliedBonus||(()=>{}),onCouponSuppressingCashback:e.onCouponSuppressingCashback||(()=>{}),onError:e.onError||(()=>{}),onCancel:e.onCancel||(()=>{}),onCardDeleted:typeof e.onCardDeleted=="function"?e.onCardDeleted:null,onConfirmPay:typeof e.onConfirmPay=="function"?e.onConfirmPay:null,onPaymentMethodSelected:typeof e.onPaymentMethodSelected=="function"?e.onPaymentMethodSelected:null,onKaspiLink:typeof e.onKaspiLink=="function"?e.onKaspiLink:null,onPayWithGooglePay:typeof e.onPayWithGooglePay=="function"?e.onPayWithGooglePay:null,onUserEvent:typeof e.onUserEvent=="function"?e.onUserEvent:null,onBeforeCheckout:typeof e.onBeforeCheckout=="function"?e.onBeforeCheckout:null,onFreedomLink:typeof e.onFreedomLink=="function"?e.onFreedomLink:null,onRequestNewTrackId:typeof e.onRequestNewTrackId=="function"?e.onRequestNewTrackId:null,idempotencyKey:e.idempotencyKey,country:typeof e.country=="string"&&e.country.trim()||void 0,merchantName:typeof e.merchantName=="string"&&Array.from(e.merchantName.trim()).slice(0,35).join("")||void 0,locale:e.locale||"ru",containerSelector:typeof e.containerSelector=="string"?e.containerSelector.trim():"",color:n||"#2F2F2F",onlyKaspiAvailable:!!e.onlyKaspiAvailable,disableKaspi:!!e.disableKaspi,disableGooglePay:!!e.disableGooglePay,disableUseBalance:!!e.disableUseBalance,isNativeAndroid:!!e.isNativeAndroid,isFridge:!!e.isFridge,bonuses:o}}const U=typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__,de="8.55.2",j=globalThis;function We(e,t,n){const r=n||j,o=r.__SENTRY__=r.__SENTRY__||{},i=o[de]=o[de]||{};return i[e]||(i[e]=t())}const vt=typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__,Gr="Sentry Logger ",An=["debug","info","warn","error","log","assert","trace"],dn={};function Ye(e){if(!("console"in j))return e();const t=j.console,n={},r=Object.keys(dn);r.forEach(o=>{const i=dn[o];n[o]=t[o],t[o]=i});try{return e()}finally{r.forEach(o=>{t[o]=n[o]})}}function Wr(){let e=!1;const t={enable:()=>{e=!0},disable:()=>{e=!1},isEnabled:()=>e};return vt?An.forEach(n=>{t[n]=(...r)=>{e&&Ye(()=>{j.console[n](`${Gr}[${n}]:`,...r)})}}):An.forEach(n=>{t[n]=()=>{}}),t}const N=We("logger",Wr),fn=50,be="?",hn=/\(error: (.*)\)/,pn=/captureMessage|captureException/;function Yr(...e){const t=e.sort((n,r)=>n[0]-r[0]).map(n=>n[1]);return(n,r=0,o=0)=>{const i=[],c=n.split(`
5
+ `);for(let u=r;u<c.length;u++){const l=c[u];if(l.length>1024)continue;const f=hn.test(l)?l.replace(hn,"$1"):l;if(!f.match(/\S*Error: /)){for(const y of t){const m=y(f);if(m){i.push(m);break}}if(i.length>=fn+o)break}}return Vr(i.slice(o))}}function Vr(e){if(!e.length)return[];const t=Array.from(e);return/sentryWrapped/.test(Ve(t).function||"")&&t.pop(),t.reverse(),pn.test(Ve(t).function||"")&&(t.pop(),pn.test(Ve(t).function||"")&&t.pop()),t.slice(0,fn).map(n=>({...n,filename:n.filename||Ve(t).filename,function:n.function||be}))}function Ve(e){return e[e.length-1]||{}}const It="<anonymous>";function Zr(e){try{return!e||typeof e!="function"?It:e.name||It}catch{return It}}function Bt(){return St(j),j}function St(e){const t=e.__SENTRY__=e.__SENTRY__||{};return t.version=t.version||de,t[de]=t[de]||{}}const gn=Object.prototype.toString;function yn(e){switch(gn.call(e)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object WebAssembly.Exception]":return!0;default:return et(e,Error)}}function Pe(e,t){return gn.call(e)===`[object ${t}]`}function mn(e){return Pe(e,"ErrorEvent")}function Cn(e){return Pe(e,"DOMError")}function $r(e){return Pe(e,"DOMException")}function bn(e){return Pe(e,"String")}function _t(e){return typeof e=="object"&&e!==null&&"__sentry_template_string__"in e&&"__sentry_template_values__"in e}function eo(e){return e===null||_t(e)||typeof e!="object"&&typeof e!="function"}function Ee(e){return Pe(e,"Object")}function Ze(e){return typeof Event<"u"&&et(e,Event)}function to(e){return typeof Element<"u"&&et(e,Element)}function $e(e){return!!(e&&e.then&&typeof e.then=="function")}function no(e){return Ee(e)&&"nativeEvent"in e&&"preventDefault"in e&&"stopPropagation"in e}function et(e,t){try{return e instanceof t}catch{return!1}}function ro(e){return!!(typeof e=="object"&&e!==null&&(e.__isVue||e._isVue))}const oo=j,so=80;function io(e,t={}){if(!e)return"<unknown>";try{let n=e;const r=5,o=[];let i=0,c=0;const u=" > ",l=u.length;let f;const y=Array.isArray(t)?t:t.keyAttrs,m=!Array.isArray(t)&&t.maxStringLength||so;for(;n&&i++<r&&(f=ao(n,y),!(f==="html"||i>1&&c+o.length*l+f.length>=m));)o.push(f),c+=f.length,n=n.parentNode;return o.reverse().join(u)}catch{return"<unknown>"}}function ao(e,t){const n=e,r=[];if(!n||!n.tagName)return"";if(oo.HTMLElement&&n instanceof HTMLElement&&n.dataset){if(n.dataset.sentryComponent)return n.dataset.sentryComponent;if(n.dataset.sentryElement)return n.dataset.sentryElement}r.push(n.tagName.toLowerCase());const o=t&&t.length?t.filter(c=>n.getAttribute(c)).map(c=>[c,n.getAttribute(c)]):null;if(o&&o.length)o.forEach(c=>{r.push(`[${c[0]}="${c[1]}"]`)});else{n.id&&r.push(`#${n.id}`);const c=n.className;if(c&&bn(c)){const u=c.split(/\s+/);for(const l of u)r.push(`.${l}`)}}const i=["aria-label","type","name","title","alt"];for(const c of i){const u=n.getAttribute(c);u&&r.push(`[${c}="${u}"]`)}return r.join("")}function we(e,t=0){return typeof e!="string"||t===0||e.length<=t?e:`${e.slice(0,t)}...`}function En(e,t,n){try{Object.defineProperty(e,t,{value:n,writable:!0,configurable:!0})}catch{vt&&N.log(`Failed to add non-enumerable property "${t}" to object`,e)}}function vn(e){if(yn(e))return{message:e.message,name:e.name,stack:e.stack,...Bn(e)};if(Ze(e)){const t={type:e.type,target:In(e.target),currentTarget:In(e.currentTarget),...Bn(e)};return typeof CustomEvent<"u"&&et(e,CustomEvent)&&(t.detail=e.detail),t}else return e}function In(e){try{return to(e)?io(e):Object.prototype.toString.call(e)}catch{return"<unknown>"}}function Bn(e){if(typeof e=="object"&&e!==null){const t={};for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t}else return{}}function co(e,t=40){const n=Object.keys(vn(e));n.sort();const r=n[0];if(!r)return"[object has no keys]";if(r.length>=t)return we(r,t);for(let o=n.length;o>0;o--){const i=n.slice(0,o).join(", ");if(!(i.length>t))return o===n.length?i:we(i,t)}return""}function Y(e){return Qt(e,new Map)}function Qt(e,t){if(uo(e)){const n=t.get(e);if(n!==void 0)return n;const r={};t.set(e,r);for(const o of Object.getOwnPropertyNames(e))typeof e[o]<"u"&&(r[o]=Qt(e[o],t));return r}if(Array.isArray(e)){const n=t.get(e);if(n!==void 0)return n;const r=[];return t.set(e,r),e.forEach(o=>{r.push(Qt(o,t))}),r}return e}function uo(e){if(!Ee(e))return!1;try{const t=Object.getPrototypeOf(e).constructor.name;return!t||t==="Object"}catch{return!0}}const Sn=1e3;function tt(){return Date.now()/Sn}function lo(){const{performance:e}=j;if(!e||!e.now)return tt;const t=Date.now()-e.now(),n=e.timeOrigin==null?t:e.timeOrigin;return()=>(n+e.now())/Sn}const _n=lo();(()=>{const{performance:e}=j;if(!e||!e.now)return;const t=3600*1e3,n=e.now(),r=Date.now(),o=e.timeOrigin?Math.abs(e.timeOrigin+n-r):t,i=o<t,c=e.timing&&e.timing.navigationStart,l=typeof c=="number"?Math.abs(c+n-r):t,f=l<t;return i||f?o<=l?e.timeOrigin:c:r})();function ee(){const e=j,t=e.crypto||e.msCrypto;let n=()=>Math.random()*16;try{if(t&&t.randomUUID)return t.randomUUID().replace(/-/g,"");t&&t.getRandomValues&&(n=()=>{const r=new Uint8Array(1);return t.getRandomValues(r),r[0]})}catch{}return("10000000100040008000"+1e11).replace(/[018]/g,r=>(r^(n()&15)>>r/4).toString(16))}function Ao(e){return e.exception&&e.exception.values?e.exception.values[0]:void 0}function Qn(e,t,n){const r=e.exception=e.exception||{},o=r.values=r.values||[],i=o[0]=o[0]||{};i.value||(i.value=t||""),i.type||(i.type="Error")}function Te(e,t){const n=Ao(e);if(!n)return;const r={type:"generic",handled:!0},o=n.mechanism;if(n.mechanism={...r,...o,...t},t&&"data"in t){const i={...o&&o.data,...t.data};n.mechanism.data=i}}function kn(e){if(fo(e))return!0;try{En(e,"__sentry_captured__",!0)}catch{}return!1}function fo(e){try{return e.__sentry_captured__}catch{}}var oe;(function(e){e[e.PENDING=0]="PENDING";const n=1;e[e.RESOLVED=n]="RESOLVED";const r=2;e[e.REJECTED=r]="REJECTED"})(oe||(oe={}));function fe(e){return new W(t=>{t(e)})}function nt(e){return new W((t,n)=>{n(e)})}class W{constructor(t){W.prototype.__init.call(this),W.prototype.__init2.call(this),W.prototype.__init3.call(this),W.prototype.__init4.call(this),this._state=oe.PENDING,this._handlers=[];try{t(this._resolve,this._reject)}catch(n){this._reject(n)}}then(t,n){return new W((r,o)=>{this._handlers.push([!1,i=>{if(!t)r(i);else try{r(t(i))}catch(c){o(c)}},i=>{if(!n)o(i);else try{r(n(i))}catch(c){o(c)}}]),this._executeHandlers()})}catch(t){return this.then(n=>n,t)}finally(t){return new W((n,r)=>{let o,i;return this.then(c=>{i=!1,o=c,t&&t()},c=>{i=!0,o=c,t&&t()}).then(()=>{if(i){r(o);return}n(o)})})}__init(){this._resolve=t=>{this._setResult(oe.RESOLVED,t)}}__init2(){this._reject=t=>{this._setResult(oe.REJECTED,t)}}__init3(){this._setResult=(t,n)=>{if(this._state===oe.PENDING){if($e(n)){n.then(this._resolve,this._reject);return}this._state=t,this._value=n,this._executeHandlers()}}}__init4(){this._executeHandlers=()=>{if(this._state===oe.PENDING)return;const t=this._handlers.slice();this._handlers=[],t.forEach(n=>{n[0]||(this._state===oe.RESOLVED&&n[1](this._value),this._state===oe.REJECTED&&n[2](this._value),n[0]=!0)})}}}function kt(e,t={}){if(t.user&&(!e.ipAddress&&t.user.ip_address&&(e.ipAddress=t.user.ip_address),!e.did&&!t.did&&(e.did=t.user.id||t.user.email||t.user.username)),e.timestamp=t.timestamp||_n(),t.abnormal_mechanism&&(e.abnormal_mechanism=t.abnormal_mechanism),t.ignoreDuration&&(e.ignoreDuration=t.ignoreDuration),t.sid&&(e.sid=t.sid.length===32?t.sid:ee()),t.init!==void 0&&(e.init=t.init),!e.did&&t.did&&(e.did=`${t.did}`),typeof t.started=="number"&&(e.started=t.started),e.ignoreDuration)e.duration=void 0;else if(typeof t.duration=="number")e.duration=t.duration;else{const n=e.timestamp-e.started;e.duration=n>=0?n:0}t.release&&(e.release=t.release),t.environment&&(e.environment=t.environment),!e.ipAddress&&t.ipAddress&&(e.ipAddress=t.ipAddress),!e.userAgent&&t.userAgent&&(e.userAgent=t.userAgent),typeof t.errors=="number"&&(e.errors=t.errors),t.status&&(e.status=t.status)}function Pn(){return ee()}function Pt(){return ee().substring(16)}function rt(e,t,n=2){if(!t||typeof t!="object"||n<=0)return t;if(e&&t&&Object.keys(t).length===0)return e;const r={...e};for(const o in t)Object.prototype.hasOwnProperty.call(t,o)&&(r[o]=rt(r[o],t[o],n-1));return r}const wt="_sentrySpan";function wn(e,t){t?En(e,wt,t):delete e[wt]}function Tn(e){return e[wt]}const ho=100;class Tt{constructor(){this._notifyingListeners=!1,this._scopeListeners=[],this._eventProcessors=[],this._breadcrumbs=[],this._attachments=[],this._user={},this._tags={},this._extra={},this._contexts={},this._sdkProcessingMetadata={},this._propagationContext={traceId:Pn(),spanId:Pt()}}clone(){const t=new Tt;return t._breadcrumbs=[...this._breadcrumbs],t._tags={...this._tags},t._extra={...this._extra},t._contexts={...this._contexts},this._contexts.flags&&(t._contexts.flags={values:[...this._contexts.flags.values]}),t._user=this._user,t._level=this._level,t._session=this._session,t._transactionName=this._transactionName,t._fingerprint=this._fingerprint,t._eventProcessors=[...this._eventProcessors],t._requestSession=this._requestSession,t._attachments=[...this._attachments],t._sdkProcessingMetadata={...this._sdkProcessingMetadata},t._propagationContext={...this._propagationContext},t._client=this._client,t._lastEventId=this._lastEventId,wn(t,Tn(this)),t}setClient(t){this._client=t}setLastEventId(t){this._lastEventId=t}getClient(){return this._client}lastEventId(){return this._lastEventId}addScopeListener(t){this._scopeListeners.push(t)}addEventProcessor(t){return this._eventProcessors.push(t),this}setUser(t){return this._user=t||{email:void 0,id:void 0,ip_address:void 0,username:void 0},this._session&&kt(this._session,{user:t}),this._notifyScopeListeners(),this}getUser(){return this._user}getRequestSession(){return this._requestSession}setRequestSession(t){return this._requestSession=t,this}setTags(t){return this._tags={...this._tags,...t},this._notifyScopeListeners(),this}setTag(t,n){return this._tags={...this._tags,[t]:n},this._notifyScopeListeners(),this}setExtras(t){return this._extra={...this._extra,...t},this._notifyScopeListeners(),this}setExtra(t,n){return this._extra={...this._extra,[t]:n},this._notifyScopeListeners(),this}setFingerprint(t){return this._fingerprint=t,this._notifyScopeListeners(),this}setLevel(t){return this._level=t,this._notifyScopeListeners(),this}setTransactionName(t){return this._transactionName=t,this._notifyScopeListeners(),this}setContext(t,n){return n===null?delete this._contexts[t]:this._contexts[t]=n,this._notifyScopeListeners(),this}setSession(t){return t?this._session=t:delete this._session,this._notifyScopeListeners(),this}getSession(){return this._session}update(t){if(!t)return this;const n=typeof t=="function"?t(this):t,[r,o]=n instanceof ce?[n.getScopeData(),n.getRequestSession()]:Ee(n)?[t,t.requestSession]:[],{tags:i,extra:c,user:u,contexts:l,level:f,fingerprint:y=[],propagationContext:m}=r||{};return this._tags={...this._tags,...i},this._extra={...this._extra,...c},this._contexts={...this._contexts,...l},u&&Object.keys(u).length&&(this._user=u),f&&(this._level=f),y.length&&(this._fingerprint=y),m&&(this._propagationContext=m),o&&(this._requestSession=o),this}clear(){return this._breadcrumbs=[],this._tags={},this._extra={},this._user={},this._contexts={},this._level=void 0,this._transactionName=void 0,this._fingerprint=void 0,this._requestSession=void 0,this._session=void 0,wn(this,void 0),this._attachments=[],this.setPropagationContext({traceId:Pn()}),this._notifyScopeListeners(),this}addBreadcrumb(t,n){const r=typeof n=="number"?n:ho;if(r<=0)return this;const o={timestamp:tt(),...t};return this._breadcrumbs.push(o),this._breadcrumbs.length>r&&(this._breadcrumbs=this._breadcrumbs.slice(-r),this._client&&this._client.recordDroppedEvent("buffer_overflow","log_item")),this._notifyScopeListeners(),this}getLastBreadcrumb(){return this._breadcrumbs[this._breadcrumbs.length-1]}clearBreadcrumbs(){return this._breadcrumbs=[],this._notifyScopeListeners(),this}addAttachment(t){return this._attachments.push(t),this}clearAttachments(){return this._attachments=[],this}getScopeData(){return{breadcrumbs:this._breadcrumbs,attachments:this._attachments,contexts:this._contexts,tags:this._tags,extra:this._extra,user:this._user,level:this._level,fingerprint:this._fingerprint||[],eventProcessors:this._eventProcessors,propagationContext:this._propagationContext,sdkProcessingMetadata:this._sdkProcessingMetadata,transactionName:this._transactionName,span:Tn(this)}}setSDKProcessingMetadata(t){return this._sdkProcessingMetadata=rt(this._sdkProcessingMetadata,t,2),this}setPropagationContext(t){return this._propagationContext={spanId:Pt(),...t},this}getPropagationContext(){return this._propagationContext}captureException(t,n){const r=n&&n.event_id?n.event_id:ee();if(!this._client)return N.warn("No client configured on scope - will not capture exception!"),r;const o=new Error("Sentry syntheticException");return this._client.captureException(t,{originalException:t,syntheticException:o,...n,event_id:r},this),r}captureMessage(t,n,r){const o=r&&r.event_id?r.event_id:ee();if(!this._client)return N.warn("No client configured on scope - will not capture message!"),o;const i=new Error(t);return this._client.captureMessage(t,n,{originalException:t,syntheticException:i,...r,event_id:o},this),o}captureEvent(t,n){const r=n&&n.event_id?n.event_id:ee();return this._client?(this._client.captureEvent(t,{...n,event_id:r},this),r):(N.warn("No client configured on scope - will not capture event!"),r)}_notifyScopeListeners(){this._notifyingListeners||(this._notifyingListeners=!0,this._scopeListeners.forEach(t=>{t(this)}),this._notifyingListeners=!1)}}const ce=Tt;function po(){return We("defaultCurrentScope",()=>new ce)}function go(){return We("defaultIsolationScope",()=>new ce)}class yo{constructor(t,n){let r;t?r=t:r=new ce;let o;n?o=n:o=new ce,this._stack=[{scope:r}],this._isolationScope=o}withScope(t){const n=this._pushScope();let r;try{r=t(n)}catch(o){throw this._popScope(),o}return $e(r)?r.then(o=>(this._popScope(),o),o=>{throw this._popScope(),o}):(this._popScope(),r)}getClient(){return this.getStackTop().client}getScope(){return this.getStackTop().scope}getIsolationScope(){return this._isolationScope}getStackTop(){return this._stack[this._stack.length-1]}_pushScope(){const t=this.getScope().clone();return this._stack.push({client:this.getClient(),scope:t}),t}_popScope(){return this._stack.length<=1?!1:!!this._stack.pop()}}function ve(){const e=Bt(),t=St(e);return t.stack=t.stack||new yo(po(),go())}function mo(e){return ve().withScope(e)}function Co(e,t){const n=ve();return n.withScope(()=>(n.getStackTop().scope=e,t(e)))}function Rn(e){return ve().withScope(()=>e(ve().getIsolationScope()))}function bo(){return{withIsolationScope:Rn,withScope:mo,withSetScope:Co,withSetIsolationScope:(e,t)=>Rn(t),getCurrentScope:()=>ve().getScope(),getIsolationScope:()=>ve().getIsolationScope()}}function Ln(e){const t=St(e);return t.acs?t.acs:bo()}function On(){const e=Bt();return Ln(e).getCurrentScope()}function Eo(){const e=Bt();return Ln(e).getIsolationScope()}function vo(){return We("globalScope",()=>new ce)}function Rt(){return On().getClient()}function Io(e){const t=e.getPropagationContext(),{traceId:n,spanId:r,parentSpanId:o}=t;return Y({trace_id:n,span_id:r,parent_span_id:o})}const Bo="_sentryMetrics";function So(e){const t=e[Bo];if(!t)return;const n={};for(const[,[r,o]]of t)(n[r]||(n[r]=[])).push(Y(o));return n}const _o="sentry.source",Qo="sentry.sample_rate",ko="sentry.op",Po="sentry.origin",wo=0,To=1,Ro="sentry-",Lo=/^sentry-/;function Oo(e){const t=No(e);if(!t)return;const n=Object.entries(t).reduce((r,[o,i])=>{if(o.match(Lo)){const c=o.slice(Ro.length);r[c]=i}return r},{});if(Object.keys(n).length>0)return n}function No(e){if(!(!e||!bn(e)&&!Array.isArray(e)))return Array.isArray(e)?e.reduce((t,n)=>{const r=Nn(n);return Object.entries(r).forEach(([o,i])=>{t[o]=i}),t},{}):Nn(e)}function Nn(e){return e.split(",").map(t=>t.split("=").map(n=>decodeURIComponent(n.trim()))).reduce((t,[n,r])=>(n&&r&&(t[n]=r),t),{})}const Do=1;let Dn=!1;function Mo(e){const{spanId:t,traceId:n,isRemote:r}=e.spanContext(),o=r?t:Lt(e).parent_span_id,i=r?Pt():t;return Y({parent_span_id:o,span_id:i,trace_id:n})}function Mn(e){return typeof e=="number"?xn(e):Array.isArray(e)?e[0]+e[1]/1e9:e instanceof Date?xn(e.getTime()):_n()}function xn(e){return e>9999999999?e/1e3:e}function Lt(e){if(Uo(e))return e.getSpanJSON();try{const{spanId:t,traceId:n}=e.spanContext();if(xo(e)){const{attributes:r,startTime:o,name:i,endTime:c,parentSpanId:u,status:l}=e;return Y({span_id:t,trace_id:n,data:r,description:i,parent_span_id:u,start_timestamp:Mn(o),timestamp:Mn(c)||void 0,status:Xo(l),op:r[ko],origin:r[Po],_metrics_summary:So(e)})}return{span_id:t,trace_id:n}}catch{return{}}}function xo(e){const t=e;return!!t.attributes&&!!t.startTime&&!!t.name&&!!t.endTime&&!!t.status}function Uo(e){return typeof e.getSpanJSON=="function"}function Fo(e){const{traceFlags:t}=e.spanContext();return t===Do}function Xo(e){if(!(!e||e.code===wo))return e.code===To?"ok":e.message||"unknown_error"}const Ho="_sentryRootSpan";function Un(e){return e[Ho]||e}function jo(){Dn||(Ye(()=>{console.warn("[Sentry] Deprecation warning: Returning null from `beforeSendSpan` will be disallowed from SDK version 9.0.0 onwards. The callback will only support mutating spans. To drop certain spans, configure the respective integrations directly.")}),Dn=!0)}function Jo(e){if(typeof __SENTRY_TRACING__=="boolean"&&!__SENTRY_TRACING__)return!1;const t=Rt(),n=t&&t.getOptions();return!!n&&(n.enableTracing||"tracesSampleRate"in n||"tracesSampler"in n)}const Fn="production",qo="_frozenDsc";function Xn(e,t){const n=t.getOptions(),{publicKey:r}=t.getDsn()||{},o=Y({environment:n.environment||Fn,release:n.release,public_key:r,trace_id:e});return t.emit("createDsc",o),o}function zo(e,t){const n=t.getPropagationContext();return n.dsc||Xn(n.traceId,e)}function Ko(e){const t=Rt();if(!t)return{};const n=Un(e),r=n[qo];if(r)return r;const o=n.spanContext().traceState,i=o&&o.get("sentry.dsc"),c=i&&Oo(i);if(c)return c;const u=Xn(e.spanContext().traceId,t),l=Lt(n),f=l.data||{},y=f[Qo];y!=null&&(u.sample_rate=`${y}`);const m=f[_o],C=l.description;return m!=="url"&&C&&(u.transaction=C),Jo()&&(u.sampled=String(Fo(n))),t.emit("createDsc",u,n),u}function Go(e){if(typeof e=="boolean")return Number(e);const t=typeof e=="string"?parseFloat(e):e;if(typeof t!="number"||isNaN(t)||t<0||t>1){U&&N.warn(`[Tracing] Given sample rate is invalid. Sample rate must be a boolean or a number between 0 and 1. Got ${JSON.stringify(e)} of type ${JSON.stringify(typeof e)}.`);return}return t}const Wo=/^(?:(\w+):)\/\/(?:(\w+)(?::(\w+)?)?@)([\w.-]+)(?::(\d+))?\/(.+)/;function Yo(e){return e==="http"||e==="https"}function ot(e,t=!1){const{host:n,path:r,pass:o,port:i,projectId:c,protocol:u,publicKey:l}=e;return`${u}://${l}${t&&o?`:${o}`:""}@${n}${i?`:${i}`:""}/${r&&`${r}/`}${c}`}function Vo(e){const t=Wo.exec(e);if(!t){Ye(()=>{console.error(`Invalid Sentry Dsn: ${e}`)});return}const[n,r,o="",i="",c="",u=""]=t.slice(1);let l="",f=u;const y=f.split("/");if(y.length>1&&(l=y.slice(0,-1).join("/"),f=y.pop()),f){const m=f.match(/^\d+/);m&&(f=m[0])}return Hn({host:i,pass:o,path:l,projectId:f,port:c,protocol:n,publicKey:r})}function Hn(e){return{protocol:e.protocol,publicKey:e.publicKey||"",pass:e.pass||"",host:e.host,port:e.port||"",path:e.path||"",projectId:e.projectId}}function Zo(e){if(!vt)return!0;const{port:t,projectId:n,protocol:r}=e;return["protocol","publicKey","host","projectId"].find(c=>e[c]?!1:(N.error(`Invalid Sentry Dsn: ${c} missing`),!0))?!1:n.match(/^\d+$/)?Yo(r)?t&&isNaN(parseInt(t,10))?(N.error(`Invalid Sentry Dsn: Invalid port ${t}`),!1):!0:(N.error(`Invalid Sentry Dsn: Invalid protocol ${r}`),!1):(N.error(`Invalid Sentry Dsn: Invalid projectId ${n}`),!1)}function $o(e){const t=typeof e=="string"?Vo(e):Hn(e);if(!(!t||!Zo(t)))return t}function es(){const e=typeof WeakSet=="function",t=e?new WeakSet:[];function n(o){if(e)return t.has(o)?!0:(t.add(o),!1);for(let i=0;i<t.length;i++)if(t[i]===o)return!0;return t.push(o),!1}function r(o){if(e)t.delete(o);else for(let i=0;i<t.length;i++)if(t[i]===o){t.splice(i,1);break}}return[n,r]}function se(e,t=100,n=1/0){try{return Ot("",e,t,n)}catch(r){return{ERROR:`**non-serializable** (${r})`}}}function jn(e,t=3,n=100*1024){const r=se(e,t);return os(r)>n?jn(e,t-1,n):r}function Ot(e,t,n=1/0,r=1/0,o=es()){const[i,c]=o;if(t==null||["boolean","string"].includes(typeof t)||typeof t=="number"&&Number.isFinite(t))return t;const u=ts(e,t);if(!u.startsWith("[object "))return u;if(t.__sentry_skip_normalization__)return t;const l=typeof t.__sentry_override_normalization_depth__=="number"?t.__sentry_override_normalization_depth__:n;if(l===0)return u.replace("object ","");if(i(t))return"[Circular ~]";const f=t;if(f&&typeof f.toJSON=="function")try{const v=f.toJSON();return Ot("",v,l-1,r,o)}catch{}const y=Array.isArray(t)?[]:{};let m=0;const C=vn(t);for(const v in C){if(!Object.prototype.hasOwnProperty.call(C,v))continue;if(m>=r){y[v]="[MaxProperties ~]";break}const B=C[v];y[v]=Ot(v,B,l-1,r,o),m++}return c(t),y}function ts(e,t){try{if(e==="domain"&&t&&typeof t=="object"&&t._events)return"[Domain]";if(e==="domainEmitter")return"[DomainEmitter]";if(typeof global<"u"&&t===global)return"[Global]";if(typeof window<"u"&&t===window)return"[Window]";if(typeof document<"u"&&t===document)return"[Document]";if(ro(t))return"[VueViewModel]";if(no(t))return"[SyntheticEvent]";if(typeof t=="number"&&!Number.isFinite(t))return`[${t}]`;if(typeof t=="function")return`[Function: ${Zr(t)}]`;if(typeof t=="symbol")return`[${String(t)}]`;if(typeof t=="bigint")return`[BigInt: ${String(t)}]`;const n=ns(t);return/^HTML(\w*)Element$/.test(n)?`[HTMLElement: ${n}]`:`[object ${n}]`}catch(n){return`**non-serializable** (${n})`}}function ns(e){const t=Object.getPrototypeOf(e);return t?t.constructor.name:"null prototype"}function rs(e){return~-encodeURI(e).split(/%..|./).length}function os(e){return rs(JSON.stringify(e))}function Re(e,t=[]){return[e,t]}function ss(e,t){const[n,r]=e;return[n,[...r,t]]}function Jn(e,t){const n=e[1];for(const r of n){const o=r[0].type;if(t(r,o))return!0}return!1}function Nt(e){return j.__SENTRY__&&j.__SENTRY__.encodePolyfill?j.__SENTRY__.encodePolyfill(e):new TextEncoder().encode(e)}function is(e){const[t,n]=e;let r=JSON.stringify(t);function o(i){typeof r=="string"?r=typeof i=="string"?r+i:[Nt(r),i]:r.push(typeof i=="string"?Nt(i):i)}for(const i of n){const[c,u]=i;if(o(`
6
6
  ${JSON.stringify(c)}
7
- `),typeof u=="string"||u instanceof Uint8Array)o(u);else{let l;try{l=JSON.stringify(u)}catch{l=JSON.stringify(oe(u))}o(l)}}return typeof r=="string"?r:as(r)}function as(e){const t=e.reduce((o,i)=>o+i.length,0),n=new Uint8Array(t);let r=0;for(const o of e)n.set(o,r),r+=o.length;return n}function cs(e){const t=typeof e.data=="string"?Nt(e.data):e.data;return[Y({type:"attachment",length:t.length,filename:e.filename,content_type:e.contentType,attachment_type:e.attachmentType}),t]}const us={session:"session",sessions:"session",attachment:"attachment",transaction:"transaction",event:"error",client_report:"internal",user_report:"default",profile:"profile",profile_chunk:"profile",replay_event:"replay",replay_recording:"replay",check_in:"monitor",feedback:"feedback",span:"span",statsd:"metric_bucket",raw_security:"security"};function qn(e){return us[e]}function zn(e){if(!e||!e.sdk)return;const{name:t,version:n}=e.sdk;return{name:t,version:n}}function ls(e,t,n,r){const o=e.sdkProcessingMetadata&&e.sdkProcessingMetadata.dynamicSamplingContext;return{event_id:e.event_id,sent_at:new Date().toISOString(),...t&&{sdk:t},...!!n&&r&&{dsn:ot(r)},...o&&{trace:Y({...o})}}}function As(e,t){return t&&(e.sdk=e.sdk||{},e.sdk.name=e.sdk.name||t.name,e.sdk.version=e.sdk.version||t.version,e.sdk.integrations=[...e.sdk.integrations||[],...t.integrations||[]],e.sdk.packages=[...e.sdk.packages||[],...t.packages||[]]),e}function ds(e,t,n,r){const o=zn(n),i={sent_at:new Date().toISOString(),...o&&{sdk:o},...!!r&&t&&{dsn:ot(t)}},c="aggregates"in e?[{type:"sessions"},e]:[{type:"session"},e.toJSON()];return Re(i,[c])}function fs(e,t,n,r){const o=zn(n),i=e.type&&e.type!=="replay_event"?e.type:"event";As(e,n&&n.sdk);const c=ls(e,o,r,t);return delete e.sdkProcessingMetadata,Re(c,[[{type:i},e]])}function Dt(e,t,n,r=0){return new W((o,i)=>{const c=e[r];if(t===null||typeof c!="function")o(t);else{const u=c({...t},n);U&&c.id&&u===null&&N.log(`Event processor "${c.id}" dropped event`),$e(u)?u.then(l=>Dt(e,l,n,r+1).then(o)).then(null,i):Dt(e,u,n,r+1).then(o).then(null,i)}})}let st,Kn,it;function hs(e){const t=j._sentryDebugIds;if(!t)return{};const n=Object.keys(t);return it&&n.length===Kn||(Kn=n.length,it=n.reduce((r,o)=>{st||(st={});const i=st[o];if(i)r[i[0]]=i[1];else{const c=e(o);for(let u=c.length-1;u>=0;u--){const l=c[u],f=l&&l.filename,y=t[o];if(f&&y){r[f]=y,st[o]=[f,y];break}}}return r},{})),it}function ps(e,t){const{fingerprint:n,span:r,breadcrumbs:o,sdkProcessingMetadata:i}=t;gs(e,t),r&&Cs(e,r),bs(e,n),ys(e,o),ms(e,i)}function Gn(e,t){const{extra:n,tags:r,user:o,contexts:i,level:c,sdkProcessingMetadata:u,breadcrumbs:l,fingerprint:f,eventProcessors:y,attachments:m,propagationContext:C,transactionName:v,span:B}=t;at(e,"extra",n),at(e,"tags",r),at(e,"user",o),at(e,"contexts",i),e.sdkProcessingMetadata=rt(e.sdkProcessingMetadata,u,2),c&&(e.level=c),v&&(e.transactionName=v),B&&(e.span=B),l.length&&(e.breadcrumbs=[...e.breadcrumbs,...l]),f.length&&(e.fingerprint=[...e.fingerprint,...f]),y.length&&(e.eventProcessors=[...e.eventProcessors,...y]),m.length&&(e.attachments=[...e.attachments,...m]),e.propagationContext={...e.propagationContext,...C}}function at(e,t,n){e[t]=rt(e[t],n,1)}function gs(e,t){const{extra:n,tags:r,user:o,contexts:i,level:c,transactionName:u}=t,l=Y(n);l&&Object.keys(l).length&&(e.extra={...l,...e.extra});const f=Y(r);f&&Object.keys(f).length&&(e.tags={...f,...e.tags});const y=Y(o);y&&Object.keys(y).length&&(e.user={...y,...e.user});const m=Y(i);m&&Object.keys(m).length&&(e.contexts={...m,...e.contexts}),c&&(e.level=c),u&&e.type!=="transaction"&&(e.transaction=u)}function ys(e,t){const n=[...e.breadcrumbs||[],...t];e.breadcrumbs=n.length?n:void 0}function ms(e,t){e.sdkProcessingMetadata={...e.sdkProcessingMetadata,...t}}function Cs(e,t){e.contexts={trace:Mo(t),...e.contexts},e.sdkProcessingMetadata={dynamicSamplingContext:Ko(t),...e.sdkProcessingMetadata};const n=Un(t),r=Lt(n).description;r&&!e.transaction&&e.type==="transaction"&&(e.transaction=r)}function bs(e,t){e.fingerprint=e.fingerprint?Array.isArray(e.fingerprint)?e.fingerprint:[e.fingerprint]:[],t&&(e.fingerprint=e.fingerprint.concat(t)),e.fingerprint&&!e.fingerprint.length&&delete e.fingerprint}function Es(e,t,n,r,o,i){const{normalizeDepth:c=3,normalizeMaxBreadth:u=1e3}=e,l={...t,event_id:t.event_id||n.event_id||ee(),timestamp:t.timestamp||tt()},f=n.integrations||e.integrations.map(S=>S.name);vs(l,e),Ss(l,f),o&&o.emit("applyFrameMetadata",t),t.type===void 0&&Is(l,e.stackParser);const y=Qs(r,n.captureContext);n.mechanism&&Te(l,n.mechanism);const m=o?o.getEventProcessors():[],C=vo().getScopeData();if(i){const S=i.getScopeData();Gn(C,S)}if(y){const S=y.getScopeData();Gn(C,S)}const v=[...n.attachments||[],...C.attachments];v.length&&(n.attachments=v),ps(l,C);const B=[...m,...C.eventProcessors];return Dt(B,l,n).then(S=>(S&&Bs(S),typeof c=="number"&&c>0?_s(S,c,u):S))}function vs(e,t){const{environment:n,release:r,dist:o,maxValueLength:i=250}=t;e.environment=e.environment||n||Fn,!e.release&&r&&(e.release=r),!e.dist&&o&&(e.dist=o),e.message&&(e.message=we(e.message,i));const c=e.exception&&e.exception.values&&e.exception.values[0];c&&c.value&&(c.value=we(c.value,i));const u=e.request;u&&u.url&&(u.url=we(u.url,i))}function Is(e,t){const n=hs(t);try{e.exception.values.forEach(r=>{r.stacktrace.frames.forEach(o=>{n&&o.filename&&(o.debug_id=n[o.filename])})})}catch{}}function Bs(e){const t={};try{e.exception.values.forEach(r=>{r.stacktrace.frames.forEach(o=>{o.debug_id&&(o.abs_path?t[o.abs_path]=o.debug_id:o.filename&&(t[o.filename]=o.debug_id),delete o.debug_id)})})}catch{}if(Object.keys(t).length===0)return;e.debug_meta=e.debug_meta||{},e.debug_meta.images=e.debug_meta.images||[];const n=e.debug_meta.images;Object.entries(t).forEach(([r,o])=>{n.push({type:"sourcemap",code_file:r,debug_id:o})})}function Ss(e,t){t.length>0&&(e.sdk=e.sdk||{},e.sdk.integrations=[...e.sdk.integrations||[],...t])}function _s(e,t,n){if(!e)return null;const r={...e,...e.breadcrumbs&&{breadcrumbs:e.breadcrumbs.map(o=>({...o,...o.data&&{data:oe(o.data,t,n)}}))},...e.user&&{user:oe(e.user,t,n)},...e.contexts&&{contexts:oe(e.contexts,t,n)},...e.extra&&{extra:oe(e.extra,t,n)}};return e.contexts&&e.contexts.trace&&r.contexts&&(r.contexts.trace=e.contexts.trace,e.contexts.trace.data&&(r.contexts.trace.data=oe(e.contexts.trace.data,t,n))),e.spans&&(r.spans=e.spans.map(o=>({...o,...o.data&&{data:oe(o.data,t,n)}}))),e.contexts&&e.contexts.flags&&r.contexts&&(r.contexts.flags=oe(e.contexts.flags,3,n)),r}function Qs(e,t){if(!t)return e;const n=e?e.clone():new ce;return n.update(t),n}const ks="7";function Ps(e){const t=e.protocol?`${e.protocol}:`:"",n=e.port?`:${e.port}`:"";return`${t}//${e.host}${n}${e.path?`/${e.path}`:""}/api/`}function ws(e){return`${Ps(e)}${e.projectId}/envelope/`}function Ts(e,t){const n={sentry_version:ks};return e.publicKey&&(n.sentry_key=e.publicKey),t&&(n.sentry_client=`${t.name}/${t.version}`),new URLSearchParams(n).toString()}function Rs(e,t,n){return t||`${ws(e)}?${Ts(e,n)}`}const Wn=[];function Ls(e,t){const n={};return t.forEach(r=>{r&&Vn(e,r,n)}),n}function Yn(e,t){for(const n of t)n&&n.afterAllSetup&&n.afterAllSetup(e)}function Vn(e,t,n){if(n[t.name]){U&&N.log(`Integration skipped because it was already installed: ${t.name}`);return}if(n[t.name]=t,Wn.indexOf(t.name)===-1&&typeof t.setupOnce=="function"&&(t.setupOnce(),Wn.push(t.name)),t.setup&&typeof t.setup=="function"&&t.setup(e),typeof t.preprocessEvent=="function"){const r=t.preprocessEvent.bind(t);e.on("preprocessEvent",(o,i)=>r(o,i,e))}if(typeof t.processEvent=="function"){const r=t.processEvent.bind(t),o=Object.assign((i,c)=>r(i,c,e),{id:t.name});e.addEventProcessor(o)}U&&N.log(`Integration installed: ${t.name}`)}function Os(e,t,n){const r=[{type:"client_report"},{timestamp:tt(),discarded_events:e}];return Re(t?{dsn:t}:{},[r])}class V extends Error{constructor(t,n="warn"){super(t),this.message=t,this.logLevel=n}}const Zn="Not capturing exception because it's already been captured.";class Ns{constructor(t){if(this._options=t,this._integrations={},this._numProcessing=0,this._outcomes={},this._hooks={},this._eventProcessors=[],t.dsn?this._dsn=$o(t.dsn):U&&N.warn("No DSN provided, client will not send events."),this._dsn){const o=Rs(this._dsn,t.tunnel,t._metadata?t._metadata.sdk:void 0);this._transport=t.transport({tunnel:this._options.tunnel,recordDroppedEvent:this.recordDroppedEvent.bind(this),...t.transportOptions,url:o})}const r=["enableTracing","tracesSampleRate","tracesSampler"].find(o=>o in t&&t[o]==null);r&&Ye(()=>{console.warn(`[Sentry] Deprecation warning: \`${r}\` is set to undefined, which leads to tracing being enabled. In v9, a value of \`undefined\` will result in tracing being disabled.`)})}captureException(t,n,r){const o=ee();if(kn(t))return U&&N.log(Zn),o;const i={event_id:o,...n};return this._process(this.eventFromException(t,i).then(c=>this._captureEvent(c,i,r))),i.event_id}captureMessage(t,n,r,o){const i={event_id:ee(),...r},c=_t(t)?t:String(t),u=eo(t)?this.eventFromMessage(c,n,i):this.eventFromException(t,i);return this._process(u.then(l=>this._captureEvent(l,i,o))),i.event_id}captureEvent(t,n,r){const o=ee();if(n&&n.originalException&&kn(n.originalException))return U&&N.log(Zn),o;const i={event_id:o,...n},u=(t.sdkProcessingMetadata||{}).capturedSpanScope;return this._process(this._captureEvent(t,i,u||r)),i.event_id}captureSession(t){typeof t.release!="string"?U&&N.warn("Discarded session because of missing or non-string release"):(this.sendSession(t),kt(t,{init:!1}))}getDsn(){return this._dsn}getOptions(){return this._options}getSdkMetadata(){return this._options._metadata}getTransport(){return this._transport}flush(t){const n=this._transport;return n?(this.emit("flush"),this._isClientDoneProcessing(t).then(r=>n.flush(t).then(o=>r&&o))):fe(!0)}close(t){return this.flush(t).then(n=>(this.getOptions().enabled=!1,this.emit("close"),n))}getEventProcessors(){return this._eventProcessors}addEventProcessor(t){this._eventProcessors.push(t)}init(){(this._isEnabled()||this._options.integrations.some(({name:t})=>t.startsWith("Spotlight")))&&this._setupIntegrations()}getIntegrationByName(t){return this._integrations[t]}addIntegration(t){const n=this._integrations[t.name];Vn(this,t,this._integrations),n||Yn(this,[t])}sendEvent(t,n={}){this.emit("beforeSendEvent",t,n);let r=fs(t,this._dsn,this._options._metadata,this._options.tunnel);for(const i of n.attachments||[])r=ss(r,cs(i));const o=this.sendEnvelope(r);o&&o.then(i=>this.emit("afterSendEvent",t,i),null)}sendSession(t){const n=ds(t,this._dsn,this._options._metadata,this._options.tunnel);this.sendEnvelope(n)}recordDroppedEvent(t,n,r){if(this._options.sendClientReports){const o=typeof r=="number"?r:1,i=`${t}:${n}`;U&&N.log(`Recording outcome: "${i}"${o>1?` (${o} times)`:""}`),this._outcomes[i]=(this._outcomes[i]||0)+o}}on(t,n){const r=this._hooks[t]=this._hooks[t]||[];return r.push(n),()=>{const o=r.indexOf(n);o>-1&&r.splice(o,1)}}emit(t,...n){const r=this._hooks[t];r&&r.forEach(o=>o(...n))}sendEnvelope(t){return this.emit("beforeEnvelope",t),this._isEnabled()&&this._transport?this._transport.send(t).then(null,n=>(U&&N.error("Error while sending envelope:",n),n)):(U&&N.error("Transport disabled"),fe({}))}_setupIntegrations(){const{integrations:t}=this._options;this._integrations=Ls(this,t),Yn(this,t)}_updateSessionFromEvent(t,n){let r=n.level==="fatal",o=!1;const i=n.exception&&n.exception.values;if(i){o=!0;for(const l of i){const f=l.mechanism;if(f&&f.handled===!1){r=!0;break}}}const c=t.status==="ok";(c&&t.errors===0||c&&r)&&(kt(t,{...r&&{status:"crashed"},errors:t.errors||Number(o||r)}),this.captureSession(t))}_isClientDoneProcessing(t){return new W(n=>{let r=0;const o=1,i=setInterval(()=>{this._numProcessing==0?(clearInterval(i),n(!0)):(r+=o,t&&r>=t&&(clearInterval(i),n(!1)))},o)})}_isEnabled(){return this.getOptions().enabled!==!1&&this._transport!==void 0}_prepareEvent(t,n,r=On(),o=Eo()){const i=this.getOptions(),c=Object.keys(this._integrations);return!n.integrations&&c.length>0&&(n.integrations=c),this.emit("preprocessEvent",t,n),t.type||o.setLastEventId(t.event_id||n.event_id),Es(i,t,n,r,this,o).then(u=>{if(u===null)return u;u.contexts={trace:Io(r),...u.contexts};const l=zo(this,r);return u.sdkProcessingMetadata={dynamicSamplingContext:l,...u.sdkProcessingMetadata},u})}_captureEvent(t,n={},r){return this._processEvent(t,n,r).then(o=>o.event_id,o=>{U&&(o instanceof V&&o.logLevel==="log"?N.log(o.message):N.warn(o))})}_processEvent(t,n,r){const o=this.getOptions(),{sampleRate:i}=o,c=er(t),u=$n(t),l=t.type||"error",f=`before send for type \`${l}\``,y=typeof i>"u"?void 0:Go(i);if(u&&typeof y=="number"&&Math.random()>y)return this.recordDroppedEvent("sample_rate","error",t),nt(new V(`Discarding event because it's not included in the random sample (sampling rate = ${i})`,"log"));const m=l==="replay_event"?"replay":l,v=(t.sdkProcessingMetadata||{}).capturedSpanIsolationScope;return this._prepareEvent(t,n,r,v).then(B=>{if(B===null)throw this.recordDroppedEvent("event_processor",m,t),new V("An event processor returned `null`, will not send event.","log");if(n.data&&n.data.__sentry__===!0)return B;const S=Ms(this,o,B,n);return Ds(S,f)}).then(B=>{if(B===null){if(this.recordDroppedEvent("before_send",m,t),c){const k=1+(t.spans||[]).length;this.recordDroppedEvent("before_send","span",k)}throw new V(`${f} returned \`null\`, will not send event.`,"log")}const Q=r&&r.getSession();if(!c&&Q&&this._updateSessionFromEvent(Q,B),c){const P=B.sdkProcessingMetadata&&B.sdkProcessingMetadata.spanCountBeforeProcessing||0,k=B.spans?B.spans.length:0,L=P-k;L>0&&this.recordDroppedEvent("before_send","span",L)}const S=B.transaction_info;if(c&&S&&B.transaction!==t.transaction){const P="custom";B.transaction_info={...S,source:P}}return this.sendEvent(B,n),B}).then(null,B=>{throw B instanceof V?B:(this.captureException(B,{data:{__sentry__:!0},originalException:B}),new V(`Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event.
8
- Reason: ${B}`))})}_process(t){this._numProcessing++,t.then(n=>(this._numProcessing--,n),n=>(this._numProcessing--,n))}_clearOutcomes(){const t=this._outcomes;return this._outcomes={},Object.entries(t).map(([n,r])=>{const[o,i]=n.split(":");return{reason:o,category:i,quantity:r}})}_flushOutcomes(){U&&N.log("Flushing outcomes...");const t=this._clearOutcomes();if(t.length===0){U&&N.log("No outcomes to send");return}if(!this._dsn){U&&N.log("No dsn provided, will not send outcomes");return}U&&N.log("Sending outcomes:",t);const n=Os(t,this._options.tunnel&&ot(this._dsn));this.sendEnvelope(n)}}function Ds(e,t){const n=`${t} must return \`null\` or a valid event.`;if($e(e))return e.then(r=>{if(!Ee(r)&&r!==null)throw new V(n);return r},r=>{throw new V(`${t} rejected with ${r}`)});if(!Ee(e)&&e!==null)throw new V(n);return e}function Ms(e,t,n,r){const{beforeSend:o,beforeSendTransaction:i,beforeSendSpan:c}=t;if($n(n)&&o)return o(n,r);if(er(n)){if(n.spans&&c){const u=[];for(const l of n.spans){const f=c(l);f?u.push(f):(jo(),e.recordDroppedEvent("before_send","span"))}n.spans=u}if(i){if(n.spans){const u=n.spans.length;n.sdkProcessingMetadata={...n.sdkProcessingMetadata,spanCountBeforeProcessing:u}}return i(n,r)}}return n}function $n(e){return e.type===void 0}function er(e){return e.type==="transaction"}function xs(e){const t=[];function n(){return e===void 0||t.length<e}function r(c){return t.splice(t.indexOf(c),1)[0]||Promise.resolve(void 0)}function o(c){if(!n())return nt(new V("Not adding Promise because buffer limit was reached."));const u=c();return t.indexOf(u)===-1&&t.push(u),u.then(()=>r(u)).then(null,()=>r(u).then(null,()=>{})),u}function i(c){return new W((u,l)=>{let f=t.length;if(!f)return u(!0);const y=setTimeout(()=>{c&&c>0&&u(!1)},c);t.forEach(m=>{fe(m).then(()=>{--f||(clearTimeout(y),u(!0))},l)})})}return{$:t,add:o,drain:i}}const Us=60*1e3;function Fs(e,t=Date.now()){const n=parseInt(`${e}`,10);if(!isNaN(n))return n*1e3;const r=Date.parse(`${e}`);return isNaN(r)?Us:r-t}function Xs(e,t){return e[t]||e.all||0}function Hs(e,t,n=Date.now()){return Xs(e,t)>n}function js(e,{statusCode:t,headers:n},r=Date.now()){const o={...e},i=n&&n["x-sentry-rate-limits"],c=n&&n["retry-after"];if(i)for(const u of i.trim().split(",")){const[l,f,,,y]=u.split(":",5),m=parseInt(l,10),C=(isNaN(m)?60:m)*1e3;if(!f)o.all=r+C;else for(const v of f.split(";"))v==="metric_bucket"?(!y||y.split(";").includes("custom"))&&(o[v]=r+C):o[v]=r+C}else c?o.all=r+Fs(c,r):t===429&&(o.all=r+60*1e3);return o}const Js=64;function qs(e,t,n=xs(e.bufferSize||Js)){let r={};const o=c=>n.drain(c);function i(c){const u=[];if(Jn(c,(m,C)=>{const v=qn(C);if(Hs(r,v)){const B=tr(m,C);e.recordDroppedEvent("ratelimit_backoff",v,B)}else u.push(m)}),u.length===0)return fe({});const l=Re(c[0],u),f=m=>{Jn(l,(C,v)=>{const B=tr(C,v);e.recordDroppedEvent(m,qn(v),B)})},y=()=>t({body:is(l)}).then(m=>(m.statusCode!==void 0&&(m.statusCode<200||m.statusCode>=300)&&U&&N.warn(`Sentry responded with status code ${m.statusCode} to sent event.`),r=js(r,m),m),m=>{throw f("network_error"),m});return n.add(y).then(m=>m,m=>{if(m instanceof V)return U&&N.error("Skipped sending event because buffer is full."),f("queue_overflow"),fe({});throw m})}return{send:i,flush:o}}function tr(e,t){if(!(t!=="event"&&t!=="transaction"))return Array.isArray(e)?e[1]:void 0}function zs(e,t,n=[t],r="npm"){const o=e._metadata||{};o.sdk||(o.sdk={name:`sentry.javascript.${t}`,packages:n.map(i=>({name:`${r}:@sentry/${i}`,version:de})),version:de}),e._metadata=o}function Ks(e){return e&&/^function\s+\w+\(\)\s+\{\s+\[native code\]\s+\}$/.test(e.toString())}function Gs(){return"npm"}const ct=j,Ws=typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__;function nr(e,t){const n=xt(e,t),r={type:ei(t),value:ti(t)};return n.length&&(r.stacktrace={frames:n}),r.type===void 0&&r.value===""&&(r.value="Unrecoverable error caught"),r}function Ys(e,t,n,r){const o=Rt(),i=o&&o.getOptions().normalizeDepth,c=ai(t),u={__serialized__:jn(t,i)};if(c)return{exception:{values:[nr(e,c)]},extra:u};const l={exception:{values:[{type:Ze(t)?t.constructor.name:r?"UnhandledRejection":"Error",value:si(t,{isUnhandledRejection:r})}]},extra:u};if(n){const f=xt(e,n);f.length&&(l.exception.values[0].stacktrace={frames:f})}return l}function Mt(e,t){return{exception:{values:[nr(e,t)]}}}function xt(e,t){const n=t.stacktrace||t.stack||"",r=Zs(t),o=$s(t);try{return e(n,r,o)}catch{}return[]}const Vs=/Minified React error #\d+;/i;function Zs(e){return e&&Vs.test(e.message)?1:0}function $s(e){return typeof e.framesToPop=="number"?e.framesToPop:0}function rr(e){return typeof WebAssembly<"u"&&typeof WebAssembly.Exception<"u"?e instanceof WebAssembly.Exception:!1}function ei(e){const t=e&&e.name;return!t&&rr(e)?e.message&&Array.isArray(e.message)&&e.message.length==2?e.message[0]:"WebAssembly.Exception":t}function ti(e){const t=e&&e.message;return t?t.error&&typeof t.error.message=="string"?t.error.message:rr(e)&&Array.isArray(e.message)&&e.message.length==2?e.message[1]:t:"No error message"}function ni(e,t,n,r){const o=n&&n.syntheticException||void 0,i=oi(e,t,o,r);return Te(i),i.level="error",n&&n.event_id&&(i.event_id=n.event_id),fe(i)}function ri(e,t,n="info",r,o){const i=r&&r.syntheticException||void 0,c=Ut(e,t,i,o);return c.level=n,r&&r.event_id&&(c.event_id=r.event_id),fe(c)}function oi(e,t,n,r,o){let i;if(mn(t)&&t.error)return Mt(e,t.error);if(Cn(t)||$r(t)){const c=t;if("stack"in t)i=Mt(e,t);else{const u=c.name||(Cn(c)?"DOMError":"DOMException"),l=c.message?`${u}: ${c.message}`:u;i=Ut(e,l,n,r),Qn(i,l)}return"code"in c&&(i.tags={...i.tags,"DOMException.code":`${c.code}`}),i}return yn(t)?Mt(e,t):Ee(t)||Ze(t)?(i=Ys(e,t,n,o),Te(i,{synthetic:!0}),i):(i=Ut(e,t,n,r),Qn(i,`${t}`),Te(i,{synthetic:!0}),i)}function Ut(e,t,n,r){const o={};if(r&&n){const i=xt(e,n);i.length&&(o.exception={values:[{value:t,stacktrace:{frames:i}}]}),Te(o,{synthetic:!0})}if(_t(t)){const{__sentry_template_string__:i,__sentry_template_values__:c}=t;return o.logentry={message:i,params:c},o}return o.message=t,o}function si(e,{isUnhandledRejection:t}){const n=co(e),r="exception";return mn(e)?`Event \`ErrorEvent\` captured as ${r} with message \`${e.message}\``:Ze(e)?`Event \`${ii(e)}\` (type=${e.type}) captured as ${r}`:`Object captured as ${r} with keys: ${n}`}function ii(e){try{const t=Object.getPrototypeOf(e);return t?t.constructor.name:void 0}catch{}}function ai(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t)){const n=e[t];if(n instanceof Error)return n}}function ci(e,{metadata:t,tunnel:n,dsn:r}){const o={event_id:e.event_id,sent_at:new Date().toISOString(),...t&&t.sdk&&{sdk:{name:t.sdk.name,version:t.sdk.version}},...!!n&&!!r&&{dsn:ot(r)}},i=ui(e);return Re(o,[i])}function ui(e){return[{type:"user_report"},e]}class li extends Ns{constructor(t){const n={parentSpanIsAlwaysRootSpan:!0,...t},r=ct.SENTRY_SDK_SOURCE||Gs();zs(n,"browser",["browser"],r),super(n),n.sendClientReports&&ct.document&&ct.document.addEventListener("visibilitychange",()=>{ct.document.visibilityState==="hidden"&&this._flushOutcomes()})}eventFromException(t,n){return ni(this._options.stackParser,t,n,this._options.attachStacktrace)}eventFromMessage(t,n="info",r){return ri(this._options.stackParser,t,n,r,this._options.attachStacktrace)}captureUserFeedback(t){if(!this._isEnabled()){Ws&&N.warn("SDK not enabled, will not capture user feedback.");return}const n=ci(t,{metadata:this.getSdkMetadata(),dsn:this.getDsn(),tunnel:this.getOptions().tunnel});this.sendEnvelope(n)}_prepareEvent(t,n,r){return t.platform=t.platform||"javascript",super._prepareEvent(t,n,r)}}const Ai=typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__,ut=j,lt={};function di(e){const t=lt[e];if(t)return t;let n=ut[e];if(Ks(n))return lt[e]=n.bind(ut);const r=ut.document;if(r&&typeof r.createElement=="function")try{const o=r.createElement("iframe");o.hidden=!0,r.head.appendChild(o);const i=o.contentWindow;i&&i[e]&&(n=i[e]),r.head.removeChild(o)}catch(o){Ai&&N.warn(`Could not create sandbox iframe for ${e} check, bailing to window.${e}: `,o)}return n&&(lt[e]=n.bind(ut))}function or(e){lt[e]=void 0}function fi(e,t=di("fetch")){let n=0,r=0;function o(i){const c=i.body.length;n+=c,r++;const u={body:i.body,method:"POST",referrerPolicy:"origin",headers:e.headers,keepalive:n<=6e4&&r<15,...e.fetchOptions};if(!t)return or("fetch"),nt("No fetch implementation available");try{return t(e.url,u).then(l=>(n-=c,r--,{statusCode:l.status,headers:{"x-sentry-rate-limits":l.headers.get("X-Sentry-Rate-Limits"),"retry-after":l.headers.get("Retry-After")}}))}catch(l){return or("fetch"),n-=c,r--,nt(l)}}return qs(e,o)}const hi=30,pi=50;function Ft(e,t,n,r){const o={filename:e,function:t==="<anonymous>"?be:t,in_app:!0};return n!==void 0&&(o.lineno=n),r!==void 0&&(o.colno=r),o}const gi=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,yi=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,mi=/\((\S*)(?::(\d+))(?::(\d+))\)/,Ci=[hi,e=>{const t=gi.exec(e);if(t){const[,r,o,i]=t;return Ft(r,be,+o,+i)}const n=yi.exec(e);if(n){if(n[2]&&n[2].indexOf("eval")===0){const c=mi.exec(n[2]);c&&(n[2]=c[1],n[3]=c[2],n[4]=c[3])}const[o,i]=sr(n[1]||be,n[2]);return Ft(i,o,n[3]?+n[3]:void 0,n[4]?+n[4]:void 0)}}],bi=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,Ei=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,vi=Yr(...[Ci,[pi,e=>{const t=bi.exec(e);if(t){if(t[3]&&t[3].indexOf(" > eval")>-1){const i=Ei.exec(t[3]);i&&(t[1]=t[1]||"eval",t[3]=i[1],t[4]=i[2],t[5]="")}let r=t[3],o=t[1]||be;return[o,r]=sr(o,r),Ft(r,o,t[4]?+t[4]:void 0,t[5]?+t[5]:void 0)}}]]),sr=(e,t)=>{const n=e.indexOf("safari-extension")!==-1,r=e.indexOf("safari-web-extension")!==-1;return n||r?[e.indexOf("@")!==-1?e.split("@")[0]:be,n?`safari-extension:${t}`:`safari-web-extension:${t}`]:[e,t]},Ii="https://bbed26c9265c425abb56ff9d3728183e@sentry.chocodev.kz/302";let Xt=null;function Bi(e){const t=new li({dsn:Ii,transport:fi,stackParser:vi,integrations:[],release:"1.1.61",environment:e.environment||"production"}),n=new ce;n.setClient(t),n.setTags(e),t.init(),Xt=n}function se(e,t){Xt&&Xt.captureException(e,t?{captureContext:{extra:t}}:void 0)}function ir(e,t){qe("webPayToken",e),t&&qe("webPayRefreshToken",t)}function ar(){Ce("webPayToken"),Ce("webPayRefreshToken")}async function Si(e){const t=r=>{ir(r.access_token,r.refresh_token),e.accessToken=r.access_token,e._tokenExpiresAt=r.expires_in?Date.now()+r.expires_in*1e3:null},n=bt("webPayRefreshToken");if(n&&e.config.clientId)try{const r=await Xr(e.apiUrl,e.config.clientId,n,e.config.country);t(r);return}catch{Ce("webPayRefreshToken")}if(!e.config.clientId){e.config.onError({attributes:{message:e.t("errorMissingTrackClient")}});return}if(!e.config.trackId&&typeof e.config.onRequestNewTrackId=="function"&&(e.config.trackId=await e.config.onRequestNewTrackId()),!e.config.trackId){e.config.onError({attributes:{message:e.t("errorMissingTrackClient")}});return}try{const r=await sn(e.apiUrl,e.config.clientId,e.config.trackId,e.config.country);t(r)}catch(r){if(typeof e.config.onRequestNewTrackId=="function"){e.config.trackId=await e.config.onRequestNewTrackId();const o=await sn(e.apiUrl,e.config.clientId,e.config.trackId,e.config.country);t(o)}else throw r}}const _i={kaspi_pay:`<svg width="17" height="16" viewBox="0 0 17 16" fill="none" xmlns="http://www.w3.org/2000/svg">
7
+ `),typeof u=="string"||u instanceof Uint8Array)o(u);else{let l;try{l=JSON.stringify(u)}catch{l=JSON.stringify(se(u))}o(l)}}return typeof r=="string"?r:as(r)}function as(e){const t=e.reduce((o,i)=>o+i.length,0),n=new Uint8Array(t);let r=0;for(const o of e)n.set(o,r),r+=o.length;return n}function cs(e){const t=typeof e.data=="string"?Nt(e.data):e.data;return[Y({type:"attachment",length:t.length,filename:e.filename,content_type:e.contentType,attachment_type:e.attachmentType}),t]}const us={session:"session",sessions:"session",attachment:"attachment",transaction:"transaction",event:"error",client_report:"internal",user_report:"default",profile:"profile",profile_chunk:"profile",replay_event:"replay",replay_recording:"replay",check_in:"monitor",feedback:"feedback",span:"span",statsd:"metric_bucket",raw_security:"security"};function qn(e){return us[e]}function zn(e){if(!e||!e.sdk)return;const{name:t,version:n}=e.sdk;return{name:t,version:n}}function ls(e,t,n,r){const o=e.sdkProcessingMetadata&&e.sdkProcessingMetadata.dynamicSamplingContext;return{event_id:e.event_id,sent_at:new Date().toISOString(),...t&&{sdk:t},...!!n&&r&&{dsn:ot(r)},...o&&{trace:Y({...o})}}}function As(e,t){return t&&(e.sdk=e.sdk||{},e.sdk.name=e.sdk.name||t.name,e.sdk.version=e.sdk.version||t.version,e.sdk.integrations=[...e.sdk.integrations||[],...t.integrations||[]],e.sdk.packages=[...e.sdk.packages||[],...t.packages||[]]),e}function ds(e,t,n,r){const o=zn(n),i={sent_at:new Date().toISOString(),...o&&{sdk:o},...!!r&&t&&{dsn:ot(t)}},c="aggregates"in e?[{type:"sessions"},e]:[{type:"session"},e.toJSON()];return Re(i,[c])}function fs(e,t,n,r){const o=zn(n),i=e.type&&e.type!=="replay_event"?e.type:"event";As(e,n&&n.sdk);const c=ls(e,o,r,t);return delete e.sdkProcessingMetadata,Re(c,[[{type:i},e]])}function Dt(e,t,n,r=0){return new W((o,i)=>{const c=e[r];if(t===null||typeof c!="function")o(t);else{const u=c({...t},n);U&&c.id&&u===null&&N.log(`Event processor "${c.id}" dropped event`),$e(u)?u.then(l=>Dt(e,l,n,r+1).then(o)).then(null,i):Dt(e,u,n,r+1).then(o).then(null,i)}})}let st,Kn,it;function hs(e){const t=j._sentryDebugIds;if(!t)return{};const n=Object.keys(t);return it&&n.length===Kn||(Kn=n.length,it=n.reduce((r,o)=>{st||(st={});const i=st[o];if(i)r[i[0]]=i[1];else{const c=e(o);for(let u=c.length-1;u>=0;u--){const l=c[u],f=l&&l.filename,y=t[o];if(f&&y){r[f]=y,st[o]=[f,y];break}}}return r},{})),it}function ps(e,t){const{fingerprint:n,span:r,breadcrumbs:o,sdkProcessingMetadata:i}=t;gs(e,t),r&&Cs(e,r),bs(e,n),ys(e,o),ms(e,i)}function Gn(e,t){const{extra:n,tags:r,user:o,contexts:i,level:c,sdkProcessingMetadata:u,breadcrumbs:l,fingerprint:f,eventProcessors:y,attachments:m,propagationContext:C,transactionName:v,span:B}=t;at(e,"extra",n),at(e,"tags",r),at(e,"user",o),at(e,"contexts",i),e.sdkProcessingMetadata=rt(e.sdkProcessingMetadata,u,2),c&&(e.level=c),v&&(e.transactionName=v),B&&(e.span=B),l.length&&(e.breadcrumbs=[...e.breadcrumbs,...l]),f.length&&(e.fingerprint=[...e.fingerprint,...f]),y.length&&(e.eventProcessors=[...e.eventProcessors,...y]),m.length&&(e.attachments=[...e.attachments,...m]),e.propagationContext={...e.propagationContext,...C}}function at(e,t,n){e[t]=rt(e[t],n,1)}function gs(e,t){const{extra:n,tags:r,user:o,contexts:i,level:c,transactionName:u}=t,l=Y(n);l&&Object.keys(l).length&&(e.extra={...l,...e.extra});const f=Y(r);f&&Object.keys(f).length&&(e.tags={...f,...e.tags});const y=Y(o);y&&Object.keys(y).length&&(e.user={...y,...e.user});const m=Y(i);m&&Object.keys(m).length&&(e.contexts={...m,...e.contexts}),c&&(e.level=c),u&&e.type!=="transaction"&&(e.transaction=u)}function ys(e,t){const n=[...e.breadcrumbs||[],...t];e.breadcrumbs=n.length?n:void 0}function ms(e,t){e.sdkProcessingMetadata={...e.sdkProcessingMetadata,...t}}function Cs(e,t){e.contexts={trace:Mo(t),...e.contexts},e.sdkProcessingMetadata={dynamicSamplingContext:Ko(t),...e.sdkProcessingMetadata};const n=Un(t),r=Lt(n).description;r&&!e.transaction&&e.type==="transaction"&&(e.transaction=r)}function bs(e,t){e.fingerprint=e.fingerprint?Array.isArray(e.fingerprint)?e.fingerprint:[e.fingerprint]:[],t&&(e.fingerprint=e.fingerprint.concat(t)),e.fingerprint&&!e.fingerprint.length&&delete e.fingerprint}function Es(e,t,n,r,o,i){const{normalizeDepth:c=3,normalizeMaxBreadth:u=1e3}=e,l={...t,event_id:t.event_id||n.event_id||ee(),timestamp:t.timestamp||tt()},f=n.integrations||e.integrations.map(S=>S.name);vs(l,e),Ss(l,f),o&&o.emit("applyFrameMetadata",t),t.type===void 0&&Is(l,e.stackParser);const y=Qs(r,n.captureContext);n.mechanism&&Te(l,n.mechanism);const m=o?o.getEventProcessors():[],C=vo().getScopeData();if(i){const S=i.getScopeData();Gn(C,S)}if(y){const S=y.getScopeData();Gn(C,S)}const v=[...n.attachments||[],...C.attachments];v.length&&(n.attachments=v),ps(l,C);const B=[...m,...C.eventProcessors];return Dt(B,l,n).then(S=>(S&&Bs(S),typeof c=="number"&&c>0?_s(S,c,u):S))}function vs(e,t){const{environment:n,release:r,dist:o,maxValueLength:i=250}=t;e.environment=e.environment||n||Fn,!e.release&&r&&(e.release=r),!e.dist&&o&&(e.dist=o),e.message&&(e.message=we(e.message,i));const c=e.exception&&e.exception.values&&e.exception.values[0];c&&c.value&&(c.value=we(c.value,i));const u=e.request;u&&u.url&&(u.url=we(u.url,i))}function Is(e,t){const n=hs(t);try{e.exception.values.forEach(r=>{r.stacktrace.frames.forEach(o=>{n&&o.filename&&(o.debug_id=n[o.filename])})})}catch{}}function Bs(e){const t={};try{e.exception.values.forEach(r=>{r.stacktrace.frames.forEach(o=>{o.debug_id&&(o.abs_path?t[o.abs_path]=o.debug_id:o.filename&&(t[o.filename]=o.debug_id),delete o.debug_id)})})}catch{}if(Object.keys(t).length===0)return;e.debug_meta=e.debug_meta||{},e.debug_meta.images=e.debug_meta.images||[];const n=e.debug_meta.images;Object.entries(t).forEach(([r,o])=>{n.push({type:"sourcemap",code_file:r,debug_id:o})})}function Ss(e,t){t.length>0&&(e.sdk=e.sdk||{},e.sdk.integrations=[...e.sdk.integrations||[],...t])}function _s(e,t,n){if(!e)return null;const r={...e,...e.breadcrumbs&&{breadcrumbs:e.breadcrumbs.map(o=>({...o,...o.data&&{data:se(o.data,t,n)}}))},...e.user&&{user:se(e.user,t,n)},...e.contexts&&{contexts:se(e.contexts,t,n)},...e.extra&&{extra:se(e.extra,t,n)}};return e.contexts&&e.contexts.trace&&r.contexts&&(r.contexts.trace=e.contexts.trace,e.contexts.trace.data&&(r.contexts.trace.data=se(e.contexts.trace.data,t,n))),e.spans&&(r.spans=e.spans.map(o=>({...o,...o.data&&{data:se(o.data,t,n)}}))),e.contexts&&e.contexts.flags&&r.contexts&&(r.contexts.flags=se(e.contexts.flags,3,n)),r}function Qs(e,t){if(!t)return e;const n=e?e.clone():new ce;return n.update(t),n}const ks="7";function Ps(e){const t=e.protocol?`${e.protocol}:`:"",n=e.port?`:${e.port}`:"";return`${t}//${e.host}${n}${e.path?`/${e.path}`:""}/api/`}function ws(e){return`${Ps(e)}${e.projectId}/envelope/`}function Ts(e,t){const n={sentry_version:ks};return e.publicKey&&(n.sentry_key=e.publicKey),t&&(n.sentry_client=`${t.name}/${t.version}`),new URLSearchParams(n).toString()}function Rs(e,t,n){return t||`${ws(e)}?${Ts(e,n)}`}const Wn=[];function Ls(e,t){const n={};return t.forEach(r=>{r&&Vn(e,r,n)}),n}function Yn(e,t){for(const n of t)n&&n.afterAllSetup&&n.afterAllSetup(e)}function Vn(e,t,n){if(n[t.name]){U&&N.log(`Integration skipped because it was already installed: ${t.name}`);return}if(n[t.name]=t,Wn.indexOf(t.name)===-1&&typeof t.setupOnce=="function"&&(t.setupOnce(),Wn.push(t.name)),t.setup&&typeof t.setup=="function"&&t.setup(e),typeof t.preprocessEvent=="function"){const r=t.preprocessEvent.bind(t);e.on("preprocessEvent",(o,i)=>r(o,i,e))}if(typeof t.processEvent=="function"){const r=t.processEvent.bind(t),o=Object.assign((i,c)=>r(i,c,e),{id:t.name});e.addEventProcessor(o)}U&&N.log(`Integration installed: ${t.name}`)}function Os(e,t,n){const r=[{type:"client_report"},{timestamp:tt(),discarded_events:e}];return Re(t?{dsn:t}:{},[r])}class V extends Error{constructor(t,n="warn"){super(t),this.message=t,this.logLevel=n}}const Zn="Not capturing exception because it's already been captured.";class Ns{constructor(t){if(this._options=t,this._integrations={},this._numProcessing=0,this._outcomes={},this._hooks={},this._eventProcessors=[],t.dsn?this._dsn=$o(t.dsn):U&&N.warn("No DSN provided, client will not send events."),this._dsn){const o=Rs(this._dsn,t.tunnel,t._metadata?t._metadata.sdk:void 0);this._transport=t.transport({tunnel:this._options.tunnel,recordDroppedEvent:this.recordDroppedEvent.bind(this),...t.transportOptions,url:o})}const r=["enableTracing","tracesSampleRate","tracesSampler"].find(o=>o in t&&t[o]==null);r&&Ye(()=>{console.warn(`[Sentry] Deprecation warning: \`${r}\` is set to undefined, which leads to tracing being enabled. In v9, a value of \`undefined\` will result in tracing being disabled.`)})}captureException(t,n,r){const o=ee();if(kn(t))return U&&N.log(Zn),o;const i={event_id:o,...n};return this._process(this.eventFromException(t,i).then(c=>this._captureEvent(c,i,r))),i.event_id}captureMessage(t,n,r,o){const i={event_id:ee(),...r},c=_t(t)?t:String(t),u=eo(t)?this.eventFromMessage(c,n,i):this.eventFromException(t,i);return this._process(u.then(l=>this._captureEvent(l,i,o))),i.event_id}captureEvent(t,n,r){const o=ee();if(n&&n.originalException&&kn(n.originalException))return U&&N.log(Zn),o;const i={event_id:o,...n},u=(t.sdkProcessingMetadata||{}).capturedSpanScope;return this._process(this._captureEvent(t,i,u||r)),i.event_id}captureSession(t){typeof t.release!="string"?U&&N.warn("Discarded session because of missing or non-string release"):(this.sendSession(t),kt(t,{init:!1}))}getDsn(){return this._dsn}getOptions(){return this._options}getSdkMetadata(){return this._options._metadata}getTransport(){return this._transport}flush(t){const n=this._transport;return n?(this.emit("flush"),this._isClientDoneProcessing(t).then(r=>n.flush(t).then(o=>r&&o))):fe(!0)}close(t){return this.flush(t).then(n=>(this.getOptions().enabled=!1,this.emit("close"),n))}getEventProcessors(){return this._eventProcessors}addEventProcessor(t){this._eventProcessors.push(t)}init(){(this._isEnabled()||this._options.integrations.some(({name:t})=>t.startsWith("Spotlight")))&&this._setupIntegrations()}getIntegrationByName(t){return this._integrations[t]}addIntegration(t){const n=this._integrations[t.name];Vn(this,t,this._integrations),n||Yn(this,[t])}sendEvent(t,n={}){this.emit("beforeSendEvent",t,n);let r=fs(t,this._dsn,this._options._metadata,this._options.tunnel);for(const i of n.attachments||[])r=ss(r,cs(i));const o=this.sendEnvelope(r);o&&o.then(i=>this.emit("afterSendEvent",t,i),null)}sendSession(t){const n=ds(t,this._dsn,this._options._metadata,this._options.tunnel);this.sendEnvelope(n)}recordDroppedEvent(t,n,r){if(this._options.sendClientReports){const o=typeof r=="number"?r:1,i=`${t}:${n}`;U&&N.log(`Recording outcome: "${i}"${o>1?` (${o} times)`:""}`),this._outcomes[i]=(this._outcomes[i]||0)+o}}on(t,n){const r=this._hooks[t]=this._hooks[t]||[];return r.push(n),()=>{const o=r.indexOf(n);o>-1&&r.splice(o,1)}}emit(t,...n){const r=this._hooks[t];r&&r.forEach(o=>o(...n))}sendEnvelope(t){return this.emit("beforeEnvelope",t),this._isEnabled()&&this._transport?this._transport.send(t).then(null,n=>(U&&N.error("Error while sending envelope:",n),n)):(U&&N.error("Transport disabled"),fe({}))}_setupIntegrations(){const{integrations:t}=this._options;this._integrations=Ls(this,t),Yn(this,t)}_updateSessionFromEvent(t,n){let r=n.level==="fatal",o=!1;const i=n.exception&&n.exception.values;if(i){o=!0;for(const l of i){const f=l.mechanism;if(f&&f.handled===!1){r=!0;break}}}const c=t.status==="ok";(c&&t.errors===0||c&&r)&&(kt(t,{...r&&{status:"crashed"},errors:t.errors||Number(o||r)}),this.captureSession(t))}_isClientDoneProcessing(t){return new W(n=>{let r=0;const o=1,i=setInterval(()=>{this._numProcessing==0?(clearInterval(i),n(!0)):(r+=o,t&&r>=t&&(clearInterval(i),n(!1)))},o)})}_isEnabled(){return this.getOptions().enabled!==!1&&this._transport!==void 0}_prepareEvent(t,n,r=On(),o=Eo()){const i=this.getOptions(),c=Object.keys(this._integrations);return!n.integrations&&c.length>0&&(n.integrations=c),this.emit("preprocessEvent",t,n),t.type||o.setLastEventId(t.event_id||n.event_id),Es(i,t,n,r,this,o).then(u=>{if(u===null)return u;u.contexts={trace:Io(r),...u.contexts};const l=zo(this,r);return u.sdkProcessingMetadata={dynamicSamplingContext:l,...u.sdkProcessingMetadata},u})}_captureEvent(t,n={},r){return this._processEvent(t,n,r).then(o=>o.event_id,o=>{U&&(o instanceof V&&o.logLevel==="log"?N.log(o.message):N.warn(o))})}_processEvent(t,n,r){const o=this.getOptions(),{sampleRate:i}=o,c=er(t),u=$n(t),l=t.type||"error",f=`before send for type \`${l}\``,y=typeof i>"u"?void 0:Go(i);if(u&&typeof y=="number"&&Math.random()>y)return this.recordDroppedEvent("sample_rate","error",t),nt(new V(`Discarding event because it's not included in the random sample (sampling rate = ${i})`,"log"));const m=l==="replay_event"?"replay":l,v=(t.sdkProcessingMetadata||{}).capturedSpanIsolationScope;return this._prepareEvent(t,n,r,v).then(B=>{if(B===null)throw this.recordDroppedEvent("event_processor",m,t),new V("An event processor returned `null`, will not send event.","log");if(n.data&&n.data.__sentry__===!0)return B;const S=Ms(this,o,B,n);return Ds(S,f)}).then(B=>{if(B===null){if(this.recordDroppedEvent("before_send",m,t),c){const k=1+(t.spans||[]).length;this.recordDroppedEvent("before_send","span",k)}throw new V(`${f} returned \`null\`, will not send event.`,"log")}const Q=r&&r.getSession();if(!c&&Q&&this._updateSessionFromEvent(Q,B),c){const P=B.sdkProcessingMetadata&&B.sdkProcessingMetadata.spanCountBeforeProcessing||0,k=B.spans?B.spans.length:0,L=P-k;L>0&&this.recordDroppedEvent("before_send","span",L)}const S=B.transaction_info;if(c&&S&&B.transaction!==t.transaction){const P="custom";B.transaction_info={...S,source:P}}return this.sendEvent(B,n),B}).then(null,B=>{throw B instanceof V?B:(this.captureException(B,{data:{__sentry__:!0},originalException:B}),new V(`Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event.
8
+ Reason: ${B}`))})}_process(t){this._numProcessing++,t.then(n=>(this._numProcessing--,n),n=>(this._numProcessing--,n))}_clearOutcomes(){const t=this._outcomes;return this._outcomes={},Object.entries(t).map(([n,r])=>{const[o,i]=n.split(":");return{reason:o,category:i,quantity:r}})}_flushOutcomes(){U&&N.log("Flushing outcomes...");const t=this._clearOutcomes();if(t.length===0){U&&N.log("No outcomes to send");return}if(!this._dsn){U&&N.log("No dsn provided, will not send outcomes");return}U&&N.log("Sending outcomes:",t);const n=Os(t,this._options.tunnel&&ot(this._dsn));this.sendEnvelope(n)}}function Ds(e,t){const n=`${t} must return \`null\` or a valid event.`;if($e(e))return e.then(r=>{if(!Ee(r)&&r!==null)throw new V(n);return r},r=>{throw new V(`${t} rejected with ${r}`)});if(!Ee(e)&&e!==null)throw new V(n);return e}function Ms(e,t,n,r){const{beforeSend:o,beforeSendTransaction:i,beforeSendSpan:c}=t;if($n(n)&&o)return o(n,r);if(er(n)){if(n.spans&&c){const u=[];for(const l of n.spans){const f=c(l);f?u.push(f):(jo(),e.recordDroppedEvent("before_send","span"))}n.spans=u}if(i){if(n.spans){const u=n.spans.length;n.sdkProcessingMetadata={...n.sdkProcessingMetadata,spanCountBeforeProcessing:u}}return i(n,r)}}return n}function $n(e){return e.type===void 0}function er(e){return e.type==="transaction"}function xs(e){const t=[];function n(){return e===void 0||t.length<e}function r(c){return t.splice(t.indexOf(c),1)[0]||Promise.resolve(void 0)}function o(c){if(!n())return nt(new V("Not adding Promise because buffer limit was reached."));const u=c();return t.indexOf(u)===-1&&t.push(u),u.then(()=>r(u)).then(null,()=>r(u).then(null,()=>{})),u}function i(c){return new W((u,l)=>{let f=t.length;if(!f)return u(!0);const y=setTimeout(()=>{c&&c>0&&u(!1)},c);t.forEach(m=>{fe(m).then(()=>{--f||(clearTimeout(y),u(!0))},l)})})}return{$:t,add:o,drain:i}}const Us=60*1e3;function Fs(e,t=Date.now()){const n=parseInt(`${e}`,10);if(!isNaN(n))return n*1e3;const r=Date.parse(`${e}`);return isNaN(r)?Us:r-t}function Xs(e,t){return e[t]||e.all||0}function Hs(e,t,n=Date.now()){return Xs(e,t)>n}function js(e,{statusCode:t,headers:n},r=Date.now()){const o={...e},i=n&&n["x-sentry-rate-limits"],c=n&&n["retry-after"];if(i)for(const u of i.trim().split(",")){const[l,f,,,y]=u.split(":",5),m=parseInt(l,10),C=(isNaN(m)?60:m)*1e3;if(!f)o.all=r+C;else for(const v of f.split(";"))v==="metric_bucket"?(!y||y.split(";").includes("custom"))&&(o[v]=r+C):o[v]=r+C}else c?o.all=r+Fs(c,r):t===429&&(o.all=r+60*1e3);return o}const Js=64;function qs(e,t,n=xs(e.bufferSize||Js)){let r={};const o=c=>n.drain(c);function i(c){const u=[];if(Jn(c,(m,C)=>{const v=qn(C);if(Hs(r,v)){const B=tr(m,C);e.recordDroppedEvent("ratelimit_backoff",v,B)}else u.push(m)}),u.length===0)return fe({});const l=Re(c[0],u),f=m=>{Jn(l,(C,v)=>{const B=tr(C,v);e.recordDroppedEvent(m,qn(v),B)})},y=()=>t({body:is(l)}).then(m=>(m.statusCode!==void 0&&(m.statusCode<200||m.statusCode>=300)&&U&&N.warn(`Sentry responded with status code ${m.statusCode} to sent event.`),r=js(r,m),m),m=>{throw f("network_error"),m});return n.add(y).then(m=>m,m=>{if(m instanceof V)return U&&N.error("Skipped sending event because buffer is full."),f("queue_overflow"),fe({});throw m})}return{send:i,flush:o}}function tr(e,t){if(!(t!=="event"&&t!=="transaction"))return Array.isArray(e)?e[1]:void 0}function zs(e,t,n=[t],r="npm"){const o=e._metadata||{};o.sdk||(o.sdk={name:`sentry.javascript.${t}`,packages:n.map(i=>({name:`${r}:@sentry/${i}`,version:de})),version:de}),e._metadata=o}function Ks(e){return e&&/^function\s+\w+\(\)\s+\{\s+\[native code\]\s+\}$/.test(e.toString())}function Gs(){return"npm"}const ct=j,Ws=typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__;function nr(e,t){const n=xt(e,t),r={type:ei(t),value:ti(t)};return n.length&&(r.stacktrace={frames:n}),r.type===void 0&&r.value===""&&(r.value="Unrecoverable error caught"),r}function Ys(e,t,n,r){const o=Rt(),i=o&&o.getOptions().normalizeDepth,c=ai(t),u={__serialized__:jn(t,i)};if(c)return{exception:{values:[nr(e,c)]},extra:u};const l={exception:{values:[{type:Ze(t)?t.constructor.name:r?"UnhandledRejection":"Error",value:si(t,{isUnhandledRejection:r})}]},extra:u};if(n){const f=xt(e,n);f.length&&(l.exception.values[0].stacktrace={frames:f})}return l}function Mt(e,t){return{exception:{values:[nr(e,t)]}}}function xt(e,t){const n=t.stacktrace||t.stack||"",r=Zs(t),o=$s(t);try{return e(n,r,o)}catch{}return[]}const Vs=/Minified React error #\d+;/i;function Zs(e){return e&&Vs.test(e.message)?1:0}function $s(e){return typeof e.framesToPop=="number"?e.framesToPop:0}function rr(e){return typeof WebAssembly<"u"&&typeof WebAssembly.Exception<"u"?e instanceof WebAssembly.Exception:!1}function ei(e){const t=e&&e.name;return!t&&rr(e)?e.message&&Array.isArray(e.message)&&e.message.length==2?e.message[0]:"WebAssembly.Exception":t}function ti(e){const t=e&&e.message;return t?t.error&&typeof t.error.message=="string"?t.error.message:rr(e)&&Array.isArray(e.message)&&e.message.length==2?e.message[1]:t:"No error message"}function ni(e,t,n,r){const o=n&&n.syntheticException||void 0,i=oi(e,t,o,r);return Te(i),i.level="error",n&&n.event_id&&(i.event_id=n.event_id),fe(i)}function ri(e,t,n="info",r,o){const i=r&&r.syntheticException||void 0,c=Ut(e,t,i,o);return c.level=n,r&&r.event_id&&(c.event_id=r.event_id),fe(c)}function oi(e,t,n,r,o){let i;if(mn(t)&&t.error)return Mt(e,t.error);if(Cn(t)||$r(t)){const c=t;if("stack"in t)i=Mt(e,t);else{const u=c.name||(Cn(c)?"DOMError":"DOMException"),l=c.message?`${u}: ${c.message}`:u;i=Ut(e,l,n,r),Qn(i,l)}return"code"in c&&(i.tags={...i.tags,"DOMException.code":`${c.code}`}),i}return yn(t)?Mt(e,t):Ee(t)||Ze(t)?(i=Ys(e,t,n,o),Te(i,{synthetic:!0}),i):(i=Ut(e,t,n,r),Qn(i,`${t}`),Te(i,{synthetic:!0}),i)}function Ut(e,t,n,r){const o={};if(r&&n){const i=xt(e,n);i.length&&(o.exception={values:[{value:t,stacktrace:{frames:i}}]}),Te(o,{synthetic:!0})}if(_t(t)){const{__sentry_template_string__:i,__sentry_template_values__:c}=t;return o.logentry={message:i,params:c},o}return o.message=t,o}function si(e,{isUnhandledRejection:t}){const n=co(e),r="exception";return mn(e)?`Event \`ErrorEvent\` captured as ${r} with message \`${e.message}\``:Ze(e)?`Event \`${ii(e)}\` (type=${e.type}) captured as ${r}`:`Object captured as ${r} with keys: ${n}`}function ii(e){try{const t=Object.getPrototypeOf(e);return t?t.constructor.name:void 0}catch{}}function ai(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t)){const n=e[t];if(n instanceof Error)return n}}function ci(e,{metadata:t,tunnel:n,dsn:r}){const o={event_id:e.event_id,sent_at:new Date().toISOString(),...t&&t.sdk&&{sdk:{name:t.sdk.name,version:t.sdk.version}},...!!n&&!!r&&{dsn:ot(r)}},i=ui(e);return Re(o,[i])}function ui(e){return[{type:"user_report"},e]}class li extends Ns{constructor(t){const n={parentSpanIsAlwaysRootSpan:!0,...t},r=ct.SENTRY_SDK_SOURCE||Gs();zs(n,"browser",["browser"],r),super(n),n.sendClientReports&&ct.document&&ct.document.addEventListener("visibilitychange",()=>{ct.document.visibilityState==="hidden"&&this._flushOutcomes()})}eventFromException(t,n){return ni(this._options.stackParser,t,n,this._options.attachStacktrace)}eventFromMessage(t,n="info",r){return ri(this._options.stackParser,t,n,r,this._options.attachStacktrace)}captureUserFeedback(t){if(!this._isEnabled()){Ws&&N.warn("SDK not enabled, will not capture user feedback.");return}const n=ci(t,{metadata:this.getSdkMetadata(),dsn:this.getDsn(),tunnel:this.getOptions().tunnel});this.sendEnvelope(n)}_prepareEvent(t,n,r){return t.platform=t.platform||"javascript",super._prepareEvent(t,n,r)}}const Ai=typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__,ut=j,lt={};function di(e){const t=lt[e];if(t)return t;let n=ut[e];if(Ks(n))return lt[e]=n.bind(ut);const r=ut.document;if(r&&typeof r.createElement=="function")try{const o=r.createElement("iframe");o.hidden=!0,r.head.appendChild(o);const i=o.contentWindow;i&&i[e]&&(n=i[e]),r.head.removeChild(o)}catch(o){Ai&&N.warn(`Could not create sandbox iframe for ${e} check, bailing to window.${e}: `,o)}return n&&(lt[e]=n.bind(ut))}function or(e){lt[e]=void 0}function fi(e,t=di("fetch")){let n=0,r=0;function o(i){const c=i.body.length;n+=c,r++;const u={body:i.body,method:"POST",referrerPolicy:"origin",headers:e.headers,keepalive:n<=6e4&&r<15,...e.fetchOptions};if(!t)return or("fetch"),nt("No fetch implementation available");try{return t(e.url,u).then(l=>(n-=c,r--,{statusCode:l.status,headers:{"x-sentry-rate-limits":l.headers.get("X-Sentry-Rate-Limits"),"retry-after":l.headers.get("Retry-After")}}))}catch(l){return or("fetch"),n-=c,r--,nt(l)}}return qs(e,o)}const hi=30,pi=50;function Ft(e,t,n,r){const o={filename:e,function:t==="<anonymous>"?be:t,in_app:!0};return n!==void 0&&(o.lineno=n),r!==void 0&&(o.colno=r),o}const gi=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,yi=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,mi=/\((\S*)(?::(\d+))(?::(\d+))\)/,Ci=[hi,e=>{const t=gi.exec(e);if(t){const[,r,o,i]=t;return Ft(r,be,+o,+i)}const n=yi.exec(e);if(n){if(n[2]&&n[2].indexOf("eval")===0){const c=mi.exec(n[2]);c&&(n[2]=c[1],n[3]=c[2],n[4]=c[3])}const[o,i]=sr(n[1]||be,n[2]);return Ft(i,o,n[3]?+n[3]:void 0,n[4]?+n[4]:void 0)}}],bi=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,Ei=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,vi=Yr(...[Ci,[pi,e=>{const t=bi.exec(e);if(t){if(t[3]&&t[3].indexOf(" > eval")>-1){const i=Ei.exec(t[3]);i&&(t[1]=t[1]||"eval",t[3]=i[1],t[4]=i[2],t[5]="")}let r=t[3],o=t[1]||be;return[o,r]=sr(o,r),Ft(r,o,t[4]?+t[4]:void 0,t[5]?+t[5]:void 0)}}]]),sr=(e,t)=>{const n=e.indexOf("safari-extension")!==-1,r=e.indexOf("safari-web-extension")!==-1;return n||r?[e.indexOf("@")!==-1?e.split("@")[0]:be,n?`safari-extension:${t}`:`safari-web-extension:${t}`]:[e,t]},Ii="https://bbed26c9265c425abb56ff9d3728183e@sentry.chocodev.kz/302";let Xt=null;function Bi(e){const t=new li({dsn:Ii,transport:fi,stackParser:vi,integrations:[],release:"1.1.62",environment:e.environment||"production"}),n=new ce;n.setClient(t),n.setTags(e),t.init(),Xt=n}function te(e,t){Xt&&Xt.captureException(e,t?{captureContext:{extra:t}}:void 0)}function ir(e,t){qe("webPayToken",e),t&&qe("webPayRefreshToken",t)}function ar(){Ce("webPayToken"),Ce("webPayRefreshToken")}async function Si(e){const t=r=>{ir(r.access_token,r.refresh_token),e.accessToken=r.access_token,e._tokenExpiresAt=r.expires_in?Date.now()+r.expires_in*1e3:null},n=bt("webPayRefreshToken");if(n&&e.config.clientId)try{const r=await Xr(e.apiUrl,e.config.clientId,n,e.config.country);t(r);return}catch{Ce("webPayRefreshToken")}if(!e.config.clientId){e.config.onError({attributes:{message:e.t("errorMissingTrackClient")}});return}if(!e.config.trackId&&typeof e.config.onRequestNewTrackId=="function"&&(e.config.trackId=await e.config.onRequestNewTrackId()),!e.config.trackId){e.config.onError({attributes:{message:e.t("errorMissingTrackClient")}});return}try{const r=await sn(e.apiUrl,e.config.clientId,e.config.trackId,e.config.country);t(r)}catch(r){if(typeof e.config.onRequestNewTrackId=="function"){e.config.trackId=await e.config.onRequestNewTrackId();const o=await sn(e.apiUrl,e.config.clientId,e.config.trackId,e.config.country);t(o)}else throw r}}const _i={kaspi_pay:`<svg width="17" height="16" viewBox="0 0 17 16" fill="none" xmlns="http://www.w3.org/2000/svg">
9
9
  <path fill-rule="evenodd" clip-rule="evenodd" d="M8.89711 8.50443C10.4185 8.72365 10.6242 9.56386 10.7471 10.3459L10.7816 10.5699L10.8557 11.0301C11.0006 11.9088 11.303 13.7327 11.303 14.6845C11.303 14.9224 11.2806 15.105 11.2396 15.2053C11.1713 15.3599 10.9724 15.5082 10.6978 15.6319C10.0332 15.7846 9.33863 15.8671 8.62315 15.8671C8.54739 15.8671 8.47285 15.8637 8.39805 15.8616C8.10889 15.785 7.89156 15.657 7.77649 15.4821C7.42905 14.9542 7.40812 13.7781 7.40116 12.4037L7.40037 12.2443L7.39755 11.8324C7.38623 10.3774 7.37651 9.1229 7.94288 8.67272C8.16223 8.49957 8.47392 8.44225 8.89711 8.50443ZM5.58009 11.6722C5.90978 11.6548 6.12181 13.1684 6.16441 14.3162C6.19427 15.1152 6.10438 15.4439 5.96084 15.5619C5.79833 15.5113 5.63864 15.4565 5.48128 15.397C5.3763 15.219 5.29607 14.9389 5.2451 14.5721C5.08947 13.4193 5.22466 11.6925 5.58009 11.6722ZM13.8455 13.934C13.825 14.0391 13.796 14.1204 13.7602 14.1889C13.4783 14.4 13.1821 14.5938 12.872 14.7682C12.7733 14.7837 12.6856 14.7729 12.6427 14.7053C12.2318 14.0314 12.0775 11.9173 12.4752 11.7333C12.9936 11.4995 13.9224 13.5685 13.8455 13.934ZM8.50042 0C13.1296 0 16.8941 3.42166 16.9979 7.67934L17 7.82651V7.89454C16.9915 9.81778 16.2332 11.5773 14.9839 12.9392C14.9386 12.918 14.8559 12.8486 14.7062 12.6395C14.5512 12.4293 13.2148 10.5096 13.2148 8.30946C13.2148 7.87768 13.8816 7.20318 14.4717 6.61114C14.9128 6.16562 15.3306 5.74539 15.4845 5.4151C15.6804 4.98892 15.5433 4.69134 15.3265 4.59047C15.1302 4.50082 14.8355 4.56621 14.6287 4.90904C14.2893 5.46389 14.1805 5.56758 13.6855 5.93882C13.1984 6.30986 12.424 6.68338 12.424 6.19988C12.424 5.93882 12.8553 5.34757 13.0684 4.93314C13.286 4.51408 13.0515 4.21072 12.6022 4.21072C11.7198 4.21072 11.1341 5.2598 11.1341 5.62326C11.1341 5.98642 11.3229 6.03813 11.3229 6.46104C11.3229 6.88713 10.3548 7.4398 9.44281 7.4398C8.56481 7.4398 8.05566 7.27394 7.8447 6.80665L7.81777 6.74105L7.75678 6.57266C7.54046 5.98255 7.38528 5.55458 7.11514 5.10733C6.9717 4.87081 6.75038 4.70684 6.55897 4.56257C6.30881 4.38121 6.17902 4.21421 6.15193 4.08967C6.12696 3.96611 6.11352 3.73326 6.54117 3.19648C6.96793 2.66277 7.02775 2.25958 6.81418 2.05153C6.73678 1.97752 6.60482 1.93011 6.43535 1.93011C6.13562 1.93011 5.71912 2.07834 5.2899 2.48551C4.62267 3.12364 5.00146 3.72951 5.00146 3.99548C5.00146 4.26127 4.87922 4.41162 4.47882 4.77323C4.07547 5.13644 3.93627 5.44783 3.89014 6.69935C3.87247 7.3442 3.75079 7.71539 3.64156 8.04453C3.54718 8.33302 3.46038 8.60425 3.45569 8.99611C3.44822 9.43038 3.52566 9.71023 3.61604 10.0331C3.70477 10.3316 3.79902 10.6736 3.8594 11.2456C3.95544 12.1312 3.92205 12.8792 3.74744 13.6437L3.70084 13.8353L3.68995 13.8903C3.65419 14.0247 3.61168 14.1879 3.55423 14.249C1.4029 12.8228 0 10.4936 0 7.86072C0 3.51974 3.80561 0 8.50042 0Z" fill="#F14635"/>
10
10
  </svg>
11
11
  `,new_card:`<svg width="21" height="12" viewBox="0 0 21 12" fill="none" xmlns="http://www.w3.org/2000/svg">
@@ -312,4 +312,4 @@ Reason: ${B}`))})}_process(t){this._numProcessing++,t.then(n=>(this._numProcessi
312
312
  </defs>
313
313
  </svg>
314
314
  </span>
315
- `,n.appendChild(r),n.appendChild(o),t.appendChild(n),ue(e)}function dr(e){var o;if(!e.selectedCoupon)return;const t=e._isCouponDisabled();t&&e.useCoupon&&(e.useCoupon=!1);const n=(o=e.container)==null?void 0:o.querySelector('[data-action="toggle-coupon"]');if(!n)return;n.classList.toggle("choco-widget-balance-toggle--disabled",t);const r=n.querySelector("input[type='checkbox']");r&&(r.disabled=t,t&&(r.checked=!1))}function he(e){e.loading=!0,ue(e)}function q(e){var m,C,v,B,Q,S,P,k;e.loading=!1;const t=(m=e.container)==null?void 0:m.querySelector(".choco-widget-payment-method"),n=(C=e.container)==null?void 0:C.querySelector(".choco-widget-pay-button"),r=(v=e.container)==null?void 0:v.querySelector(".choco-widget-google-pay-button-slot button"),o=(B=e.container)==null?void 0:B.querySelector(".choco-widget-apple-pay-button-slot button"),i=(Q=e.container)==null?void 0:Q.querySelector(".choco-widget-google-pay-amount"),c=(S=e.container)==null?void 0:S.querySelector(".choco-widget-google-pay-row"),u=(P=e.container)==null?void 0:P.querySelector(".choco-widget-apple-pay-row"),l=(k=e.container)==null?void 0:k.querySelector(".choco-widget-balance-section"),f=e._isInteractionBlocked(),y=e.paymentMethodDisabled||f;t&&(t.disabled=y),n&&(n.disabled=f,n.classList.remove("choco-widget-pay-button--loading")),r&&(r.disabled=f),o&&(o.disabled=f),i==null||i.classList.toggle("choco-widget-wallet-blocked",f),i==null||i.setAttribute("aria-disabled",String(f)),c==null||c.classList.toggle("choco-widget-wallet-blocked",f),c==null||c.setAttribute("aria-disabled",String(f)),u==null||u.classList.toggle("choco-widget-wallet-blocked",f),u==null||u.setAttribute("aria-disabled",String(f)),l==null||l.classList.remove("disabled")}function ue(e){var C,v,B,Q,S,P,k,L,R;const t=(C=e.container)==null?void 0:C.querySelector(".choco-widget-payment-method"),n=(v=e.container)==null?void 0:v.querySelector(".choco-widget-pay-button"),r=(B=e.container)==null?void 0:B.querySelector(".choco-widget-freedom-card-btn"),o=(Q=e.container)==null?void 0:Q.querySelector(".choco-widget-google-pay-button-slot button"),i=(S=e.container)==null?void 0:S.querySelector(".choco-widget-apple-pay-button-slot button"),c=(P=e.container)==null?void 0:P.querySelector(".choco-widget-google-pay-amount"),u=(k=e.container)==null?void 0:k.querySelector(".choco-widget-google-pay-row"),l=(L=e.container)==null?void 0:L.querySelector(".choco-widget-apple-pay-row"),f=(R=e.container)==null?void 0:R.querySelector(".choco-widget-balance-section"),y=e._isInteractionBlocked(),m=e.paymentMethodDisabled||y;f==null||f.classList.toggle("disabled",y),t&&(t.disabled=m),n&&(n.disabled=y,n.classList.toggle("choco-widget-pay-button--loading",e.loading)),r&&(r.disabled=y),o&&(o.disabled=y),i&&(i.disabled=y),c==null||c.classList.toggle("choco-widget-wallet-blocked",y),c==null||c.setAttribute("aria-disabled",String(y)),u==null||u.classList.toggle("choco-widget-wallet-blocked",y),u==null||u.setAttribute("aria-disabled",String(y)),l==null||l.classList.toggle("choco-widget-wallet-blocked",y),l==null||l.setAttribute("aria-disabled",String(y))}function fr(e){var n;if(e._isInteractionBlocked())return;const t=(n=e.container)==null?void 0:n.querySelector('[data-sheet="payment"]');t&&(t.classList.add("choco-widget-payment-sheet--open"),e.isPaymentSheetOpen=!0,Oe(e))}function le(e){var n;const t=(n=e.container)==null?void 0:n.querySelector('[data-sheet="payment"]');if(t){ft(e);const r=t.querySelector(".choco-widget-sheet-content");r&&(r.style.transform="",r.classList.remove("choco-widget-sheet-content--dragging")),t.classList.remove("choco-widget-payment-sheet--open"),e.isPaymentSheetOpen=!1,e.isPaymentSheetEditMode&&(e.isPaymentSheetEditMode=!1,Le(e),Oe(e))}}function Oe(e){var l;const t=(l=e.container)==null?void 0:l.querySelector('[data-sheet="payment"]');if(!t)return;const n=t.querySelector(".choco-widget-sheet-title"),r=t.querySelector('[data-action="close-sheet"]'),o=t.querySelector('[data-action="edit-sheet"]'),i=t.querySelector('[data-action="previous-sheet"]'),u=e.getAvailablePaymentMethods().some(f=>f.type==="card");e.isPaymentSheetEditMode?(t.classList.add("choco-widget-payment-sheet--edit"),n&&(n.textContent=e.t("editCards")),r&&(r.style.display="none"),o&&(o.style.display="none"),i&&(i.style.display="")):(t.classList.remove("choco-widget-payment-sheet--edit"),t.classList.toggle("choco-widget-payment-sheet--no-cards",!u),n&&(n.textContent=e.t("paymentMethods")),r&&(r.style.display=""),o&&(o.style.display=u?"":"none"),i&&(i.style.display="none"))}function jt(e){if(!e.addCardActionUrl||!e.container)return;const t=e.container.querySelector('[data-sheet="add-card"]'),n=e.container.querySelector("#choco-widget-add-card-iframe");t&&n&&(n.src=e.addCardActionUrl,t.classList.add("choco-widget-payment-sheet--open"),t.style.display="flex",t.setAttribute("aria-hidden","false"),e.isAddCardViewOpen=!0,ji(e))}function Ie(e){var r,o;const t=(r=e.container)==null?void 0:r.querySelector('[data-sheet="add-card"]'),n=(o=e.container)==null?void 0:o.querySelector("#choco-widget-add-card-iframe");t&&(t.classList.remove("choco-widget-payment-sheet--open"),t.style.display="none",t.setAttribute("aria-hidden","true")),n&&(n.src="about:blank"),e.addCardActionUrl=null,e.isAddCardViewOpen=!1,Ji(e)}function ji(e){e._boundAddCardMessage=t=>{var n;e.isAddCardViewOpen&&(n=t.data)!=null&&n.message&&t.origin==="https://rahmetapp.kz"&&he(e)},window.addEventListener("message",e._boundAddCardMessage)}function Ji(e){e._boundAddCardMessage&&(window.removeEventListener("message",e._boundAddCardMessage),e._boundAddCardMessage=null)}function qi(e,t){var c;e._pendingDeleteMethod=t;const n=(c=e.container)==null?void 0:c.querySelector('[data-sheet="payment"]');if(!n)return;n.classList.add("choco-widget-payment-sheet--delete-confirm");const r=n.querySelector(".choco-widget-sheet-title"),o=n.querySelector('[data-action="edit-sheet"]'),i=n.querySelector('[data-action="previous-sheet"]');r&&(r.textContent=e.t("confirmDeleteCard")),o&&(o.style.display="none"),i&&(i.style.display="none")}function ft(e){var n;e._pendingDeleteMethod=null,Jt(e,!1);const t=(n=e.container)==null?void 0:n.querySelector('[data-sheet="payment"]');t==null||t.classList.remove("choco-widget-payment-sheet--delete-confirm"),Oe(e)}function Jt(e,t){var i,c,u;const n=(i=e.container)==null?void 0:i.querySelector(".choco-widget-sheet-delete-confirm-actions"),r=(c=e.container)==null?void 0:c.querySelector('[data-action="confirm-delete-cancel"]'),o=(u=e.container)==null?void 0:u.querySelector('[data-action="confirm-delete-submit"]');n==null||n.classList.toggle("choco-widget-sheet-delete-confirm-actions--loading",t),r&&(r.disabled=t),o&&(o.disabled=t,o.classList.toggle("choco-widget-delete-confirm-btn--loading",t))}async function zi(e,t){var r,o;const n=t==null?void 0:t.cardId;if(!(!n||(t==null?void 0:t.type)!=="card"))try{await Hr(e.apiUrl,e._getApiConfig(),n),e.checkoutContext=await Et(e.apiUrl,e._getApiConfig()),((r=e.selectedPaymentMethod)==null?void 0:r.type)==="card"&&((o=e.selectedPaymentMethod)==null?void 0:o.cardId)===n&&(e.selectedPaymentMethod=Ct(e.checkoutContext.data,e._getKaspiOptions()),e._emitPaymentMethodSelected(),lr(e)),Le(e),e.config.onSuccess({message:e.t("cardDeleted")}),e.config.onCardDeleted&&e.config.onCardDeleted({cardId:n})}catch(i){e.config.onError({attributes:{message:(i==null?void 0:i.message)||e.t("paymentError")}})}}function hr(e,t){if(e._isInteractionBlocked())return;if(e.selectedPaymentMethod=t,e._emitPaymentMethodSelected(),t.type==="new_card"){e._emitUserEvent("one_click_pay_method_resolved",{payment_method:t.type}),le(e),e.handlePayment();return}const n=e._getPaymentMethodForUserEvent();n!=null&&e._emitUserEvent("one_click_pay_method_resolved",{payment_method:n}),Le(e),le(e),lr(e)}const ht="choco_pending_order_id",Ki=1800*1e3;function Gi(e){qe(ht,JSON.stringify({id:e,ts:Date.now()}))}function Wi(){const e=bt(ht);if(!e)return null;try{const{id:t,ts:n}=JSON.parse(e);return!t||typeof n!="number"?null:Date.now()-n>Ki?(Ce(ht),null):String(t)}catch{return null}}function pr(e){e._pendingOrderId=null,Ce(ht)}function gr(e,t){var r;const n=t.type||((r=t.data)==null?void 0:r.type);if(!n){console.warn("Unknown event format:",t);return}switch(n){case"order.paid":e._orderStatusResolved=!0,pe(e),mr(e,t);break;case"order.failed":e._orderStatusResolved=!0,pe(e),Cr(e,t);break;case"order.action_required":Yi(e,t);break;default:console.warn("Unknown event type:",n)}}function pe(e){e._orderStatusPollingId&&(clearInterval(e._orderStatusPollingId),e._orderStatusPollingId=null)}function ge(e,t){pe(e),e._orderStatusResolved=!1,e._pendingOrderId=String(t),Gi(String(t));const n=6e3,r=5;let o=0;const i=async()=>{if(!e._orderStatusResolved){if(o>=r){pe(e),q(e),e.config.onError({attributes:{message:e.t("errorNoServerResponseRetry")}});return}o+=1;try{let c;try{c=await an(e.apiUrl,e._getApiConfig(),String(t))}catch(y){if((y==null?void 0:y.status)===401)await e._obtainTokenByRefreshOrTrackId(),c=await an(e.apiUrl,e._getApiConfig(),String(t));else throw y}const{data:u}=c,l=u==null?void 0:u.status,f=(u==null?void 0:u.payload)||{};if(l==="success"){e._orderStatusResolved=!0,pe(e),mr(e,{id:String(f.id||t),attributes:{amount:f.amount,paid_at:f.paid_at||""}});return}l==="fail"&&(e._orderStatusResolved=!0,pe(e),Cr(e,{id:String(f.id||t),attributes:{message:f.message||e.t("paymentError")}}))}catch(c){console.warn("[Polling] checkOrderStatus error:",c)}}};e._orderStatusPollingId=setInterval(i,n),i()}function pt(){return typeof document>"u"?!1:document.hidden||document.visibilityState==="hidden"}function yr(e,t){q(e),e.config.onSuccess(t)}function qt(e){if(!e._pendingSuccessPayload||pt())return;const t=e._pendingSuccessPayload;e._pendingSuccessPayload=null,yr(e,t)}function Ne(e){if(pt()||e._orderStatusResolved)return;const t=e._pendingOrderId||Wi();t&&(e._pendingOrderId=t,ge(e,t))}function mr(e,t){var o,i;pr(e),e.isAddCardViewOpen&&Ie(e);const n=t.attributes||((o=t.data)==null?void 0:o.attributes)||{},r={id:t.id||((i=t.data)==null?void 0:i.id),attributes:n};if(pt()){e._pendingSuccessPayload=r;return}yr(e,r)}function Cr(e,t){var r,o;pr(e),e.isAddCardViewOpen&&Ie(e),q(e);const n=t.attributes||((r=t.data)==null?void 0:r.attributes)||{};e.config.onError({id:t.id||((o=t.data)==null?void 0:o.id),attributes:n})}function Yi(e,t){var i,c,u;const n=t.attributes||((i=t.data)==null?void 0:i.attributes)||{},r=n.action_link||n.action_url,o=n.action_url_type||n.action_type||"redirect";if(!r){console.error(e.t("errorActionUrlMissing")),e.waitingForNewCardAction&&(e.waitingForNewCardAction=!1,q(e),e.config.onError({attributes:{message:e.t("errorNoServerResponse")}}));return}if(e.waitingForNewCardAction&&(e.waitingForNewCardAction=!1,e._clearNewCardActionTimeout()),o==="inner"){e.addCardActionUrl=r,q(e),e._showAddCardView();return}if(((c=e.selectedPaymentMethod)==null?void 0:c.type)==="kaspi_pay"){const l=t.id||((u=t.data)==null?void 0:u.id);if(l&&!e._orderStatusResolved&&!e._orderStatusPollingId&&ge(e,String(l)),typeof e.config.onKaspiLink=="function"){e.config.onKaspiLink({action_link:r,action_url:r,action_type:o,event:t});return}}window.location.href=r}async function Vi(e){var n,r,o,i,c;if(!e.selectedPaymentMethod){e.config.onError({attributes:{message:e.t("errorPaymentMethodNotSelected")}});return}const{checkoutOptions:t}=e._getPaymentBreakdown();if(e._isBalanceFullyCoveringAmount()){he(e);try{const u=await cn(e.apiUrl,e._getApiConfig(),e.deviceId,e.selectedPaymentMethod,t);await br(e);const l=(u==null?void 0:u.id)??((n=u==null?void 0:u.data)==null?void 0:n.id);return l&&ge(e,String(l)),u}catch(u){throw q(e),se(u,{paymentMethod:"balance"}),e.config.onError({attributes:{message:e._resolveErrorMessage(u)}}),u}}if(e.selectedPaymentMethod.type==="new_card"){await Zi(e,t);return}if(e.selectedPaymentMethod.type==="apple_pay"){await $i(e,t);return}if(e.selectedPaymentMethod.type==="google_pay"){await ea(e,t);return}he(e);try{const u=await cn(e.apiUrl,e._getApiConfig(),e.deviceId,e.selectedPaymentMethod,t);await br(e);const l=(u==null?void 0:u.id)??((r=u==null?void 0:u.data)==null?void 0:r.id);if(l&&ge(e,String(l)),((o=e.selectedPaymentMethod)==null?void 0:o.type)==="kaspi_pay"){const f=(u==null?void 0:u.attributes)||((i=u==null?void 0:u.data)==null?void 0:i.attributes)||{},y=f.action_link||f.action_url,m=f.action_url_type||f.action_type||"redirect";if(y)return typeof e.config.onKaspiLink=="function"?(e.config.onKaspiLink({action_link:y,action_url:y,action_type:m,event:u}),u):(window.location.href=y,u)}return u}catch(u){throw q(e),se(u,{paymentMethod:((c=e.selectedPaymentMethod)==null?void 0:c.type)||"card"}),e.config.onError({message:e._resolveErrorMessage(u)}),u}}async function br(e){var t,n;if(!(((t=e.selectedPaymentMethod)==null?void 0:t.type)!=="card"||!((n=e.selectedPaymentMethod)!=null&&n.cardId)))try{await jr(e.apiUrl,e._getApiConfig(),e.selectedPaymentMethod.cardId)}catch(r){console.warn("Failed to mark selected card as default:",r)}}async function Zi(e,t){he(e),e.waitingForNewCardAction=!0,e._setNewCardActionTimeout();try{await Jr(e.apiUrl,e._getApiConfig(),e.deviceId,t)}catch(n){e.waitingForNewCardAction=!1,e._clearNewCardActionTimeout(),q(e),se(n,{paymentMethod:"new_card"}),e.config.onError({attributes:{message:e._resolveErrorMessage(n)}}),console.error("New card payment error:",n)}}let De=null,Be=!1,gt=!1;async function $i(e,t){const n=window.ApplePaySession;if(!n||!n.canMakePayments()){e.config.onError({attributes:{message:e.t("errorApplePayUnsupported")}});return}if(De)return;he(e);const r={countryCode:e.config.currency==="GEL"?"GE":"KZ",currencyCode:e.config.currency,supportedNetworks:["visa","masterCard"],merchantCapabilities:["supports3DS"],total:{label:e.config.merchantName||"Choco",amount:String(e._getPayableAmount()),type:"final"}},o=new n(3,r);De=o,Be=!1,gt=!1,o.onvalidatemerchant=async i=>{var c,u;try{let l;try{l=await un(e.apiUrl,e._getApiConfig(),i.validationURL)}catch(m){if(m.status===401)await e._obtainTokenByRefreshOrTrackId(),l=await un(e.apiUrl,e._getApiConfig(),i.validationURL);else throw m}const f=((u=(c=l==null?void 0:l.data)==null?void 0:c.attributes)==null?void 0:u.session)||l,y=JSON.parse(atob(f));o.completeMerchantValidation(y),Be=!0}catch(l){console.error("Apple Pay session error:",l),se(l,{paymentMethod:"apple_pay",phase:"merchant_validation"}),q(e),gt=!0,o.abort(),e.config.onError({attributes:{message:e.t("errorApplePayInit")}})}},o.onpaymentauthorized=async i=>{var c;try{if(typeof e.config.onBeforeCheckout=="function"){const f=await e.config.onBeforeCheckout();f&&typeof f=="object"&&Object.assign(e.config,f)}const u=await zr(e.apiUrl,e._getApiConfig(),e.deviceId,i.payment,t);o.completePayment(n.STATUS_SUCCESS),De=null,Be=!1;const l=(u==null?void 0:u.id)??((c=u==null?void 0:u.data)==null?void 0:c.id);l&&!e._orderStatusResolved&&ge(e,String(l))}catch(u){console.error("Apple Pay payment error:",u),se(u,{paymentMethod:"apple_pay",phase:"payment_authorized"}),o.completePayment(n.STATUS_FAILURE),De=null,Be=!1,q(e),e.config.onError({attributes:{message:e._resolveErrorMessage(u,"errorApplePayPayment")}})}},o.oncancel=()=>{var u;const i=Be,c=gt;if(De=null,Be=!1,gt=!1,q(e),!c){if(((u=e.selectedPaymentMethod)==null?void 0:u.type)==="apple_pay"&&!i){e.config.onError({attributes:{message:e.t("errorApplePayInterrupted")}});return}e.config.onCancel()}},o.begin()}async function ea(e,t){var S,P,k,L,R,z;const n=(S=e.checkoutContext)==null?void 0:S.data,r=((k=(P=n==null?void 0:n.payment_methods)==null?void 0:P.data)==null?void 0:k.attributes)||{},o=r.google_pay_settings||{};if(!(r.payment_method_google_pay==="enabled"||r.payment_method_google_pay===!0)){e.config.onError({attributes:{message:e.t("errorGooglePayUnsupported")}});return}const c=o==null?void 0:o.gateway,u=o==null?void 0:o.merchant_id;if(!c||!u){e.config.onError({attributes:{message:e.t("errorGooglePaySettingsUnavailable")}});return}const l=e.config.environment==="production",f=(o==null?void 0:o.merchant_name)||"Choco",y=o==null?void 0:o.google_merchant_id;if(l&&!y){e.config.onError({attributes:{message:e.t("errorGooglePaySettingsUnavailable")}});return}if(e.config.isNativeAndroid){await ta(e,t,{gateway:c,gatewayMerchantId:u});return}const m=Number(e._getCheckoutAmount()).toFixed(2);try{await e._loadGooglePaySdk()}catch(D){console.error("Google Pay SDK load error:",D),e.config.onError({attributes:{message:e.t("errorGooglePayUnsupported")}});return}const C=window.google;if(!(C!=null&&C.payments)){e.config.onError({attributes:{message:e.t("errorGooglePayUnsupported")}});return}const v=[{type:"CARD",parameters:{allowedAuthMethods:["PAN_ONLY","CRYPTOGRAM_3DS"],allowedCardNetworks:["VISA","MASTERCARD"],billingAddressRequired:!1},tokenizationSpecification:{type:"PAYMENT_GATEWAY",parameters:{gateway:c,gatewayMerchantId:u}}}],B={apiVersion:2,apiVersionMinor:0,allowedPaymentMethods:v,transactionInfo:{totalPriceStatus:"FINAL",totalPriceLabel:"Итого",totalPrice:m,currencyCode:e.config.currency,countryCode:e.config.currency==="GEL"?"GE":"KZ"},merchantInfo:l?{merchantId:y,merchantName:f}:{merchantName:f}},Q=new C.payments.api.PaymentsClient({environment:l?"PRODUCTION":"TEST"});try{const D=await Q.isReadyToPay({apiVersion:2,apiVersionMinor:0,allowedPaymentMethods:v});if(!(D!=null&&D.result)){e.config.onError({attributes:{message:e.t("errorGooglePayUnsupported")}});return}he(e);const G=await Q.loadPaymentData(B),K=(R=(L=G==null?void 0:G.paymentMethodData)==null?void 0:L.tokenizationData)==null?void 0:R.token;if(!K)throw new Error(e.t("errorGooglePayPayment"));const J=JSON.parse(K),M=await ln(e.apiUrl,e._getApiConfig(),e.deviceId,J,t),I=(M==null?void 0:M.id)??((z=M==null?void 0:M.data)==null?void 0:z.id);I&&ge(e,String(I))}catch(D){q(e),D.statusCode==="CANCELED"?e.config.onCancel():(se(D,{paymentMethod:"google_pay"}),e.config.onError({attributes:{message:e._resolveErrorMessage(D,"errorGooglePayPayment")}}),console.error("Google Pay error:",D))}}async function ta(e,t,n){var r;if(!e.config.onPayWithGooglePay){e.config.onError({attributes:{message:e.t("errorGooglePayUnsupported")}});return}he(e);try{const o=await e.config.onPayWithGooglePay({amount:Number(e._getCheckoutAmount()),gateway:n.gateway,gatewayMerchantId:n.gatewayMerchantId}),i=JSON.parse(o),c=await ln(e.apiUrl,e._getApiConfig(),e.deviceId,i,t),u=(c==null?void 0:c.id)??((r=c==null?void 0:c.data)==null?void 0:r.id);u&&ge(e,String(u))}catch(o){q(e),o.statusCode==="CANCELED"?e.config.onCancel():(se(o,{paymentMethod:"google_pay_native"}),e.config.onError({attributes:{message:e._resolveErrorMessage(o,"errorGooglePayPayment")}}),console.error("Google Pay native error:",o))}}function na(e){var c,u,l,f,y,m,C,v,B,Q,S,P;const t=e.container;(c=t.querySelector('[data-action="freedom-card"]'))==null||c.addEventListener("click",()=>{e.config.onFreedomLink&&e.config.onFreedomLink()}),(u=t.querySelector('[data-action="pay"]'))==null||u.addEventListener("click",()=>e.handlePayment()),(l=t.querySelector('[data-action="change-method"]'))==null||l.addEventListener("click",()=>fr(e)),t.querySelectorAll('[data-action="close"]').forEach(k=>k.addEventListener("click",()=>e.close())),(f=t.querySelector('[data-action="close-sheet"]'))==null||f.addEventListener("click",()=>{e._pendingDeleteMethod?ft(e):le(e)}),(y=t.querySelector('[data-action="edit-sheet"]'))==null||y.addEventListener("click",()=>{e.isPaymentSheetEditMode=!0,Le(e),Oe(e)}),(m=t.querySelector('[data-action="previous-sheet"]'))==null||m.addEventListener("click",()=>{e.isPaymentSheetEditMode=!1,Le(e),Oe(e)}),(C=t.querySelector('[data-action="close-add-card"]'))==null||C.addEventListener("click",()=>Ie(e)),(v=t.querySelector('[data-action="confirm-delete-cancel"]'))==null||v.addEventListener("click",()=>ft(e)),(B=t.querySelector('[data-action="confirm-delete-submit"]'))==null||B.addEventListener("click",()=>{if(e._pendingDeleteMethod){const k=e._pendingDeleteMethod;Jt(e,!0),zi(e,k).then(()=>le(e)).finally(()=>Jt(e,!1))}}),t.querySelectorAll(".choco-widget-method-item").forEach(k=>{k.addEventListener("click",L=>{const R=JSON.parse(L.currentTarget.getAttribute("data-method")||"{}");hr(e,R)})});const n=t.querySelector('[data-sheet="payment"]');n&&(n.addEventListener("click",k=>{k.target===n&&le(e)}),oa(e,n));const r=t.querySelector('[data-action="toggle-balance"]');r&&((Q=r.querySelector("input[type='checkbox']"))==null||Q.addEventListener("change",k=>{e.useBalance=k.target.checked,dr(e),e._updatePayButtonAmount()}));const o=t.querySelector('[data-action="toggle-bonuses"]');o&&((S=o.querySelector("input[type='checkbox']"))==null||S.addEventListener("change",k=>{e.useBonuses=k.target.checked,e.config.onAppliedBonus(e.useBonuses),dr(e),e._updatePayButtonAmount()}));const i=t.querySelector('[data-action="toggle-coupon"]');i&&((P=i.querySelector("input[type='checkbox']"))==null||P.addEventListener("change",k=>{e.useCoupon=k.target.checked,e._updatePayButtonAmount(),e._emitCouponSuppressingCashback()})),document.removeEventListener("keydown",e._boundKeyDown),document.addEventListener("keydown",e._boundKeyDown),Ar(e)}function ra(e,t){var n,r;e.isOpen&&(t.key==="Escape"&&(t.preventDefault(),e._pendingDeleteMethod?ft(e):e.isAddCardViewOpen?Ie(e):e.isPaymentSheetOpen?le(e):e.close()),t.key==="Enter"&&((r=(n=t.target)==null?void 0:n.dataset)==null?void 0:r.action)==="pay"&&(t.preventDefault(),e.handlePayment()))}function oa(e,t){const n=t.querySelector('[data-action="sheet-drag-handle"]'),r=t.querySelector(".choco-widget-sheet-content");if(!n||!r)return;const o=80;let i=0,c=0;const u=f=>{c=f.clientY;const y=Math.max(0,c-i);r.style.transform=`translateY(${y}px)`},l=f=>{n.releasePointerCapture(f.pointerId),n.removeEventListener("pointermove",u),n.removeEventListener("pointerup",l),n.removeEventListener("pointercancel",l);const y=Math.max(0,c-i);if(r.classList.remove("choco-widget-sheet-content--dragging"),y>=o){r.style.transform="translateY(100%)";const m=()=>{r.removeEventListener("transitionend",m),r.style.transform="",le(e)};r.addEventListener("transitionend",m)}else r.style.transform=""};n.addEventListener("pointerdown",f=>{!e.isPaymentSheetOpen||f.button!==0||(f.preventDefault(),i=f.clientY,c=f.clientY,r.classList.add("choco-widget-sheet-content--dragging"),n.setPointerCapture(f.pointerId),n.addEventListener("pointermove",u),n.addEventListener("pointerup",l),n.addEventListener("pointercancel",l))})}class ye{static _getAuthStorageValue(t){return bt(t)}static _setAuthStorageValue(t,n){qe(t,n)}static _removeAuthStorageValue(t){Ce(t)}static async logout(){ar()}constructor(t){this.config=Kr(t),this.accessToken=null,this._tokenExpiresAt=null,this._tokenPrewarmPromise=null,this.deviceId=Zt(),this.apiUrl=kr(this.config.environment),this.translations=Qe,this.checkoutContext=null,this.centrifuge=null,this.selectedPaymentMethod=null,this.selectedCoupon=null,this.useCoupon=!1,this.container=null,this.isOpen=!1,this.isPaymentSheetOpen=!1,this.isPaymentSheetEditMode=!1,this.loading=!1,this.disabled=!1,this.paymentMethodDisabled=!1,this.useBalance=!1,this.useBonuses=!1,this.addCardActionUrl=null,this.isAddCardViewOpen=!1,this.waitingForNewCardAction=!1,this.newCardActionRequiredTimeoutId=null,this._googlePayScriptPromise=null,this._googlePayButtonRenderVersion=0,this._orderStatusPollingId=null,this._orderStatusResolved=!1,this._pendingOrderId=null,this._pendingDeleteMethod=null,this._pendingSuccessPayload=null,this._lifecycleListenersAttached=!1,this._destroyed=!1,this._boundAddCardMessage=null,this._boundKeyDown=n=>ra(this,n),this._boundVisibilityChange=()=>this._onVisibilityChange(),this._boundWindowFocus=()=>this._onWindowFocus(),this._boundPageShow=()=>this._onPageShow(),Bi({clientId:String(this.config.clientId),terminalId:String(this.config.terminalId),environment:this.config.environment})}t(t,n={}){var i;const r=this.config.locale||"ru",o=((i=this.translations[r])==null?void 0:i[t])||this.translations.ru[t];return typeof o!="string"?t:o.replace(/{(\w+)}/g,(c,u)=>Object.prototype.hasOwnProperty.call(n,u)?String(n[u]):c)}_resolveErrorMessage(t,n="paymentError"){return(t==null?void 0:t.message)||this.t(n)}_getApiConfig(){return{...this.config,accessToken:this.accessToken}}_isInteractionBlocked(){return this.disabled||this.loading}_getBalanceAmount(){var o,i,c,u;const t=(u=(c=(i=(o=this.checkoutContext)==null?void 0:o.data)==null?void 0:i.balance)==null?void 0:c.data)==null?void 0:u.money,n=this.config.currency||"KZT",r=Number(t==null?void 0:t[n]);return Number.isFinite(r)&&r>0?r:0}_getBonusesAmount(){var n;const t=Number((n=this.config.bonuses)==null?void 0:n.amount);return Number.isFinite(t)&&t>0?t:0}_getBonusesPercent(){var n;const t=Number((n=this.config.bonuses)==null?void 0:n.percent);return!Number.isFinite(t)||t<=0?0:t>=100?100:t}_getAvailableBonus(){var n;const t=Number((n=this.config.bonuses)==null?void 0:n.availableBonus);return Number.isFinite(t)&&t>0?t:0}_getCouponDiscount(){if(!this.useCoupon||!this.selectedCoupon||this._isCouponDisabled()||this.selectedCoupon.type==="coupon")return 0;const t=Number(this.selectedCoupon.reward_amount);return Number.isFinite(t)&&t>0?t:0}_getPaymentBreakdown(){const t=this.config.amount,n=this._getBalanceAmount(),r=this.useBalance?Math.min(n,t):0,o=t-r,i=this.useBalance&&r>=t,c=this.useBonuses?this._getAvailableBonus():0,u=Math.max(o-c,0),l=this._getCouponDiscount(),f=Math.max(u-l,0),y=this.useBalance?t:f,m=this.useBalance&&!i,v=this.useCoupon&&this.selectedCoupon&&!this._isCouponDisabled()?{id:this.selectedCoupon.voucher_id,template_id:this.selectedCoupon.template_id,type:this.selectedCoupon.type}:void 0;return{payableAmount:f,checkoutOptions:{checkoutAmount:y,forceBalanceMethod:i,useBalance:m,voucher:v}}}_getPayableAmount(){return this._getPaymentBreakdown().payableAmount}_isBalanceFullyCoveringAmount(){return this._getPaymentBreakdown().checkoutOptions.forceBalanceMethod}_getCheckoutAmount(){return this._getPaymentBreakdown().checkoutOptions.checkoutAmount??this.config.amount}_getPaymentMethodForUserEvent(){var t;return this._isBalanceFullyCoveringAmount()?"balance":((t=this.selectedPaymentMethod)==null?void 0:t.type)??null}_getKaspiOptions(){return{onlyKaspiAvailable:this.config.onlyKaspiAvailable,disableKaspi:this.config.disableKaspi,disableGooglePay:this.config.disableGooglePay}}_emitUserEvent(t,n={}){typeof this.config.onUserEvent=="function"&&this.config.onUserEvent({eventName:t,eventProperties:n})}_emitPaymentMethodSelected(t=this.selectedPaymentMethod){typeof this.config.onPaymentMethodSelected=="function"&&this.config.onPaymentMethodSelected(t||null)}_emitCouponSuppressingCashback(){var n;const t=this.useCoupon&&((n=this.selectedCoupon)==null?void 0:n.suppresses_cashback)===!0;this.config.onCouponSuppressingCashback(t)}_attachEventListeners(){na(this)}_updatePayButtonAmount(){dt(this)}_showAddCardView(){jt(this)}_closeAddCardView(){Ie(this)}_setNewCardActionTimeout(){this._clearNewCardActionTimeout(),this.newCardActionRequiredTimeoutId=setTimeout(()=>{this.waitingForNewCardAction&&(this.waitingForNewCardAction=!1,q(this),this.config.onError({attributes:{message:this.t("errorNoServerResponseRetry")}})),this.newCardActionRequiredTimeoutId=null},6e4)}_clearNewCardActionTimeout(){this.newCardActionRequiredTimeoutId&&(window.clearTimeout(this.newCardActionRequiredTimeoutId),this.newCardActionRequiredTimeoutId=null)}_saveTokensToStorage(t,n){ir(t,n)}_clearAuthStorage(){ar()}_getAuthStorageValue(t){return ye._getAuthStorageValue(t)}_setAuthStorageValue(t,n){ye._setAuthStorageValue(t,n)}_removeAuthStorageValue(t){ye._removeAuthStorageValue(t)}_loadGooglePaySdk(){var t,n;return typeof window>"u"||typeof document>"u"?Promise.reject(new Error("Google Pay SDK requires browser environment")):(n=(t=window.google)==null?void 0:t.payments)!=null&&n.api?Promise.resolve():this._googlePayScriptPromise?this._googlePayScriptPromise:(this._googlePayScriptPromise=new Promise((r,o)=>{const i=document.querySelector('script[data-choco-google-pay-sdk="true"]');if(i){i.addEventListener("load",()=>r(),{once:!0}),i.addEventListener("error",()=>o(new Error("Failed to load Google Pay SDK")),{once:!0});return}const c=document.createElement("script");c.src="https://pay.google.com/gp/p/js/pay.js",c.async=!0,c.defer=!0,c.setAttribute("data-choco-google-pay-sdk","true"),c.onload=()=>r(),c.onerror=()=>o(new Error("Failed to load Google Pay SDK")),document.head.appendChild(c)}).finally(()=>{var r,o;(o=(r=window.google)==null?void 0:r.payments)!=null&&o.api||(this._googlePayScriptPromise=null)}),this._googlePayScriptPromise)}_attachLifecycleListeners(){this._lifecycleListenersAttached||(document.addEventListener("visibilitychange",this._boundVisibilityChange),window.addEventListener("focus",this._boundWindowFocus),window.addEventListener("pageshow",this._boundPageShow),this._lifecycleListenersAttached=!0)}_detachLifecycleListeners(){this._lifecycleListenersAttached&&(document.removeEventListener("visibilitychange",this._boundVisibilityChange),window.removeEventListener("focus",this._boundWindowFocus),window.removeEventListener("pageshow",this._boundPageShow),this._lifecycleListenersAttached=!1)}_onVisibilityChange(){pt()||(qt(this),Ne(this))}_onWindowFocus(){qt(this),Ne(this)}_onPageShow(){qt(this),Ne(this)}async _obtainTokenByRefreshOrTrackId(){await Si(this)}_isTokenExpiringSoon(t=9e4){return this.accessToken?this._tokenExpiresAt==null?!1:Date.now()>=this._tokenExpiresAt-t:!0}_prewarmAuthToken(){this._destroyed||this.paymentMethodDisabled||this._tokenPrewarmPromise||!this._isTokenExpiringSoon()||(this._tokenPrewarmPromise=this._obtainTokenByRefreshOrTrackId().catch(()=>{}).finally(()=>{this._tokenPrewarmPromise=null}))}async _fetchCheckoutContextWithRetry(){try{this.checkoutContext=await Et(this.apiUrl,this._getApiConfig())}catch(t){if(t.status===401)this._removeAuthStorageValue("webPayToken"),await this._obtainTokenByRefreshOrTrackId(),this.checkoutContext=await Et(this.apiUrl,this._getApiConfig());else throw t}}async _fetchCoupons(){try{const t=await qr(this.apiUrl,this._getApiConfig()),r=(Array.isArray(t)?t:Array.isArray(t==null?void 0:t.data)?t.data:[]).filter(o=>Number(o.reward_amount)>0).sort((o,i)=>o.sort_weight-i.sort_weight);this.selectedCoupon=r.length>0?r[0]:null,this.useCoupon=!1}catch{this.selectedCoupon=null,this.useCoupon=!1}}_isCouponDisabled(){if(!this.selectedCoupon)return!1;if(this.config.amount<this.selectedCoupon.min_pay_amount)return!0;const t=this._getBalanceAmount(),n=this.useBalance?Math.min(t,this.config.amount):0,r=this.config.amount-n,o=this.useBonuses?Math.min(this._getAvailableBonus(),r):0;return r-o<this.selectedCoupon.reward_amount}_prerender(){Ui(this)}_render(){Fi(this)}async init(){var t,n;try{if(this._prerender(),this._attachLifecycleListeners(),!this.config.clientId)return this.config.onError({attributes:{message:this.t("errorMissingTrackClient")}}),!1;if(this.accessToken=this._getAuthStorageValue("webPayToken"),!this.config.trackId&&!this.accessToken)return this.paymentMethodDisabled=!0,this._render(),!0;if(!this.accessToken&&(await this._obtainTokenByRefreshOrTrackId(),this._destroyed))return!1;try{await this._fetchCheckoutContextWithRetry()}catch(o){const i=o;return this.config.onError({attributes:{message:i.message}}),!1}if(this._destroyed||(await this._fetchCoupons(),this._emitCouponSuppressingCashback(),this._destroyed))return!1;const r=tn((n=(t=this.checkoutContext)==null?void 0:t.data)==null?void 0:n.socket_connections,o=>gr(this,o));return r&&(this.centrifuge=r.centrifuge),Ne(this),this.selectedPaymentMethod=Ct(this.checkoutContext.data,this._getKaspiOptions()),this._emitPaymentMethodSelected(),this._render(),!0}catch(r){return console.error(`${this.t("errorWidgetInit")}:`,r),se(r,{phase:"init"}),this.config.onError({attributes:{message:r.message}}),!1}}close(){this.config.onCancel()}destroy(){this._destroyed=!0;const t=document.getElementById("choco-one-click-widget");t&&(t.style.display="none"),this._clearNewCardActionTimeout(),pe(this),this._pendingSuccessPayload=null,this._detachLifecycleListeners(),this.isAddCardViewOpen&&Ie(this),this.centrifuge&&(this.centrifuge.disconnect(),this.centrifuge=null),document.removeEventListener("keydown",this._boundKeyDown),this.container&&(this.container.classList.remove("choco-one-click-widget--visible"),setTimeout(()=>{var n;(n=this.container)==null||n.remove(),this.container=null},300)),this.isOpen=!1,this.isPaymentSheetOpen=!1,this.isAddCardViewOpen=!1,this.selectedPaymentMethod=null}getAvailablePaymentMethods(){var t;return(t=this.checkoutContext)!=null&&t.data?Ur(this.checkoutContext.data,n=>this.t(n),this._getKaspiOptions()):[]}async createOrder(){return Vi(this)}async pay(){try{await this.createOrder()}catch(t){console.error(`${this.t("errorPaymentProcess")}:`,t)}}async handlePayment(){if(this._isInteractionBlocked())return;const t=this._getPaymentMethodForUserEvent();t!=null&&this._emitUserEvent("one_click_pay_cta_tapped",{payment_method:t});try{if(this.config.onConfirmPay){this.config.onConfirmPay(this.selectedPaymentMethod||null);return}await this.pay()}catch(n){console.error(`${this.t("errorPaymentProcess")}:`,n)}}openPaymentSheet(){fr(this)}closePaymentSheet(){le(this)}resumeOrderStatusCheck(){Ne(this)}async updateAmount(t){var n;if(typeof t!="number"||!Number.isFinite(t)||t<0)throw new Error("amount must be a non-negative number");if(this.config.amount=t,this._isCouponDisabled()&&(this.useCoupon=!1),this.selectedCoupon){const r=this.isPaymentSheetOpen,o=this.isAddCardViewOpen;if(this._render(),ue(this),r){const i=(n=this.container)==null?void 0:n.querySelector('[data-sheet="payment"]');i&&(i.classList.add("choco-widget-payment-sheet--open"),this.isPaymentSheetOpen=!0)}o&&jt(this);return}dt(this)}async updateAvailableBonus(t){if(typeof t!="number"||!Number.isFinite(t)||t<0)throw new Error("availableBonus must be a non-negative number");this.config.bonuses&&(this.config.bonuses.availableBonus=t),dt(this)}async updateLocale(t){if(typeof t!="string"||!this.translations[t])throw new Error(`Unsupported locale: ${t}`);if(this.config.locale=t,!this.container)return;const n=this.isPaymentSheetOpen,r=this.isAddCardViewOpen;if(this._render(),ue(this),n){const o=this.container.querySelector('[data-sheet="payment"]');o&&(o.classList.add("choco-widget-payment-sheet--open"),this.isPaymentSheetOpen=!0)}r&&jt(this)}async setLoading(t){this.loading=!!t,ue(this)}async setDisabled(t){this.disabled=!!t,ue(this)}async setPreorderId(t){this.config.preorderId=t}async setMerchantOrderId(t){this.config.merchantOrderId=t}async setIdempotencyKey(t){this.config.idempotencyKey=t}async logout(){await ye.logout(),this.accessToken=null}async updateTrackId(t){var n,r;if(this.config.trackId=t,!this.config.clientId)return this.config.onError({attributes:{message:this.t("errorMissingTrackClient")}}),!1;try{this._prerender(),await this._obtainTokenByRefreshOrTrackId();try{await this._fetchCheckoutContextWithRetry()}catch(i){const c=i;return this.config.onError({attributes:{message:c.message}}),!1}await this._fetchCoupons(),this._emitCouponSuppressingCashback(),this.centrifuge&&(this.centrifuge.disconnect(),this.centrifuge=null);const o=tn((r=(n=this.checkoutContext)==null?void 0:n.data)==null?void 0:r.socket_connections,i=>gr(this,i));return o&&(this.centrifuge=o.centrifuge),this.selectedPaymentMethod=Ct(this.checkoutContext.data,this._getKaspiOptions()),this._emitPaymentMethodSelected(),this.paymentMethodDisabled=!1,this._render(),!0}catch(o){return console.error(`${this.t("errorWidgetInit")}:`,o),se(o,{phase:"updateTrackId"}),this.config.onError({attributes:{message:o.message}}),!1}}async onConfirmPay(t){if(typeof t!="function")throw new Error("onConfirmPay callback must be a function");this.config.onConfirmPay=t}async onPaymentMethodSelected(t){if(typeof t!="function")throw new Error("onPaymentMethodSelected callback must be a function");this.config.onPaymentMethodSelected=t,this._emitPaymentMethodSelected()}async onKaspiLink(t){if(typeof t!="function")throw new Error("onKaspiLink callback must be a function");this.config.onKaspiLink=t}async onUserEvent(t){if(typeof t!="function")throw new Error("onUserEvent callback must be a function");this.config.onUserEvent=t}async onFreedomLink(t){if(typeof t!="function")throw new Error("onFreedomLink callback must be a function");this.config.onFreedomLink=t}async onAppliedBonus(t){if(typeof t!="function")throw new Error("onAppliedBonus callback must be a function");this.config.onAppliedBonus=t}async onCouponSuppressingCashback(t){if(typeof t!="function")throw new Error("onCouponSuppressingCashback callback must be a function");this.config.onCouponSuppressingCashback=t}}return typeof window<"u"&&(window.ChocoOneClickWidget=ye),ye}));
315
+ `,n.appendChild(r),n.appendChild(o),t.appendChild(n),ue(e)}function dr(e){var o;if(!e.selectedCoupon)return;const t=e._isCouponDisabled();t&&e.useCoupon&&(e.useCoupon=!1);const n=(o=e.container)==null?void 0:o.querySelector('[data-action="toggle-coupon"]');if(!n)return;n.classList.toggle("choco-widget-balance-toggle--disabled",t);const r=n.querySelector("input[type='checkbox']");r&&(r.disabled=t,t&&(r.checked=!1))}function he(e){e.loading=!0,ue(e)}function q(e){var m,C,v,B,Q,S,P,k;e.loading=!1;const t=(m=e.container)==null?void 0:m.querySelector(".choco-widget-payment-method"),n=(C=e.container)==null?void 0:C.querySelector(".choco-widget-pay-button"),r=(v=e.container)==null?void 0:v.querySelector(".choco-widget-google-pay-button-slot button"),o=(B=e.container)==null?void 0:B.querySelector(".choco-widget-apple-pay-button-slot button"),i=(Q=e.container)==null?void 0:Q.querySelector(".choco-widget-google-pay-amount"),c=(S=e.container)==null?void 0:S.querySelector(".choco-widget-google-pay-row"),u=(P=e.container)==null?void 0:P.querySelector(".choco-widget-apple-pay-row"),l=(k=e.container)==null?void 0:k.querySelector(".choco-widget-balance-section"),f=e._isInteractionBlocked(),y=e.paymentMethodDisabled||f;t&&(t.disabled=y),n&&(n.disabled=f,n.classList.remove("choco-widget-pay-button--loading")),r&&(r.disabled=f),o&&(o.disabled=f),i==null||i.classList.toggle("choco-widget-wallet-blocked",f),i==null||i.setAttribute("aria-disabled",String(f)),c==null||c.classList.toggle("choco-widget-wallet-blocked",f),c==null||c.setAttribute("aria-disabled",String(f)),u==null||u.classList.toggle("choco-widget-wallet-blocked",f),u==null||u.setAttribute("aria-disabled",String(f)),l==null||l.classList.remove("disabled")}function ue(e){var C,v,B,Q,S,P,k,L,R;const t=(C=e.container)==null?void 0:C.querySelector(".choco-widget-payment-method"),n=(v=e.container)==null?void 0:v.querySelector(".choco-widget-pay-button"),r=(B=e.container)==null?void 0:B.querySelector(".choco-widget-freedom-card-btn"),o=(Q=e.container)==null?void 0:Q.querySelector(".choco-widget-google-pay-button-slot button"),i=(S=e.container)==null?void 0:S.querySelector(".choco-widget-apple-pay-button-slot button"),c=(P=e.container)==null?void 0:P.querySelector(".choco-widget-google-pay-amount"),u=(k=e.container)==null?void 0:k.querySelector(".choco-widget-google-pay-row"),l=(L=e.container)==null?void 0:L.querySelector(".choco-widget-apple-pay-row"),f=(R=e.container)==null?void 0:R.querySelector(".choco-widget-balance-section"),y=e._isInteractionBlocked(),m=e.paymentMethodDisabled||y;f==null||f.classList.toggle("disabled",y),t&&(t.disabled=m),n&&(n.disabled=y,n.classList.toggle("choco-widget-pay-button--loading",e.loading)),r&&(r.disabled=y),o&&(o.disabled=y),i&&(i.disabled=y),c==null||c.classList.toggle("choco-widget-wallet-blocked",y),c==null||c.setAttribute("aria-disabled",String(y)),u==null||u.classList.toggle("choco-widget-wallet-blocked",y),u==null||u.setAttribute("aria-disabled",String(y)),l==null||l.classList.toggle("choco-widget-wallet-blocked",y),l==null||l.setAttribute("aria-disabled",String(y))}function fr(e){var n;if(e._isInteractionBlocked())return;const t=(n=e.container)==null?void 0:n.querySelector('[data-sheet="payment"]');t&&(t.classList.add("choco-widget-payment-sheet--open"),e.isPaymentSheetOpen=!0,Oe(e))}function le(e){var n;const t=(n=e.container)==null?void 0:n.querySelector('[data-sheet="payment"]');if(t){ft(e);const r=t.querySelector(".choco-widget-sheet-content");r&&(r.style.transform="",r.classList.remove("choco-widget-sheet-content--dragging")),t.classList.remove("choco-widget-payment-sheet--open"),e.isPaymentSheetOpen=!1,e.isPaymentSheetEditMode&&(e.isPaymentSheetEditMode=!1,Le(e),Oe(e))}}function Oe(e){var l;const t=(l=e.container)==null?void 0:l.querySelector('[data-sheet="payment"]');if(!t)return;const n=t.querySelector(".choco-widget-sheet-title"),r=t.querySelector('[data-action="close-sheet"]'),o=t.querySelector('[data-action="edit-sheet"]'),i=t.querySelector('[data-action="previous-sheet"]'),u=e.getAvailablePaymentMethods().some(f=>f.type==="card");e.isPaymentSheetEditMode?(t.classList.add("choco-widget-payment-sheet--edit"),n&&(n.textContent=e.t("editCards")),r&&(r.style.display="none"),o&&(o.style.display="none"),i&&(i.style.display="")):(t.classList.remove("choco-widget-payment-sheet--edit"),t.classList.toggle("choco-widget-payment-sheet--no-cards",!u),n&&(n.textContent=e.t("paymentMethods")),r&&(r.style.display=""),o&&(o.style.display=u?"":"none"),i&&(i.style.display="none"))}function jt(e){if(!e.addCardActionUrl||!e.container)return;const t=e.container.querySelector('[data-sheet="add-card"]'),n=e.container.querySelector("#choco-widget-add-card-iframe");t&&n&&(n.src=e.addCardActionUrl,t.classList.add("choco-widget-payment-sheet--open"),t.style.display="flex",t.setAttribute("aria-hidden","false"),e.isAddCardViewOpen=!0,ji(e))}function Ie(e){var r,o;const t=(r=e.container)==null?void 0:r.querySelector('[data-sheet="add-card"]'),n=(o=e.container)==null?void 0:o.querySelector("#choco-widget-add-card-iframe");t&&(t.classList.remove("choco-widget-payment-sheet--open"),t.style.display="none",t.setAttribute("aria-hidden","true")),n&&(n.src="about:blank"),e.addCardActionUrl=null,e.isAddCardViewOpen=!1,Ji(e)}function ji(e){e._boundAddCardMessage=t=>{var n;e.isAddCardViewOpen&&(n=t.data)!=null&&n.message&&t.origin==="https://rahmetapp.kz"&&he(e)},window.addEventListener("message",e._boundAddCardMessage)}function Ji(e){e._boundAddCardMessage&&(window.removeEventListener("message",e._boundAddCardMessage),e._boundAddCardMessage=null)}function qi(e,t){var c;e._pendingDeleteMethod=t;const n=(c=e.container)==null?void 0:c.querySelector('[data-sheet="payment"]');if(!n)return;n.classList.add("choco-widget-payment-sheet--delete-confirm");const r=n.querySelector(".choco-widget-sheet-title"),o=n.querySelector('[data-action="edit-sheet"]'),i=n.querySelector('[data-action="previous-sheet"]');r&&(r.textContent=e.t("confirmDeleteCard")),o&&(o.style.display="none"),i&&(i.style.display="none")}function ft(e){var n;e._pendingDeleteMethod=null,Jt(e,!1);const t=(n=e.container)==null?void 0:n.querySelector('[data-sheet="payment"]');t==null||t.classList.remove("choco-widget-payment-sheet--delete-confirm"),Oe(e)}function Jt(e,t){var i,c,u;const n=(i=e.container)==null?void 0:i.querySelector(".choco-widget-sheet-delete-confirm-actions"),r=(c=e.container)==null?void 0:c.querySelector('[data-action="confirm-delete-cancel"]'),o=(u=e.container)==null?void 0:u.querySelector('[data-action="confirm-delete-submit"]');n==null||n.classList.toggle("choco-widget-sheet-delete-confirm-actions--loading",t),r&&(r.disabled=t),o&&(o.disabled=t,o.classList.toggle("choco-widget-delete-confirm-btn--loading",t))}async function zi(e,t){var r,o;const n=t==null?void 0:t.cardId;if(!(!n||(t==null?void 0:t.type)!=="card"))try{await Hr(e.apiUrl,e._getApiConfig(),n),e.checkoutContext=await Et(e.apiUrl,e._getApiConfig()),((r=e.selectedPaymentMethod)==null?void 0:r.type)==="card"&&((o=e.selectedPaymentMethod)==null?void 0:o.cardId)===n&&(e.selectedPaymentMethod=Ct(e.checkoutContext.data,e._getKaspiOptions()),e._emitPaymentMethodSelected(),lr(e)),Le(e),e.config.onSuccess({message:e.t("cardDeleted")}),e.config.onCardDeleted&&e.config.onCardDeleted({cardId:n})}catch(i){e.config.onError({attributes:{message:(i==null?void 0:i.message)||e.t("paymentError")}})}}function hr(e,t){if(e._isInteractionBlocked())return;if(e.selectedPaymentMethod=t,e._emitPaymentMethodSelected(),t.type==="new_card"){e._emitUserEvent("one_click_pay_method_resolved",{payment_method:t.type}),le(e),e.handlePayment();return}const n=e._getPaymentMethodForUserEvent();n!=null&&e._emitUserEvent("one_click_pay_method_resolved",{payment_method:n}),Le(e),le(e),lr(e)}const ht="choco_pending_order_id",Ki=1800*1e3;function Gi(e){qe(ht,JSON.stringify({id:e,ts:Date.now()}))}function Wi(){const e=bt(ht);if(!e)return null;try{const{id:t,ts:n}=JSON.parse(e);return!t||typeof n!="number"?null:Date.now()-n>Ki?(Ce(ht),null):String(t)}catch{return null}}function pr(e){e._pendingOrderId=null,Ce(ht)}function gr(e,t){var r;const n=t.type||((r=t.data)==null?void 0:r.type);if(!n){console.warn("Unknown event format:",t);return}switch(n){case"order.paid":e._orderStatusResolved=!0,pe(e),mr(e,t);break;case"order.failed":e._orderStatusResolved=!0,pe(e),Cr(e,t);break;case"order.action_required":Yi(e,t);break;default:console.warn("Unknown event type:",n)}}function pe(e){e._orderStatusPollingId&&(clearInterval(e._orderStatusPollingId),e._orderStatusPollingId=null)}function ge(e,t){pe(e),e._orderStatusResolved=!1,e._pendingOrderId=String(t),Gi(String(t));const n=6e3,r=5;let o=0;const i=async()=>{if(!e._orderStatusResolved){if(o>=r){pe(e),q(e),e.config.onError({attributes:{message:e.t("errorNoServerResponseRetry")}});return}o+=1;try{let c;try{c=await an(e.apiUrl,e._getApiConfig(),String(t))}catch(y){if((y==null?void 0:y.status)===401)await e._obtainTokenByRefreshOrTrackId(),c=await an(e.apiUrl,e._getApiConfig(),String(t));else throw y}const{data:u}=c,l=u==null?void 0:u.status,f=(u==null?void 0:u.payload)||{};if(l==="success"){e._orderStatusResolved=!0,pe(e),mr(e,{id:String(f.id||t),attributes:{amount:f.amount,paid_at:f.paid_at||""}});return}l==="fail"&&(e._orderStatusResolved=!0,pe(e),Cr(e,{id:String(f.id||t),attributes:{message:f.message||e.t("paymentError")}}))}catch(c){console.warn("[Polling] checkOrderStatus error:",c)}}};e._orderStatusPollingId=setInterval(i,n),i()}function pt(){return typeof document>"u"?!1:document.hidden||document.visibilityState==="hidden"}function yr(e,t){q(e),e.config.onSuccess(t)}function qt(e){if(!e._pendingSuccessPayload||pt())return;const t=e._pendingSuccessPayload;e._pendingSuccessPayload=null,yr(e,t)}function Ne(e){if(pt()||e._orderStatusResolved)return;const t=e._pendingOrderId||Wi();t&&(e._pendingOrderId=t,ge(e,t))}function mr(e,t){var o,i;pr(e),e.isAddCardViewOpen&&Ie(e);const n=t.attributes||((o=t.data)==null?void 0:o.attributes)||{},r={id:t.id||((i=t.data)==null?void 0:i.id),attributes:n};if(pt()){e._pendingSuccessPayload=r;return}yr(e,r)}function Cr(e,t){var r,o;pr(e),e.isAddCardViewOpen&&Ie(e),q(e);const n=t.attributes||((r=t.data)==null?void 0:r.attributes)||{};e.config.onError({id:t.id||((o=t.data)==null?void 0:o.id),attributes:n})}function Yi(e,t){var i,c,u;const n=t.attributes||((i=t.data)==null?void 0:i.attributes)||{},r=n.action_link||n.action_url,o=n.action_url_type||n.action_type||"redirect";if(!r){console.error(e.t("errorActionUrlMissing")),e.waitingForNewCardAction&&(e.waitingForNewCardAction=!1,q(e),e.config.onError({attributes:{message:e.t("errorNoServerResponse")}}));return}if(e.waitingForNewCardAction&&(e.waitingForNewCardAction=!1,e._clearNewCardActionTimeout()),o==="inner"){e.addCardActionUrl=r,q(e),e._showAddCardView();return}if(((c=e.selectedPaymentMethod)==null?void 0:c.type)==="kaspi_pay"){const l=t.id||((u=t.data)==null?void 0:u.id);if(l&&!e._orderStatusResolved&&!e._orderStatusPollingId&&ge(e,String(l)),typeof e.config.onKaspiLink=="function"){e.config.onKaspiLink({action_link:r,action_url:r,action_type:o,event:t});return}}window.location.href=r}async function Vi(e){var n,r,o,i,c;if(!e.selectedPaymentMethod){e.config.onError({attributes:{message:e.t("errorPaymentMethodNotSelected")}});return}const{checkoutOptions:t}=e._getPaymentBreakdown();if(e._isBalanceFullyCoveringAmount()){he(e);try{const u=await cn(e.apiUrl,e._getApiConfig(),e.deviceId,e.selectedPaymentMethod,t);await br(e);const l=(u==null?void 0:u.id)??((n=u==null?void 0:u.data)==null?void 0:n.id);return l&&ge(e,String(l)),u}catch(u){throw q(e),te(u,{paymentMethod:"balance"}),e.config.onError({attributes:{message:e._resolveErrorMessage(u)}}),u}}if(e.selectedPaymentMethod.type==="new_card"){await Zi(e,t);return}if(e.selectedPaymentMethod.type==="apple_pay"){await $i(e,t);return}if(e.selectedPaymentMethod.type==="google_pay"){await ea(e,t);return}he(e);try{const u=await cn(e.apiUrl,e._getApiConfig(),e.deviceId,e.selectedPaymentMethod,t);await br(e);const l=(u==null?void 0:u.id)??((r=u==null?void 0:u.data)==null?void 0:r.id);if(l&&ge(e,String(l)),((o=e.selectedPaymentMethod)==null?void 0:o.type)==="kaspi_pay"){const f=(u==null?void 0:u.attributes)||((i=u==null?void 0:u.data)==null?void 0:i.attributes)||{},y=f.action_link||f.action_url,m=f.action_url_type||f.action_type||"redirect";if(y)return typeof e.config.onKaspiLink=="function"?(e.config.onKaspiLink({action_link:y,action_url:y,action_type:m,event:u}),u):(window.location.href=y,u)}return u}catch(u){throw q(e),te(u,{paymentMethod:((c=e.selectedPaymentMethod)==null?void 0:c.type)||"card"}),e.config.onError({message:e._resolveErrorMessage(u)}),u}}async function br(e){var t,n;if(!(((t=e.selectedPaymentMethod)==null?void 0:t.type)!=="card"||!((n=e.selectedPaymentMethod)!=null&&n.cardId)))try{await jr(e.apiUrl,e._getApiConfig(),e.selectedPaymentMethod.cardId)}catch(r){console.warn("Failed to mark selected card as default:",r)}}async function Zi(e,t){he(e),e.waitingForNewCardAction=!0,e._setNewCardActionTimeout();try{await Jr(e.apiUrl,e._getApiConfig(),e.deviceId,t)}catch(n){e.waitingForNewCardAction=!1,e._clearNewCardActionTimeout(),q(e),te(n,{paymentMethod:"new_card"}),e.config.onError({attributes:{message:e._resolveErrorMessage(n)}}),console.error("New card payment error:",n)}}let De=null,Be=!1,gt=!1;async function $i(e,t){const n=window.ApplePaySession;if(!n||!n.canMakePayments()){e.config.onError({attributes:{message:e.t("errorApplePayUnsupported")}});return}if(De)return;he(e);const r={countryCode:e.config.currency==="GEL"?"GE":"KZ",currencyCode:e.config.currency,supportedNetworks:["visa","masterCard"],merchantCapabilities:["supports3DS"],total:{label:e.config.merchantName||"Choco",amount:String(e._getPayableAmount()),type:"final"}},o=new n(3,r);De=o,Be=!1,gt=!1,o.onvalidatemerchant=async i=>{var c,u;try{let l;try{l=await un(e.apiUrl,e._getApiConfig(),i.validationURL)}catch(m){if(m.status===401)await e._obtainTokenByRefreshOrTrackId(),l=await un(e.apiUrl,e._getApiConfig(),i.validationURL);else throw m}const f=((u=(c=l==null?void 0:l.data)==null?void 0:c.attributes)==null?void 0:u.session)||l,y=JSON.parse(atob(f));o.completeMerchantValidation(y),Be=!0}catch(l){console.error("Apple Pay session error:",l),te(l,{paymentMethod:"apple_pay",phase:"merchant_validation"}),q(e),gt=!0,o.abort(),e.config.onError({attributes:{message:e.t("errorApplePayInit")}})}},o.onpaymentauthorized=async i=>{var c;try{if(typeof e.config.onBeforeCheckout=="function"){const f=await e.config.onBeforeCheckout();f&&typeof f=="object"&&Object.assign(e.config,f)}const u=await zr(e.apiUrl,e._getApiConfig(),e.deviceId,i.payment,t);o.completePayment(n.STATUS_SUCCESS),De=null,Be=!1;const l=(u==null?void 0:u.id)??((c=u==null?void 0:u.data)==null?void 0:c.id);l&&!e._orderStatusResolved&&ge(e,String(l))}catch(u){console.error("Apple Pay payment error:",u),te(u,{paymentMethod:"apple_pay",phase:"payment_authorized"}),o.completePayment(n.STATUS_FAILURE),De=null,Be=!1,q(e),e.config.onError({attributes:{message:e._resolveErrorMessage(u,"errorApplePayPayment")}})}},o.oncancel=()=>{var u;const i=Be,c=gt;if(De=null,Be=!1,gt=!1,q(e),!c){if(((u=e.selectedPaymentMethod)==null?void 0:u.type)==="apple_pay"&&!i){e.config.onError({attributes:{message:e.t("errorApplePayInterrupted")}});return}e.config.onCancel()}},o.begin()}async function ea(e,t){var S,P,k,L,R,z;const n=(S=e.checkoutContext)==null?void 0:S.data,r=((k=(P=n==null?void 0:n.payment_methods)==null?void 0:P.data)==null?void 0:k.attributes)||{},o=r.google_pay_settings||{};if(!(r.payment_method_google_pay==="enabled"||r.payment_method_google_pay===!0)){e.config.onError({attributes:{message:e.t("errorGooglePayUnsupported")}});return}const c=o==null?void 0:o.gateway,u=o==null?void 0:o.merchant_id;if(!c||!u){e.config.onError({attributes:{message:e.t("errorGooglePaySettingsUnavailable")}});return}const l=e.config.environment==="production",f=(o==null?void 0:o.merchant_name)||"Choco",y=o==null?void 0:o.google_merchant_id;if(l&&!y){e.config.onError({attributes:{message:e.t("errorGooglePaySettingsUnavailable")}});return}if(e.config.isNativeAndroid){await ta(e,t,{gateway:c,gatewayMerchantId:u});return}const m=Number(e._getCheckoutAmount()).toFixed(2);try{await e._loadGooglePaySdk()}catch(D){console.error("Google Pay SDK load error:",D),e.config.onError({attributes:{message:e.t("errorGooglePayUnsupported")}});return}const C=window.google;if(!(C!=null&&C.payments)){e.config.onError({attributes:{message:e.t("errorGooglePayUnsupported")}});return}const v=[{type:"CARD",parameters:{allowedAuthMethods:["PAN_ONLY","CRYPTOGRAM_3DS"],allowedCardNetworks:["VISA","MASTERCARD"],billingAddressRequired:!1},tokenizationSpecification:{type:"PAYMENT_GATEWAY",parameters:{gateway:c,gatewayMerchantId:u}}}],B={apiVersion:2,apiVersionMinor:0,allowedPaymentMethods:v,transactionInfo:{totalPriceStatus:"FINAL",totalPriceLabel:"Итого",totalPrice:m,currencyCode:e.config.currency,countryCode:e.config.currency==="GEL"?"GE":"KZ"},merchantInfo:l?{merchantId:y,merchantName:f}:{merchantName:f}},Q=new C.payments.api.PaymentsClient({environment:l?"PRODUCTION":"TEST"});try{const D=await Q.isReadyToPay({apiVersion:2,apiVersionMinor:0,allowedPaymentMethods:v});if(!(D!=null&&D.result)){e.config.onError({attributes:{message:e.t("errorGooglePayUnsupported")}});return}he(e);const G=await Q.loadPaymentData(B),K=(R=(L=G==null?void 0:G.paymentMethodData)==null?void 0:L.tokenizationData)==null?void 0:R.token;if(!K)throw new Error(e.t("errorGooglePayPayment"));const J=JSON.parse(K),M=await ln(e.apiUrl,e._getApiConfig(),e.deviceId,J,t),I=(M==null?void 0:M.id)??((z=M==null?void 0:M.data)==null?void 0:z.id);I&&ge(e,String(I))}catch(D){q(e),D.statusCode==="CANCELED"?e.config.onCancel():(te(D,{paymentMethod:"google_pay"}),e.config.onError({attributes:{message:e._resolveErrorMessage(D,"errorGooglePayPayment")}}),console.error("Google Pay error:",D))}}async function ta(e,t,n){var r;if(!e.config.onPayWithGooglePay){e.config.onError({attributes:{message:e.t("errorGooglePayUnsupported")}});return}he(e);try{const o=await e.config.onPayWithGooglePay({amount:Number(e._getCheckoutAmount()),gateway:n.gateway,gatewayMerchantId:n.gatewayMerchantId}),i=JSON.parse(o),c=await ln(e.apiUrl,e._getApiConfig(),e.deviceId,i,t),u=(c==null?void 0:c.id)??((r=c==null?void 0:c.data)==null?void 0:r.id);u&&ge(e,String(u))}catch(o){q(e),o.statusCode==="CANCELED"?e.config.onCancel():(te(o,{paymentMethod:"google_pay_native"}),e.config.onError({attributes:{message:e._resolveErrorMessage(o,"errorGooglePayPayment")}}),console.error("Google Pay native error:",o))}}function na(e){var c,u,l,f,y,m,C,v,B,Q,S,P;const t=e.container;(c=t.querySelector('[data-action="freedom-card"]'))==null||c.addEventListener("click",()=>{e.config.onFreedomLink&&e.config.onFreedomLink()}),(u=t.querySelector('[data-action="pay"]'))==null||u.addEventListener("click",()=>e.handlePayment()),(l=t.querySelector('[data-action="change-method"]'))==null||l.addEventListener("click",()=>fr(e)),t.querySelectorAll('[data-action="close"]').forEach(k=>k.addEventListener("click",()=>e.close())),(f=t.querySelector('[data-action="close-sheet"]'))==null||f.addEventListener("click",()=>{e._pendingDeleteMethod?ft(e):le(e)}),(y=t.querySelector('[data-action="edit-sheet"]'))==null||y.addEventListener("click",()=>{e.isPaymentSheetEditMode=!0,Le(e),Oe(e)}),(m=t.querySelector('[data-action="previous-sheet"]'))==null||m.addEventListener("click",()=>{e.isPaymentSheetEditMode=!1,Le(e),Oe(e)}),(C=t.querySelector('[data-action="close-add-card"]'))==null||C.addEventListener("click",()=>Ie(e)),(v=t.querySelector('[data-action="confirm-delete-cancel"]'))==null||v.addEventListener("click",()=>ft(e)),(B=t.querySelector('[data-action="confirm-delete-submit"]'))==null||B.addEventListener("click",()=>{if(e._pendingDeleteMethod){const k=e._pendingDeleteMethod;Jt(e,!0),zi(e,k).then(()=>le(e)).finally(()=>Jt(e,!1))}}),t.querySelectorAll(".choco-widget-method-item").forEach(k=>{k.addEventListener("click",L=>{const R=JSON.parse(L.currentTarget.getAttribute("data-method")||"{}");hr(e,R)})});const n=t.querySelector('[data-sheet="payment"]');n&&(n.addEventListener("click",k=>{k.target===n&&le(e)}),oa(e,n));const r=t.querySelector('[data-action="toggle-balance"]');r&&((Q=r.querySelector("input[type='checkbox']"))==null||Q.addEventListener("change",k=>{e.useBalance=k.target.checked,dr(e),e._updatePayButtonAmount()}));const o=t.querySelector('[data-action="toggle-bonuses"]');o&&((S=o.querySelector("input[type='checkbox']"))==null||S.addEventListener("change",k=>{e.useBonuses=k.target.checked,e.config.onAppliedBonus(e.useBonuses),dr(e),e._updatePayButtonAmount()}));const i=t.querySelector('[data-action="toggle-coupon"]');i&&((P=i.querySelector("input[type='checkbox']"))==null||P.addEventListener("change",k=>{e.useCoupon=k.target.checked,e._updatePayButtonAmount(),e._emitCouponSuppressingCashback()})),document.removeEventListener("keydown",e._boundKeyDown),document.addEventListener("keydown",e._boundKeyDown),Ar(e)}function ra(e,t){var n,r;e.isOpen&&(t.key==="Escape"&&(t.preventDefault(),e._pendingDeleteMethod?ft(e):e.isAddCardViewOpen?Ie(e):e.isPaymentSheetOpen?le(e):e.close()),t.key==="Enter"&&((r=(n=t.target)==null?void 0:n.dataset)==null?void 0:r.action)==="pay"&&(t.preventDefault(),e.handlePayment()))}function oa(e,t){const n=t.querySelector('[data-action="sheet-drag-handle"]'),r=t.querySelector(".choco-widget-sheet-content");if(!n||!r)return;const o=80;let i=0,c=0;const u=f=>{c=f.clientY;const y=Math.max(0,c-i);r.style.transform=`translateY(${y}px)`},l=f=>{n.releasePointerCapture(f.pointerId),n.removeEventListener("pointermove",u),n.removeEventListener("pointerup",l),n.removeEventListener("pointercancel",l);const y=Math.max(0,c-i);if(r.classList.remove("choco-widget-sheet-content--dragging"),y>=o){r.style.transform="translateY(100%)";const m=()=>{r.removeEventListener("transitionend",m),r.style.transform="",le(e)};r.addEventListener("transitionend",m)}else r.style.transform=""};n.addEventListener("pointerdown",f=>{!e.isPaymentSheetOpen||f.button!==0||(f.preventDefault(),i=f.clientY,c=f.clientY,r.classList.add("choco-widget-sheet-content--dragging"),n.setPointerCapture(f.pointerId),n.addEventListener("pointermove",u),n.addEventListener("pointerup",l),n.addEventListener("pointercancel",l))})}class ye{static _getAuthStorageValue(t){return bt(t)}static _setAuthStorageValue(t,n){qe(t,n)}static _removeAuthStorageValue(t){Ce(t)}static async logout(){ar()}constructor(t){this.config=Kr(t),this.accessToken=null,this._tokenExpiresAt=null,this._tokenPrewarmPromise=null,this.deviceId=Zt(),this.apiUrl=kr(this.config.environment),this.translations=Qe,this.checkoutContext=null,this.centrifuge=null,this.selectedPaymentMethod=null,this.selectedCoupon=null,this.useCoupon=!1,this.container=null,this.isOpen=!1,this.isPaymentSheetOpen=!1,this.isPaymentSheetEditMode=!1,this.loading=!1,this.disabled=!1,this.paymentMethodDisabled=!1,this.useBalance=!1,this.useBonuses=!1,this.addCardActionUrl=null,this.isAddCardViewOpen=!1,this.waitingForNewCardAction=!1,this.newCardActionRequiredTimeoutId=null,this._googlePayScriptPromise=null,this._googlePayButtonRenderVersion=0,this._orderStatusPollingId=null,this._orderStatusResolved=!1,this._pendingOrderId=null,this._pendingDeleteMethod=null,this._pendingSuccessPayload=null,this._lifecycleListenersAttached=!1,this._destroyed=!1,this._boundAddCardMessage=null,this._boundKeyDown=n=>ra(this,n),this._boundVisibilityChange=()=>this._onVisibilityChange(),this._boundWindowFocus=()=>this._onWindowFocus(),this._boundPageShow=()=>this._onPageShow(),Bi({clientId:String(this.config.clientId),terminalId:String(this.config.terminalId),environment:this.config.environment})}t(t,n={}){var i;const r=this.config.locale||"ru",o=((i=this.translations[r])==null?void 0:i[t])||this.translations.ru[t];return typeof o!="string"?t:o.replace(/{(\w+)}/g,(c,u)=>Object.prototype.hasOwnProperty.call(n,u)?String(n[u]):c)}_resolveErrorMessage(t,n="paymentError"){return(t==null?void 0:t.message)||this.t(n)}_getApiConfig(){return{...this.config,accessToken:this.accessToken}}_isInteractionBlocked(){return this.disabled||this.loading}_getBalanceAmount(){var o,i,c,u;const t=(u=(c=(i=(o=this.checkoutContext)==null?void 0:o.data)==null?void 0:i.balance)==null?void 0:c.data)==null?void 0:u.money,n=this.config.currency||"KZT",r=Number(t==null?void 0:t[n]);return Number.isFinite(r)&&r>0?r:0}_getBonusesAmount(){var n;const t=Number((n=this.config.bonuses)==null?void 0:n.amount);return Number.isFinite(t)&&t>0?t:0}_getBonusesPercent(){var n;const t=Number((n=this.config.bonuses)==null?void 0:n.percent);return!Number.isFinite(t)||t<=0?0:t>=100?100:t}_getAvailableBonus(){var n;const t=Number((n=this.config.bonuses)==null?void 0:n.availableBonus);return Number.isFinite(t)&&t>0?t:0}_getCouponDiscount(){if(!this.useCoupon||!this.selectedCoupon||this._isCouponDisabled()||this.selectedCoupon.type==="coupon")return 0;const t=Number(this.selectedCoupon.reward_amount);return Number.isFinite(t)&&t>0?t:0}_getPaymentBreakdown(){const t=this.config.amount,n=this._getBalanceAmount(),r=this.useBalance?Math.min(n,t):0,o=t-r,i=this.useBalance&&r>=t,c=this.useBonuses?this._getAvailableBonus():0,u=Math.max(o-c,0),l=this._getCouponDiscount(),f=Math.max(u-l,0),y=this.useBalance?t:f,m=this.useBalance&&!i,v=this.useCoupon&&this.selectedCoupon&&!this._isCouponDisabled()?{id:this.selectedCoupon.voucher_id,template_id:this.selectedCoupon.template_id,type:this.selectedCoupon.type}:void 0;return{payableAmount:f,checkoutOptions:{checkoutAmount:y,forceBalanceMethod:i,useBalance:m,voucher:v}}}_getPayableAmount(){return this._getPaymentBreakdown().payableAmount}_isBalanceFullyCoveringAmount(){return this._getPaymentBreakdown().checkoutOptions.forceBalanceMethod}_getCheckoutAmount(){return this._getPaymentBreakdown().checkoutOptions.checkoutAmount??this.config.amount}_getPaymentMethodForUserEvent(){var t;return this._isBalanceFullyCoveringAmount()?"balance":((t=this.selectedPaymentMethod)==null?void 0:t.type)??null}_getKaspiOptions(){return{onlyKaspiAvailable:this.config.onlyKaspiAvailable,disableKaspi:this.config.disableKaspi,disableGooglePay:this.config.disableGooglePay}}_emitUserEvent(t,n={}){typeof this.config.onUserEvent=="function"&&this.config.onUserEvent({eventName:t,eventProperties:n})}_emitPaymentMethodSelected(t=this.selectedPaymentMethod){typeof this.config.onPaymentMethodSelected=="function"&&this.config.onPaymentMethodSelected(t||null)}_emitCouponSuppressingCashback(){var n;const t=this.useCoupon&&((n=this.selectedCoupon)==null?void 0:n.suppresses_cashback)===!0;this.config.onCouponSuppressingCashback(t)}_attachEventListeners(){na(this)}_updatePayButtonAmount(){dt(this)}_showAddCardView(){jt(this)}_closeAddCardView(){Ie(this)}_setNewCardActionTimeout(){this._clearNewCardActionTimeout(),this.newCardActionRequiredTimeoutId=setTimeout(()=>{this.waitingForNewCardAction&&(this.waitingForNewCardAction=!1,q(this),this.config.onError({attributes:{message:this.t("errorNoServerResponseRetry")}})),this.newCardActionRequiredTimeoutId=null},6e4)}_clearNewCardActionTimeout(){this.newCardActionRequiredTimeoutId&&(window.clearTimeout(this.newCardActionRequiredTimeoutId),this.newCardActionRequiredTimeoutId=null)}_saveTokensToStorage(t,n){ir(t,n)}_clearAuthStorage(){ar()}_getAuthStorageValue(t){return ye._getAuthStorageValue(t)}_setAuthStorageValue(t,n){ye._setAuthStorageValue(t,n)}_removeAuthStorageValue(t){ye._removeAuthStorageValue(t)}_loadGooglePaySdk(){var t,n;return typeof window>"u"||typeof document>"u"?Promise.reject(new Error("Google Pay SDK requires browser environment")):(n=(t=window.google)==null?void 0:t.payments)!=null&&n.api?Promise.resolve():this._googlePayScriptPromise?this._googlePayScriptPromise:(this._googlePayScriptPromise=new Promise((r,o)=>{const i=document.querySelector('script[data-choco-google-pay-sdk="true"]');if(i){i.addEventListener("load",()=>r(),{once:!0}),i.addEventListener("error",()=>o(new Error("Failed to load Google Pay SDK")),{once:!0});return}const c=document.createElement("script");c.src="https://pay.google.com/gp/p/js/pay.js",c.async=!0,c.defer=!0,c.setAttribute("data-choco-google-pay-sdk","true"),c.onload=()=>r(),c.onerror=()=>o(new Error("Failed to load Google Pay SDK")),document.head.appendChild(c)}).finally(()=>{var r,o;(o=(r=window.google)==null?void 0:r.payments)!=null&&o.api||(this._googlePayScriptPromise=null)}),this._googlePayScriptPromise)}_attachLifecycleListeners(){this._lifecycleListenersAttached||(document.addEventListener("visibilitychange",this._boundVisibilityChange),window.addEventListener("focus",this._boundWindowFocus),window.addEventListener("pageshow",this._boundPageShow),this._lifecycleListenersAttached=!0)}_detachLifecycleListeners(){this._lifecycleListenersAttached&&(document.removeEventListener("visibilitychange",this._boundVisibilityChange),window.removeEventListener("focus",this._boundWindowFocus),window.removeEventListener("pageshow",this._boundPageShow),this._lifecycleListenersAttached=!1)}_onVisibilityChange(){pt()||(qt(this),Ne(this))}_onWindowFocus(){qt(this),Ne(this)}_onPageShow(){qt(this),Ne(this)}async _obtainTokenByRefreshOrTrackId(){await Si(this)}_isTokenExpiringSoon(t=9e4){return this.accessToken?this._tokenExpiresAt==null?!1:Date.now()>=this._tokenExpiresAt-t:!0}_prewarmAuthToken(){this._destroyed||this.paymentMethodDisabled||this._tokenPrewarmPromise||!this._isTokenExpiringSoon()||(this._tokenPrewarmPromise=this._obtainTokenByRefreshOrTrackId().catch(()=>{}).finally(()=>{this._tokenPrewarmPromise=null}))}async _fetchCheckoutContextWithRetry(){try{this.checkoutContext=await Et(this.apiUrl,this._getApiConfig())}catch(t){if(t.status===401)this._removeAuthStorageValue("webPayToken"),await this._obtainTokenByRefreshOrTrackId(),this.checkoutContext=await Et(this.apiUrl,this._getApiConfig());else throw t}}async _acquireCheckoutContextWithBackoff(){const t=[500,1500,3e3,5e3,8e3];for(let n=0;;n++){if(this._destroyed)return!1;try{return this.accessToken||await this._obtainTokenByRefreshOrTrackId(),this._destroyed?!1:(await this._fetchCheckoutContextWithRetry(),!0)}catch(r){if(this._destroyed)return!1;if(n>=t.length)return this.config.onError({attributes:{message:r.message}}),te(r,{phase:"init_context",attempts:n+1}),!1;await this._delay(t[n])}}}_delay(t){return new Promise(n=>setTimeout(n,t))}async _fetchCoupons(){try{const t=await qr(this.apiUrl,this._getApiConfig()),r=(Array.isArray(t)?t:Array.isArray(t==null?void 0:t.data)?t.data:[]).filter(o=>Number(o.reward_amount)>0).sort((o,i)=>o.sort_weight-i.sort_weight);this.selectedCoupon=r.length>0?r[0]:null,this.useCoupon=!1}catch{this.selectedCoupon=null,this.useCoupon=!1}}_isCouponDisabled(){if(!this.selectedCoupon)return!1;if(this.config.amount<this.selectedCoupon.min_pay_amount)return!0;const t=this._getBalanceAmount(),n=this.useBalance?Math.min(t,this.config.amount):0,r=this.config.amount-n,o=this.useBonuses?Math.min(this._getAvailableBonus(),r):0;return r-o<this.selectedCoupon.reward_amount}_prerender(){Ui(this)}_render(){Fi(this)}async init(){var t,n;try{if(this._prerender(),this._attachLifecycleListeners(),!this.config.clientId)return this.config.onError({attributes:{message:this.t("errorMissingTrackClient")}}),!1;if(this.accessToken=this._getAuthStorageValue("webPayToken"),!this.config.trackId&&!this.accessToken)return this.paymentMethodDisabled=!0,this._render(),!0;if(!await this._acquireCheckoutContextWithBackoff()||this._destroyed||(await this._fetchCoupons(),this._emitCouponSuppressingCashback(),this._destroyed))return!1;const o=tn((n=(t=this.checkoutContext)==null?void 0:t.data)==null?void 0:n.socket_connections,i=>gr(this,i));return o&&(this.centrifuge=o.centrifuge),Ne(this),this.selectedPaymentMethod=Ct(this.checkoutContext.data,this._getKaspiOptions()),this._emitPaymentMethodSelected(),this._render(),!0}catch(r){return console.error(`${this.t("errorWidgetInit")}:`,r),te(r,{phase:"init"}),this.config.onError({attributes:{message:r.message}}),!1}}close(){this.config.onCancel()}destroy(){this._destroyed=!0;const t=document.getElementById("choco-one-click-widget");t&&(t.style.display="none"),this._clearNewCardActionTimeout(),pe(this),this._pendingSuccessPayload=null,this._detachLifecycleListeners(),this.isAddCardViewOpen&&Ie(this),this.centrifuge&&(this.centrifuge.disconnect(),this.centrifuge=null),document.removeEventListener("keydown",this._boundKeyDown),this.container&&(this.container.classList.remove("choco-one-click-widget--visible"),setTimeout(()=>{var n;(n=this.container)==null||n.remove(),this.container=null},300)),this.isOpen=!1,this.isPaymentSheetOpen=!1,this.isAddCardViewOpen=!1,this.selectedPaymentMethod=null}getAvailablePaymentMethods(){var t;return(t=this.checkoutContext)!=null&&t.data?Ur(this.checkoutContext.data,n=>this.t(n),this._getKaspiOptions()):[]}async createOrder(){return Vi(this)}async pay(){try{await this.createOrder()}catch(t){console.error(`${this.t("errorPaymentProcess")}:`,t)}}async handlePayment(){if(this._isInteractionBlocked())return;const t=this._getPaymentMethodForUserEvent();t!=null&&this._emitUserEvent("one_click_pay_cta_tapped",{payment_method:t});try{if(this.config.onConfirmPay){this.config.onConfirmPay(this.selectedPaymentMethod||null);return}await this.pay()}catch(n){console.error(`${this.t("errorPaymentProcess")}:`,n)}}openPaymentSheet(){fr(this)}closePaymentSheet(){le(this)}resumeOrderStatusCheck(){Ne(this)}async updateAmount(t){var n;if(typeof t!="number"||!Number.isFinite(t)||t<0)throw new Error("amount must be a non-negative number");if(this.config.amount=t,this._isCouponDisabled()&&(this.useCoupon=!1),this.selectedCoupon){const r=this.isPaymentSheetOpen,o=this.isAddCardViewOpen;if(this._render(),ue(this),r){const i=(n=this.container)==null?void 0:n.querySelector('[data-sheet="payment"]');i&&(i.classList.add("choco-widget-payment-sheet--open"),this.isPaymentSheetOpen=!0)}o&&jt(this);return}dt(this)}async updateAvailableBonus(t){if(typeof t!="number"||!Number.isFinite(t)||t<0)throw new Error("availableBonus must be a non-negative number");this.config.bonuses&&(this.config.bonuses.availableBonus=t),dt(this)}async updateLocale(t){if(typeof t!="string"||!this.translations[t])throw new Error(`Unsupported locale: ${t}`);if(this.config.locale=t,!this.container)return;const n=this.isPaymentSheetOpen,r=this.isAddCardViewOpen;if(this._render(),ue(this),n){const o=this.container.querySelector('[data-sheet="payment"]');o&&(o.classList.add("choco-widget-payment-sheet--open"),this.isPaymentSheetOpen=!0)}r&&jt(this)}async setLoading(t){this.loading=!!t,ue(this)}async setDisabled(t){this.disabled=!!t,ue(this)}async setPreorderId(t){this.config.preorderId=t}async setMerchantOrderId(t){this.config.merchantOrderId=t}async setIdempotencyKey(t){this.config.idempotencyKey=t}async logout(){await ye.logout(),this.accessToken=null}async updateTrackId(t){var n,r;if(this.config.trackId=t,!this.config.clientId)return this.config.onError({attributes:{message:this.t("errorMissingTrackClient")}}),!1;try{this._prerender(),await this._obtainTokenByRefreshOrTrackId();try{await this._fetchCheckoutContextWithRetry()}catch(i){const c=i;return this.config.onError({attributes:{message:c.message}}),!1}await this._fetchCoupons(),this._emitCouponSuppressingCashback(),this.centrifuge&&(this.centrifuge.disconnect(),this.centrifuge=null);const o=tn((r=(n=this.checkoutContext)==null?void 0:n.data)==null?void 0:r.socket_connections,i=>gr(this,i));return o&&(this.centrifuge=o.centrifuge),this.selectedPaymentMethod=Ct(this.checkoutContext.data,this._getKaspiOptions()),this._emitPaymentMethodSelected(),this.paymentMethodDisabled=!1,this._render(),!0}catch(o){return console.error(`${this.t("errorWidgetInit")}:`,o),te(o,{phase:"updateTrackId"}),this.config.onError({attributes:{message:o.message}}),!1}}async onConfirmPay(t){if(typeof t!="function")throw new Error("onConfirmPay callback must be a function");this.config.onConfirmPay=t}async onPaymentMethodSelected(t){if(typeof t!="function")throw new Error("onPaymentMethodSelected callback must be a function");this.config.onPaymentMethodSelected=t,this._emitPaymentMethodSelected()}async onKaspiLink(t){if(typeof t!="function")throw new Error("onKaspiLink callback must be a function");this.config.onKaspiLink=t}async onUserEvent(t){if(typeof t!="function")throw new Error("onUserEvent callback must be a function");this.config.onUserEvent=t}async onFreedomLink(t){if(typeof t!="function")throw new Error("onFreedomLink callback must be a function");this.config.onFreedomLink=t}async onAppliedBonus(t){if(typeof t!="function")throw new Error("onAppliedBonus callback must be a function");this.config.onAppliedBonus=t}async onCouponSuppressingCashback(t){if(typeof t!="function")throw new Error("onCouponSuppressingCashback callback must be a function");this.config.onCouponSuppressingCashback=t}}return typeof window<"u"&&(window.ChocoOneClickWidget=ye),ye}));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "choco-one-click-payment",
3
- "version": "1.1.61",
3
+ "version": "1.1.62",
4
4
  "description": "Встраиваемый виджет для быстрой оплаты с bottom sheet интерфейсом",
5
5
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.esm.js",