@foxford/services 1.4.7 → 1.4.8
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 +22 -7
- package/index.js +1 -1
- package/index.js.flow +30 -6
- package/index.mjs +1 -1
- package/package.json +2 -2
package/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// Generated by dts-bundle-generator
|
|
1
|
+
// Generated by dts-bundle-generator v9.5.1
|
|
2
2
|
|
|
3
3
|
export interface ApiTransformer {
|
|
4
4
|
(data: any, headers?: any): any;
|
|
@@ -129,6 +129,7 @@ export interface ResponseError {
|
|
|
129
129
|
errorText: string;
|
|
130
130
|
headers: ApiResponse["headers"];
|
|
131
131
|
data: ApiResponse["data"];
|
|
132
|
+
config?: ApiRequestConfig;
|
|
132
133
|
}
|
|
133
134
|
export type ApiErrorExtended = ApiError & {
|
|
134
135
|
config: ApiRequestConfig & {
|
|
@@ -140,26 +141,34 @@ export type ApiRequestConfigExtended = ApiRequestConfig & {
|
|
|
140
141
|
withCaptcha?: boolean;
|
|
141
142
|
withReferrer?: boolean;
|
|
142
143
|
};
|
|
144
|
+
export interface ApiServiceInterface {
|
|
145
|
+
createFoxApiInstance(params: ApiConfig): ApiInstance;
|
|
146
|
+
createApiInstance(params: ApiConfig): ApiInstance;
|
|
147
|
+
createStaticApiInstance(): ApiStatic;
|
|
148
|
+
}
|
|
143
149
|
export interface RequestPluginInterface {
|
|
144
150
|
pluginType: "request";
|
|
145
151
|
pluginName: string;
|
|
146
152
|
execute(config: ApiRequestConfigExtended, instance: ApiInstance): Promise<ApiRequestConfigExtended>;
|
|
147
153
|
isApplicable(config: ApiRequestConfigExtended): boolean;
|
|
148
154
|
}
|
|
149
|
-
export interface ApiServiceInterface {
|
|
150
|
-
createFoxApiInstance(params: ApiConfig): ApiInstance;
|
|
151
|
-
createApiInstance(params: ApiConfig): ApiInstance;
|
|
152
|
-
createStaticApiInstance(): ApiStatic;
|
|
153
|
-
}
|
|
154
155
|
export interface ResponseSuccessPluginInterface {
|
|
155
156
|
pluginType: "responseSuccess";
|
|
156
157
|
pluginName: string;
|
|
157
158
|
execute(response: ApiResponse, instance: ApiInstance): Promise<ApiResponse>;
|
|
158
159
|
isApplicable(response: ApiResponse): boolean;
|
|
159
160
|
}
|
|
161
|
+
export interface ResponseFailPluginInterface {
|
|
162
|
+
pluginType: "responseFail";
|
|
163
|
+
pluginName: string;
|
|
164
|
+
execute(error: ApiErrorExtended, instance: ApiInstance): Promise<ApiErrorExtended | ApiRequestConfig>;
|
|
165
|
+
isApplicable(error: ApiErrorExtended): boolean;
|
|
166
|
+
}
|
|
167
|
+
export type ApiPlugin = RequestPluginInterface | ResponseSuccessPluginInterface | ResponseFailPluginInterface;
|
|
168
|
+
export type ApiPluginType = ApiPlugin["pluginType"];
|
|
160
169
|
export type ApiConfig = {
|
|
161
170
|
config: ApiRequestConfigExtended;
|
|
162
|
-
plugins?: Array<
|
|
171
|
+
plugins?: Array<ApiPlugin>;
|
|
163
172
|
};
|
|
164
173
|
export interface GenericFormData {
|
|
165
174
|
append(name: string, value: any, options?: any): any;
|
|
@@ -200,6 +209,12 @@ export declare abstract class ResponseSuccessPlugin implements ResponseSuccessPl
|
|
|
200
209
|
abstract execute(response: ApiResponse, instance: ApiInstance): Promise<ApiResponse>;
|
|
201
210
|
abstract isApplicable(response: ApiResponse): boolean;
|
|
202
211
|
}
|
|
212
|
+
export declare abstract class ResponseFailPlugin implements ResponseFailPluginInterface {
|
|
213
|
+
pluginType: "responseFail";
|
|
214
|
+
abstract pluginName: string;
|
|
215
|
+
abstract execute(error: ApiErrorExtended, instance: ApiInstance): Promise<ApiErrorExtended | ApiRequestConfig>;
|
|
216
|
+
abstract isApplicable(error: ApiErrorExtended): boolean;
|
|
217
|
+
}
|
|
203
218
|
declare const apiServiceInstance: ApiServiceInterface;
|
|
204
219
|
export declare class CaptchaError extends Error {
|
|
205
220
|
level?: "fatal" | "error";
|
package/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
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()}};
|
|
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){return"object"==typeof e&&null!==e&&"url"in e}function l(e,t,n){return r(this,void 0,void 0,(function*(){if("object"!=typeof(i=e)||null===i||!("response"in i)||!("config"in i)||null===i.config||null===i.response)return Promise.reject(e);var i;const o=yield function(e,t,n){return r(this,void 0,void 0,(function*(){let i=e;for(const r of n)if(r.isApplicable(e)&&(i=yield r.execute(e,t),c(i)))return i;return i}))}(e,t,n);if(c(o))return t.request(o);const s=function(e){const{response:t,config:n}=e;return a.includes(t.status)&&(n._retry=!0),Object.assign({errorText:e.toString(),headers:t.headers,status:t.status,statusText:t.statusText},"object"==typeof t.data?t.data:{data:t.data})}(e);return Promise.reject(s)}))}const d=new class{createFoxApiInstance({config:n,plugins:i=[]}){const r=e.create(n),a=this.filterPlugins(i,"request"),c=this.filterPlugins(i,"responseSuccess"),d=this.filterPlugins(i,"responseFail");return r.interceptors.request.use((e=>o(e,r,[...a]))),r.interceptors.response.use((e=>s(e,r,[...c])),(e=>l(e,r,[...d]))),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)):[]}},h="turnstile-container",u="turnstile-widget";var p=`\n<div id="${h}" 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="${u}">\n <div class="fox-cf-turnstile__loader"></div>\n </div>\n </div>\n</div>\n`;class f extends Error{constructor(e,t="error"){super(e),this.level="error",this.name="CaptchaError",this.message=e,this.level=t}}function g(...e){const t=["[CaptchaService] ",...e];console.debug.apply(console,t)}const v=(...e)=>{};class w{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:v,this.sitekey=null!=e?e:null,this.onRenderCaptcha=null!=i?i:v,this.onSuccessChallenge=null!=r?r:v,this.onErrorChallenge=null!=o?o:v,this.onWarnChallenge=null!=s?s:v,this.onBeforeInteractiveChallenge=null!=a?a:v,this.onAfterInteractiveChallenge=null!=c?c:v,t&&(this.locale=t),this.addDomElements(),w.DEBUG&&(window.cf=this)}notify(...e){this.notifyHandler&&this.notifyHandler(...e)}addDomElements(){this.container||document.getElementById(h)||(document.body.insertAdjacentHTML("beforeend",p),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(h))}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"),w.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"),w.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 w.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 f("Cloudflare Turnstile is not available"))},e().catch((()=>n(new f("Could not load Cloudflare Turnstile"))))}))}))}turnstileReady(){var e,t;g("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(`#${u}`,{action:w.normalizeLocation(null==e?void 0:e.location),"after-interactive-callback":()=>{g("after-interactive-callback"),this.onAfterInteractiveChallenge(this.provider)},"before-interactive-callback":()=>{g("before-interactive-callback"),this.onBeforeInteractiveChallenge(this.provider),this.show()},callback:e=>{g("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){g("Captcha error with code:",e);let t=[...w.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){g("Load cloudflare script");try{yield this.loadScript()}catch(e){const t=e instanceof f?e:new f("Could not load captcha with error: "+e.toString());throw this.onErrorChallenge(this.provider,t),t}if(!window.turnstile){const e=new f("Cloudflare Turnstile is not available in window");throw this.onErrorChallenge(this.provider,e),e}try{g("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 f("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 f("Invalid sitekey or domain is not allowed");throw t.code=e,this.onErrorChallenge(this.provider,t),t}if(w.NO_RETRY_ERROR_CODES.some((t=>e.startsWith(t)))){const t=new f("Captcha challenge is failed");t.code=e,this.onErrorChallenge(this.provider,t)}else{const t=new f("Captcha challenge has error");t.reason=["timeout","expired"].includes(e)?e:void 0,t.code=e,this.onWarnChallenge(this.provider,t)}}}}))}}w.DEBUG=!1,w.NO_RETRY_ERROR_CODES=["100","105","106","110100","110110","110200","110420","110430","110500","110510","120","200010","200100"];const m="recaptcha-widget";function b(){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 y=(...e)=>{};class C{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:y,this.onRenderCaptcha=null!=i?i:y,this.onSuccessChallenge=null!=r?r:y,this.onWarnChallenge=null!=o?o:y,this.onErrorChallenge=null!=s?s:y,t&&(this.locale=t),this.addDomElements(),C.DEBUG&&(window.gr=this)}recaptchaReady(){g("Google recaptcha is ready",window.grecaptcha,this)}addDomElements(){if(this.container||document.getElementById(m))return;document.body.insertAdjacentHTML("beforeend",`<div id="${m}"></div>`);const e=document.getElementById(m);e.style.display="none",this.container=e}static getGrecaptchaCallbackNames(){return{error:`${C.ERROR_FUNC_NAME}`,expired:`${C.EXPIRED_FUNC_NAME}`,resolve:`${C.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 C.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 f("Recaptcha is not available"))},e().catch((()=>n(new f("Could not load Recaptcha"))))}))}))}notify(...e){this.notifyHandler&&this.notifyHandler(...e)}errorHandler(e){switch(g("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=`${m}_${b()}`;o.id=s,null===(n=document.getElementById(m))||void 0===n||n.appendChild(o);const a=C.getGrecaptchaCallbackNames();let c=NaN;function l(){var e;null===(e=window.grecaptcha)||void 0===e||e.reset(),setTimeout((()=>{o.remove()}),1e3)}C.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){g("Load recaptcha script");try{yield this.loadScript()}catch(e){const t=e instanceof f?e:new f("Could not load captcha with error: "+e.toString());throw this.onErrorChallenge(this.provider,t),t}if(!window.grecaptcha){const e=new f("Recaptcha is not available in window");throw this.onErrorChallenge(this.provider,e),e}try{g("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 f("Could not execute captcha with error: "+e.toString());throw this.onErrorChallenge(this.provider,t),t}if("expired"===e){const e=new f("Challenge or token expired");e.reason="expired",this.onWarnChallenge(this.provider,e)}if("error"===e){const e=new f("Error during captcha execution");this.onErrorChallenge(this.provider,e)}}}}))}}C.RESOLVE_FUNC_NAME="grecaptcha_resolved",C.ERROR_FUNC_NAME="grecaptcha_error",C.EXPIRED_FUNC_NAME="grecaptcha_expired",C.DEBUG=!1;const x="smartcaptcha-container",E=(...e)=>{};class k{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:E,this.onRenderCaptcha=null!=i?i:E,this.onSuccessChallenge=null!=r?r:E,this.onWarnChallenge=null!=o?o:E,this.onErrorChallenge=null!=s?s:E,this.onBeforeInteractiveChallenge=null!=a?a:E,this.onAfterInteractiveChallenge=null!=c?c:E,this.addDomElements()}smartCaptchaReady(){g("Smart captcha is ready",window.smartCaptcha,this)}addDomElements(){if(this.container||document.getElementById(x))return;document.body.insertAdjacentHTML("beforeend",`<div id="${x}"></div>`);const e=document.getElementById(x);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 k.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 f("SmartCaptcha is not available"))},e().catch((()=>n(new f("Could not load SmartCaptcha"))))}))}))}notify(...e){this.notifyHandler&&this.notifyHandler(...e)}errorHandler(e){switch(g("SmartCaptcha error:",e),e){case"closed":this.notify("Вы не завершили прохождение проверки. Попробуйте еще раз.");break;case"timeout":this.notify("Возможно произшла ошибка с сетевым подключением. Попробуйте ещё раз. Если не помогает, обратитесь в поддержку.");break;default:this.notify("Что-то пошло не так. Попробуйте ещё раз. Если не помогает, обратитесь в поддержку.")}}static getDebugValue(){try{if("true"===localStorage.getItem(k.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=`${x}_${b()}`;u.id=p,null===(t=document.getElementById(x))||void 0===t||t.appendChild(u),this.onRenderCaptcha(this.provider);const g=window.smartCaptcha.render(p,{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:k.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 f("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 f("Network error");e.reason="timeout",h(e)})),null===(a=window.smartCaptcha)||void 0===a||a.subscribe(g,"javascript-error",(e=>{new f("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){g("Load smartCaptcha script");try{yield this.loadScript()}catch(e){const t=e instanceof f?e:new f("Could not load captcha with error: "+e.toString());throw this.onErrorChallenge(this.provider,t),t}if(!window.smartCaptcha){const e=new f("SmartCaptcha is not available in window");throw this.onErrorChallenge(this.provider,e),e}try{g("Render SmartCaptcha widget");return yield this.renderWidget(e)}catch(e){if(!e)return;if(e instanceof f)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 f("Could not render captcha with error","fatal");t.cause=e,this.onErrorChallenge(this.provider,t)}}}}))}}k.LOCALE_STORAGE_DEBUG_KEY="captcha:smart-captcha:debug";exports.ApiService=d,exports.CaptchaError=f,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 k(e);break;case"cloudflare_turnstile":this.captcha=new w(e);break;case"recaptcha":this.captcha=new C(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 g("Receive answer from captcha provider"),{captcha_provider:this.provider,captcha_token:t||""}}))}},exports.RequestPlugin=class{constructor(){this.pluginType="request"}},exports.ResponseFailPlugin=class{constructor(){this.pluginType="responseFail"}},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
|
@@ -175,6 +175,7 @@ export interface ResponseError {
|
|
|
175
175
|
errorText: string;
|
|
176
176
|
headers: $PropertyType<ApiResponse<>, "headers">;
|
|
177
177
|
data: $PropertyType<ApiResponse<>, "data">;
|
|
178
|
+
config?: ApiRequestConfig;
|
|
178
179
|
}
|
|
179
180
|
export type ApiErrorExtended = {|
|
|
180
181
|
...ApiError<>,
|
|
@@ -195,6 +196,11 @@ export type ApiRequestConfigExtended = {|
|
|
|
195
196
|
withReferrer?: boolean,
|
|
196
197
|
|},
|
|
197
198
|
|};
|
|
199
|
+
export interface ApiServiceInterface {
|
|
200
|
+
createFoxApiInstance(params: ApiConfig): ApiInstance;
|
|
201
|
+
createApiInstance(params: ApiConfig): ApiInstance;
|
|
202
|
+
createStaticApiInstance(): ApiStatic;
|
|
203
|
+
}
|
|
198
204
|
export interface RequestPluginInterface {
|
|
199
205
|
pluginType: "request";
|
|
200
206
|
pluginName: string;
|
|
@@ -204,11 +210,6 @@ export interface RequestPluginInterface {
|
|
|
204
210
|
): Promise<ApiRequestConfigExtended>;
|
|
205
211
|
isApplicable(config: ApiRequestConfigExtended): boolean;
|
|
206
212
|
}
|
|
207
|
-
export interface ApiServiceInterface {
|
|
208
|
-
createFoxApiInstance(params: ApiConfig): ApiInstance;
|
|
209
|
-
createApiInstance(params: ApiConfig): ApiInstance;
|
|
210
|
-
createStaticApiInstance(): ApiStatic;
|
|
211
|
-
}
|
|
212
213
|
export interface ResponseSuccessPluginInterface {
|
|
213
214
|
pluginType: "responseSuccess";
|
|
214
215
|
pluginName: string;
|
|
@@ -218,9 +219,23 @@ export interface ResponseSuccessPluginInterface {
|
|
|
218
219
|
): Promise<ApiResponse<>>;
|
|
219
220
|
isApplicable(response: ApiResponse<>): boolean;
|
|
220
221
|
}
|
|
222
|
+
export interface ResponseFailPluginInterface {
|
|
223
|
+
pluginType: "responseFail";
|
|
224
|
+
pluginName: string;
|
|
225
|
+
execute(
|
|
226
|
+
error: ApiErrorExtended,
|
|
227
|
+
instance: ApiInstance
|
|
228
|
+
): Promise<ApiErrorExtended | ApiRequestConfig>;
|
|
229
|
+
isApplicable(error: ApiErrorExtended): boolean;
|
|
230
|
+
}
|
|
231
|
+
export type ApiPlugin =
|
|
232
|
+
| RequestPluginInterface
|
|
233
|
+
| ResponseSuccessPluginInterface
|
|
234
|
+
| ResponseFailPluginInterface;
|
|
235
|
+
export type ApiPluginType = $PropertyType<ApiPlugin, "pluginType">;
|
|
221
236
|
export type ApiConfig = {|
|
|
222
237
|
config: ApiRequestConfigExtended,
|
|
223
|
-
plugins?: Array<
|
|
238
|
+
plugins?: Array<ApiPlugin>,
|
|
224
239
|
|};
|
|
225
240
|
export interface GenericFormData {
|
|
226
241
|
append(name: string, value: any, options?: any): any;
|
|
@@ -274,6 +289,15 @@ declare export class ResponseSuccessPlugin
|
|
|
274
289
|
): Promise<ApiResponse<>>;
|
|
275
290
|
isApplicable(response: ApiResponse<>): boolean;
|
|
276
291
|
}
|
|
292
|
+
declare export class ResponseFailPlugin implements ResponseFailPluginInterface {
|
|
293
|
+
pluginType: "responseFail";
|
|
294
|
+
pluginName: string;
|
|
295
|
+
execute(
|
|
296
|
+
error: ApiErrorExtended,
|
|
297
|
+
instance: ApiInstance
|
|
298
|
+
): Promise<ApiErrorExtended | ApiRequestConfig>;
|
|
299
|
+
isApplicable(error: ApiErrorExtended): boolean;
|
|
300
|
+
}
|
|
277
301
|
declare var apiServiceInstance: ApiServiceInterface;
|
|
278
302
|
declare export class CaptchaError mixins Error {
|
|
279
303
|
level?: "fatal" | "error";
|
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,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};
|
|
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){return"object"==typeof e&&null!==e&&"url"in e}function d(e,t,n){return o(this,void 0,void 0,(function*(){if("object"!=typeof(i=e)||null===i||!("response"in i)||!("config"in i)||null===i.config||null===i.response)return Promise.reject(e);var i;const r=yield function(e,t,n){return o(this,void 0,void 0,(function*(){let i=e;for(const r of n)if(r.isApplicable(e)&&(i=yield r.execute(e,t),l(i)))return i;return i}))}(e,t,n);if(l(r))return t.request(r);const s=function(e){const{response:t,config:n}=e;return c.includes(t.status)&&(n._retry=!0),Object.assign({errorText:e.toString(),headers:t.headers,status:t.status,statusText:t.statusText},"object"==typeof t.data?t.data:{data:t.data})}(e);return Promise.reject(s)}))}class h{constructor(){this.pluginType="request"}}class u{constructor(){this.pluginType="responseSuccess"}}class p{constructor(){this.pluginType="responseFail"}}const f=new class{createFoxApiInstance({config:n,plugins:i=[]}){const r=e.create(n),o=this.filterPlugins(i,"request"),c=this.filterPlugins(i,"responseSuccess"),l=this.filterPlugins(i,"responseFail");return r.interceptors.request.use((e=>s(e,r,[...o]))),r.interceptors.response.use((e=>a(e,r,[...c])),(e=>d(e,r,[...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)):[]}},g="turnstile-container",v="turnstile-widget";var w=`\n<div id="${g}" 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="${v}">\n <div class="fox-cf-turnstile__loader"></div>\n </div>\n </div>\n</div>\n`;class m extends Error{constructor(e,t="error"){super(e),this.level="error",this.name="CaptchaError",this.message=e,this.level=t}}function b(...e){const t=["[CaptchaService] ",...e];console.debug.apply(console,t)}const y=(...e)=>{};class C{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:y,this.sitekey=null!=e?e:null,this.onRenderCaptcha=null!=i?i:y,this.onSuccessChallenge=null!=r?r:y,this.onErrorChallenge=null!=o?o:y,this.onWarnChallenge=null!=s?s:y,this.onBeforeInteractiveChallenge=null!=a?a:y,this.onAfterInteractiveChallenge=null!=c?c:y,t&&(this.locale=t),this.addDomElements(),C.DEBUG&&(window.cf=this)}notify(...e){this.notifyHandler&&this.notifyHandler(...e)}addDomElements(){this.container||document.getElementById(g)||(document.body.insertAdjacentHTML("beforeend",w),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(g))}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"),C.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"),C.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 C.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 m("Cloudflare Turnstile is not available"))},e().catch((()=>n(new m("Could not load Cloudflare Turnstile"))))}))}))}turnstileReady(){var e,t;b("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(`#${v}`,{action:C.normalizeLocation(null==e?void 0:e.location),"after-interactive-callback":()=>{b("after-interactive-callback"),this.onAfterInteractiveChallenge(this.provider)},"before-interactive-callback":()=>{b("before-interactive-callback"),this.onBeforeInteractiveChallenge(this.provider),this.show()},callback:e=>{b("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){b("Captcha error with code:",e);let t=[...C.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){b("Load cloudflare script");try{yield this.loadScript()}catch(e){const t=e instanceof m?e:new m("Could not load captcha with error: "+e.toString());throw this.onErrorChallenge(this.provider,t),t}if(!window.turnstile){const e=new m("Cloudflare Turnstile is not available in window");throw this.onErrorChallenge(this.provider,e),e}try{b("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 m("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 m("Invalid sitekey or domain is not allowed");throw t.code=e,this.onErrorChallenge(this.provider,t),t}if(C.NO_RETRY_ERROR_CODES.some((t=>e.startsWith(t)))){const t=new m("Captcha challenge is failed");t.code=e,this.onErrorChallenge(this.provider,t)}else{const t=new m("Captcha challenge has error");t.reason=["timeout","expired"].includes(e)?e:void 0,t.code=e,this.onWarnChallenge(this.provider,t)}}}}))}}C.DEBUG=!1,C.NO_RETRY_ERROR_CODES=["100","105","106","110100","110110","110200","110420","110430","110500","110510","120","200010","200100"];const x="recaptcha-widget";function E(){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 k=(...e)=>{};class _{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:k,this.onRenderCaptcha=null!=i?i:k,this.onSuccessChallenge=null!=r?r:k,this.onWarnChallenge=null!=o?o:k,this.onErrorChallenge=null!=s?s:k,t&&(this.locale=t),this.addDomElements(),_.DEBUG&&(window.gr=this)}recaptchaReady(){b("Google recaptcha is ready",window.grecaptcha,this)}addDomElements(){if(this.container||document.getElementById(x))return;document.body.insertAdjacentHTML("beforeend",`<div id="${x}"></div>`);const e=document.getElementById(x);e.style.display="none",this.container=e}static getGrecaptchaCallbackNames(){return{error:`${_.ERROR_FUNC_NAME}`,expired:`${_.EXPIRED_FUNC_NAME}`,resolve:`${_.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 _.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 m("Recaptcha is not available"))},e().catch((()=>n(new m("Could not load Recaptcha"))))}))}))}notify(...e){this.notifyHandler&&this.notifyHandler(...e)}errorHandler(e){switch(b("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=`${x}_${E()}`;o.id=s,null===(n=document.getElementById(x))||void 0===n||n.appendChild(o);const a=_.getGrecaptchaCallbackNames();let c=NaN;function l(){var e;null===(e=window.grecaptcha)||void 0===e||e.reset(),setTimeout((()=>{o.remove()}),1e3)}_.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){b("Load recaptcha script");try{yield this.loadScript()}catch(e){const t=e instanceof m?e:new m("Could not load captcha with error: "+e.toString());throw this.onErrorChallenge(this.provider,t),t}if(!window.grecaptcha){const e=new m("Recaptcha is not available in window");throw this.onErrorChallenge(this.provider,e),e}try{b("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 m("Could not execute captcha with error: "+e.toString());throw this.onErrorChallenge(this.provider,t),t}if("expired"===e){const e=new m("Challenge or token expired");e.reason="expired",this.onWarnChallenge(this.provider,e)}if("error"===e){const e=new m("Error during captcha execution");this.onErrorChallenge(this.provider,e)}}}}))}}_.RESOLVE_FUNC_NAME="grecaptcha_resolved",_.ERROR_FUNC_NAME="grecaptcha_error",_.EXPIRED_FUNC_NAME="grecaptcha_expired",_.DEBUG=!1;const S="smartcaptcha-container",R=(...e)=>{};class T{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:R,this.onRenderCaptcha=null!=i?i:R,this.onSuccessChallenge=null!=r?r:R,this.onWarnChallenge=null!=o?o:R,this.onErrorChallenge=null!=s?s:R,this.onBeforeInteractiveChallenge=null!=a?a:R,this.onAfterInteractiveChallenge=null!=c?c:R,this.addDomElements()}smartCaptchaReady(){b("Smart captcha is ready",window.smartCaptcha,this)}addDomElements(){if(this.container||document.getElementById(S))return;document.body.insertAdjacentHTML("beforeend",`<div id="${S}"></div>`);const e=document.getElementById(S);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 T.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 m("SmartCaptcha is not available"))},e().catch((()=>n(new m("Could not load SmartCaptcha"))))}))}))}notify(...e){this.notifyHandler&&this.notifyHandler(...e)}errorHandler(e){switch(b("SmartCaptcha error:",e),e){case"closed":this.notify("Вы не завершили прохождение проверки. Попробуйте еще раз.");break;case"timeout":this.notify("Возможно произшла ошибка с сетевым подключением. Попробуйте ещё раз. Если не помогает, обратитесь в поддержку.");break;default:this.notify("Что-то пошло не так. Попробуйте ещё раз. Если не помогает, обратитесь в поддержку.")}}static getDebugValue(){try{if("true"===localStorage.getItem(T.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=`${S}_${E()}`;u.id=p,null===(t=document.getElementById(S))||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:T.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 m("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 m("Network error");e.reason="timeout",h(e)})),null===(a=window.smartCaptcha)||void 0===a||a.subscribe(f,"javascript-error",(e=>{new m("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){b("Load smartCaptcha script");try{yield this.loadScript()}catch(e){const t=e instanceof m?e:new m("Could not load captcha with error: "+e.toString());throw this.onErrorChallenge(this.provider,t),t}if(!window.smartCaptcha){const e=new m("SmartCaptcha is not available in window");throw this.onErrorChallenge(this.provider,e),e}try{b("Render SmartCaptcha widget");return yield this.renderWidget(e)}catch(e){if(!e)return;if(e instanceof m)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 m("Could not render captcha with error","fatal");t.cause=e,this.onErrorChallenge(this.provider,t)}}}}))}}T.LOCALE_STORAGE_DEBUG_KEY="captcha:smart-captcha:debug";class L{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 T(e);break;case"cloudflare_turnstile":this.captcha=new C(e);break;case"recaptcha":this.captcha=new _(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 b("Receive answer from captcha provider"),{captcha_provider:this.provider,captcha_token:t||""}}))}}class W{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{f as ApiService,m as CaptchaError,L as CaptchaService,h as RequestPlugin,p as ResponseFailPlugin,u as ResponseSuccessPlugin,W as SocketService};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@foxford/services",
|
|
3
|
-
"version": "1.4.
|
|
3
|
+
"version": "1.4.8",
|
|
4
4
|
"description": "Foxford services",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"foxford",
|
|
@@ -53,5 +53,5 @@
|
|
|
53
53
|
"README.md"
|
|
54
54
|
],
|
|
55
55
|
"sideEffects": false,
|
|
56
|
-
"sha": "
|
|
56
|
+
"sha": "8e10b356"
|
|
57
57
|
}
|