@foxford/services 1.4.1 → 1.4.2-beta-d9b2a40f-20250224

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/index.d.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  // Generated by dts-bundle-generator v8.0.1
2
2
 
3
+ import { AxiosInstance, AxiosRequestConfig, CreateAxiosDefaults } from 'axios';
4
+
3
5
  export interface ApiTransformer {
4
6
  (data: any, headers?: any): any;
5
7
  }
@@ -21,37 +23,7 @@ export interface ApiProxyConfig {
21
23
  }
22
24
  export type ApiMethod = "get" | "GET" | "delete" | "DELETE" | "head" | "HEAD" | "options" | "OPTIONS" | "post" | "POST" | "put" | "PUT" | "patch" | "PATCH" | "purge" | "PURGE" | "link" | "LINK" | "unlink" | "UNLINK";
23
25
  export type ApiResponseType = "arraybuffer" | "blob" | "document" | "json" | "text" | "stream";
24
- export type ApiRequestConfig = {
25
- url?: string;
26
- method?: ApiMethod;
27
- baseURL?: string;
28
- transformRequest?: ApiTransformer | ApiTransformer[];
29
- transformResponse?: ApiTransformer | ApiTransformer[];
30
- headers?: any;
31
- params?: any;
32
- paramsSerializer?: (params: any) => string;
33
- data?: any;
34
- timeout?: number;
35
- timeoutErrorMessage?: string;
36
- withCredentials?: boolean;
37
- adapter?: ApiAdapter;
38
- auth?: ApiBasicCredentials;
39
- responseType?: ApiResponseType;
40
- xsrfCookieName?: string;
41
- xsrfHeaderName?: string;
42
- onUploadProgress?: (progressEvent: any) => void;
43
- onDownloadProgress?: (progressEvent: any) => void;
44
- maxContentLength?: number;
45
- validateStatus?: ((status: number) => boolean) | null;
46
- maxBodyLength?: number;
47
- maxRedirects?: number;
48
- socketPath?: string | null;
49
- httpAgent?: any;
50
- httpsAgent?: any;
51
- proxy?: ApiProxyConfig | false;
52
- cancelToken?: CancelToken;
53
- decompress?: boolean;
54
- };
26
+ export type ApiRequestConfig = AxiosRequestConfig;
55
27
  export interface ApiResponse<T = any, R = T> {
56
28
  data: R;
57
29
  status: number;
@@ -95,24 +67,7 @@ export interface ApiInterceptorManager<V> {
95
67
  use(onFulfilled?: (value: V) => V | Promise<V>, onRejected?: (error: any) => any): number;
96
68
  eject(id: number): void;
97
69
  }
98
- export interface ApiInstance {
99
- <T, R>(config: ApiRequestConfigExtended): ApiPromise<T, R>;
100
- <T, R>(url: string, config?: ApiRequestConfigExtended): ApiPromise<T, R>;
101
- defaults: ApiRequestConfigExtended;
102
- interceptors: {
103
- request: ApiInterceptorManager<ApiRequestConfigExtended>;
104
- response: ApiInterceptorManager<ApiResponse>;
105
- };
106
- getUri(config?: ApiRequestConfigExtended): string;
107
- request<T = any, R = ApiPromise<T>>(config: ApiRequestConfigExtended): ApiPromise<T, R>;
108
- get<R>(url: string, config?: ApiRequestConfigExtended): ApiPromise<R>;
109
- delete<R>(url: string, config?: ApiRequestConfigExtended): ApiPromise<R>;
110
- head<R>(url: string, config?: ApiRequestConfigExtended): ApiPromise<R>;
111
- options<R>(url: string, config?: ApiRequestConfigExtended): ApiPromise<R>;
112
- post<T = any, R = ApiPromise<T>>(url: string, data?: T, config?: ApiRequestConfigExtended): ApiPromise<T, R>;
113
- put<T = any, R = ApiPromise<T>>(url: string, data?: T, config?: ApiRequestConfigExtended): ApiPromise<T, R>;
114
- patch<T = any, R = ApiPromise<T>>(url: string, data?: T, config?: ApiRequestConfigExtended): ApiPromise<T, R>;
115
- }
70
+ export type ApiInstance = AxiosInstance;
116
71
  export interface ApiStatic extends ApiInstance {
117
72
  create(config?: ApiRequestConfig): ApiInstance;
118
73
  Cancel: CancelStatic;
@@ -157,7 +112,7 @@ export interface ResponseSuccessPluginInterface {
157
112
  isApplicable(response: ApiResponse): boolean;
158
113
  }
159
114
  export type ApiConfig = {
160
- config: ApiRequestConfigExtended;
115
+ config: CreateAxiosDefaults;
161
116
  plugins?: Array<RequestPluginInterface | ResponseSuccessPluginInterface>;
162
117
  };
163
118
  export declare abstract class RequestPlugin implements RequestPluginInterface {
@@ -174,11 +129,11 @@ export declare abstract class ResponseSuccessPlugin implements ResponseSuccessPl
174
129
  }
175
130
  declare const apiServiceInstance: ApiServiceInterface;
176
131
  export declare class CaptchaError extends Error {
177
- reason?: "error" | "timeout" | "expired";
132
+ level?: "fatal" | "error";
133
+ reason?: "timeout" | "expired";
178
134
  code?: string;
179
135
  cause?: any;
180
- capture?: boolean;
181
- constructor(message: string);
136
+ constructor(message: string, level?: "fatal" | "error");
182
137
  }
183
138
  export type CaptchaProviderName = "recaptcha" | "cloudflare_turnstile" | "yandex_smart_captcha";
184
139
  export type CaptchaAnswer = {
package/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";var e=require("axios"),t=require("axios-retry"),n=require("broadcast-channel"),r=require("centrifuge");function i(e,t,n,r){return new(n||(n=Promise))((function(i,o){function s(e){try{c(r.next(e))}catch(e){o(e)}}function a(e){try{c(r.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}c((r=r.apply(e,t||[])).next())}))}function o(e,t,n){return e.headers=Object.assign({"Content-Type":"application/json"},e.headers),window&&window.location&&window.location.pathname&&window.location.origin&&(e.headers=Object.assign(Object.assign({},e.headers),{"X-Referer":window.location.origin+window.location.pathname})),n.length>0?function(e,t,n){return i(this,void 0,void 0,(function*(){for(const r of n)r.isApplicable(e)&&(e=yield r.execute(e,t));return e}))}(e,t,n):e}function s(e,t,n){return n.length>0?function(e,t,n){return i(this,void 0,void 0,(function*(){for(const r of n)r.isApplicable(e)&&(e=yield r.execute(e,t));return e}))}(e,t,n):e}void 0===Promise.withResolvers&&(Promise.withResolvers=()=>{let e,t;return{promise:new Promise(((n,r)=>{e=n,t=r})),reject:t,resolve:e}}),"function"==typeof SuppressedError&&SuppressedError;const a=[422,401];function c(e){const{config:t=null,response:n=null}=e;if(null===t||null===n)return Promise.reject(e);const r=t;a.includes(n.status)&&(r._retry=!0);const i=Object.assign({errorText:e.toString(),headers:n.headers,status:n.status,statusText:n.statusText},"object"==typeof n.data?n.data:{data:n.data});return Promise.reject(i)}const l=new class{createFoxApiInstance({config:n,plugins:r=[]}){const i=e.create(n),a=this.filterPlugins(r,"request"),l=this.filterPlugins(r,"responseSuccess");return i.interceptors.request.use((e=>o(e,i,[...a]))),i.interceptors.response.use((e=>s(e,i,[...l])),c),t(i,{retries:3,retryDelay:t.exponentialDelay}),i}createApiInstance({config:t}){return e.create(t)}createStaticApiInstance(){const t=e;return t.isApiError=e=>"object"==typeof e&&!0===e.isAxiosError,t}filterPlugins(e,t){return e?e.filter((e=>e.pluginType===t)):[]}},d="turnstile-container",h="turnstile-widget";var u=`\n<div id="${d}" class="fox-cf-turnstile">\n <div class="fox-cf-turnstile__overlay"></div>\n <div class="fox-cf-turnstile__content">\n <div class="fox-cf-turnstile__content__text">\n <h3>Надо убедиться, что вы человек</h3>\n <span>Поставьте галочку, нажав на белый квадрат ниже — проверка займёт буквально секунду</span>\n </div>\n <div id="${h}">\n <div class="fox-cf-turnstile__loader"></div>\n </div>\n </div>\n</div>\n`;class p extends Error{constructor(e){super(e),this.capture=!0,this.name="CaptchaError",this.message=e}}function f(...e){const t=["[CaptchaService] ",...e];console.debug.apply(console,t)}const g=(...e)=>{};class v{constructor({sitekey:e,locale:t,notify:n,onRenderCaptcha:r,onSuccessChallenge:i,onErrorChallenge:o,onWarnChallenge:s,onBeforeInteractiveChallenge:a,onAfterInteractiveChallenge:c}){this.sitekey=null,this.locale="ru",this.provider="cloudflare_turnstile",this.container=null,this.notifyHandler=null!=n?n:g,this.sitekey=null!=e?e:null,this.onRenderCaptcha=null!=r?r:g,this.onSuccessChallenge=null!=i?i:g,this.onErrorChallenge=null!=o?o:g,this.onWarnChallenge=null!=s?s:g,this.onBeforeInteractiveChallenge=null!=a?a:g,this.onAfterInteractiveChallenge=null!=c?c:g,t&&(this.locale=t),this.addDomElements(),v.DEBUG&&(window.cf=this)}notify(...e){this.notifyHandler&&this.notifyHandler(...e)}addDomElements(){this.container||document.getElementById(d)||(document.body.insertAdjacentHTML("beforeend",u),document.body.insertAdjacentHTML("beforeend","<style>\n.fox-cf-turnstile {\n position: fixed;\n top: 0;\n left: 0;\n display: flex;\n align-items: center;\n justify-content: center;\n width: 100vw;\n height: 100vh;\n z-index: -1;\n}\n.fox-cf-turnstile__noscroll {\n position: fixed; \n top: var(--st, 0);\n inline-size: 100%;\n overflow-y:scroll; \n}\n.fox-cf-turnstile--showing {\n z-index: 9999;\n}\n.fox-cf-turnstile__overlay {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n background: rgba(246, 247, 251, 0.9);\n opacity: 0;\n transition: all .3s ease;\n transition-delay: .2s;\n z-index: 0;\n}\n.fox-cf-turnstile__content {\n background: white;\n border-radius: 5px;\n max-width: 500px;\n max-height: 50vh;\n position: relative;\n z-index: 1;\n box-shadow: rgba(0, 0, 0, 0.08) 0px 10px 20px 0px;\n height: 1px;\n width: 1px;\n overflow: hidden;\n transition: all .8s ease, opacity 0.3s ease;\n transition-delay: .3s;\n opacity: 0;\n display: flex;\n align-items: center;\n justify-content: center;\n flex-direction: column;\n font-size: 1.2rem;\n}\n.fox-cf-turnstile__content__text {\n flex: 1;\n margin-bottom: 20px;\n opacity: 1;\n overflow: hidden;\n transition: opacity 0.3s ease;\n text-align: center;\n}\n.fox-cf-turnstile--showing .fox-cf-turnstile__overlay, .fox-cf-turnstile--show .fox-cf-turnstile__overlay {\n opacity: 1;\n}\n.fox-cf-turnstile--showing .fox-cf-turnstile__content, .fox-cf-turnstile--show .fox-cf-turnstile__content {\n width: 100%;\n height: auto;\n min-height: 20vh;\n min-width: 30vw;\n padding: 30px;\n opacity: 1;\n}\n.fox-cf-turnstile__content__text h3 {\n font-size: 1.4rem;\n}\n.fox-cf-turnstile__loader {\n font-size: 10px;\n margin: 50px auto;\n text-indent: -9999em;\n width: 5em;\n height: 5em;\n border-radius: 50%;\n background: #8b1feb;\n background: -moz-linear-gradient(left, #8b1feb 10%, rgba(139,31,235, 0) 42%);\n background: -webkit-linear-gradient(left, #8b1feb 10%, rgba(139,31,235, 0) 42%);\n background: -o-linear-gradient(left, #8b1feb 10%, rgba(139,31,235, 0) 42%);\n background: -ms-linear-gradient(left, #8b1feb 10%, rgba(139,31,235, 0) 42%);\n background: linear-gradient(to right, #8b1feb 10%, rgba(139,31,235, 0) 42%);\n position: relative;\n -webkit-animation: load3 1.4s infinite linear;\n animation: load3 1.4s infinite linear;\n -webkit-transform: translateZ(0);\n -ms-transform: translateZ(0);\n transform: translateZ(0);\n}\n.fox-cf-turnstile__loader:before {\n width: 50%;\n height: 50%;\n background: #8b1feb;\n border-radius: 100% 0 0 0;\n position: absolute;\n top: 0;\n left: 0;\n content: '';\n}\n.fox-cf-turnstile__loader:after {\n background: white;\n width: 75%;\n height: 75%;\n border-radius: 50%;\n content: '';\n margin: auto;\n position: absolute;\n top: 0;\n left: 0;\n bottom: 0;\n right: 0;\n}\n@-webkit-keyframes load3 {\n 0% {\n -webkit-transform: rotate(0deg);\n transform: rotate(0deg);\n }\n 100% {\n -webkit-transform: rotate(360deg);\n transform: rotate(360deg);\n }\n}\n@keyframes load3 {\n 0% {\n -webkit-transform: rotate(0deg);\n transform: rotate(0deg);\n }\n 100% {\n -webkit-transform: rotate(360deg);\n transform: rotate(360deg);\n }\n} \n</style>"),this.container=document.getElementById(d))}static appendScript(e){return i(this,void 0,void 0,(function*(){if("string"!=typeof e||""===e)throw new TypeError("src script is not defined");const t=document.createElement("script");return t.src=e,document.body&&document.body.appendChild(t),new Promise(((e,n)=>{t.addEventListener("load",(()=>{e(!0)})),t.addEventListener("error",(()=>{n()}))}))}))}show(){var e;null===(e=this.container)||void 0===e||e.classList.add("fox-cf-turnstile--showing"),v.bodyScrollLock()}hide(){var e,t;null===(e=this.container)||void 0===e||e.classList.remove("fox-cf-turnstile--show"),null===(t=this.container)||void 0===t||t.classList.remove("fox-cf-turnstile--showing"),v.bodyScrollUnlock()}loadScript(){return i(this,void 0,void 0,(function*(){if(window.turnstile)return Promise.resolve(window.turnstile);const e=()=>i(this,void 0,void 0,(function*(){return yield v.appendScript("https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit&onload=onloadTurnstileCallback")}));return new Promise(((t,n)=>{window.onloadTurnstileCallback=()=>{this.turnstileReady(),window.turnstile?t(window.turnstile):n(new p("Cloudflare Turnstile is not available"))},e().catch((()=>n(new p("Could not load Cloudflare Turnstile"))))}))}))}turnstileReady(){var e,t;f("Cloudflare Turnstile is ready",window.turnstile),null===(t=null===(e=this.container)||void 0===e?void 0:e.querySelector(".fox-cf-turnstile__loader"))||void 0===t||t.remove()}static normalizeLocation(e=""){return e.substring(0,31).replace(/\//g,"_")}static bodyScrollLock(){const e=document.body;e.style.setProperty("--st",`-${document.documentElement.scrollTop}px`),e.classList.add("fox-cf-turnstile__noscroll")}static bodyScrollUnlock(){document.body.classList.remove("fox-cf-turnstile__noscroll")}renderWidget(e){return i(this,void 0,void 0,(function*(){return new Promise(((t,n)=>{var r;let i="";function o(){var e;null===(e=window.turnstile)||void 0===e||e.reset(i),setTimeout((()=>{var e;null===(e=window.turnstile)||void 0===e||e.remove(i)}),500)}i=null===(r=window.turnstile)||void 0===r?void 0:r.render(`#${h}`,{action:v.normalizeLocation(null==e?void 0:e.location),"after-interactive-callback":()=>{f("after-interactive-callback"),this.onAfterInteractiveChallenge(this.provider)},"before-interactive-callback":()=>{f("before-interactive-callback"),this.onBeforeInteractiveChallenge(this.provider),this.show()},callback:e=>{f("Challenge Success"),this.hide(),t(e),o()},"error-callback":e=>{n(e),o()},"expired-callback":()=>{this.hide(),n("expired"),o()},language:this.locale,sitekey:this.sitekey,theme:"light","timeout-callback":()=>{this.hide(),n("timeout"),o()},"unsupported-callback":()=>{n("110500"),o()}})}))}))}errorHandler(e){f("Captcha error with code:",e);let t=[...v.NO_RETRY_ERROR_CODES];if("string"!=typeof e)return void this.notify("Что-то пошло не так. Попробуйте ещё раз. Если не помогает, обратитесь в поддержку.");const n=e;switch(!0){case n.startsWith("110500"):t=t.filter((e=>!e.startsWith("110500"))),this.notify("Ваш браузер устарел. Попробуйте ещё раз, используя другой браузер или устройство.");break;case n.startsWith("110600"):t=t.filter((e=>!e.startsWith("110600"))),this.notify("Прошло слишком много времени с момента начала проверки. Попробуйте еще раз.");break;case n.startsWith("110510"):t=t.filter((e=>!e.startsWith("110510"))),this.notify("Что-то пошло не так — возможно, вы используете технологию подмены User agent. Попробуйте ещё раз или обратитесь в поддержку");break;case n.startsWith("200010"):this.notify('Что-то пошло не так. Попробуйте <a href="https://yandex.ru/support/common/browsers-settings/cache.html" target="_blank" rel="nofollow noopener">очистить кеш браузера</a>. Если не помогает, обратитесь в поддержку.');break;case n.startsWith("200100"):t=t.filter((e=>!e.startsWith("200100"))),this.notify("Кажется, часы на вашем компьютере показывают неправильное время. Настройте часы и попробуйте ещё раз.");break;case n.startsWith("300"):case n.startsWith("600"):t=t.filter((e=>!e.startsWith("300")||!e.startsWith("600"))),this.notify("Потвердите еще раз что вы человек")}t.some((e=>n.startsWith(e)))&&this.notify(`Что-то пошло не так, код ошибки — ${n}. Мы уже знаем о проблеме и скоро всё поправим. Попробуйте ещё раз через некоторое время.`)}execute(e){return i(this,void 0,void 0,(function*(){if(this.sitekey){f("Load cloudflare script");try{yield this.loadScript()}catch(e){const t=e instanceof p?e:new p("Could not load captcha with error: "+e.toString());throw this.onErrorChallenge(this.provider,t),t}if(!window.turnstile){const e=new p("Cloudflare Turnstile is not available in window");throw this.onErrorChallenge(this.provider,e),e}try{f("Render turnstile widget"),this.onRenderCaptcha(this.provider);const t=yield this.renderWidget(e);return this.onSuccessChallenge(this.provider),t}catch(e){if(this.errorHandler(e),"string"!=typeof e){const t=new p("Could not execute captcha with error: "+e.toString());throw this.onErrorChallenge(this.provider,t),t}if(["110200","110100","110110"].some((t=>e.startsWith(t)))){const t=new p("Invalid sitekey or domain is not allowed");throw t.code=e,this.onErrorChallenge(this.provider,t),t}if(v.NO_RETRY_ERROR_CODES.some((t=>e.startsWith(t)))){const t=new p("Captcha challenge is failed");t.reason="error",t.capture=!1,t.code=e,this.onErrorChallenge(this.provider,t)}else{const t=new p("Captcha challenge has error");t.reason=["timeout","expired"].includes(e)?e:"error",t.capture=!1,t.code=e,this.onWarnChallenge(this.provider,t)}}}}))}}v.DEBUG=!1,v.NO_RETRY_ERROR_CODES=["100","105","106","110100","110110","110200","110420","110430","110500","110510","120","200010","200100"];const w="recaptcha-widget";function m(){let e=(new Date).getTime(),t="undefined"!=typeof performance&&performance.now&&1e3*performance.now()||0;return"xxxx-xxxx-4xxx-yxxx".replace(/[xy]/g,(function(n){let r=16*Math.random();return e>0?(r=(e+r)%16|0,e=Math.floor(e/16)):(r=(t+r)%16|0,t=Math.floor(t/16)),("x"===n?r:3&r|8).toString(16)}))}const b=(...e)=>{};class y{constructor({sitekey:e,locale:t,notify:n,onRenderCaptcha:r,onSuccessChallenge:i,onWarnChallenge:o,onErrorChallenge:s}){this.sitekey=null,this.locale="ru",this.container=null,this.provider="recaptcha",this.sitekey=null!=e?e:null,this.notifyHandler=null!=n?n:b,this.onRenderCaptcha=null!=r?r:b,this.onSuccessChallenge=null!=i?i:b,this.onWarnChallenge=null!=o?o:b,this.onErrorChallenge=null!=s?s:b,t&&(this.locale=t),this.addDomElements(),y.DEBUG&&(window.gr=this)}recaptchaReady(){f("Google recaptcha is ready",window.grecaptcha,this)}addDomElements(){if(this.container||document.getElementById(w))return;document.body.insertAdjacentHTML("beforeend",`<div id="${w}"></div>`);const e=document.getElementById(w);e.style.display="none",this.container=e}static getGrecaptchaCallbackNames(){return{error:`${y.ERROR_FUNC_NAME}`,expired:`${y.EXPIRED_FUNC_NAME}`,resolve:`${y.RESOLVE_FUNC_NAME}`}}static appendScript(e){return i(this,void 0,void 0,(function*(){if("string"!=typeof e||""===e)throw new TypeError("src script is not defined");const t=document.createElement("script");return t.src=e,document.body&&document.body.appendChild(t),new Promise(((e,n)=>{t.addEventListener("load",(()=>{e(!0)})),t.addEventListener("error",(()=>{n()}))}))}))}loadScript(){return i(this,void 0,void 0,(function*(){if(window.grecaptcha)return Promise.resolve(window.grecaptcha);const e=()=>i(this,void 0,void 0,(function*(){return yield y.appendScript(`https://www.google.com/recaptcha/api.js?hl=${this.locale}&onload=onloadRecaptchaCallback`)}));return new Promise(((t,n)=>{window.onloadRecaptchaCallback=()=>{this.recaptchaReady(),window.grecaptcha?t(window.grecaptcha):n(new p("Recaptcha is not available"))},e().catch((()=>n(new p("Could not load Recaptcha"))))}))}))}notify(...e){this.notifyHandler&&this.notifyHandler(...e)}errorHandler(e){switch(f("Recaptcha error:",e),e){case"expired":this.notify("Прошло слишком много времени с момента начала проверки. Попробуйте еще раз.");break;case"closed":this.notify("Вы не завершили прохождение проверки. Попробуйте еще раз.");break;case"timeout":this.notify("Возможно произшла ошибка с сетевым подключением. Попробуйте ещё раз. Если не помогает, обратитесь в поддержку.");break;default:this.notify("Что-то пошло не так. Попробуйте ещё раз. Если не помогает, обратитесь в поддержку.")}}static detectCaptchaChallengeIsShown(){return new Promise((function(e){const t=document.body;const n=new MutationObserver((function(t){t.forEach((t=>{if(t.addedNodes.length){const r=t.addedNodes[0];if(!r)return;if(r.querySelectorAll('iframe[src^="https://www.google.com/recaptcha"][src*="bframe"]').length){const t=r.firstChild;t&&(n.disconnect(),e(t))}}}))}));n.observe(t,{attributeOldValue:!1,attributes:!1,characterData:!1,characterDataOldValue:!1,childList:!0,subtree:!1})}))}renderWidget(e){return new Promise(((e,t)=>{var n,r,i;const o=document.createElement("div"),s=`${w}_${m()}`;o.id=s,null===(n=document.getElementById(w))||void 0===n||n.appendChild(o);const a=y.getGrecaptchaCallbackNames();let c=NaN;function l(){var e;null===(e=window.grecaptcha)||void 0===e||e.reset(),setTimeout((()=>{o.remove()}),1e3)}y.detectCaptchaChallengeIsShown().then((e=>{if(!e.parentElement)return;const n=new MutationObserver((function(){var r,i;"hidden"!==(null===(r=e.parentElement)||void 0===r?void 0:r.style.visibility)||(null===(i=window.grecaptcha)||void 0===i?void 0:i.getResponse(c))||(n.disconnect(),t("closed"),l())}));n.observe(e.parentElement,{attributeFilter:["style"],attributes:!0})})),window[a.resolve]=()=>{var t;const n=null===(t=window.grecaptcha)||void 0===t?void 0:t.getResponse(c);e(null!=n?n:""),l()},window[a.error]=()=>{t("error"),l()},window[a.expired]=()=>{t("expired"),l()},c=null===(r=window.grecaptcha)||void 0===r?void 0:r.render(s,{callback:a.resolve,"error-callback":a.error,"expired-callback":a.expired,sitekey:this.sitekey,size:"invisible"});const d=null===(i=window.grecaptcha)||void 0===i?void 0:i.execute(c);if(!d)return t(new Error("cannot call method execute from grecaptcha")),void l();d.catch((e=>{t(e instanceof Error?e:new Error(e.toString())),l()}))}))}execute(e){return i(this,void 0,void 0,(function*(){if(this.sitekey){f("Load recaptcha script");try{yield this.loadScript()}catch(e){const t=e instanceof p?e:new p("Could not load captcha with error: "+e.toString());throw this.onErrorChallenge(this.provider,t),t}if(!window.grecaptcha){const e=new p("Recaptcha is not available in window");throw this.onErrorChallenge(this.provider,e),e}try{f("Render Recaptcha widget"),this.onRenderCaptcha(this.provider);const t=yield this.renderWidget(e);return this.onSuccessChallenge(this.provider),t}catch(e){if(this.errorHandler(e),"string"!=typeof e){const t=new p("Could not execute captcha with error: "+e.toString());throw this.onErrorChallenge(this.provider,t),t}if("expired"===e){const e=new p("Challenge or token expired");e.reason="expired",e.capture=!1,this.onWarnChallenge(this.provider,e)}if("error"===e){const e=new p("Error during captcha execution");e.reason="error",e.capture=!1,this.onErrorChallenge(this.provider,e)}}}}))}}y.RESOLVE_FUNC_NAME="grecaptcha_resolved",y.ERROR_FUNC_NAME="grecaptcha_error",y.EXPIRED_FUNC_NAME="grecaptcha_expired",y.DEBUG=!1;const C="smartcaptcha-container",x=(...e)=>{};class E{constructor({sitekey:e,locale:t,notify:n,onRenderCaptcha:r,onSuccessChallenge:i,onWarnChallenge:o,onErrorChallenge:s,onBeforeInteractiveChallenge:a,onAfterInteractiveChallenge:c}){this.sitekey=null,this.container=null,this.provider="yandex_smart_captcha",this.locale=null!=t?t:"ru",this.sitekey=null!=e?e:null,this.notifyHandler=null!=n?n:x,this.onRenderCaptcha=null!=r?r:x,this.onSuccessChallenge=null!=i?i:x,this.onWarnChallenge=null!=o?o:x,this.onErrorChallenge=null!=s?s:x,this.onBeforeInteractiveChallenge=null!=a?a:x,this.onAfterInteractiveChallenge=null!=c?c:x,this.addDomElements()}smartCaptchaReady(){f("Smart captcha is ready",window.smartCaptcha,this)}addDomElements(){if(this.container||document.getElementById(C))return;document.body.insertAdjacentHTML("beforeend",`<div id="${C}"></div>`);const e=document.getElementById(C);e.style.display="none",this.container=e}static appendScript(e){return i(this,void 0,void 0,(function*(){if("string"!=typeof e||""===e)throw new TypeError("src script is not defined");const t=document.createElement("script");return t.src=e,document.body&&document.body.appendChild(t),new Promise(((e,n)=>{t.addEventListener("load",(()=>{e(!0)})),t.addEventListener("error",(()=>{n()}))}))}))}loadScript(){return i(this,void 0,void 0,(function*(){if(window.smartCaptcha)return Promise.resolve(window.smartCaptcha);const e=()=>i(this,void 0,void 0,(function*(){return yield E.appendScript("https://smartcaptcha.yandexcloud.net/captcha.js?render=onload&onload=onloadSmartCaptchaCallback")}));return new Promise(((t,n)=>{window.onloadSmartCaptchaCallback=()=>{this.smartCaptchaReady(),window.smartCaptcha?t(window.smartCaptcha):n(new p("SmartCaptcha is not available"))},e().catch((()=>n(new p("Could not load SmartCaptcha"))))}))}))}notify(...e){this.notifyHandler&&this.notifyHandler(...e)}errorHandler(e){switch(f("SmartCaptcha error:",e),e){case"closed":this.notify("Вы не завершили прохождение проверки. Попробуйте еще раз.");break;case"timeout":this.notify("Возможно произшла ошибка с сетевым подключением. Попробуйте ещё раз. Если не помогает, обратитесь в поддержку.");break;default:this.notify("Что-то пошло не так. Попробуйте ещё раз. Если не помогает, обратитесь в поддержку.")}}static getDebugValue(){try{if("true"===localStorage.getItem(E.LOCALE_STORAGE_DEBUG_KEY))return!0}catch(e){}return!1}renderWidget(e){var t,n,r,i,o,s,a,c;const{promise:l,resolve:d,reject:h}=Promise.withResolvers(),u=document.createElement("div"),f=`${C}_${m()}`;u.id=f,null===(t=document.getElementById(C))||void 0===t||t.appendChild(u),this.onRenderCaptcha(this.provider);const g=window.smartCaptcha.render(f,{callback:e=>{d(e),function(){var e;null===(e=window.smartCaptcha)||void 0===e||e.destroy(g),setTimeout((()=>{u.remove()}),100)}()},hideShield:!0,hl:this.locale,invisible:!0,sitekey:this.sitekey,test:E.getDebugValue()});return null===(n=window.smartCaptcha)||void 0===n||n.subscribe(g,"challenge-visible",(()=>{this.onBeforeInteractiveChallenge(this.provider)})),null===(r=window.smartCaptcha)||void 0===r||r.subscribe(g,"challenge-hidden",(()=>{this.onAfterInteractiveChallenge(this.provider),h()})),null===(i=window.smartCaptcha)||void 0===i||i.subscribe(g,"token-expired",(()=>{const e=new p("Token expired");e.reason="expired",h(e)})),null===(o=window.smartCaptcha)||void 0===o||o.subscribe(g,"success",(()=>{this.onSuccessChallenge(this.provider)})),null===(s=window.smartCaptcha)||void 0===s||s.subscribe(g,"network-error",(()=>{const e=new p("Network error");e.reason="timeout",e.capture=!0,h(e)})),null===(a=window.smartCaptcha)||void 0===a||a.subscribe(g,"javascript-error",(e=>{const t=new p("Javascript error");t.reason="error",t.capture=!0,t.cause=e,h("javascript-error")})),null===(c=window.smartCaptcha)||void 0===c||c.execute(g),l}execute(e){return i(this,void 0,void 0,(function*(){if(this.sitekey){f("Load smartCaptcha script");try{yield this.loadScript()}catch(e){const t=e instanceof p?e:new p("Could not load captcha with error: "+e.toString());throw this.onErrorChallenge(this.provider,t),t}if(!window.smartCaptcha){const e=new p("SmartCaptcha is not available in window");throw this.onErrorChallenge(this.provider,e),e}try{f("Render SmartCaptcha widget");return yield this.renderWidget(e)}catch(e){if(!e)return;if(e instanceof p)switch(this.errorHandler(e),e.reason){case"expired":this.notify("Прошло слишком много времени с момента начала проверки. Попробуйте еще раз."),this.onWarnChallenge(this.provider,e);break;case"timeout":this.notify("Вероятно у вас проблемы с подключением к сети. Попробуйте еще раз."),this.onErrorChallenge(this.provider,e);break;case"error":this.notify("Произошла непредвиденная ошибка. Мы уже делаем все возможное чтобы устранить её."),this.onErrorChallenge(this.provider,e)}const t=new p("Could not render captcha with error");t.capture=!0,t.cause=e,this.onErrorChallenge(this.provider,t)}}}))}}E.LOCALE_STORAGE_DEBUG_KEY="captcha:smart-captcha:debug";exports.ApiService=l,exports.CaptchaError=p,exports.CaptchaService=class{constructor(e){var t,n;switch(this.sitekey=null,this.provider=null,this.captcha=null,this.sitekey=null!==(t=e.sitekey)&&void 0!==t?t:null,this.provider=null!==(n=e.provider)&&void 0!==n?n:null,e.provider){case"yandex_smart_captcha":this.captcha=new E(e);break;case"cloudflare_turnstile":this.captcha=new v(e);break;case"recaptcha":this.captcha=new y(e)}}isEnabled(){return"string"==typeof this.sitekey&&""!==this.sitekey}execute(e){return i(this,void 0,void 0,(function*(){if(!1===this.isEnabled())return;if(!this.provider)return;if(!this.captcha)return;const t=yield this.captcha.execute(e);return f("Receive answer from captcha provider"),{captcha_provider:this.provider,captcha_token:t||""}}))}},exports.RequestPlugin=class{constructor(){this.pluginType="request"}},exports.ResponseSuccessPlugin=class{constructor(){this.pluginType="responseSuccess"}},exports.SocketService=class{constructor(e){var t;this.channel=new n.BroadcastChannel("shared-socket"),this.elector=void 0,this.client=void 0,this.connected=!1,this.logger=console,this.config=e,this.logger=null!==(t=null==e?void 0:e.logger)&&void 0!==t?t:this.logger,globalThis.addEventListener("beforeunload",(()=>{this.disconnect()}))}setToken(e){var t;this.config.token=e,null===(t=this.client)||void 0===t||t.setToken(e)}createClient(){var e,t,n;if(this.connected||void 0!==this.client)return this.client;this.logger.debug("Try to connect with Centrifuge client");const i=null!==(e=this.config.transport)&&void 0!==e?e:[],o=(()=>{const e=i.find((e=>"http_stream"===e.transport));if(e)return`${new URL(e.endpoint).origin}/emulation`})();try{return this.client=new r.Centrifuge(null!==(t=this.config.transport)&&void 0!==t?t:[],{debug:null!==(n=this.config.debug)&&void 0!==n&&n,emulationEndpoint:o,getToken:()=>this.config.refreshToken(),token:this.config.token}),this.logger.debug("Create Centrifuge instance",this.client),this.client.on("disconnected",(e=>{this.connected=!1,this.logger.debug("Centrifuge connection is closed and will not be reconnected",e)})),this.client.on("connected",(e=>{this.connected=!0,this.logger.debug("Centrifuge is connected with context",e)})),this.client}catch(e){this.logger.error("Failed to create the Centrifuge instance",{reason:e.toString()})}}disconnect(){var e;void 0!==this.client&&(null===(e=this.channel)||void 0===e||e.close(),this.client.disconnect(),this.client=void 0,this.elector=void 0,this.connected=!1)}subscriptionExists(e){if(!this.client)return!1;const t=this.client.subscriptions();return Boolean(t[e])}join(e,t){var n;const r=this.createClient();if(!r)return;const i=null===(n=this.client)||void 0===n?void 0:n.newSubscription(e);this.logger.debug("Create centrifuge subscription",i),i&&(i.on("publication",(({data:e})=>{var n;this.logger.debug("Get message from ws: ",e),t(e),null===(n=this.channel)||void 0===n||n.postMessage(e)})),i.subscribe(),r.connect())}subscribe(e,t){return i(this,void 0,void 0,(function*(){this.subscriptionExists(e)?this.logger.debug("Subscription to the channel is exists. Ignore subscribe."):(this.logger.debug("Create broadcast channel with name",e),this.channel=new n.BroadcastChannel(e),this.elector=n.createLeaderElection(this.channel),this.logger.debug("Wait leader",this.elector),this.elector.onduplicate=()=>{this.disconnect(),this.subscribe(e,t)},this.elector.awaitLeadership().then((()=>{this.logger.debug("Current tab is leader",this.elector),this.join(e,t)})),this.channel.addEventListener("message",(e=>{this.logger.debug("Get message from broadcast: ",e),t(e)})))}))}unsubscribe(e){var t;const n=null===(t=this.client)||void 0===t?void 0:t.subscriptions()[e];n&&n.unsubscribe()}};
1
+ "use strict";var e=require("axios"),t=require("axios-retry"),n=require("broadcast-channel"),i=require("centrifuge");function r(e,t,n,i){return new(n||(n=Promise))((function(r,o){function s(e){try{c(i.next(e))}catch(e){o(e)}}function a(e){try{c(i.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}c((i=i.apply(e,t||[])).next())}))}function o(e,t,n){return e.headers=Object.assign({"Content-Type":"application/json"},e.headers),window&&window.location&&window.location.pathname&&window.location.origin&&(e.headers=Object.assign(Object.assign({},e.headers),{"X-Referer":window.location.origin+window.location.pathname})),n.length>0?function(e,t,n){return r(this,void 0,void 0,(function*(){for(const i of n)i.isApplicable(e)&&(e=yield i.execute(e,t));return e}))}(e,t,n):e}function s(e,t,n){return n.length>0?function(e,t,n){return r(this,void 0,void 0,(function*(){for(const i of n)i.isApplicable(e)&&(e=yield i.execute(e,t));return e}))}(e,t,n):e}void 0===Promise.withResolvers&&(Promise.withResolvers=()=>{let e,t;return{promise:new Promise(((n,i)=>{e=n,t=i})),reject:t,resolve:e}}),"function"==typeof SuppressedError&&SuppressedError;const a=[422,401];function c(e){const{config:t=null,response:n=null}=e;if(null===t||null===n)return Promise.reject(e);const i=t;a.includes(n.status)&&(i._retry=!0);const r=Object.assign({errorText:e.toString(),headers:n.headers,status:n.status,statusText:n.statusText},"object"==typeof n.data?n.data:{data:n.data});return Promise.reject(r)}const l=new class{createFoxApiInstance({config:n,plugins:i=[]}){const r=e.create(n),a=this.filterPlugins(i,"request"),l=this.filterPlugins(i,"responseSuccess");return r.interceptors.request.use((e=>o(e,r,[...a]))),r.interceptors.response.use((e=>s(e,r,[...l])),c),t(r,{retries:3,retryDelay:t.exponentialDelay}),r}createApiInstance({config:t}){return e.create(t)}createStaticApiInstance(){const t=e;return t.isApiError=e=>"object"==typeof e&&!0===e.isAxiosError,t}filterPlugins(e,t){return e?e.filter((e=>e.pluginType===t)):[]}},d="turnstile-container",h="turnstile-widget";var u=`\n<div id="${d}" class="fox-cf-turnstile">\n <div class="fox-cf-turnstile__overlay"></div>\n <div class="fox-cf-turnstile__content">\n <div class="fox-cf-turnstile__content__text">\n <h3>Надо убедиться, что вы человек</h3>\n <span>Поставьте галочку, нажав на белый квадрат ниже — проверка займёт буквально секунду</span>\n </div>\n <div id="${h}">\n <div class="fox-cf-turnstile__loader"></div>\n </div>\n </div>\n</div>\n`;class p extends Error{constructor(e,t="error"){super(e),this.level="error",this.name="CaptchaError",this.message=e,this.level=t}}function f(...e){const t=["[CaptchaService] ",...e];console.debug.apply(console,t)}const g=(...e)=>{};class v{constructor({sitekey:e,locale:t,notify:n,onRenderCaptcha:i,onSuccessChallenge:r,onErrorChallenge:o,onWarnChallenge:s,onBeforeInteractiveChallenge:a,onAfterInteractiveChallenge:c}){this.sitekey=null,this.locale="ru",this.provider="cloudflare_turnstile",this.container=null,this.notifyHandler=null!=n?n:g,this.sitekey=null!=e?e:null,this.onRenderCaptcha=null!=i?i:g,this.onSuccessChallenge=null!=r?r:g,this.onErrorChallenge=null!=o?o:g,this.onWarnChallenge=null!=s?s:g,this.onBeforeInteractiveChallenge=null!=a?a:g,this.onAfterInteractiveChallenge=null!=c?c:g,t&&(this.locale=t),this.addDomElements(),v.DEBUG&&(window.cf=this)}notify(...e){this.notifyHandler&&this.notifyHandler(...e)}addDomElements(){this.container||document.getElementById(d)||(document.body.insertAdjacentHTML("beforeend",u),document.body.insertAdjacentHTML("beforeend","<style>\n.fox-cf-turnstile {\n position: fixed;\n top: 0;\n left: 0;\n display: flex;\n align-items: center;\n justify-content: center;\n width: 100vw;\n height: 100vh;\n z-index: -1;\n}\n.fox-cf-turnstile__noscroll {\n position: fixed; \n top: var(--st, 0);\n inline-size: 100%;\n overflow-y:scroll; \n}\n.fox-cf-turnstile--showing {\n z-index: 9999;\n}\n.fox-cf-turnstile__overlay {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n background: rgba(246, 247, 251, 0.9);\n opacity: 0;\n transition: all .3s ease;\n transition-delay: .2s;\n z-index: 0;\n}\n.fox-cf-turnstile__content {\n background: white;\n border-radius: 5px;\n max-width: 500px;\n max-height: 50vh;\n position: relative;\n z-index: 1;\n box-shadow: rgba(0, 0, 0, 0.08) 0px 10px 20px 0px;\n height: 1px;\n width: 1px;\n overflow: hidden;\n transition: all .8s ease, opacity 0.3s ease;\n transition-delay: .3s;\n opacity: 0;\n display: flex;\n align-items: center;\n justify-content: center;\n flex-direction: column;\n font-size: 1.2rem;\n}\n.fox-cf-turnstile__content__text {\n flex: 1;\n margin-bottom: 20px;\n opacity: 1;\n overflow: hidden;\n transition: opacity 0.3s ease;\n text-align: center;\n}\n.fox-cf-turnstile--showing .fox-cf-turnstile__overlay, .fox-cf-turnstile--show .fox-cf-turnstile__overlay {\n opacity: 1;\n}\n.fox-cf-turnstile--showing .fox-cf-turnstile__content, .fox-cf-turnstile--show .fox-cf-turnstile__content {\n width: 100%;\n height: auto;\n min-height: 20vh;\n min-width: 30vw;\n padding: 30px;\n opacity: 1;\n}\n.fox-cf-turnstile__content__text h3 {\n font-size: 1.4rem;\n}\n.fox-cf-turnstile__loader {\n font-size: 10px;\n margin: 50px auto;\n text-indent: -9999em;\n width: 5em;\n height: 5em;\n border-radius: 50%;\n background: #8b1feb;\n background: -moz-linear-gradient(left, #8b1feb 10%, rgba(139,31,235, 0) 42%);\n background: -webkit-linear-gradient(left, #8b1feb 10%, rgba(139,31,235, 0) 42%);\n background: -o-linear-gradient(left, #8b1feb 10%, rgba(139,31,235, 0) 42%);\n background: -ms-linear-gradient(left, #8b1feb 10%, rgba(139,31,235, 0) 42%);\n background: linear-gradient(to right, #8b1feb 10%, rgba(139,31,235, 0) 42%);\n position: relative;\n -webkit-animation: load3 1.4s infinite linear;\n animation: load3 1.4s infinite linear;\n -webkit-transform: translateZ(0);\n -ms-transform: translateZ(0);\n transform: translateZ(0);\n}\n.fox-cf-turnstile__loader:before {\n width: 50%;\n height: 50%;\n background: #8b1feb;\n border-radius: 100% 0 0 0;\n position: absolute;\n top: 0;\n left: 0;\n content: '';\n}\n.fox-cf-turnstile__loader:after {\n background: white;\n width: 75%;\n height: 75%;\n border-radius: 50%;\n content: '';\n margin: auto;\n position: absolute;\n top: 0;\n left: 0;\n bottom: 0;\n right: 0;\n}\n@-webkit-keyframes load3 {\n 0% {\n -webkit-transform: rotate(0deg);\n transform: rotate(0deg);\n }\n 100% {\n -webkit-transform: rotate(360deg);\n transform: rotate(360deg);\n }\n}\n@keyframes load3 {\n 0% {\n -webkit-transform: rotate(0deg);\n transform: rotate(0deg);\n }\n 100% {\n -webkit-transform: rotate(360deg);\n transform: rotate(360deg);\n }\n} \n</style>"),this.container=document.getElementById(d))}static appendScript(e){return r(this,void 0,void 0,(function*(){if("string"!=typeof e||""===e)throw new TypeError("src script is not defined");const t=document.createElement("script");return t.src=e,document.body&&document.body.appendChild(t),new Promise(((e,n)=>{t.addEventListener("load",(()=>{e(!0)})),t.addEventListener("error",(()=>{n()}))}))}))}show(){var e;null===(e=this.container)||void 0===e||e.classList.add("fox-cf-turnstile--showing"),v.bodyScrollLock()}hide(){var e,t;null===(e=this.container)||void 0===e||e.classList.remove("fox-cf-turnstile--show"),null===(t=this.container)||void 0===t||t.classList.remove("fox-cf-turnstile--showing"),v.bodyScrollUnlock()}loadScript(){return r(this,void 0,void 0,(function*(){if(window.turnstile)return Promise.resolve(window.turnstile);const e=()=>r(this,void 0,void 0,(function*(){return yield v.appendScript("https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit&onload=onloadTurnstileCallback")}));return new Promise(((t,n)=>{window.onloadTurnstileCallback=()=>{this.turnstileReady(),window.turnstile?t(window.turnstile):n(new p("Cloudflare Turnstile is not available"))},e().catch((()=>n(new p("Could not load Cloudflare Turnstile"))))}))}))}turnstileReady(){var e,t;f("Cloudflare Turnstile is ready",window.turnstile),null===(t=null===(e=this.container)||void 0===e?void 0:e.querySelector(".fox-cf-turnstile__loader"))||void 0===t||t.remove()}static normalizeLocation(e=""){return e.substring(0,31).replace(/\//g,"_")}static bodyScrollLock(){const e=document.body;e.style.setProperty("--st",`-${document.documentElement.scrollTop}px`),e.classList.add("fox-cf-turnstile__noscroll")}static bodyScrollUnlock(){document.body.classList.remove("fox-cf-turnstile__noscroll")}renderWidget(e){return r(this,void 0,void 0,(function*(){return new Promise(((t,n)=>{var i;let r="";function o(){var e;null===(e=window.turnstile)||void 0===e||e.reset(r),setTimeout((()=>{var e;null===(e=window.turnstile)||void 0===e||e.remove(r)}),500)}r=null===(i=window.turnstile)||void 0===i?void 0:i.render(`#${h}`,{action:v.normalizeLocation(null==e?void 0:e.location),"after-interactive-callback":()=>{f("after-interactive-callback"),this.onAfterInteractiveChallenge(this.provider)},"before-interactive-callback":()=>{f("before-interactive-callback"),this.onBeforeInteractiveChallenge(this.provider),this.show()},callback:e=>{f("Challenge Success"),this.hide(),t(e),o()},"error-callback":e=>{n(e),o()},"expired-callback":()=>{this.hide(),n("expired"),o()},language:this.locale,sitekey:this.sitekey,theme:"light","timeout-callback":()=>{this.hide(),n("timeout"),o()},"unsupported-callback":()=>{n("110500"),o()}})}))}))}errorHandler(e){f("Captcha error with code:",e);let t=[...v.NO_RETRY_ERROR_CODES];if("string"!=typeof e)return void this.notify("Что-то пошло не так. Попробуйте ещё раз. Если не помогает, обратитесь в поддержку.");const n=e;switch(!0){case n.startsWith("110500"):t=t.filter((e=>!e.startsWith("110500"))),this.notify("Ваш браузер устарел. Попробуйте ещё раз, используя другой браузер или устройство.");break;case n.startsWith("110600"):t=t.filter((e=>!e.startsWith("110600"))),this.notify("Прошло слишком много времени с момента начала проверки. Попробуйте еще раз.");break;case n.startsWith("110510"):t=t.filter((e=>!e.startsWith("110510"))),this.notify("Что-то пошло не так — возможно, вы используете технологию подмены User agent. Попробуйте ещё раз или обратитесь в поддержку");break;case n.startsWith("200010"):this.notify('Что-то пошло не так. Попробуйте <a href="https://yandex.ru/support/common/browsers-settings/cache.html" target="_blank" rel="nofollow noopener">очистить кеш браузера</a>. Если не помогает, обратитесь в поддержку.');break;case n.startsWith("200100"):t=t.filter((e=>!e.startsWith("200100"))),this.notify("Кажется, часы на вашем компьютере показывают неправильное время. Настройте часы и попробуйте ещё раз.");break;case n.startsWith("300"):case n.startsWith("600"):t=t.filter((e=>!e.startsWith("300")||!e.startsWith("600"))),this.notify("Потвердите еще раз что вы человек")}t.some((e=>n.startsWith(e)))&&this.notify(`Что-то пошло не так, код ошибки — ${n}. Мы уже знаем о проблеме и скоро всё поправим. Попробуйте ещё раз через некоторое время.`)}execute(e){return r(this,void 0,void 0,(function*(){if(this.sitekey){f("Load cloudflare script");try{yield this.loadScript()}catch(e){const t=e instanceof p?e:new p("Could not load captcha with error: "+e.toString());throw this.onErrorChallenge(this.provider,t),t}if(!window.turnstile){const e=new p("Cloudflare Turnstile is not available in window");throw this.onErrorChallenge(this.provider,e),e}try{f("Render turnstile widget"),this.onRenderCaptcha(this.provider);const t=yield this.renderWidget(e);return this.onSuccessChallenge(this.provider),t}catch(e){if(this.errorHandler(e),"string"!=typeof e){const t=new p("Could not execute captcha with error: "+e.toString());throw this.onErrorChallenge(this.provider,t),t}if(["110200","110100","110110"].some((t=>e.startsWith(t)))){const t=new p("Invalid sitekey or domain is not allowed");throw t.code=e,this.onErrorChallenge(this.provider,t),t}if(v.NO_RETRY_ERROR_CODES.some((t=>e.startsWith(t)))){const t=new p("Captcha challenge is failed");t.code=e,this.onErrorChallenge(this.provider,t)}else{const t=new p("Captcha challenge has error");t.reason=["timeout","expired"].includes(e)?e:void 0,t.code=e,this.onWarnChallenge(this.provider,t)}}}}))}}v.DEBUG=!1,v.NO_RETRY_ERROR_CODES=["100","105","106","110100","110110","110200","110420","110430","110500","110510","120","200010","200100"];const w="recaptcha-widget";function m(){let e=(new Date).getTime(),t="undefined"!=typeof performance&&performance.now&&1e3*performance.now()||0;return"xxxx-xxxx-4xxx-yxxx".replace(/[xy]/g,(function(n){let i=16*Math.random();return e>0?(i=(e+i)%16|0,e=Math.floor(e/16)):(i=(t+i)%16|0,t=Math.floor(t/16)),("x"===n?i:3&i|8).toString(16)}))}const b=(...e)=>{};class y{constructor({sitekey:e,locale:t,notify:n,onRenderCaptcha:i,onSuccessChallenge:r,onWarnChallenge:o,onErrorChallenge:s}){this.sitekey=null,this.locale="ru",this.container=null,this.provider="recaptcha",this.sitekey=null!=e?e:null,this.notifyHandler=null!=n?n:b,this.onRenderCaptcha=null!=i?i:b,this.onSuccessChallenge=null!=r?r:b,this.onWarnChallenge=null!=o?o:b,this.onErrorChallenge=null!=s?s:b,t&&(this.locale=t),this.addDomElements(),y.DEBUG&&(window.gr=this)}recaptchaReady(){f("Google recaptcha is ready",window.grecaptcha,this)}addDomElements(){if(this.container||document.getElementById(w))return;document.body.insertAdjacentHTML("beforeend",`<div id="${w}"></div>`);const e=document.getElementById(w);e.style.display="none",this.container=e}static getGrecaptchaCallbackNames(){return{error:`${y.ERROR_FUNC_NAME}`,expired:`${y.EXPIRED_FUNC_NAME}`,resolve:`${y.RESOLVE_FUNC_NAME}`}}static appendScript(e){return r(this,void 0,void 0,(function*(){if("string"!=typeof e||""===e)throw new TypeError("src script is not defined");const t=document.createElement("script");return t.src=e,document.body&&document.body.appendChild(t),new Promise(((e,n)=>{t.addEventListener("load",(()=>{e(!0)})),t.addEventListener("error",(()=>{n()}))}))}))}loadScript(){return r(this,void 0,void 0,(function*(){if(window.grecaptcha)return Promise.resolve(window.grecaptcha);const e=()=>r(this,void 0,void 0,(function*(){return yield y.appendScript(`https://www.google.com/recaptcha/api.js?hl=${this.locale}&onload=onloadRecaptchaCallback`)}));return new Promise(((t,n)=>{window.onloadRecaptchaCallback=()=>{this.recaptchaReady(),window.grecaptcha?t(window.grecaptcha):n(new p("Recaptcha is not available"))},e().catch((()=>n(new p("Could not load Recaptcha"))))}))}))}notify(...e){this.notifyHandler&&this.notifyHandler(...e)}errorHandler(e){switch(f("Recaptcha error:",e),e){case"expired":this.notify("Прошло слишком много времени с момента начала проверки. Попробуйте еще раз.");break;case"closed":this.notify("Вы не завершили прохождение проверки. Попробуйте еще раз.");break;case"timeout":this.notify("Возможно произшла ошибка с сетевым подключением. Попробуйте ещё раз. Если не помогает, обратитесь в поддержку.");break;default:this.notify("Что-то пошло не так. Попробуйте ещё раз. Если не помогает, обратитесь в поддержку.")}}static detectCaptchaChallengeIsShown(){return new Promise((function(e){const t=document.body;const n=new MutationObserver((function(t){t.forEach((t=>{if(t.addedNodes.length){const i=t.addedNodes[0];if(!i)return;if(i.querySelectorAll('iframe[src^="https://www.google.com/recaptcha"][src*="bframe"]').length){const t=i.firstChild;t&&(n.disconnect(),e(t))}}}))}));n.observe(t,{attributeOldValue:!1,attributes:!1,characterData:!1,characterDataOldValue:!1,childList:!0,subtree:!1})}))}renderWidget(e){return new Promise(((e,t)=>{var n,i,r;const o=document.createElement("div"),s=`${w}_${m()}`;o.id=s,null===(n=document.getElementById(w))||void 0===n||n.appendChild(o);const a=y.getGrecaptchaCallbackNames();let c=NaN;function l(){var e;null===(e=window.grecaptcha)||void 0===e||e.reset(),setTimeout((()=>{o.remove()}),1e3)}y.detectCaptchaChallengeIsShown().then((e=>{if(!e.parentElement)return;const n=new MutationObserver((function(){var i,r;"hidden"!==(null===(i=e.parentElement)||void 0===i?void 0:i.style.visibility)||(null===(r=window.grecaptcha)||void 0===r?void 0:r.getResponse(c))||(n.disconnect(),t("closed"),l())}));n.observe(e.parentElement,{attributeFilter:["style"],attributes:!0})})),window[a.resolve]=()=>{var t;const n=null===(t=window.grecaptcha)||void 0===t?void 0:t.getResponse(c);e(null!=n?n:""),l()},window[a.error]=()=>{t("error"),l()},window[a.expired]=()=>{t("expired"),l()},c=null===(i=window.grecaptcha)||void 0===i?void 0:i.render(s,{callback:a.resolve,"error-callback":a.error,"expired-callback":a.expired,sitekey:this.sitekey,size:"invisible"});const d=null===(r=window.grecaptcha)||void 0===r?void 0:r.execute(c);if(!d)return t(new Error("cannot call method execute from grecaptcha")),void l();d.catch((e=>{t(e instanceof Error?e:new Error(e.toString())),l()}))}))}execute(e){return r(this,void 0,void 0,(function*(){if(this.sitekey){f("Load recaptcha script");try{yield this.loadScript()}catch(e){const t=e instanceof p?e:new p("Could not load captcha with error: "+e.toString());throw this.onErrorChallenge(this.provider,t),t}if(!window.grecaptcha){const e=new p("Recaptcha is not available in window");throw this.onErrorChallenge(this.provider,e),e}try{f("Render Recaptcha widget"),this.onRenderCaptcha(this.provider);const t=yield this.renderWidget(e);return this.onSuccessChallenge(this.provider),t}catch(e){if(this.errorHandler(e),"string"!=typeof e){const t=new p("Could not execute captcha with error: "+e.toString());throw this.onErrorChallenge(this.provider,t),t}if("expired"===e){const e=new p("Challenge or token expired");e.reason="expired",this.onWarnChallenge(this.provider,e)}if("error"===e){const e=new p("Error during captcha execution");this.onErrorChallenge(this.provider,e)}}}}))}}y.RESOLVE_FUNC_NAME="grecaptcha_resolved",y.ERROR_FUNC_NAME="grecaptcha_error",y.EXPIRED_FUNC_NAME="grecaptcha_expired",y.DEBUG=!1;const C="smartcaptcha-container",x=(...e)=>{};class E{constructor({sitekey:e,locale:t,notify:n,onRenderCaptcha:i,onSuccessChallenge:r,onWarnChallenge:o,onErrorChallenge:s,onBeforeInteractiveChallenge:a,onAfterInteractiveChallenge:c}){this.sitekey=null,this.container=null,this.provider="yandex_smart_captcha",this.locale=null!=t?t:"ru",this.sitekey=null!=e?e:null,this.notifyHandler=null!=n?n:x,this.onRenderCaptcha=null!=i?i:x,this.onSuccessChallenge=null!=r?r:x,this.onWarnChallenge=null!=o?o:x,this.onErrorChallenge=null!=s?s:x,this.onBeforeInteractiveChallenge=null!=a?a:x,this.onAfterInteractiveChallenge=null!=c?c:x,this.addDomElements()}smartCaptchaReady(){f("Smart captcha is ready",window.smartCaptcha,this)}addDomElements(){if(this.container||document.getElementById(C))return;document.body.insertAdjacentHTML("beforeend",`<div id="${C}"></div>`);const e=document.getElementById(C);e.style.display="none",this.container=e}static appendScript(e){return r(this,void 0,void 0,(function*(){if("string"!=typeof e||""===e)throw new TypeError("src script is not defined");const t=document.createElement("script");return t.src=e,document.body&&document.body.appendChild(t),new Promise(((e,n)=>{t.addEventListener("load",(()=>{e(!0)})),t.addEventListener("error",(()=>{n()}))}))}))}loadScript(){return r(this,void 0,void 0,(function*(){if(window.smartCaptcha)return Promise.resolve(window.smartCaptcha);const e=()=>r(this,void 0,void 0,(function*(){return yield E.appendScript("https://smartcaptcha.yandexcloud.net/captcha.js?render=onload&onload=onloadSmartCaptchaCallback")}));return new Promise(((t,n)=>{window.onloadSmartCaptchaCallback=()=>{this.smartCaptchaReady(),window.smartCaptcha?t(window.smartCaptcha):n(new p("SmartCaptcha is not available"))},e().catch((()=>n(new p("Could not load SmartCaptcha"))))}))}))}notify(...e){this.notifyHandler&&this.notifyHandler(...e)}errorHandler(e){switch(f("SmartCaptcha error:",e),e){case"closed":this.notify("Вы не завершили прохождение проверки. Попробуйте еще раз.");break;case"timeout":this.notify("Возможно произшла ошибка с сетевым подключением. Попробуйте ещё раз. Если не помогает, обратитесь в поддержку.");break;default:this.notify("Что-то пошло не так. Попробуйте ещё раз. Если не помогает, обратитесь в поддержку.")}}static getDebugValue(){try{if("true"===localStorage.getItem(E.LOCALE_STORAGE_DEBUG_KEY))return!0}catch(e){}return!1}renderWidget(e){var t,n,i,r,o,s,a,c;const{promise:l,resolve:d,reject:h}=Promise.withResolvers(),u=document.createElement("div"),f=`${C}_${m()}`;u.id=f,null===(t=document.getElementById(C))||void 0===t||t.appendChild(u),this.onRenderCaptcha(this.provider);const g=window.smartCaptcha.render(f,{callback:e=>{d(e),function(){var e;null===(e=window.smartCaptcha)||void 0===e||e.destroy(g),setTimeout((()=>{u.remove()}),100)}()},hideShield:!0,hl:this.locale,invisible:!0,sitekey:this.sitekey,test:E.getDebugValue()});return null===(n=window.smartCaptcha)||void 0===n||n.subscribe(g,"challenge-visible",(()=>{this.onBeforeInteractiveChallenge(this.provider)})),null===(i=window.smartCaptcha)||void 0===i||i.subscribe(g,"challenge-hidden",(()=>{this.onAfterInteractiveChallenge(this.provider),h()})),null===(r=window.smartCaptcha)||void 0===r||r.subscribe(g,"token-expired",(()=>{const e=new p("Token expired");e.reason="expired",h(e)})),null===(o=window.smartCaptcha)||void 0===o||o.subscribe(g,"success",(()=>{this.onSuccessChallenge(this.provider)})),null===(s=window.smartCaptcha)||void 0===s||s.subscribe(g,"network-error",(()=>{const e=new p("Network error");e.reason="timeout",h(e)})),null===(a=window.smartCaptcha)||void 0===a||a.subscribe(g,"javascript-error",(e=>{new p("Javascript error","fatal").cause=e,h("javascript-error")})),null===(c=window.smartCaptcha)||void 0===c||c.execute(g),l}execute(e){return r(this,void 0,void 0,(function*(){if(this.sitekey){f("Load smartCaptcha script");try{yield this.loadScript()}catch(e){const t=e instanceof p?e:new p("Could not load captcha with error: "+e.toString());throw this.onErrorChallenge(this.provider,t),t}if(!window.smartCaptcha){const e=new p("SmartCaptcha is not available in window");throw this.onErrorChallenge(this.provider,e),e}try{f("Render SmartCaptcha widget");return yield this.renderWidget(e)}catch(e){if(!e)return;if(e instanceof p)if(this.errorHandler(e),"fatal"===e.level)this.notify("Произошла непредвиденная ошибка. Мы уже делаем все возможное чтобы устранить её."),this.onErrorChallenge(this.provider,e);else switch(e.reason){case"expired":this.notify("Прошло слишком много времени с момента начала проверки. Попробуйте еще раз."),this.onWarnChallenge(this.provider,e);break;case"timeout":this.notify("Вероятно у вас проблемы с подключением к сети. Попробуйте еще раз."),this.onErrorChallenge(this.provider,e)}else{const t=new p("Could not render captcha with error","fatal");t.cause=e,this.onErrorChallenge(this.provider,t)}}}}))}}E.LOCALE_STORAGE_DEBUG_KEY="captcha:smart-captcha:debug";exports.ApiService=l,exports.CaptchaError=p,exports.CaptchaService=class{constructor(e){var t,n;switch(this.sitekey=null,this.provider=null,this.captcha=null,this.sitekey=null!==(t=e.sitekey)&&void 0!==t?t:null,this.provider=null!==(n=e.provider)&&void 0!==n?n:null,e.provider){case"yandex_smart_captcha":this.captcha=new E(e);break;case"cloudflare_turnstile":this.captcha=new v(e);break;case"recaptcha":this.captcha=new y(e)}}isEnabled(){return"string"==typeof this.sitekey&&""!==this.sitekey}execute(e){return r(this,void 0,void 0,(function*(){if(!1===this.isEnabled())return;if(!this.provider)return;if(!this.captcha)return;const t=yield this.captcha.execute(e);return f("Receive answer from captcha provider"),{captcha_provider:this.provider,captcha_token:t||""}}))}},exports.RequestPlugin=class{constructor(){this.pluginType="request"}},exports.ResponseSuccessPlugin=class{constructor(){this.pluginType="responseSuccess"}},exports.SocketService=class{constructor(e){var t;this.channel=new n.BroadcastChannel("shared-socket"),this.elector=void 0,this.client=void 0,this.connected=!1,this.logger=console,this.config=e,this.logger=null!==(t=null==e?void 0:e.logger)&&void 0!==t?t:this.logger,globalThis.addEventListener("beforeunload",(()=>{this.disconnect()}))}setToken(e){var t;this.config.token=e,null===(t=this.client)||void 0===t||t.setToken(e)}createClient(){var e,t,n;if(this.connected||void 0!==this.client)return this.client;this.logger.debug("Try to connect with Centrifuge client");const r=null!==(e=this.config.transport)&&void 0!==e?e:[],o=(()=>{const e=r.find((e=>"http_stream"===e.transport));if(e)return`${new URL(e.endpoint).origin}/emulation`})();try{return this.client=new i.Centrifuge(null!==(t=this.config.transport)&&void 0!==t?t:[],{debug:null!==(n=this.config.debug)&&void 0!==n&&n,emulationEndpoint:o,getToken:()=>this.config.refreshToken(),token:this.config.token}),this.logger.debug("Create Centrifuge instance",this.client),this.client.on("disconnected",(e=>{this.connected=!1,this.logger.debug("Centrifuge connection is closed and will not be reconnected",e)})),this.client.on("connected",(e=>{this.connected=!0,this.logger.debug("Centrifuge is connected with context",e)})),this.client}catch(e){this.logger.error("Failed to create the Centrifuge instance",{reason:e.toString()})}}disconnect(){var e;void 0!==this.client&&(null===(e=this.channel)||void 0===e||e.close(),this.client.disconnect(),this.client=void 0,this.elector=void 0,this.connected=!1)}subscriptionExists(e){if(!this.client)return!1;const t=this.client.subscriptions();return Boolean(t[e])}join(e,t){var n;const i=this.createClient();if(!i)return;const r=null===(n=this.client)||void 0===n?void 0:n.newSubscription(e);this.logger.debug("Create centrifuge subscription",r),r&&(r.on("publication",(({data:e})=>{var n;this.logger.debug("Get message from ws: ",e),t(e),null===(n=this.channel)||void 0===n||n.postMessage(e)})),r.subscribe(),i.connect())}subscribe(e,t){return r(this,void 0,void 0,(function*(){this.subscriptionExists(e)?this.logger.debug("Subscription to the channel is exists. Ignore subscribe."):(this.logger.debug("Create broadcast channel with name",e),this.channel=new n.BroadcastChannel(e),this.elector=n.createLeaderElection(this.channel),this.logger.debug("Wait leader",this.elector),this.elector.onduplicate=()=>{this.disconnect(),this.subscribe(e,t)},this.elector.awaitLeadership().then((()=>{this.logger.debug("Current tab is leader",this.elector),this.join(e,t)})),this.channel.addEventListener("message",(e=>{this.logger.debug("Get message from broadcast: ",e),t(e)})))}))}unsubscribe(e){var t;const n=null===(t=this.client)||void 0===t?void 0:t.subscriptions()[e];n&&n.unsubscribe()}};
package/index.js.flow CHANGED
@@ -5,6 +5,7 @@
5
5
  * @flow
6
6
  */
7
7
 
8
+ import { AxiosInstance, AxiosRequestConfig, CreateAxiosDefaults } from "axios";
8
9
  export interface ApiTransformer {
9
10
  (data: any, headers?: any): any;
10
11
  }
@@ -52,37 +53,7 @@ export type ApiResponseType =
52
53
  | "json"
53
54
  | "text"
54
55
  | "stream";
55
- export type ApiRequestConfig = {|
56
- url?: string,
57
- method?: ApiMethod,
58
- baseURL?: string,
59
- transformRequest?: ApiTransformer | ApiTransformer[],
60
- transformResponse?: ApiTransformer | ApiTransformer[],
61
- headers?: any,
62
- params?: any,
63
- paramsSerializer?: (params: any) => string,
64
- data?: any,
65
- timeout?: number,
66
- timeoutErrorMessage?: string,
67
- withCredentials?: boolean,
68
- adapter?: ApiAdapter,
69
- auth?: ApiBasicCredentials,
70
- responseType?: ApiResponseType,
71
- xsrfCookieName?: string,
72
- xsrfHeaderName?: string,
73
- onUploadProgress?: (progressEvent: any) => void,
74
- onDownloadProgress?: (progressEvent: any) => void,
75
- maxContentLength?: number,
76
- validateStatus?: ((status: number) => boolean) | null,
77
- maxBodyLength?: number,
78
- maxRedirects?: number,
79
- socketPath?: string | null,
80
- httpAgent?: any,
81
- httpsAgent?: any,
82
- proxy?: ApiProxyConfig | false,
83
- cancelToken?: CancelToken,
84
- decompress?: boolean,
85
- |};
56
+ export type ApiRequestConfig = AxiosRequestConfig;
86
57
  export interface ApiResponse<T = any, R = T> {
87
58
  data: R;
88
59
  status: number;
@@ -129,36 +100,7 @@ export interface ApiInterceptorManager<V> {
129
100
  ): number;
130
101
  eject(id: number): void;
131
102
  }
132
- export interface ApiInstance {
133
- <T, R>(config: ApiRequestConfigExtended): ApiPromise<T, R>;
134
- <T, R>(url: string, config?: ApiRequestConfigExtended): ApiPromise<T, R>;
135
- defaults: ApiRequestConfigExtended;
136
- interceptors: {|
137
- request: ApiInterceptorManager<ApiRequestConfigExtended>,
138
- response: ApiInterceptorManager<ApiResponse<>>,
139
- |};
140
- getUri(config?: ApiRequestConfigExtended): string;
141
- request<T, R>(config: ApiRequestConfigExtended): ApiPromise<T, R>;
142
- get<R>(url: string, config?: ApiRequestConfigExtended): ApiPromise<R>;
143
- delete<R>(url: string, config?: ApiRequestConfigExtended): ApiPromise<R>;
144
- head<R>(url: string, config?: ApiRequestConfigExtended): ApiPromise<R>;
145
- options<R>(url: string, config?: ApiRequestConfigExtended): ApiPromise<R>;
146
- post<T, R>(
147
- url: string,
148
- data?: T,
149
- config?: ApiRequestConfigExtended
150
- ): ApiPromise<T, R>;
151
- put<T, R>(
152
- url: string,
153
- data?: T,
154
- config?: ApiRequestConfigExtended
155
- ): ApiPromise<T, R>;
156
- patch<T, R>(
157
- url: string,
158
- data?: T,
159
- config?: ApiRequestConfigExtended
160
- ): ApiPromise<T, R>;
161
- }
103
+ export type ApiInstance = AxiosInstance;
162
104
  export type ApiStatic = {
163
105
  create(config?: ApiRequestConfig): ApiInstance,
164
106
  Cancel: CancelStatic,
@@ -218,7 +160,7 @@ export interface ResponseSuccessPluginInterface {
218
160
  isApplicable(response: ApiResponse<>): boolean;
219
161
  }
220
162
  export type ApiConfig = {|
221
- config: ApiRequestConfigExtended,
163
+ config: CreateAxiosDefaults,
222
164
  plugins?: Array<RequestPluginInterface | ResponseSuccessPluginInterface>,
223
165
  |};
224
166
  declare export class RequestPlugin implements RequestPluginInterface {
@@ -243,11 +185,11 @@ declare export class ResponseSuccessPlugin
243
185
  }
244
186
  declare var apiServiceInstance: ApiServiceInterface;
245
187
  declare export class CaptchaError mixins Error {
246
- reason?: "error" | "timeout" | "expired";
188
+ level?: "fatal" | "error";
189
+ reason?: "timeout" | "expired";
247
190
  code?: string;
248
191
  cause?: any;
249
- capture?: boolean;
250
- constructor(message: string): this;
192
+ constructor(message: string, level?: "fatal" | "error"): this;
251
193
  }
252
194
  export type CaptchaProviderName =
253
195
  | "recaptcha"
package/index.mjs CHANGED
@@ -1 +1 @@
1
- import e from"axios";import t from"axios-retry";import{BroadcastChannel as n,createLeaderElection as i}from"broadcast-channel";import{Centrifuge as r}from"centrifuge";function o(e,t,n,i){return new(n||(n=Promise))((function(r,o){function s(e){try{c(i.next(e))}catch(e){o(e)}}function a(e){try{c(i.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}c((i=i.apply(e,t||[])).next())}))}function s(e,t,n){return e.headers=Object.assign({"Content-Type":"application/json"},e.headers),window&&window.location&&window.location.pathname&&window.location.origin&&(e.headers=Object.assign(Object.assign({},e.headers),{"X-Referer":window.location.origin+window.location.pathname})),n.length>0?function(e,t,n){return o(this,void 0,void 0,(function*(){for(const i of n)i.isApplicable(e)&&(e=yield i.execute(e,t));return e}))}(e,t,n):e}function a(e,t,n){return n.length>0?function(e,t,n){return o(this,void 0,void 0,(function*(){for(const i of n)i.isApplicable(e)&&(e=yield i.execute(e,t));return e}))}(e,t,n):e}void 0===Promise.withResolvers&&(Promise.withResolvers=()=>{let e,t;return{promise:new Promise(((n,i)=>{e=n,t=i})),reject:t,resolve:e}}),"function"==typeof SuppressedError&&SuppressedError;const c=[422,401];function l(e){const{config:t=null,response:n=null}=e;if(null===t||null===n)return Promise.reject(e);const i=t;c.includes(n.status)&&(i._retry=!0);const r=Object.assign({errorText:e.toString(),headers:n.headers,status:n.status,statusText:n.statusText},"object"==typeof n.data?n.data:{data:n.data});return Promise.reject(r)}class d{constructor(){this.pluginType="request"}}class h{constructor(){this.pluginType="responseSuccess"}}const u=new class{createFoxApiInstance({config:n,plugins:i=[]}){const r=e.create(n),o=this.filterPlugins(i,"request"),c=this.filterPlugins(i,"responseSuccess");return r.interceptors.request.use((e=>s(e,r,[...o]))),r.interceptors.response.use((e=>a(e,r,[...c])),l),t(r,{retries:3,retryDelay:t.exponentialDelay}),r}createApiInstance({config:t}){return e.create(t)}createStaticApiInstance(){const t=e;return t.isApiError=e=>"object"==typeof e&&!0===e.isAxiosError,t}filterPlugins(e,t){return e?e.filter((e=>e.pluginType===t)):[]}},p="turnstile-container",f="turnstile-widget";var g=`\n<div id="${p}" class="fox-cf-turnstile">\n <div class="fox-cf-turnstile__overlay"></div>\n <div class="fox-cf-turnstile__content">\n <div class="fox-cf-turnstile__content__text">\n <h3>Надо убедиться, что вы человек</h3>\n <span>Поставьте галочку, нажав на белый квадрат ниже — проверка займёт буквально секунду</span>\n </div>\n <div id="${f}">\n <div class="fox-cf-turnstile__loader"></div>\n </div>\n </div>\n</div>\n`;class v extends Error{constructor(e){super(e),this.capture=!0,this.name="CaptchaError",this.message=e}}function w(...e){const t=["[CaptchaService] ",...e];console.debug.apply(console,t)}const m=(...e)=>{};class b{constructor({sitekey:e,locale:t,notify:n,onRenderCaptcha:i,onSuccessChallenge:r,onErrorChallenge:o,onWarnChallenge:s,onBeforeInteractiveChallenge:a,onAfterInteractiveChallenge:c}){this.sitekey=null,this.locale="ru",this.provider="cloudflare_turnstile",this.container=null,this.notifyHandler=null!=n?n:m,this.sitekey=null!=e?e:null,this.onRenderCaptcha=null!=i?i:m,this.onSuccessChallenge=null!=r?r:m,this.onErrorChallenge=null!=o?o:m,this.onWarnChallenge=null!=s?s:m,this.onBeforeInteractiveChallenge=null!=a?a:m,this.onAfterInteractiveChallenge=null!=c?c:m,t&&(this.locale=t),this.addDomElements(),b.DEBUG&&(window.cf=this)}notify(...e){this.notifyHandler&&this.notifyHandler(...e)}addDomElements(){this.container||document.getElementById(p)||(document.body.insertAdjacentHTML("beforeend",g),document.body.insertAdjacentHTML("beforeend","<style>\n.fox-cf-turnstile {\n position: fixed;\n top: 0;\n left: 0;\n display: flex;\n align-items: center;\n justify-content: center;\n width: 100vw;\n height: 100vh;\n z-index: -1;\n}\n.fox-cf-turnstile__noscroll {\n position: fixed; \n top: var(--st, 0);\n inline-size: 100%;\n overflow-y:scroll; \n}\n.fox-cf-turnstile--showing {\n z-index: 9999;\n}\n.fox-cf-turnstile__overlay {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n background: rgba(246, 247, 251, 0.9);\n opacity: 0;\n transition: all .3s ease;\n transition-delay: .2s;\n z-index: 0;\n}\n.fox-cf-turnstile__content {\n background: white;\n border-radius: 5px;\n max-width: 500px;\n max-height: 50vh;\n position: relative;\n z-index: 1;\n box-shadow: rgba(0, 0, 0, 0.08) 0px 10px 20px 0px;\n height: 1px;\n width: 1px;\n overflow: hidden;\n transition: all .8s ease, opacity 0.3s ease;\n transition-delay: .3s;\n opacity: 0;\n display: flex;\n align-items: center;\n justify-content: center;\n flex-direction: column;\n font-size: 1.2rem;\n}\n.fox-cf-turnstile__content__text {\n flex: 1;\n margin-bottom: 20px;\n opacity: 1;\n overflow: hidden;\n transition: opacity 0.3s ease;\n text-align: center;\n}\n.fox-cf-turnstile--showing .fox-cf-turnstile__overlay, .fox-cf-turnstile--show .fox-cf-turnstile__overlay {\n opacity: 1;\n}\n.fox-cf-turnstile--showing .fox-cf-turnstile__content, .fox-cf-turnstile--show .fox-cf-turnstile__content {\n width: 100%;\n height: auto;\n min-height: 20vh;\n min-width: 30vw;\n padding: 30px;\n opacity: 1;\n}\n.fox-cf-turnstile__content__text h3 {\n font-size: 1.4rem;\n}\n.fox-cf-turnstile__loader {\n font-size: 10px;\n margin: 50px auto;\n text-indent: -9999em;\n width: 5em;\n height: 5em;\n border-radius: 50%;\n background: #8b1feb;\n background: -moz-linear-gradient(left, #8b1feb 10%, rgba(139,31,235, 0) 42%);\n background: -webkit-linear-gradient(left, #8b1feb 10%, rgba(139,31,235, 0) 42%);\n background: -o-linear-gradient(left, #8b1feb 10%, rgba(139,31,235, 0) 42%);\n background: -ms-linear-gradient(left, #8b1feb 10%, rgba(139,31,235, 0) 42%);\n background: linear-gradient(to right, #8b1feb 10%, rgba(139,31,235, 0) 42%);\n position: relative;\n -webkit-animation: load3 1.4s infinite linear;\n animation: load3 1.4s infinite linear;\n -webkit-transform: translateZ(0);\n -ms-transform: translateZ(0);\n transform: translateZ(0);\n}\n.fox-cf-turnstile__loader:before {\n width: 50%;\n height: 50%;\n background: #8b1feb;\n border-radius: 100% 0 0 0;\n position: absolute;\n top: 0;\n left: 0;\n content: '';\n}\n.fox-cf-turnstile__loader:after {\n background: white;\n width: 75%;\n height: 75%;\n border-radius: 50%;\n content: '';\n margin: auto;\n position: absolute;\n top: 0;\n left: 0;\n bottom: 0;\n right: 0;\n}\n@-webkit-keyframes load3 {\n 0% {\n -webkit-transform: rotate(0deg);\n transform: rotate(0deg);\n }\n 100% {\n -webkit-transform: rotate(360deg);\n transform: rotate(360deg);\n }\n}\n@keyframes load3 {\n 0% {\n -webkit-transform: rotate(0deg);\n transform: rotate(0deg);\n }\n 100% {\n -webkit-transform: rotate(360deg);\n transform: rotate(360deg);\n }\n} \n</style>"),this.container=document.getElementById(p))}static appendScript(e){return o(this,void 0,void 0,(function*(){if("string"!=typeof e||""===e)throw new TypeError("src script is not defined");const t=document.createElement("script");return t.src=e,document.body&&document.body.appendChild(t),new Promise(((e,n)=>{t.addEventListener("load",(()=>{e(!0)})),t.addEventListener("error",(()=>{n()}))}))}))}show(){var e;null===(e=this.container)||void 0===e||e.classList.add("fox-cf-turnstile--showing"),b.bodyScrollLock()}hide(){var e,t;null===(e=this.container)||void 0===e||e.classList.remove("fox-cf-turnstile--show"),null===(t=this.container)||void 0===t||t.classList.remove("fox-cf-turnstile--showing"),b.bodyScrollUnlock()}loadScript(){return o(this,void 0,void 0,(function*(){if(window.turnstile)return Promise.resolve(window.turnstile);const e=()=>o(this,void 0,void 0,(function*(){return yield b.appendScript("https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit&onload=onloadTurnstileCallback")}));return new Promise(((t,n)=>{window.onloadTurnstileCallback=()=>{this.turnstileReady(),window.turnstile?t(window.turnstile):n(new v("Cloudflare Turnstile is not available"))},e().catch((()=>n(new v("Could not load Cloudflare Turnstile"))))}))}))}turnstileReady(){var e,t;w("Cloudflare Turnstile is ready",window.turnstile),null===(t=null===(e=this.container)||void 0===e?void 0:e.querySelector(".fox-cf-turnstile__loader"))||void 0===t||t.remove()}static normalizeLocation(e=""){return e.substring(0,31).replace(/\//g,"_")}static bodyScrollLock(){const e=document.body;e.style.setProperty("--st",`-${document.documentElement.scrollTop}px`),e.classList.add("fox-cf-turnstile__noscroll")}static bodyScrollUnlock(){document.body.classList.remove("fox-cf-turnstile__noscroll")}renderWidget(e){return o(this,void 0,void 0,(function*(){return new Promise(((t,n)=>{var i;let r="";function o(){var e;null===(e=window.turnstile)||void 0===e||e.reset(r),setTimeout((()=>{var e;null===(e=window.turnstile)||void 0===e||e.remove(r)}),500)}r=null===(i=window.turnstile)||void 0===i?void 0:i.render(`#${f}`,{action:b.normalizeLocation(null==e?void 0:e.location),"after-interactive-callback":()=>{w("after-interactive-callback"),this.onAfterInteractiveChallenge(this.provider)},"before-interactive-callback":()=>{w("before-interactive-callback"),this.onBeforeInteractiveChallenge(this.provider),this.show()},callback:e=>{w("Challenge Success"),this.hide(),t(e),o()},"error-callback":e=>{n(e),o()},"expired-callback":()=>{this.hide(),n("expired"),o()},language:this.locale,sitekey:this.sitekey,theme:"light","timeout-callback":()=>{this.hide(),n("timeout"),o()},"unsupported-callback":()=>{n("110500"),o()}})}))}))}errorHandler(e){w("Captcha error with code:",e);let t=[...b.NO_RETRY_ERROR_CODES];if("string"!=typeof e)return void this.notify("Что-то пошло не так. Попробуйте ещё раз. Если не помогает, обратитесь в поддержку.");const n=e;switch(!0){case n.startsWith("110500"):t=t.filter((e=>!e.startsWith("110500"))),this.notify("Ваш браузер устарел. Попробуйте ещё раз, используя другой браузер или устройство.");break;case n.startsWith("110600"):t=t.filter((e=>!e.startsWith("110600"))),this.notify("Прошло слишком много времени с момента начала проверки. Попробуйте еще раз.");break;case n.startsWith("110510"):t=t.filter((e=>!e.startsWith("110510"))),this.notify("Что-то пошло не так — возможно, вы используете технологию подмены User agent. Попробуйте ещё раз или обратитесь в поддержку");break;case n.startsWith("200010"):this.notify('Что-то пошло не так. Попробуйте <a href="https://yandex.ru/support/common/browsers-settings/cache.html" target="_blank" rel="nofollow noopener">очистить кеш браузера</a>. Если не помогает, обратитесь в поддержку.');break;case n.startsWith("200100"):t=t.filter((e=>!e.startsWith("200100"))),this.notify("Кажется, часы на вашем компьютере показывают неправильное время. Настройте часы и попробуйте ещё раз.");break;case n.startsWith("300"):case n.startsWith("600"):t=t.filter((e=>!e.startsWith("300")||!e.startsWith("600"))),this.notify("Потвердите еще раз что вы человек")}t.some((e=>n.startsWith(e)))&&this.notify(`Что-то пошло не так, код ошибки — ${n}. Мы уже знаем о проблеме и скоро всё поправим. Попробуйте ещё раз через некоторое время.`)}execute(e){return o(this,void 0,void 0,(function*(){if(this.sitekey){w("Load cloudflare script");try{yield this.loadScript()}catch(e){const t=e instanceof v?e:new v("Could not load captcha with error: "+e.toString());throw this.onErrorChallenge(this.provider,t),t}if(!window.turnstile){const e=new v("Cloudflare Turnstile is not available in window");throw this.onErrorChallenge(this.provider,e),e}try{w("Render turnstile widget"),this.onRenderCaptcha(this.provider);const t=yield this.renderWidget(e);return this.onSuccessChallenge(this.provider),t}catch(e){if(this.errorHandler(e),"string"!=typeof e){const t=new v("Could not execute captcha with error: "+e.toString());throw this.onErrorChallenge(this.provider,t),t}if(["110200","110100","110110"].some((t=>e.startsWith(t)))){const t=new v("Invalid sitekey or domain is not allowed");throw t.code=e,this.onErrorChallenge(this.provider,t),t}if(b.NO_RETRY_ERROR_CODES.some((t=>e.startsWith(t)))){const t=new v("Captcha challenge is failed");t.reason="error",t.capture=!1,t.code=e,this.onErrorChallenge(this.provider,t)}else{const t=new v("Captcha challenge has error");t.reason=["timeout","expired"].includes(e)?e:"error",t.capture=!1,t.code=e,this.onWarnChallenge(this.provider,t)}}}}))}}b.DEBUG=!1,b.NO_RETRY_ERROR_CODES=["100","105","106","110100","110110","110200","110420","110430","110500","110510","120","200010","200100"];const y="recaptcha-widget";function C(){let e=(new Date).getTime(),t="undefined"!=typeof performance&&performance.now&&1e3*performance.now()||0;return"xxxx-xxxx-4xxx-yxxx".replace(/[xy]/g,(function(n){let i=16*Math.random();return e>0?(i=(e+i)%16|0,e=Math.floor(e/16)):(i=(t+i)%16|0,t=Math.floor(t/16)),("x"===n?i:3&i|8).toString(16)}))}const x=(...e)=>{};class E{constructor({sitekey:e,locale:t,notify:n,onRenderCaptcha:i,onSuccessChallenge:r,onWarnChallenge:o,onErrorChallenge:s}){this.sitekey=null,this.locale="ru",this.container=null,this.provider="recaptcha",this.sitekey=null!=e?e:null,this.notifyHandler=null!=n?n:x,this.onRenderCaptcha=null!=i?i:x,this.onSuccessChallenge=null!=r?r:x,this.onWarnChallenge=null!=o?o:x,this.onErrorChallenge=null!=s?s:x,t&&(this.locale=t),this.addDomElements(),E.DEBUG&&(window.gr=this)}recaptchaReady(){w("Google recaptcha is ready",window.grecaptcha,this)}addDomElements(){if(this.container||document.getElementById(y))return;document.body.insertAdjacentHTML("beforeend",`<div id="${y}"></div>`);const e=document.getElementById(y);e.style.display="none",this.container=e}static getGrecaptchaCallbackNames(){return{error:`${E.ERROR_FUNC_NAME}`,expired:`${E.EXPIRED_FUNC_NAME}`,resolve:`${E.RESOLVE_FUNC_NAME}`}}static appendScript(e){return o(this,void 0,void 0,(function*(){if("string"!=typeof e||""===e)throw new TypeError("src script is not defined");const t=document.createElement("script");return t.src=e,document.body&&document.body.appendChild(t),new Promise(((e,n)=>{t.addEventListener("load",(()=>{e(!0)})),t.addEventListener("error",(()=>{n()}))}))}))}loadScript(){return o(this,void 0,void 0,(function*(){if(window.grecaptcha)return Promise.resolve(window.grecaptcha);const e=()=>o(this,void 0,void 0,(function*(){return yield E.appendScript(`https://www.google.com/recaptcha/api.js?hl=${this.locale}&onload=onloadRecaptchaCallback`)}));return new Promise(((t,n)=>{window.onloadRecaptchaCallback=()=>{this.recaptchaReady(),window.grecaptcha?t(window.grecaptcha):n(new v("Recaptcha is not available"))},e().catch((()=>n(new v("Could not load Recaptcha"))))}))}))}notify(...e){this.notifyHandler&&this.notifyHandler(...e)}errorHandler(e){switch(w("Recaptcha error:",e),e){case"expired":this.notify("Прошло слишком много времени с момента начала проверки. Попробуйте еще раз.");break;case"closed":this.notify("Вы не завершили прохождение проверки. Попробуйте еще раз.");break;case"timeout":this.notify("Возможно произшла ошибка с сетевым подключением. Попробуйте ещё раз. Если не помогает, обратитесь в поддержку.");break;default:this.notify("Что-то пошло не так. Попробуйте ещё раз. Если не помогает, обратитесь в поддержку.")}}static detectCaptchaChallengeIsShown(){return new Promise((function(e){const t=document.body;const n=new MutationObserver((function(t){t.forEach((t=>{if(t.addedNodes.length){const i=t.addedNodes[0];if(!i)return;if(i.querySelectorAll('iframe[src^="https://www.google.com/recaptcha"][src*="bframe"]').length){const t=i.firstChild;t&&(n.disconnect(),e(t))}}}))}));n.observe(t,{attributeOldValue:!1,attributes:!1,characterData:!1,characterDataOldValue:!1,childList:!0,subtree:!1})}))}renderWidget(e){return new Promise(((e,t)=>{var n,i,r;const o=document.createElement("div"),s=`${y}_${C()}`;o.id=s,null===(n=document.getElementById(y))||void 0===n||n.appendChild(o);const a=E.getGrecaptchaCallbackNames();let c=NaN;function l(){var e;null===(e=window.grecaptcha)||void 0===e||e.reset(),setTimeout((()=>{o.remove()}),1e3)}E.detectCaptchaChallengeIsShown().then((e=>{if(!e.parentElement)return;const n=new MutationObserver((function(){var i,r;"hidden"!==(null===(i=e.parentElement)||void 0===i?void 0:i.style.visibility)||(null===(r=window.grecaptcha)||void 0===r?void 0:r.getResponse(c))||(n.disconnect(),t("closed"),l())}));n.observe(e.parentElement,{attributeFilter:["style"],attributes:!0})})),window[a.resolve]=()=>{var t;const n=null===(t=window.grecaptcha)||void 0===t?void 0:t.getResponse(c);e(null!=n?n:""),l()},window[a.error]=()=>{t("error"),l()},window[a.expired]=()=>{t("expired"),l()},c=null===(i=window.grecaptcha)||void 0===i?void 0:i.render(s,{callback:a.resolve,"error-callback":a.error,"expired-callback":a.expired,sitekey:this.sitekey,size:"invisible"});const d=null===(r=window.grecaptcha)||void 0===r?void 0:r.execute(c);if(!d)return t(new Error("cannot call method execute from grecaptcha")),void l();d.catch((e=>{t(e instanceof Error?e:new Error(e.toString())),l()}))}))}execute(e){return o(this,void 0,void 0,(function*(){if(this.sitekey){w("Load recaptcha script");try{yield this.loadScript()}catch(e){const t=e instanceof v?e:new v("Could not load captcha with error: "+e.toString());throw this.onErrorChallenge(this.provider,t),t}if(!window.grecaptcha){const e=new v("Recaptcha is not available in window");throw this.onErrorChallenge(this.provider,e),e}try{w("Render Recaptcha widget"),this.onRenderCaptcha(this.provider);const t=yield this.renderWidget(e);return this.onSuccessChallenge(this.provider),t}catch(e){if(this.errorHandler(e),"string"!=typeof e){const t=new v("Could not execute captcha with error: "+e.toString());throw this.onErrorChallenge(this.provider,t),t}if("expired"===e){const e=new v("Challenge or token expired");e.reason="expired",e.capture=!1,this.onWarnChallenge(this.provider,e)}if("error"===e){const e=new v("Error during captcha execution");e.reason="error",e.capture=!1,this.onErrorChallenge(this.provider,e)}}}}))}}E.RESOLVE_FUNC_NAME="grecaptcha_resolved",E.ERROR_FUNC_NAME="grecaptcha_error",E.EXPIRED_FUNC_NAME="grecaptcha_expired",E.DEBUG=!1;const k="smartcaptcha-container",_=(...e)=>{};class S{constructor({sitekey:e,locale:t,notify:n,onRenderCaptcha:i,onSuccessChallenge:r,onWarnChallenge:o,onErrorChallenge:s,onBeforeInteractiveChallenge:a,onAfterInteractiveChallenge:c}){this.sitekey=null,this.container=null,this.provider="yandex_smart_captcha",this.locale=null!=t?t:"ru",this.sitekey=null!=e?e:null,this.notifyHandler=null!=n?n:_,this.onRenderCaptcha=null!=i?i:_,this.onSuccessChallenge=null!=r?r:_,this.onWarnChallenge=null!=o?o:_,this.onErrorChallenge=null!=s?s:_,this.onBeforeInteractiveChallenge=null!=a?a:_,this.onAfterInteractiveChallenge=null!=c?c:_,this.addDomElements()}smartCaptchaReady(){w("Smart captcha is ready",window.smartCaptcha,this)}addDomElements(){if(this.container||document.getElementById(k))return;document.body.insertAdjacentHTML("beforeend",`<div id="${k}"></div>`);const e=document.getElementById(k);e.style.display="none",this.container=e}static appendScript(e){return o(this,void 0,void 0,(function*(){if("string"!=typeof e||""===e)throw new TypeError("src script is not defined");const t=document.createElement("script");return t.src=e,document.body&&document.body.appendChild(t),new Promise(((e,n)=>{t.addEventListener("load",(()=>{e(!0)})),t.addEventListener("error",(()=>{n()}))}))}))}loadScript(){return o(this,void 0,void 0,(function*(){if(window.smartCaptcha)return Promise.resolve(window.smartCaptcha);const e=()=>o(this,void 0,void 0,(function*(){return yield S.appendScript("https://smartcaptcha.yandexcloud.net/captcha.js?render=onload&onload=onloadSmartCaptchaCallback")}));return new Promise(((t,n)=>{window.onloadSmartCaptchaCallback=()=>{this.smartCaptchaReady(),window.smartCaptcha?t(window.smartCaptcha):n(new v("SmartCaptcha is not available"))},e().catch((()=>n(new v("Could not load SmartCaptcha"))))}))}))}notify(...e){this.notifyHandler&&this.notifyHandler(...e)}errorHandler(e){switch(w("SmartCaptcha error:",e),e){case"closed":this.notify("Вы не завершили прохождение проверки. Попробуйте еще раз.");break;case"timeout":this.notify("Возможно произшла ошибка с сетевым подключением. Попробуйте ещё раз. Если не помогает, обратитесь в поддержку.");break;default:this.notify("Что-то пошло не так. Попробуйте ещё раз. Если не помогает, обратитесь в поддержку.")}}static getDebugValue(){try{if("true"===localStorage.getItem(S.LOCALE_STORAGE_DEBUG_KEY))return!0}catch(e){}return!1}renderWidget(e){var t,n,i,r,o,s,a,c;const{promise:l,resolve:d,reject:h}=Promise.withResolvers(),u=document.createElement("div"),p=`${k}_${C()}`;u.id=p,null===(t=document.getElementById(k))||void 0===t||t.appendChild(u),this.onRenderCaptcha(this.provider);const f=window.smartCaptcha.render(p,{callback:e=>{d(e),function(){var e;null===(e=window.smartCaptcha)||void 0===e||e.destroy(f),setTimeout((()=>{u.remove()}),100)}()},hideShield:!0,hl:this.locale,invisible:!0,sitekey:this.sitekey,test:S.getDebugValue()});return null===(n=window.smartCaptcha)||void 0===n||n.subscribe(f,"challenge-visible",(()=>{this.onBeforeInteractiveChallenge(this.provider)})),null===(i=window.smartCaptcha)||void 0===i||i.subscribe(f,"challenge-hidden",(()=>{this.onAfterInteractiveChallenge(this.provider),h()})),null===(r=window.smartCaptcha)||void 0===r||r.subscribe(f,"token-expired",(()=>{const e=new v("Token expired");e.reason="expired",h(e)})),null===(o=window.smartCaptcha)||void 0===o||o.subscribe(f,"success",(()=>{this.onSuccessChallenge(this.provider)})),null===(s=window.smartCaptcha)||void 0===s||s.subscribe(f,"network-error",(()=>{const e=new v("Network error");e.reason="timeout",e.capture=!0,h(e)})),null===(a=window.smartCaptcha)||void 0===a||a.subscribe(f,"javascript-error",(e=>{const t=new v("Javascript error");t.reason="error",t.capture=!0,t.cause=e,h("javascript-error")})),null===(c=window.smartCaptcha)||void 0===c||c.execute(f),l}execute(e){return o(this,void 0,void 0,(function*(){if(this.sitekey){w("Load smartCaptcha script");try{yield this.loadScript()}catch(e){const t=e instanceof v?e:new v("Could not load captcha with error: "+e.toString());throw this.onErrorChallenge(this.provider,t),t}if(!window.smartCaptcha){const e=new v("SmartCaptcha is not available in window");throw this.onErrorChallenge(this.provider,e),e}try{w("Render SmartCaptcha widget");return yield this.renderWidget(e)}catch(e){if(!e)return;if(e instanceof v)switch(this.errorHandler(e),e.reason){case"expired":this.notify("Прошло слишком много времени с момента начала проверки. Попробуйте еще раз."),this.onWarnChallenge(this.provider,e);break;case"timeout":this.notify("Вероятно у вас проблемы с подключением к сети. Попробуйте еще раз."),this.onErrorChallenge(this.provider,e);break;case"error":this.notify("Произошла непредвиденная ошибка. Мы уже делаем все возможное чтобы устранить её."),this.onErrorChallenge(this.provider,e)}const t=new v("Could not render captcha with error");t.capture=!0,t.cause=e,this.onErrorChallenge(this.provider,t)}}}))}}S.LOCALE_STORAGE_DEBUG_KEY="captcha:smart-captcha:debug";class R{constructor(e){var t,n;switch(this.sitekey=null,this.provider=null,this.captcha=null,this.sitekey=null!==(t=e.sitekey)&&void 0!==t?t:null,this.provider=null!==(n=e.provider)&&void 0!==n?n:null,e.provider){case"yandex_smart_captcha":this.captcha=new S(e);break;case"cloudflare_turnstile":this.captcha=new b(e);break;case"recaptcha":this.captcha=new E(e)}}isEnabled(){return"string"==typeof this.sitekey&&""!==this.sitekey}execute(e){return o(this,void 0,void 0,(function*(){if(!1===this.isEnabled())return;if(!this.provider)return;if(!this.captcha)return;const t=yield this.captcha.execute(e);return w("Receive answer from captcha provider"),{captcha_provider:this.provider,captcha_token:t||""}}))}}class T{constructor(e){var t;this.channel=new n("shared-socket"),this.elector=void 0,this.client=void 0,this.connected=!1,this.logger=console,this.config=e,this.logger=null!==(t=null==e?void 0:e.logger)&&void 0!==t?t:this.logger,globalThis.addEventListener("beforeunload",(()=>{this.disconnect()}))}setToken(e){var t;this.config.token=e,null===(t=this.client)||void 0===t||t.setToken(e)}createClient(){var e,t,n;if(this.connected||void 0!==this.client)return this.client;this.logger.debug("Try to connect with Centrifuge client");const i=null!==(e=this.config.transport)&&void 0!==e?e:[],o=(()=>{const e=i.find((e=>"http_stream"===e.transport));if(e)return`${new URL(e.endpoint).origin}/emulation`})();try{return this.client=new r(null!==(t=this.config.transport)&&void 0!==t?t:[],{debug:null!==(n=this.config.debug)&&void 0!==n&&n,emulationEndpoint:o,getToken:()=>this.config.refreshToken(),token:this.config.token}),this.logger.debug("Create Centrifuge instance",this.client),this.client.on("disconnected",(e=>{this.connected=!1,this.logger.debug("Centrifuge connection is closed and will not be reconnected",e)})),this.client.on("connected",(e=>{this.connected=!0,this.logger.debug("Centrifuge is connected with context",e)})),this.client}catch(e){this.logger.error("Failed to create the Centrifuge instance",{reason:e.toString()})}}disconnect(){var e;void 0!==this.client&&(null===(e=this.channel)||void 0===e||e.close(),this.client.disconnect(),this.client=void 0,this.elector=void 0,this.connected=!1)}subscriptionExists(e){if(!this.client)return!1;const t=this.client.subscriptions();return Boolean(t[e])}join(e,t){var n;const i=this.createClient();if(!i)return;const r=null===(n=this.client)||void 0===n?void 0:n.newSubscription(e);this.logger.debug("Create centrifuge subscription",r),r&&(r.on("publication",(({data:e})=>{var n;this.logger.debug("Get message from ws: ",e),t(e),null===(n=this.channel)||void 0===n||n.postMessage(e)})),r.subscribe(),i.connect())}subscribe(e,t){return o(this,void 0,void 0,(function*(){this.subscriptionExists(e)?this.logger.debug("Subscription to the channel is exists. Ignore subscribe."):(this.logger.debug("Create broadcast channel with name",e),this.channel=new n(e),this.elector=i(this.channel),this.logger.debug("Wait leader",this.elector),this.elector.onduplicate=()=>{this.disconnect(),this.subscribe(e,t)},this.elector.awaitLeadership().then((()=>{this.logger.debug("Current tab is leader",this.elector),this.join(e,t)})),this.channel.addEventListener("message",(e=>{this.logger.debug("Get message from broadcast: ",e),t(e)})))}))}unsubscribe(e){var t;const n=null===(t=this.client)||void 0===t?void 0:t.subscriptions()[e];n&&n.unsubscribe()}}export{u as ApiService,v as CaptchaError,R as CaptchaService,d as RequestPlugin,h as ResponseSuccessPlugin,T as SocketService};
1
+ import e from"axios";import t from"axios-retry";import{BroadcastChannel as n,createLeaderElection as i}from"broadcast-channel";import{Centrifuge as r}from"centrifuge";function o(e,t,n,i){return new(n||(n=Promise))((function(r,o){function s(e){try{c(i.next(e))}catch(e){o(e)}}function a(e){try{c(i.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}c((i=i.apply(e,t||[])).next())}))}function s(e,t,n){return e.headers=Object.assign({"Content-Type":"application/json"},e.headers),window&&window.location&&window.location.pathname&&window.location.origin&&(e.headers=Object.assign(Object.assign({},e.headers),{"X-Referer":window.location.origin+window.location.pathname})),n.length>0?function(e,t,n){return o(this,void 0,void 0,(function*(){for(const i of n)i.isApplicable(e)&&(e=yield i.execute(e,t));return e}))}(e,t,n):e}function a(e,t,n){return n.length>0?function(e,t,n){return o(this,void 0,void 0,(function*(){for(const i of n)i.isApplicable(e)&&(e=yield i.execute(e,t));return e}))}(e,t,n):e}void 0===Promise.withResolvers&&(Promise.withResolvers=()=>{let e,t;return{promise:new Promise(((n,i)=>{e=n,t=i})),reject:t,resolve:e}}),"function"==typeof SuppressedError&&SuppressedError;const c=[422,401];function l(e){const{config:t=null,response:n=null}=e;if(null===t||null===n)return Promise.reject(e);const i=t;c.includes(n.status)&&(i._retry=!0);const r=Object.assign({errorText:e.toString(),headers:n.headers,status:n.status,statusText:n.statusText},"object"==typeof n.data?n.data:{data:n.data});return Promise.reject(r)}class d{constructor(){this.pluginType="request"}}class h{constructor(){this.pluginType="responseSuccess"}}const u=new class{createFoxApiInstance({config:n,plugins:i=[]}){const r=e.create(n),o=this.filterPlugins(i,"request"),c=this.filterPlugins(i,"responseSuccess");return r.interceptors.request.use((e=>s(e,r,[...o]))),r.interceptors.response.use((e=>a(e,r,[...c])),l),t(r,{retries:3,retryDelay:t.exponentialDelay}),r}createApiInstance({config:t}){return e.create(t)}createStaticApiInstance(){const t=e;return t.isApiError=e=>"object"==typeof e&&!0===e.isAxiosError,t}filterPlugins(e,t){return e?e.filter((e=>e.pluginType===t)):[]}},p="turnstile-container",f="turnstile-widget";var g=`\n<div id="${p}" class="fox-cf-turnstile">\n <div class="fox-cf-turnstile__overlay"></div>\n <div class="fox-cf-turnstile__content">\n <div class="fox-cf-turnstile__content__text">\n <h3>Надо убедиться, что вы человек</h3>\n <span>Поставьте галочку, нажав на белый квадрат ниже — проверка займёт буквально секунду</span>\n </div>\n <div id="${f}">\n <div class="fox-cf-turnstile__loader"></div>\n </div>\n </div>\n</div>\n`;class v extends Error{constructor(e,t="error"){super(e),this.level="error",this.name="CaptchaError",this.message=e,this.level=t}}function w(...e){const t=["[CaptchaService] ",...e];console.debug.apply(console,t)}const m=(...e)=>{};class b{constructor({sitekey:e,locale:t,notify:n,onRenderCaptcha:i,onSuccessChallenge:r,onErrorChallenge:o,onWarnChallenge:s,onBeforeInteractiveChallenge:a,onAfterInteractiveChallenge:c}){this.sitekey=null,this.locale="ru",this.provider="cloudflare_turnstile",this.container=null,this.notifyHandler=null!=n?n:m,this.sitekey=null!=e?e:null,this.onRenderCaptcha=null!=i?i:m,this.onSuccessChallenge=null!=r?r:m,this.onErrorChallenge=null!=o?o:m,this.onWarnChallenge=null!=s?s:m,this.onBeforeInteractiveChallenge=null!=a?a:m,this.onAfterInteractiveChallenge=null!=c?c:m,t&&(this.locale=t),this.addDomElements(),b.DEBUG&&(window.cf=this)}notify(...e){this.notifyHandler&&this.notifyHandler(...e)}addDomElements(){this.container||document.getElementById(p)||(document.body.insertAdjacentHTML("beforeend",g),document.body.insertAdjacentHTML("beforeend","<style>\n.fox-cf-turnstile {\n position: fixed;\n top: 0;\n left: 0;\n display: flex;\n align-items: center;\n justify-content: center;\n width: 100vw;\n height: 100vh;\n z-index: -1;\n}\n.fox-cf-turnstile__noscroll {\n position: fixed; \n top: var(--st, 0);\n inline-size: 100%;\n overflow-y:scroll; \n}\n.fox-cf-turnstile--showing {\n z-index: 9999;\n}\n.fox-cf-turnstile__overlay {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n background: rgba(246, 247, 251, 0.9);\n opacity: 0;\n transition: all .3s ease;\n transition-delay: .2s;\n z-index: 0;\n}\n.fox-cf-turnstile__content {\n background: white;\n border-radius: 5px;\n max-width: 500px;\n max-height: 50vh;\n position: relative;\n z-index: 1;\n box-shadow: rgba(0, 0, 0, 0.08) 0px 10px 20px 0px;\n height: 1px;\n width: 1px;\n overflow: hidden;\n transition: all .8s ease, opacity 0.3s ease;\n transition-delay: .3s;\n opacity: 0;\n display: flex;\n align-items: center;\n justify-content: center;\n flex-direction: column;\n font-size: 1.2rem;\n}\n.fox-cf-turnstile__content__text {\n flex: 1;\n margin-bottom: 20px;\n opacity: 1;\n overflow: hidden;\n transition: opacity 0.3s ease;\n text-align: center;\n}\n.fox-cf-turnstile--showing .fox-cf-turnstile__overlay, .fox-cf-turnstile--show .fox-cf-turnstile__overlay {\n opacity: 1;\n}\n.fox-cf-turnstile--showing .fox-cf-turnstile__content, .fox-cf-turnstile--show .fox-cf-turnstile__content {\n width: 100%;\n height: auto;\n min-height: 20vh;\n min-width: 30vw;\n padding: 30px;\n opacity: 1;\n}\n.fox-cf-turnstile__content__text h3 {\n font-size: 1.4rem;\n}\n.fox-cf-turnstile__loader {\n font-size: 10px;\n margin: 50px auto;\n text-indent: -9999em;\n width: 5em;\n height: 5em;\n border-radius: 50%;\n background: #8b1feb;\n background: -moz-linear-gradient(left, #8b1feb 10%, rgba(139,31,235, 0) 42%);\n background: -webkit-linear-gradient(left, #8b1feb 10%, rgba(139,31,235, 0) 42%);\n background: -o-linear-gradient(left, #8b1feb 10%, rgba(139,31,235, 0) 42%);\n background: -ms-linear-gradient(left, #8b1feb 10%, rgba(139,31,235, 0) 42%);\n background: linear-gradient(to right, #8b1feb 10%, rgba(139,31,235, 0) 42%);\n position: relative;\n -webkit-animation: load3 1.4s infinite linear;\n animation: load3 1.4s infinite linear;\n -webkit-transform: translateZ(0);\n -ms-transform: translateZ(0);\n transform: translateZ(0);\n}\n.fox-cf-turnstile__loader:before {\n width: 50%;\n height: 50%;\n background: #8b1feb;\n border-radius: 100% 0 0 0;\n position: absolute;\n top: 0;\n left: 0;\n content: '';\n}\n.fox-cf-turnstile__loader:after {\n background: white;\n width: 75%;\n height: 75%;\n border-radius: 50%;\n content: '';\n margin: auto;\n position: absolute;\n top: 0;\n left: 0;\n bottom: 0;\n right: 0;\n}\n@-webkit-keyframes load3 {\n 0% {\n -webkit-transform: rotate(0deg);\n transform: rotate(0deg);\n }\n 100% {\n -webkit-transform: rotate(360deg);\n transform: rotate(360deg);\n }\n}\n@keyframes load3 {\n 0% {\n -webkit-transform: rotate(0deg);\n transform: rotate(0deg);\n }\n 100% {\n -webkit-transform: rotate(360deg);\n transform: rotate(360deg);\n }\n} \n</style>"),this.container=document.getElementById(p))}static appendScript(e){return o(this,void 0,void 0,(function*(){if("string"!=typeof e||""===e)throw new TypeError("src script is not defined");const t=document.createElement("script");return t.src=e,document.body&&document.body.appendChild(t),new Promise(((e,n)=>{t.addEventListener("load",(()=>{e(!0)})),t.addEventListener("error",(()=>{n()}))}))}))}show(){var e;null===(e=this.container)||void 0===e||e.classList.add("fox-cf-turnstile--showing"),b.bodyScrollLock()}hide(){var e,t;null===(e=this.container)||void 0===e||e.classList.remove("fox-cf-turnstile--show"),null===(t=this.container)||void 0===t||t.classList.remove("fox-cf-turnstile--showing"),b.bodyScrollUnlock()}loadScript(){return o(this,void 0,void 0,(function*(){if(window.turnstile)return Promise.resolve(window.turnstile);const e=()=>o(this,void 0,void 0,(function*(){return yield b.appendScript("https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit&onload=onloadTurnstileCallback")}));return new Promise(((t,n)=>{window.onloadTurnstileCallback=()=>{this.turnstileReady(),window.turnstile?t(window.turnstile):n(new v("Cloudflare Turnstile is not available"))},e().catch((()=>n(new v("Could not load Cloudflare Turnstile"))))}))}))}turnstileReady(){var e,t;w("Cloudflare Turnstile is ready",window.turnstile),null===(t=null===(e=this.container)||void 0===e?void 0:e.querySelector(".fox-cf-turnstile__loader"))||void 0===t||t.remove()}static normalizeLocation(e=""){return e.substring(0,31).replace(/\//g,"_")}static bodyScrollLock(){const e=document.body;e.style.setProperty("--st",`-${document.documentElement.scrollTop}px`),e.classList.add("fox-cf-turnstile__noscroll")}static bodyScrollUnlock(){document.body.classList.remove("fox-cf-turnstile__noscroll")}renderWidget(e){return o(this,void 0,void 0,(function*(){return new Promise(((t,n)=>{var i;let r="";function o(){var e;null===(e=window.turnstile)||void 0===e||e.reset(r),setTimeout((()=>{var e;null===(e=window.turnstile)||void 0===e||e.remove(r)}),500)}r=null===(i=window.turnstile)||void 0===i?void 0:i.render(`#${f}`,{action:b.normalizeLocation(null==e?void 0:e.location),"after-interactive-callback":()=>{w("after-interactive-callback"),this.onAfterInteractiveChallenge(this.provider)},"before-interactive-callback":()=>{w("before-interactive-callback"),this.onBeforeInteractiveChallenge(this.provider),this.show()},callback:e=>{w("Challenge Success"),this.hide(),t(e),o()},"error-callback":e=>{n(e),o()},"expired-callback":()=>{this.hide(),n("expired"),o()},language:this.locale,sitekey:this.sitekey,theme:"light","timeout-callback":()=>{this.hide(),n("timeout"),o()},"unsupported-callback":()=>{n("110500"),o()}})}))}))}errorHandler(e){w("Captcha error with code:",e);let t=[...b.NO_RETRY_ERROR_CODES];if("string"!=typeof e)return void this.notify("Что-то пошло не так. Попробуйте ещё раз. Если не помогает, обратитесь в поддержку.");const n=e;switch(!0){case n.startsWith("110500"):t=t.filter((e=>!e.startsWith("110500"))),this.notify("Ваш браузер устарел. Попробуйте ещё раз, используя другой браузер или устройство.");break;case n.startsWith("110600"):t=t.filter((e=>!e.startsWith("110600"))),this.notify("Прошло слишком много времени с момента начала проверки. Попробуйте еще раз.");break;case n.startsWith("110510"):t=t.filter((e=>!e.startsWith("110510"))),this.notify("Что-то пошло не так — возможно, вы используете технологию подмены User agent. Попробуйте ещё раз или обратитесь в поддержку");break;case n.startsWith("200010"):this.notify('Что-то пошло не так. Попробуйте <a href="https://yandex.ru/support/common/browsers-settings/cache.html" target="_blank" rel="nofollow noopener">очистить кеш браузера</a>. Если не помогает, обратитесь в поддержку.');break;case n.startsWith("200100"):t=t.filter((e=>!e.startsWith("200100"))),this.notify("Кажется, часы на вашем компьютере показывают неправильное время. Настройте часы и попробуйте ещё раз.");break;case n.startsWith("300"):case n.startsWith("600"):t=t.filter((e=>!e.startsWith("300")||!e.startsWith("600"))),this.notify("Потвердите еще раз что вы человек")}t.some((e=>n.startsWith(e)))&&this.notify(`Что-то пошло не так, код ошибки — ${n}. Мы уже знаем о проблеме и скоро всё поправим. Попробуйте ещё раз через некоторое время.`)}execute(e){return o(this,void 0,void 0,(function*(){if(this.sitekey){w("Load cloudflare script");try{yield this.loadScript()}catch(e){const t=e instanceof v?e:new v("Could not load captcha with error: "+e.toString());throw this.onErrorChallenge(this.provider,t),t}if(!window.turnstile){const e=new v("Cloudflare Turnstile is not available in window");throw this.onErrorChallenge(this.provider,e),e}try{w("Render turnstile widget"),this.onRenderCaptcha(this.provider);const t=yield this.renderWidget(e);return this.onSuccessChallenge(this.provider),t}catch(e){if(this.errorHandler(e),"string"!=typeof e){const t=new v("Could not execute captcha with error: "+e.toString());throw this.onErrorChallenge(this.provider,t),t}if(["110200","110100","110110"].some((t=>e.startsWith(t)))){const t=new v("Invalid sitekey or domain is not allowed");throw t.code=e,this.onErrorChallenge(this.provider,t),t}if(b.NO_RETRY_ERROR_CODES.some((t=>e.startsWith(t)))){const t=new v("Captcha challenge is failed");t.code=e,this.onErrorChallenge(this.provider,t)}else{const t=new v("Captcha challenge has error");t.reason=["timeout","expired"].includes(e)?e:void 0,t.code=e,this.onWarnChallenge(this.provider,t)}}}}))}}b.DEBUG=!1,b.NO_RETRY_ERROR_CODES=["100","105","106","110100","110110","110200","110420","110430","110500","110510","120","200010","200100"];const y="recaptcha-widget";function C(){let e=(new Date).getTime(),t="undefined"!=typeof performance&&performance.now&&1e3*performance.now()||0;return"xxxx-xxxx-4xxx-yxxx".replace(/[xy]/g,(function(n){let i=16*Math.random();return e>0?(i=(e+i)%16|0,e=Math.floor(e/16)):(i=(t+i)%16|0,t=Math.floor(t/16)),("x"===n?i:3&i|8).toString(16)}))}const x=(...e)=>{};class E{constructor({sitekey:e,locale:t,notify:n,onRenderCaptcha:i,onSuccessChallenge:r,onWarnChallenge:o,onErrorChallenge:s}){this.sitekey=null,this.locale="ru",this.container=null,this.provider="recaptcha",this.sitekey=null!=e?e:null,this.notifyHandler=null!=n?n:x,this.onRenderCaptcha=null!=i?i:x,this.onSuccessChallenge=null!=r?r:x,this.onWarnChallenge=null!=o?o:x,this.onErrorChallenge=null!=s?s:x,t&&(this.locale=t),this.addDomElements(),E.DEBUG&&(window.gr=this)}recaptchaReady(){w("Google recaptcha is ready",window.grecaptcha,this)}addDomElements(){if(this.container||document.getElementById(y))return;document.body.insertAdjacentHTML("beforeend",`<div id="${y}"></div>`);const e=document.getElementById(y);e.style.display="none",this.container=e}static getGrecaptchaCallbackNames(){return{error:`${E.ERROR_FUNC_NAME}`,expired:`${E.EXPIRED_FUNC_NAME}`,resolve:`${E.RESOLVE_FUNC_NAME}`}}static appendScript(e){return o(this,void 0,void 0,(function*(){if("string"!=typeof e||""===e)throw new TypeError("src script is not defined");const t=document.createElement("script");return t.src=e,document.body&&document.body.appendChild(t),new Promise(((e,n)=>{t.addEventListener("load",(()=>{e(!0)})),t.addEventListener("error",(()=>{n()}))}))}))}loadScript(){return o(this,void 0,void 0,(function*(){if(window.grecaptcha)return Promise.resolve(window.grecaptcha);const e=()=>o(this,void 0,void 0,(function*(){return yield E.appendScript(`https://www.google.com/recaptcha/api.js?hl=${this.locale}&onload=onloadRecaptchaCallback`)}));return new Promise(((t,n)=>{window.onloadRecaptchaCallback=()=>{this.recaptchaReady(),window.grecaptcha?t(window.grecaptcha):n(new v("Recaptcha is not available"))},e().catch((()=>n(new v("Could not load Recaptcha"))))}))}))}notify(...e){this.notifyHandler&&this.notifyHandler(...e)}errorHandler(e){switch(w("Recaptcha error:",e),e){case"expired":this.notify("Прошло слишком много времени с момента начала проверки. Попробуйте еще раз.");break;case"closed":this.notify("Вы не завершили прохождение проверки. Попробуйте еще раз.");break;case"timeout":this.notify("Возможно произшла ошибка с сетевым подключением. Попробуйте ещё раз. Если не помогает, обратитесь в поддержку.");break;default:this.notify("Что-то пошло не так. Попробуйте ещё раз. Если не помогает, обратитесь в поддержку.")}}static detectCaptchaChallengeIsShown(){return new Promise((function(e){const t=document.body;const n=new MutationObserver((function(t){t.forEach((t=>{if(t.addedNodes.length){const i=t.addedNodes[0];if(!i)return;if(i.querySelectorAll('iframe[src^="https://www.google.com/recaptcha"][src*="bframe"]').length){const t=i.firstChild;t&&(n.disconnect(),e(t))}}}))}));n.observe(t,{attributeOldValue:!1,attributes:!1,characterData:!1,characterDataOldValue:!1,childList:!0,subtree:!1})}))}renderWidget(e){return new Promise(((e,t)=>{var n,i,r;const o=document.createElement("div"),s=`${y}_${C()}`;o.id=s,null===(n=document.getElementById(y))||void 0===n||n.appendChild(o);const a=E.getGrecaptchaCallbackNames();let c=NaN;function l(){var e;null===(e=window.grecaptcha)||void 0===e||e.reset(),setTimeout((()=>{o.remove()}),1e3)}E.detectCaptchaChallengeIsShown().then((e=>{if(!e.parentElement)return;const n=new MutationObserver((function(){var i,r;"hidden"!==(null===(i=e.parentElement)||void 0===i?void 0:i.style.visibility)||(null===(r=window.grecaptcha)||void 0===r?void 0:r.getResponse(c))||(n.disconnect(),t("closed"),l())}));n.observe(e.parentElement,{attributeFilter:["style"],attributes:!0})})),window[a.resolve]=()=>{var t;const n=null===(t=window.grecaptcha)||void 0===t?void 0:t.getResponse(c);e(null!=n?n:""),l()},window[a.error]=()=>{t("error"),l()},window[a.expired]=()=>{t("expired"),l()},c=null===(i=window.grecaptcha)||void 0===i?void 0:i.render(s,{callback:a.resolve,"error-callback":a.error,"expired-callback":a.expired,sitekey:this.sitekey,size:"invisible"});const d=null===(r=window.grecaptcha)||void 0===r?void 0:r.execute(c);if(!d)return t(new Error("cannot call method execute from grecaptcha")),void l();d.catch((e=>{t(e instanceof Error?e:new Error(e.toString())),l()}))}))}execute(e){return o(this,void 0,void 0,(function*(){if(this.sitekey){w("Load recaptcha script");try{yield this.loadScript()}catch(e){const t=e instanceof v?e:new v("Could not load captcha with error: "+e.toString());throw this.onErrorChallenge(this.provider,t),t}if(!window.grecaptcha){const e=new v("Recaptcha is not available in window");throw this.onErrorChallenge(this.provider,e),e}try{w("Render Recaptcha widget"),this.onRenderCaptcha(this.provider);const t=yield this.renderWidget(e);return this.onSuccessChallenge(this.provider),t}catch(e){if(this.errorHandler(e),"string"!=typeof e){const t=new v("Could not execute captcha with error: "+e.toString());throw this.onErrorChallenge(this.provider,t),t}if("expired"===e){const e=new v("Challenge or token expired");e.reason="expired",this.onWarnChallenge(this.provider,e)}if("error"===e){const e=new v("Error during captcha execution");this.onErrorChallenge(this.provider,e)}}}}))}}E.RESOLVE_FUNC_NAME="grecaptcha_resolved",E.ERROR_FUNC_NAME="grecaptcha_error",E.EXPIRED_FUNC_NAME="grecaptcha_expired",E.DEBUG=!1;const k="smartcaptcha-container",_=(...e)=>{};class S{constructor({sitekey:e,locale:t,notify:n,onRenderCaptcha:i,onSuccessChallenge:r,onWarnChallenge:o,onErrorChallenge:s,onBeforeInteractiveChallenge:a,onAfterInteractiveChallenge:c}){this.sitekey=null,this.container=null,this.provider="yandex_smart_captcha",this.locale=null!=t?t:"ru",this.sitekey=null!=e?e:null,this.notifyHandler=null!=n?n:_,this.onRenderCaptcha=null!=i?i:_,this.onSuccessChallenge=null!=r?r:_,this.onWarnChallenge=null!=o?o:_,this.onErrorChallenge=null!=s?s:_,this.onBeforeInteractiveChallenge=null!=a?a:_,this.onAfterInteractiveChallenge=null!=c?c:_,this.addDomElements()}smartCaptchaReady(){w("Smart captcha is ready",window.smartCaptcha,this)}addDomElements(){if(this.container||document.getElementById(k))return;document.body.insertAdjacentHTML("beforeend",`<div id="${k}"></div>`);const e=document.getElementById(k);e.style.display="none",this.container=e}static appendScript(e){return o(this,void 0,void 0,(function*(){if("string"!=typeof e||""===e)throw new TypeError("src script is not defined");const t=document.createElement("script");return t.src=e,document.body&&document.body.appendChild(t),new Promise(((e,n)=>{t.addEventListener("load",(()=>{e(!0)})),t.addEventListener("error",(()=>{n()}))}))}))}loadScript(){return o(this,void 0,void 0,(function*(){if(window.smartCaptcha)return Promise.resolve(window.smartCaptcha);const e=()=>o(this,void 0,void 0,(function*(){return yield S.appendScript("https://smartcaptcha.yandexcloud.net/captcha.js?render=onload&onload=onloadSmartCaptchaCallback")}));return new Promise(((t,n)=>{window.onloadSmartCaptchaCallback=()=>{this.smartCaptchaReady(),window.smartCaptcha?t(window.smartCaptcha):n(new v("SmartCaptcha is not available"))},e().catch((()=>n(new v("Could not load SmartCaptcha"))))}))}))}notify(...e){this.notifyHandler&&this.notifyHandler(...e)}errorHandler(e){switch(w("SmartCaptcha error:",e),e){case"closed":this.notify("Вы не завершили прохождение проверки. Попробуйте еще раз.");break;case"timeout":this.notify("Возможно произшла ошибка с сетевым подключением. Попробуйте ещё раз. Если не помогает, обратитесь в поддержку.");break;default:this.notify("Что-то пошло не так. Попробуйте ещё раз. Если не помогает, обратитесь в поддержку.")}}static getDebugValue(){try{if("true"===localStorage.getItem(S.LOCALE_STORAGE_DEBUG_KEY))return!0}catch(e){}return!1}renderWidget(e){var t,n,i,r,o,s,a,c;const{promise:l,resolve:d,reject:h}=Promise.withResolvers(),u=document.createElement("div"),p=`${k}_${C()}`;u.id=p,null===(t=document.getElementById(k))||void 0===t||t.appendChild(u),this.onRenderCaptcha(this.provider);const f=window.smartCaptcha.render(p,{callback:e=>{d(e),function(){var e;null===(e=window.smartCaptcha)||void 0===e||e.destroy(f),setTimeout((()=>{u.remove()}),100)}()},hideShield:!0,hl:this.locale,invisible:!0,sitekey:this.sitekey,test:S.getDebugValue()});return null===(n=window.smartCaptcha)||void 0===n||n.subscribe(f,"challenge-visible",(()=>{this.onBeforeInteractiveChallenge(this.provider)})),null===(i=window.smartCaptcha)||void 0===i||i.subscribe(f,"challenge-hidden",(()=>{this.onAfterInteractiveChallenge(this.provider),h()})),null===(r=window.smartCaptcha)||void 0===r||r.subscribe(f,"token-expired",(()=>{const e=new v("Token expired");e.reason="expired",h(e)})),null===(o=window.smartCaptcha)||void 0===o||o.subscribe(f,"success",(()=>{this.onSuccessChallenge(this.provider)})),null===(s=window.smartCaptcha)||void 0===s||s.subscribe(f,"network-error",(()=>{const e=new v("Network error");e.reason="timeout",h(e)})),null===(a=window.smartCaptcha)||void 0===a||a.subscribe(f,"javascript-error",(e=>{new v("Javascript error","fatal").cause=e,h("javascript-error")})),null===(c=window.smartCaptcha)||void 0===c||c.execute(f),l}execute(e){return o(this,void 0,void 0,(function*(){if(this.sitekey){w("Load smartCaptcha script");try{yield this.loadScript()}catch(e){const t=e instanceof v?e:new v("Could not load captcha with error: "+e.toString());throw this.onErrorChallenge(this.provider,t),t}if(!window.smartCaptcha){const e=new v("SmartCaptcha is not available in window");throw this.onErrorChallenge(this.provider,e),e}try{w("Render SmartCaptcha widget");return yield this.renderWidget(e)}catch(e){if(!e)return;if(e instanceof v)if(this.errorHandler(e),"fatal"===e.level)this.notify("Произошла непредвиденная ошибка. Мы уже делаем все возможное чтобы устранить её."),this.onErrorChallenge(this.provider,e);else switch(e.reason){case"expired":this.notify("Прошло слишком много времени с момента начала проверки. Попробуйте еще раз."),this.onWarnChallenge(this.provider,e);break;case"timeout":this.notify("Вероятно у вас проблемы с подключением к сети. Попробуйте еще раз."),this.onErrorChallenge(this.provider,e)}else{const t=new v("Could not render captcha with error","fatal");t.cause=e,this.onErrorChallenge(this.provider,t)}}}}))}}S.LOCALE_STORAGE_DEBUG_KEY="captcha:smart-captcha:debug";class R{constructor(e){var t,n;switch(this.sitekey=null,this.provider=null,this.captcha=null,this.sitekey=null!==(t=e.sitekey)&&void 0!==t?t:null,this.provider=null!==(n=e.provider)&&void 0!==n?n:null,e.provider){case"yandex_smart_captcha":this.captcha=new S(e);break;case"cloudflare_turnstile":this.captcha=new b(e);break;case"recaptcha":this.captcha=new E(e)}}isEnabled(){return"string"==typeof this.sitekey&&""!==this.sitekey}execute(e){return o(this,void 0,void 0,(function*(){if(!1===this.isEnabled())return;if(!this.provider)return;if(!this.captcha)return;const t=yield this.captcha.execute(e);return w("Receive answer from captcha provider"),{captcha_provider:this.provider,captcha_token:t||""}}))}}class T{constructor(e){var t;this.channel=new n("shared-socket"),this.elector=void 0,this.client=void 0,this.connected=!1,this.logger=console,this.config=e,this.logger=null!==(t=null==e?void 0:e.logger)&&void 0!==t?t:this.logger,globalThis.addEventListener("beforeunload",(()=>{this.disconnect()}))}setToken(e){var t;this.config.token=e,null===(t=this.client)||void 0===t||t.setToken(e)}createClient(){var e,t,n;if(this.connected||void 0!==this.client)return this.client;this.logger.debug("Try to connect with Centrifuge client");const i=null!==(e=this.config.transport)&&void 0!==e?e:[],o=(()=>{const e=i.find((e=>"http_stream"===e.transport));if(e)return`${new URL(e.endpoint).origin}/emulation`})();try{return this.client=new r(null!==(t=this.config.transport)&&void 0!==t?t:[],{debug:null!==(n=this.config.debug)&&void 0!==n&&n,emulationEndpoint:o,getToken:()=>this.config.refreshToken(),token:this.config.token}),this.logger.debug("Create Centrifuge instance",this.client),this.client.on("disconnected",(e=>{this.connected=!1,this.logger.debug("Centrifuge connection is closed and will not be reconnected",e)})),this.client.on("connected",(e=>{this.connected=!0,this.logger.debug("Centrifuge is connected with context",e)})),this.client}catch(e){this.logger.error("Failed to create the Centrifuge instance",{reason:e.toString()})}}disconnect(){var e;void 0!==this.client&&(null===(e=this.channel)||void 0===e||e.close(),this.client.disconnect(),this.client=void 0,this.elector=void 0,this.connected=!1)}subscriptionExists(e){if(!this.client)return!1;const t=this.client.subscriptions();return Boolean(t[e])}join(e,t){var n;const i=this.createClient();if(!i)return;const r=null===(n=this.client)||void 0===n?void 0:n.newSubscription(e);this.logger.debug("Create centrifuge subscription",r),r&&(r.on("publication",(({data:e})=>{var n;this.logger.debug("Get message from ws: ",e),t(e),null===(n=this.channel)||void 0===n||n.postMessage(e)})),r.subscribe(),i.connect())}subscribe(e,t){return o(this,void 0,void 0,(function*(){this.subscriptionExists(e)?this.logger.debug("Subscription to the channel is exists. Ignore subscribe."):(this.logger.debug("Create broadcast channel with name",e),this.channel=new n(e),this.elector=i(this.channel),this.logger.debug("Wait leader",this.elector),this.elector.onduplicate=()=>{this.disconnect(),this.subscribe(e,t)},this.elector.awaitLeadership().then((()=>{this.logger.debug("Current tab is leader",this.elector),this.join(e,t)})),this.channel.addEventListener("message",(e=>{this.logger.debug("Get message from broadcast: ",e),t(e)})))}))}unsubscribe(e){var t;const n=null===(t=this.client)||void 0===t?void 0:t.subscriptions()[e];n&&n.unsubscribe()}}export{u as ApiService,v as CaptchaError,R as CaptchaService,d as RequestPlugin,h as ResponseSuccessPlugin,T as SocketService};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@foxford/services",
3
- "version": "1.4.1",
3
+ "version": "1.4.2-beta-d9b2a40f-20250224",
4
4
  "description": "Foxford services",
5
5
  "keywords": [
6
6
  "foxford",
@@ -26,8 +26,8 @@
26
26
  "main": "./index.js",
27
27
  "types": "./index.d.ts",
28
28
  "dependencies": {
29
- "axios": "0.21.1",
30
- "axios-retry": "3.1.9",
29
+ "axios": "0.28.1",
30
+ "axios-retry": "3.3.1",
31
31
  "broadcast-channel": "5.5.1",
32
32
  "centrifuge": "5.1.1"
33
33
  },
@@ -54,3 +54,4 @@
54
54
  ],
55
55
  "sideEffects": false
56
56
  }
57
+