muryshev commited on
Commit
4a9ed95
·
1 Parent(s): e5569db
dist/assets/{index-CQM8MSM2.js → index-DE9FQJMi.js} RENAMED
@@ -90,6 +90,6 @@ Error generating stack: `+l.message+`
90
  `)}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t,...n){const r=new this(t);return n.forEach(i=>r.set(i)),r}static accessor(t){const r=(this[em]=this[em]={accessors:{}}).accessors,i=this.prototype;function l(o){const s=ll(o);r[s]||(aO(i,o),r[s]=!0)}return _.isArray(t)?t.forEach(l):l(t),this}};st.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);_.reduceDescriptors(st.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(r){this[n]=r}}});_.freezeMethods(st);function ca(e,t){const n=this||so,r=t||n,i=st.from(r.headers);let l=r.data;return _.forEach(e,function(s){l=s.call(n,l,i.normalize(),t?t.status:void 0)}),i.normalize(),l}function k0(e){return!!(e&&e.__CANCEL__)}function Wi(e,t,n){G.call(this,e??"canceled",G.ERR_CANCELED,t,n),this.name="CanceledError"}_.inherits(Wi,G,{__CANCEL__:!0});function E0(e,t,n){const r=n.config.validateStatus;!n.status||!r||r(n.status)?e(n):t(new G("Request failed with status code "+n.status,[G.ERR_BAD_REQUEST,G.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}function cO(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function fO(e,t){e=e||10;const n=new Array(e),r=new Array(e);let i=0,l=0,o;return t=t!==void 0?t:1e3,function(u){const a=Date.now(),c=r[l];o||(o=a),n[i]=u,r[i]=a;let f=l,h=0;for(;f!==i;)h+=n[f++],f=f%e;if(i=(i+1)%e,i===l&&(l=(l+1)%e),a-o<t)return;const d=c&&a-c;return d?Math.round(h*1e3/d):void 0}}function dO(e,t){let n=0,r=1e3/t,i,l;const o=(a,c=Date.now())=>{n=c,i=null,l&&(clearTimeout(l),l=null),e.apply(null,a)};return[(...a)=>{const c=Date.now(),f=c-n;f>=r?o(a,c):(i=a,l||(l=setTimeout(()=>{l=null,o(i)},r-f)))},()=>i&&o(i)]}const Ds=(e,t,n=3)=>{let r=0;const i=fO(50,250);return dO(l=>{const o=l.loaded,s=l.lengthComputable?l.total:void 0,u=o-r,a=i(u),c=o<=s;r=o;const f={loaded:o,total:s,progress:s?o/s:void 0,bytes:u,rate:a||void 0,estimated:a&&s&&c?(s-o)/a:void 0,event:l,lengthComputable:s!=null,[t?"download":"upload"]:!0};e(f)},n)},tm=(e,t)=>{const n=e!=null;return[r=>t[0]({lengthComputable:n,total:e,loaded:r}),t[1]]},nm=e=>(...t)=>_.asap(()=>e(...t)),hO=$e.hasStandardBrowserEnv?((e,t)=>n=>(n=new URL(n,$e.origin),e.protocol===n.protocol&&e.host===n.host&&(t||e.port===n.port)))(new URL($e.origin),$e.navigator&&/(msie|trident)/i.test($e.navigator.userAgent)):()=>!0,pO=$e.hasStandardBrowserEnv?{write(e,t,n,r,i,l){const o=[e+"="+encodeURIComponent(t)];_.isNumber(n)&&o.push("expires="+new Date(n).toGMTString()),_.isString(r)&&o.push("path="+r),_.isString(i)&&o.push("domain="+i),l===!0&&o.push("secure"),document.cookie=o.join("; ")},read(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function mO(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function yO(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function C0(e,t,n){let r=!mO(t);return e&&(r||n==!1)?yO(e,t):t}const rm=e=>e instanceof st?{...e}:e;function jr(e,t){t=t||{};const n={};function r(a,c,f,h){return _.isPlainObject(a)&&_.isPlainObject(c)?_.merge.call({caseless:h},a,c):_.isPlainObject(c)?_.merge({},c):_.isArray(c)?c.slice():c}function i(a,c,f,h){if(_.isUndefined(c)){if(!_.isUndefined(a))return r(void 0,a,f,h)}else return r(a,c,f,h)}function l(a,c){if(!_.isUndefined(c))return r(void 0,c)}function o(a,c){if(_.isUndefined(c)){if(!_.isUndefined(a))return r(void 0,a)}else return r(void 0,c)}function s(a,c,f){if(f in t)return r(a,c);if(f in e)return r(void 0,a)}const u={url:l,method:l,data:l,baseURL:o,transformRequest:o,transformResponse:o,paramsSerializer:o,timeout:o,timeoutMessage:o,withCredentials:o,withXSRFToken:o,adapter:o,responseType:o,xsrfCookieName:o,xsrfHeaderName:o,onUploadProgress:o,onDownloadProgress:o,decompress:o,maxContentLength:o,maxBodyLength:o,beforeRedirect:o,transport:o,httpAgent:o,httpsAgent:o,cancelToken:o,socketPath:o,responseEncoding:o,validateStatus:s,headers:(a,c,f)=>i(rm(a),rm(c),f,!0)};return _.forEach(Object.keys(Object.assign({},e,t)),function(c){const f=u[c]||i,h=f(e[c],t[c],c);_.isUndefined(h)&&f!==s||(n[c]=h)}),n}const P0=e=>{const t=jr({},e);let{data:n,withXSRFToken:r,xsrfHeaderName:i,xsrfCookieName:l,headers:o,auth:s}=t;t.headers=o=st.from(o),t.url=w0(C0(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),s&&o.set("Authorization","Basic "+btoa((s.username||"")+":"+(s.password?unescape(encodeURIComponent(s.password)):"")));let u;if(_.isFormData(n)){if($e.hasStandardBrowserEnv||$e.hasStandardBrowserWebWorkerEnv)o.setContentType(void 0);else if((u=o.getContentType())!==!1){const[a,...c]=u?u.split(";").map(f=>f.trim()).filter(Boolean):[];o.setContentType([a||"multipart/form-data",...c].join("; "))}}if($e.hasStandardBrowserEnv&&(r&&_.isFunction(r)&&(r=r(t)),r||r!==!1&&hO(t.url))){const a=i&&l&&pO.read(l);a&&o.set(i,a)}return t},gO=typeof XMLHttpRequest<"u",vO=gO&&function(e){return new Promise(function(n,r){const i=P0(e);let l=i.data;const o=st.from(i.headers).normalize();let{responseType:s,onUploadProgress:u,onDownloadProgress:a}=i,c,f,h,d,m;function v(){d&&d(),m&&m(),i.cancelToken&&i.cancelToken.unsubscribe(c),i.signal&&i.signal.removeEventListener("abort",c)}let x=new XMLHttpRequest;x.open(i.method.toUpperCase(),i.url,!0),x.timeout=i.timeout;function p(){if(!x)return;const g=st.from("getAllResponseHeaders"in x&&x.getAllResponseHeaders()),P={data:!s||s==="text"||s==="json"?x.responseText:x.response,status:x.status,statusText:x.statusText,headers:g,config:e,request:x};E0(function(T){n(T),v()},function(T){r(T),v()},P),x=null}"onloadend"in x?x.onloadend=p:x.onreadystatechange=function(){!x||x.readyState!==4||x.status===0&&!(x.responseURL&&x.responseURL.indexOf("file:")===0)||setTimeout(p)},x.onabort=function(){x&&(r(new G("Request aborted",G.ECONNABORTED,e,x)),x=null)},x.onerror=function(){r(new G("Network Error",G.ERR_NETWORK,e,x)),x=null},x.ontimeout=function(){let C=i.timeout?"timeout of "+i.timeout+"ms exceeded":"timeout exceeded";const P=i.transitional||x0;i.timeoutErrorMessage&&(C=i.timeoutErrorMessage),r(new G(C,P.clarifyTimeoutError?G.ETIMEDOUT:G.ECONNABORTED,e,x)),x=null},l===void 0&&o.setContentType(null),"setRequestHeader"in x&&_.forEach(o.toJSON(),function(C,P){x.setRequestHeader(P,C)}),_.isUndefined(i.withCredentials)||(x.withCredentials=!!i.withCredentials),s&&s!=="json"&&(x.responseType=i.responseType),a&&([h,m]=Ds(a,!0),x.addEventListener("progress",h)),u&&x.upload&&([f,d]=Ds(u),x.upload.addEventListener("progress",f),x.upload.addEventListener("loadend",d)),(i.cancelToken||i.signal)&&(c=g=>{x&&(r(!g||g.type?new Wi(null,e,x):g),x.abort(),x=null)},i.cancelToken&&i.cancelToken.subscribe(c),i.signal&&(i.signal.aborted?c():i.signal.addEventListener("abort",c)));const y=cO(i.url);if(y&&$e.protocols.indexOf(y)===-1){r(new G("Unsupported protocol "+y+":",G.ERR_BAD_REQUEST,e));return}x.send(l||null)})},wO=(e,t)=>{const{length:n}=e=e?e.filter(Boolean):[];if(t||n){let r=new AbortController,i;const l=function(a){if(!i){i=!0,s();const c=a instanceof Error?a:this.reason;r.abort(c instanceof G?c:new Wi(c instanceof Error?c.message:c))}};let o=t&&setTimeout(()=>{o=null,l(new G(`timeout ${t} of ms exceeded`,G.ETIMEDOUT))},t);const s=()=>{e&&(o&&clearTimeout(o),o=null,e.forEach(a=>{a.unsubscribe?a.unsubscribe(l):a.removeEventListener("abort",l)}),e=null)};e.forEach(a=>a.addEventListener("abort",l));const{signal:u}=r;return u.unsubscribe=()=>_.asap(s),u}},xO=function*(e,t){let n=e.byteLength;if(n<t){yield e;return}let r=0,i;for(;r<n;)i=r+t,yield e.slice(r,i),r=i},SO=async function*(e,t){for await(const n of kO(e))yield*xO(n,t)},kO=async function*(e){if(e[Symbol.asyncIterator]){yield*e;return}const t=e.getReader();try{for(;;){const{done:n,value:r}=await t.read();if(n)break;yield r}}finally{await t.cancel()}},im=(e,t,n,r)=>{const i=SO(e,t);let l=0,o,s=u=>{o||(o=!0,r&&r(u))};return new ReadableStream({async pull(u){try{const{done:a,value:c}=await i.next();if(a){s(),u.close();return}let f=c.byteLength;if(n){let h=l+=f;n(h)}u.enqueue(new Uint8Array(c))}catch(a){throw s(a),a}},cancel(u){return s(u),i.return()}},{highWaterMark:2})},mu=typeof fetch=="function"&&typeof Request=="function"&&typeof Response=="function",_0=mu&&typeof ReadableStream=="function",EO=mu&&(typeof TextEncoder=="function"?(e=>t=>e.encode(t))(new TextEncoder):async e=>new Uint8Array(await new Response(e).arrayBuffer())),T0=(e,...t)=>{try{return!!e(...t)}catch{return!1}},CO=_0&&T0(()=>{let e=!1;const t=new Request($e.origin,{body:new ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t}),lm=64*1024,Uc=_0&&T0(()=>_.isReadableStream(new Response("").body)),Fs={stream:Uc&&(e=>e.body)};mu&&(e=>{["text","arrayBuffer","blob","formData","stream"].forEach(t=>{!Fs[t]&&(Fs[t]=_.isFunction(e[t])?n=>n[t]():(n,r)=>{throw new G(`Response type '${t}' is not supported`,G.ERR_NOT_SUPPORT,r)})})})(new Response);const PO=async e=>{if(e==null)return 0;if(_.isBlob(e))return e.size;if(_.isSpecCompliantForm(e))return(await new Request($e.origin,{method:"POST",body:e}).arrayBuffer()).byteLength;if(_.isArrayBufferView(e)||_.isArrayBuffer(e))return e.byteLength;if(_.isURLSearchParams(e)&&(e=e+""),_.isString(e))return(await EO(e)).byteLength},_O=async(e,t)=>{const n=_.toFiniteNumber(e.getContentLength());return n??PO(t)},TO=mu&&(async e=>{let{url:t,method:n,data:r,signal:i,cancelToken:l,timeout:o,onDownloadProgress:s,onUploadProgress:u,responseType:a,headers:c,withCredentials:f="same-origin",fetchOptions:h}=P0(e);a=a?(a+"").toLowerCase():"text";let d=wO([i,l&&l.toAbortSignal()],o),m;const v=d&&d.unsubscribe&&(()=>{d.unsubscribe()});let x;try{if(u&&CO&&n!=="get"&&n!=="head"&&(x=await _O(c,r))!==0){let P=new Request(t,{method:"POST",body:r,duplex:"half"}),E;if(_.isFormData(r)&&(E=P.headers.get("content-type"))&&c.setContentType(E),P.body){const[T,R]=tm(x,Ds(nm(u)));r=im(P.body,lm,T,R)}}_.isString(f)||(f=f?"include":"omit");const p="credentials"in Request.prototype;m=new Request(t,{...h,signal:d,method:n.toUpperCase(),headers:c.normalize().toJSON(),body:r,duplex:"half",credentials:p?f:void 0});let y=await fetch(m);const g=Uc&&(a==="stream"||a==="response");if(Uc&&(s||g&&v)){const P={};["status","statusText","headers"].forEach(L=>{P[L]=y[L]});const E=_.toFiniteNumber(y.headers.get("content-length")),[T,R]=s&&tm(E,Ds(nm(s),!0))||[];y=new Response(im(y.body,lm,T,()=>{R&&R(),v&&v()}),P)}a=a||"text";let C=await Fs[_.findKey(Fs,a)||"text"](y,e);return!g&&v&&v(),await new Promise((P,E)=>{E0(P,E,{data:C,headers:st.from(y.headers),status:y.status,statusText:y.statusText,config:e,request:m})})}catch(p){throw v&&v(),p&&p.name==="TypeError"&&/fetch/i.test(p.message)?Object.assign(new G("Network Error",G.ERR_NETWORK,e,m),{cause:p.cause||p}):G.from(p,p&&p.code,e,m)}}),$c={http:$R,xhr:vO,fetch:TO};_.forEach($c,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});const om=e=>`- ${e}`,RO=e=>_.isFunction(e)||e===null||e===!1,R0={getAdapter:e=>{e=_.isArray(e)?e:[e];const{length:t}=e;let n,r;const i={};for(let l=0;l<t;l++){n=e[l];let o;if(r=n,!RO(n)&&(r=$c[(o=String(n)).toLowerCase()],r===void 0))throw new G(`Unknown adapter '${o}'`);if(r)break;i[o||"#"+l]=r}if(!r){const l=Object.entries(i).map(([s,u])=>`adapter ${s} `+(u===!1?"is not supported by the environment":"is not available in the build"));let o=t?l.length>1?`since :
91
  `+l.map(om).join(`
92
  `):" "+om(l[0]):"as no adapter specified";throw new G("There is no suitable adapter to dispatch the request "+o,"ERR_NOT_SUPPORT")}return r},adapters:$c};function fa(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new Wi(null,e)}function sm(e){return fa(e),e.headers=st.from(e.headers),e.data=ca.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),R0.getAdapter(e.adapter||so.adapter)(e).then(function(r){return fa(e),r.data=ca.call(e,e.transformResponse,r),r.headers=st.from(r.headers),r},function(r){return k0(r)||(fa(e),r&&r.response&&(r.response.data=ca.call(e,e.transformResponse,r.response),r.response.headers=st.from(r.response.headers))),Promise.reject(r)})}const O0="1.8.4",yu={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{yu[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});const um={};yu.transitional=function(t,n,r){function i(l,o){return"[Axios v"+O0+"] Transitional option '"+l+"'"+o+(r?". "+r:"")}return(l,o,s)=>{if(t===!1)throw new G(i(o," has been removed"+(n?" in "+n:"")),G.ERR_DEPRECATED);return n&&!um[o]&&(um[o]=!0,console.warn(i(o," has been deprecated since v"+n+" and will be removed in the near future"))),t?t(l,o,s):!0}};yu.spelling=function(t){return(n,r)=>(console.warn(`${r} is likely a misspelling of ${t}`),!0)};function OO(e,t,n){if(typeof e!="object")throw new G("options must be an object",G.ERR_BAD_OPTION_VALUE);const r=Object.keys(e);let i=r.length;for(;i-- >0;){const l=r[i],o=t[l];if(o){const s=e[l],u=s===void 0||o(s,l,e);if(u!==!0)throw new G("option "+l+" must be "+u,G.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new G("Unknown option "+l,G.ERR_BAD_OPTION)}}const Jo={assertOptions:OO,validators:yu},Gt=Jo.validators;let Or=class{constructor(t){this.defaults=t,this.interceptors={request:new Zp,response:new Zp}}async request(t,n){try{return await this._request(t,n)}catch(r){if(r instanceof Error){let i={};Error.captureStackTrace?Error.captureStackTrace(i):i=new Error;const l=i.stack?i.stack.replace(/^.+\n/,""):"";try{r.stack?l&&!String(r.stack).endsWith(l.replace(/^.+\n.+\n/,""))&&(r.stack+=`
93
- `+l):r.stack=l}catch{}}throw r}}_request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=jr(this.defaults,n);const{transitional:r,paramsSerializer:i,headers:l}=n;r!==void 0&&Jo.assertOptions(r,{silentJSONParsing:Gt.transitional(Gt.boolean),forcedJSONParsing:Gt.transitional(Gt.boolean),clarifyTimeoutError:Gt.transitional(Gt.boolean)},!1),i!=null&&(_.isFunction(i)?n.paramsSerializer={serialize:i}:Jo.assertOptions(i,{encode:Gt.function,serialize:Gt.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),Jo.assertOptions(n,{baseUrl:Gt.spelling("baseURL"),withXsrfToken:Gt.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let o=l&&_.merge(l.common,l[n.method]);l&&_.forEach(["delete","get","head","post","put","patch","common"],m=>{delete l[m]}),n.headers=st.concat(o,l);const s=[];let u=!0;this.interceptors.request.forEach(function(v){typeof v.runWhen=="function"&&v.runWhen(n)===!1||(u=u&&v.synchronous,s.unshift(v.fulfilled,v.rejected))});const a=[];this.interceptors.response.forEach(function(v){a.push(v.fulfilled,v.rejected)});let c,f=0,h;if(!u){const m=[sm.bind(this),void 0];for(m.unshift.apply(m,s),m.push.apply(m,a),h=m.length,c=Promise.resolve(n);f<h;)c=c.then(m[f++],m[f++]);return c}h=s.length;let d=n;for(f=0;f<h;){const m=s[f++],v=s[f++];try{d=m(d)}catch(x){v.call(this,x);break}}try{c=sm.call(this,d)}catch(m){return Promise.reject(m)}for(f=0,h=a.length;f<h;)c=c.then(a[f++],a[f++]);return c}getUri(t){t=jr(this.defaults,t);const n=C0(t.baseURL,t.url,t.allowAbsoluteUrls);return w0(n,t.params,t.paramsSerializer)}};_.forEach(["delete","get","head","options"],function(t){Or.prototype[t]=function(n,r){return this.request(jr(r||{},{method:t,url:n,data:(r||{}).data}))}});_.forEach(["post","put","patch"],function(t){function n(r){return function(l,o,s){return this.request(jr(s||{},{method:t,headers:r?{"Content-Type":"multipart/form-data"}:{},url:l,data:o}))}}Or.prototype[t]=n(),Or.prototype[t+"Form"]=n(!0)});let bO=class b0{constructor(t){if(typeof t!="function")throw new TypeError("executor must be a function.");let n;this.promise=new Promise(function(l){n=l});const r=this;this.promise.then(i=>{if(!r._listeners)return;let l=r._listeners.length;for(;l-- >0;)r._listeners[l](i);r._listeners=null}),this.promise.then=i=>{let l;const o=new Promise(s=>{r.subscribe(s),l=s}).then(i);return o.cancel=function(){r.unsubscribe(l)},o},t(function(l,o,s){r.reason||(r.reason=new Wi(l,o,s),n(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;const n=this._listeners.indexOf(t);n!==-1&&this._listeners.splice(n,1)}toAbortSignal(){const t=new AbortController,n=r=>{t.abort(r)};return this.subscribe(n),t.signal.unsubscribe=()=>this.unsubscribe(n),t.signal}static source(){let t;return{token:new b0(function(i){t=i}),cancel:t}}};function NO(e){return function(n){return e.apply(null,n)}}function IO(e){return _.isObject(e)&&e.isAxiosError===!0}const Hc={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(Hc).forEach(([e,t])=>{Hc[t]=e});function N0(e){const t=new Or(e),n=u0(Or.prototype.request,t);return _.extend(n,Or.prototype,t,{allOwnKeys:!0}),_.extend(n,t,null,{allOwnKeys:!0}),n.create=function(i){return N0(jr(e,i))},n}const Se=N0(so);Se.Axios=Or;Se.CanceledError=Wi;Se.CancelToken=bO;Se.isCancel=k0;Se.VERSION=O0;Se.toFormData=pu;Se.AxiosError=G;Se.Cancel=Se.CanceledError;Se.all=function(t){return Promise.all(t)};Se.spread=NO;Se.isAxiosError=IO;Se.mergeConfig=jr;Se.AxiosHeaders=st;Se.formToJSON=e=>S0(_.isHTMLForm(e)?new FormData(e):e);Se.getAdapter=R0.getAdapter;Se.HttpStatusCode=Hc;Se.default=Se;const{Axios:YO,AxiosError:ZO,CanceledError:e2,isCancel:t2,CancelToken:n2,VERSION:r2,all:i2,Cancel:l2,isAxiosError:o2,spread:s2,toFormData:u2,AxiosHeaders:a2,HttpStatusCode:c2,formToJSON:f2,getAdapter:d2,mergeConfig:h2}=Se,I0="http://localhost:8885",pd=Se.create({baseURL:`${I0}`,timeout:6e5}),AO=e=>{const t=localStorage.getItem("authToken");return t&&(e.headers.Authorization=`Bearer ${t}`),e},LO=e=>e,DO=async e=>{var n;const t=e.message;return t.includes("409")&&(console.log("409"),D0.invalidateQueries({queryKey:["processing"]})),((n=e.response)==null?void 0:n.status)===401?(localStorage.removeItem("authToken"),window.location.href="/login"):!Se.isCancel(e)&&!t.includes("409")&&alert(`${t} Произошла ошибка`),Promise.reject(e)};pd.interceptors.request.use(AO);pd.interceptors.response.use(LO,DO);const A0=async({url:e,signal:t,...n},r=I0)=>{var o,s,u;const i=new AbortController,l=t||i.signal;try{console.log("Попытка отправки запроса");const a=await pd({url:`${r}${e}`,signal:l,...n});return console.log("Запрос отправлен, результат:",a),{data:a.data,headers:a.headers}}catch(a){if(Se.isCancel(a))return console.log("Запрос отменен"),{error:{status:"Cancelled",data:"Request was cancelled",notCauseError:!0}};const c=a;return console.log("Ошибка при отправке запроса"),{error:{status:(o=c.response)==null?void 0:o.status,data:(s=c.response)==null?void 0:s.data,headers:(u=c.response)==null?void 0:u.headers}}}finally{t||i.abort()}},FO=async e=>{const t=await A0({url:"/auth/login",method:"post",data:e});if("error"in t)throw new Error(`Ошибка авторизации: ${t.error.status}`);return t.data},zO=async()=>{const e=localStorage.getItem("authToken");return"current_user"in(await A0({url:"/auth/checktoken",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},method:"post"})).data},L0=b.createContext(void 0),MO=({children:e})=>{const[t,n]=b.useState(()=>!!localStorage.getItem("authToken")),r=rR({mutationFn:o=>FO(o),onSuccess:o=>{localStorage.setItem("authToken",o.access_token),n(!0)},onError:o=>{console.error("Login Error:",o)}}),i=async o=>{await r.mutateAsync(o)},l=()=>{localStorage.removeItem("authToken"),n(!1)};return D.jsx(L0.Provider,{value:{isAuthenticated:t,login:i,logout:l,isLoading:r.isPending,error:r.error},children:e})},gu=()=>{const e=b.useContext(L0);if(!e)throw new Error("useAuth must be used within an AuthProvider");return e},jO=()=>{const{logout:e}=gu();return D.jsx("button",{className:"logout-button",onClick:e,children:"Выйти"})},BO=({isVisible:e,toggleSidebar:t,sidebarRef:n})=>{const r=qg(),i=Es(m=>m.chat.chats),l=Es(m=>m.chat.activeChatId),[o,s]=b.useState(null),[u,a]=b.useState(""),c=()=>{const m={id:Date.now().toString(),name:`Чат ${i.length+1}`,history:[]};r(fT(m))},f=m=>{var v;o===m&&u.trim()?(r(hT({chatId:m,newName:u})),s(null),a("")):(s(m),a(((v=i.find(x=>x.id===m))==null?void 0:v.name)||""))},h=m=>{r(dT(m))},d=()=>{console.log("Hide button clicked"),t()};return D.jsxs("div",{ref:n,className:`chat-sidebar ${e?"visible":""}`,children:[D.jsxs("div",{className:"sidebar-header",children:[D.jsx("button",{onClick:c,children:"Новый чат"}),D.jsx("button",{className:"icon-button toggle",onClick:d,title:"Скрыть меню",children:D.jsx(kT,{})})]}),D.jsx("ul",{children:i.map(m=>D.jsxs("li",{className:m.id===l?"active":"",onClick:()=>r(Qv(m.id)),children:[o===m.id?D.jsx("input",{value:u,onChange:v=>a(v.target.value),onBlur:()=>f(m.id),onKeyDown:v=>v.key==="Enter"&&f(m.id),autoFocus:!0,className:"chat-input"}):D.jsx("span",{className:"chat-name",children:m.name}),D.jsxs("div",{className:"chat-actions",children:[D.jsx("button",{className:"icon-button rename",onClick:v=>{v.stopPropagation(),f(m.id)},title:"Переименовать",children:D.jsx(ET,{})}),D.jsx("button",{className:"icon-button delete",onClick:v=>{v.stopPropagation(),h(m.id)},title:"Удалить",children:D.jsx(CT,{})})]})]},m.id))}),D.jsx("div",{className:"sidebar-header",children:D.jsx(jO,{})})]})};class UO{constructor(){this.dbName="ChatDB",this.storeName="chats",this.db=null}async initDB(){return this.db?this.db:new Promise((t,n)=>{const r=indexedDB.open(this.dbName,1);r.onupgradeneeded=()=>{r.result.createObjectStore(this.storeName,{keyPath:"id"})},r.onsuccess=()=>{this.db=r.result,t(this.db)},r.onerror=()=>n(r.error)})}async getChats(){const t=await this.initDB();return new Promise((n,r)=>{const o=t.transaction(this.storeName,"readonly").objectStore(this.storeName).getAll();o.onsuccess=()=>n(o.result),o.onerror=()=>r(o.error)})}async saveChat(t){const n=await this.initDB();return new Promise((r,i)=>{const s=n.transaction(this.storeName,"readwrite").objectStore(this.storeName).put(t);s.onsuccess=()=>r(),s.onerror=()=>i(s.error)})}async deleteChat(t){const n=await this.initDB();return new Promise((r,i)=>{const s=n.transaction(this.storeName,"readwrite").objectStore(this.storeName).delete(t);s.onsuccess=()=>r(),s.onerror=()=>i(s.error)})}async renameChat(t,n){const i=(await this.getChats()).find(l=>l.id===t);i&&(i.name=n,await this.saveChat(i))}}const Ao=new UO,$O=()=>{const[e,t]=b.useState(""),[n,r]=b.useState(null),[i,l]=b.useState(!1),[o,s]=b.useState(!1),[u,a]=b.useState(window.innerWidth>1800),[c,f]=b.useState(!1),h=Es(N=>N.chat.chats),d=Es(N=>N.chat.activeChatId),m=h.find(N=>N.id===d),v=(m==null?void 0:m.history)||[],x=qg(),p=b.useRef(null),y=b.useRef(null),{logout:g,isAuthenticated:C}=gu(),P=Uf(),E=b.useRef(!1),T=b.useRef(null);b.useEffect(()=>{const N=$=>{const X=document.getElementsByClassName("sidebar-toggle-close").length>0?document.getElementsByClassName("sidebar-toggle-close")[0].contains($.target):!1;u&&T.current&&!T.current.contains($.target)&&!X&&a(!1)};return document.addEventListener("mousedown",N),()=>{document.removeEventListener("mousedown",N)}},[u]);const R=()=>{console.log("Toggling sidebar, current state:",u),a(N=>!N)},L=()=>{const N=document.querySelector(".messages");if(N){const $=N.getBoundingClientRect(),X=window.innerHeight;return $.bottom<=X+10}return!0},j=()=>{p.current&&(p.current.abort(),l(!1),s(!1),y.current=null,console.log("Generation stopped by user"))};b.useEffect(()=>{(async()=>{try{console.log("Loading chats from storage...");const $=await Ao.getChats(),X=$.length>0?$:[{id:Date.now().toString(),name:"Чат 1",history:[]}];x(sT(X)),f(!0),console.log("Chats loaded:",X)}catch($){console.error("Failed to load chats:",$),r("Не удалось загрузить чаты"),f(!0)}})()},[x]),b.useEffect(()=>{(async()=>{if(c)try{const X=(await Ao.getChats()).filter(Q=>!h.some(pe=>pe.id===Q.id));for(const Q of X)await Ao.deleteChat(Q.id),console.log("Deleted chat from storage:",Q.id);for(const Q of h)await Ao.saveChat(Q)}catch($){console.error("Failed to sync chats with storage:",$),r("Ошибка синхронизации чатов")}})()},[h,c]),b.useEffect(()=>{if(!C||!c||E.current){console.log("Waiting for initialization or already attempted resend...",{isAuthenticated:C,isChatsLoaded:c,hasAttemptedResend:E.current});return}const N=localStorage.getItem("pendingMessage");if(N)try{const{text:$,chatId:X}=JSON.parse(N);console.log("Pending message found:",{text:$,chatId:X}),h.some(Q=>Q.id===X)?(console.log("Resending pending message to chat:",X),x(Qv(X)),M($),localStorage.removeItem("pendingMessage")):(console.log("Chat not found, discarding pending message"),localStorage.removeItem("pendingMessage"),r("Чат для отложенного сообщения не найден"))}catch($){console.error("Failed to parse pending message:",$),localStorage.removeItem("pendingMessage"),r("Ошибка обработки отложенного сообщения")}finally{E.current=!0}else console.log("No pending message found"),E.current=!0},[C,c,h]),b.useEffect(()=>{if(n){const N=setTimeout(()=>r(null),5e3);return()=>clearTimeout(N)}},[n]);const M=async N=>{var pe;if(!N.trim()||i||!C||!d)return;t(""),l(!0),s(!1),console.log("Start request - isLoading:",i,"isGeneratingTokens:",o);const $="http://localhost:8885/llm/chat/stream",X=localStorage.getItem("authToken"),Q={role:"user",content:N,searchResults:"",searchEntities:[]};x(uT({chatId:d,message:Q})),y.current=d;try{const le=new AbortController;p.current=le;const z=setTimeout(()=>{le.abort(),r("Сервер временно недоступен")},6e4),H=await fetch($,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${X}`},body:JSON.stringify({history:[...v,Q]}),signal:le.signal});if(clearTimeout(z),!H.ok){if(H.status===401){console.log("Saving pending message:",N,"for chat:",d),localStorage.setItem("pendingMessage",JSON.stringify({text:N,chatId:d})),x(aT(d)),r("Сессия истекла. Пожалуйста, войдите заново."),g(),P("/login"),l(!1),y.current=null;return}throw new Error(`HTTP error! status: ${H.status}`)}const w=(pe=H.body)==null?void 0:pe.getReader();if(!w)throw new Error("Response body is not readable");const ee=new TextDecoder;let ie="",k="",Z=[...v,Q];for(;;){const{done:at,value:ae}=await w.read();if(at)break;ie+=ee.decode(ae,{stream:!0});const Qe=ie.split(`
94
 
95
  `);for(let ct=0;ct<Qe.length-1;ct++){const Et=Qe[ct].trim();if(Et.startsWith("data: ")){const Hr=Et.slice(6);try{const ze=JSON.parse(Hr),Vr=y.current;if(ze.event==="done"){x(No({chatId:Vr,history:Z})),l(!1),y.current=null,console.log("Done - isLoading:",i,"isGeneratingTokens:",o);break}else if(ze.event==="error"){r("Произошла непредвиденная ошибка во время генерации ответа. Попробуйте повторить запрос."),l(!1),y.current=null,console.error("SSE error:",ze.data);break}else if(ze.event==="debug")console.log("Debug data:",ze.data);else if(ze.event==="search_results")l(!0),Z=Z.map((Lt,un)=>un===Z.length-1&&Lt.role==="user"?{...Lt,searchResults:ze.data.text,searchEntities:ze.data.ids}:Lt),x(No({chatId:Vr,history:Z})),console.log("After search_results - isLoading:",i,"isGeneratingTokens:",o);else if(ze.event==="reasoning")console.log("reasoning"),l(!0),Z=Z.map((Lt,un)=>un===Z.length-1&&Lt.role==="user"?{...Lt,reasoning:ze.data.text}:Lt),x(No({chatId:Vr,history:Z}));else if(ze.event==="token"){o||(s(!0),console.log("Before first token - isLoading:",i,"isGeneratingTokens:",o)),k+=ze.data;const Lt=Z.findLastIndex(an=>an.role==="user"),un=Z.findIndex((an,Qr)=>an.role==="assistant"&&Qr>Lt);un>=0?Z=Z.map((an,Qr)=>Qr===un?{...an,content:k}:an):Z=[...Z,{role:"assistant",content:k,searchResults:"",searchEntities:[]}],x(No({chatId:Vr,history:Z}))}}catch(ze){console.error("Failed to parse SSE data:",ze),r("Ошибка обработки данных от сервера")}}}ie=Qe[Qe.length-1];const At=document.querySelector(".messages");if(At&&y.current===d){const ct=At.querySelectorAll("div"),Et=ct[ct.length-1];Et&&L()&&setTimeout(()=>{Et.scrollIntoView({behavior:"smooth",block:"start"})},0)}}}catch(le){console.error("Stream error:",le),l(!1),s(!1),y.current=null,le instanceof DOMException&&le.name==="AbortError"&&!p.current?r("Сервер временно недоступен"):le instanceof DOMException&&le.name==="AbortError"||r("Произошла ошибка при запросе")}finally{p.current=null}};return b.useEffect(()=>{const N=$=>{$.ctrlKey&&$.shiftKey&&$.key==="F8"&&($.preventDefault(),Iv("expert_mode")==="true"?(S_("expert_mode"),console.log("Expert mode disabled")):(x_("expert_mode","true"),console.log("Expert mode enabled")))};return window.addEventListener("keydown",N),()=>{window.removeEventListener("keydown",N)}},[]),D.jsx("div",{className:"app-container",children:D.jsxs("div",{className:"chat-layout",children:[D.jsx(BO,{isVisible:u,toggleSidebar:R,sidebarRef:T}),D.jsx("div",{className:"sidebar-toggle-wrapper",children:u?D.jsx("button",{className:"sidebar-toggle-close",onClick:R,title:"Скрыть меню",children:D.jsx(Bp,{})}):D.jsx("button",{className:"sidebar-toggle-open",onClick:R,title:"Показать меню",children:D.jsx(Bp,{})})}),D.jsxs("div",{className:"chat-content",children:[n&&D.jsx("div",{className:"error-toast",children:n}),D.jsxs("div",{className:"messages",children:[v.map((N,$)=>D.jsx(Tp,{role:N.role,content:N.content,searchResults:N.searchResults,reasoning:N.reasoning},$)),i&&!o&&y.current===d&&D.jsx(Tp,{role:"assistant",content:"",isLoading:!0,searchResults:""},"loading")]}),D.jsxs("div",{className:"input-area",children:[D.jsx(k_,{onSend:M,text:e,setText:t}),D.jsxs("div",{className:"buttons",children:[i?D.jsx("button",{className:"stop-button",onClick:j,children:"Остановить"}):D.jsx("button",{className:"send-button",onClick:()=>M(e),children:"Отправить"}),D.jsx("a",{href:"#",className:"clear-link",onClick:N=>{N.preventDefault(),x(cT(d))},children:"Очистить"})]})]})]})]})})},HO=q_({reducer:{chat:pT}}),VO=()=>D.jsx(bS,{store:HO,children:D.jsx($O,{})}),QO=()=>{const[e,t]=b.useState(""),[n,r]=b.useState(""),{login:i,isLoading:l,error:o}=gu(),s=Uf(),u=async a=>{a.preventDefault();try{await i({username:e,password:n}),s("/",{replace:!0})}catch{}};return D.jsx("div",{className:"login-page",children:D.jsxs("form",{onSubmit:u,children:[D.jsxs("div",{children:[D.jsx("label",{children:"Логин:"}),D.jsx("input",{type:"text",value:e,onChange:a=>t(a.target.value)})]}),D.jsxs("div",{children:[D.jsx("label",{children:"Пароль:"}),D.jsx("input",{type:"password",value:n,onChange:a=>r(a.target.value)})]}),o&&D.jsx("p",{className:"error",children:"Неверный логин или пароль"}),D.jsx("button",{type:"submit",disabled:l,children:l?"Вход...":"Войти"})]})})},WO=!1,qO=({children:e,checkInterval:t=WO})=>{const{isAuthenticated:n,logout:r}=gu(),i=Uf(),{isLoading:l,data:o,error:s}=nR({queryKey:["tokenValid"],queryFn:zO,enabled:n,refetchInterval:t,refetchOnWindowFocus:!1});return b.useEffect(()=>{(s||!n||o===!1)&&(console.error("Token validation error:",s),r(),i("/login",{replace:!0}))},[n,o,s,r,i]),l?D.jsx("div",{children:"Loading..."}):s||!n||o===!1?null:D.jsx(D.Fragment,{children:e})},D0=new jT;da.createRoot(document.getElementById("root")).render(D.jsx(wn.StrictMode,{children:D.jsx(VT,{client:D0,children:D.jsx(MO,{children:D.jsx(cS,{children:D.jsxs(sS,{children:[D.jsx(oc,{path:"/login",element:D.jsx(QO,{})}),D.jsx(oc,{path:"/",element:D.jsx(qO,{children:D.jsx(VO,{})})})]})})})})}));
 
90
  `)}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t,...n){const r=new this(t);return n.forEach(i=>r.set(i)),r}static accessor(t){const r=(this[em]=this[em]={accessors:{}}).accessors,i=this.prototype;function l(o){const s=ll(o);r[s]||(aO(i,o),r[s]=!0)}return _.isArray(t)?t.forEach(l):l(t),this}};st.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);_.reduceDescriptors(st.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(r){this[n]=r}}});_.freezeMethods(st);function ca(e,t){const n=this||so,r=t||n,i=st.from(r.headers);let l=r.data;return _.forEach(e,function(s){l=s.call(n,l,i.normalize(),t?t.status:void 0)}),i.normalize(),l}function k0(e){return!!(e&&e.__CANCEL__)}function Wi(e,t,n){G.call(this,e??"canceled",G.ERR_CANCELED,t,n),this.name="CanceledError"}_.inherits(Wi,G,{__CANCEL__:!0});function E0(e,t,n){const r=n.config.validateStatus;!n.status||!r||r(n.status)?e(n):t(new G("Request failed with status code "+n.status,[G.ERR_BAD_REQUEST,G.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}function cO(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function fO(e,t){e=e||10;const n=new Array(e),r=new Array(e);let i=0,l=0,o;return t=t!==void 0?t:1e3,function(u){const a=Date.now(),c=r[l];o||(o=a),n[i]=u,r[i]=a;let f=l,h=0;for(;f!==i;)h+=n[f++],f=f%e;if(i=(i+1)%e,i===l&&(l=(l+1)%e),a-o<t)return;const d=c&&a-c;return d?Math.round(h*1e3/d):void 0}}function dO(e,t){let n=0,r=1e3/t,i,l;const o=(a,c=Date.now())=>{n=c,i=null,l&&(clearTimeout(l),l=null),e.apply(null,a)};return[(...a)=>{const c=Date.now(),f=c-n;f>=r?o(a,c):(i=a,l||(l=setTimeout(()=>{l=null,o(i)},r-f)))},()=>i&&o(i)]}const Ds=(e,t,n=3)=>{let r=0;const i=fO(50,250);return dO(l=>{const o=l.loaded,s=l.lengthComputable?l.total:void 0,u=o-r,a=i(u),c=o<=s;r=o;const f={loaded:o,total:s,progress:s?o/s:void 0,bytes:u,rate:a||void 0,estimated:a&&s&&c?(s-o)/a:void 0,event:l,lengthComputable:s!=null,[t?"download":"upload"]:!0};e(f)},n)},tm=(e,t)=>{const n=e!=null;return[r=>t[0]({lengthComputable:n,total:e,loaded:r}),t[1]]},nm=e=>(...t)=>_.asap(()=>e(...t)),hO=$e.hasStandardBrowserEnv?((e,t)=>n=>(n=new URL(n,$e.origin),e.protocol===n.protocol&&e.host===n.host&&(t||e.port===n.port)))(new URL($e.origin),$e.navigator&&/(msie|trident)/i.test($e.navigator.userAgent)):()=>!0,pO=$e.hasStandardBrowserEnv?{write(e,t,n,r,i,l){const o=[e+"="+encodeURIComponent(t)];_.isNumber(n)&&o.push("expires="+new Date(n).toGMTString()),_.isString(r)&&o.push("path="+r),_.isString(i)&&o.push("domain="+i),l===!0&&o.push("secure"),document.cookie=o.join("; ")},read(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function mO(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function yO(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function C0(e,t,n){let r=!mO(t);return e&&(r||n==!1)?yO(e,t):t}const rm=e=>e instanceof st?{...e}:e;function jr(e,t){t=t||{};const n={};function r(a,c,f,h){return _.isPlainObject(a)&&_.isPlainObject(c)?_.merge.call({caseless:h},a,c):_.isPlainObject(c)?_.merge({},c):_.isArray(c)?c.slice():c}function i(a,c,f,h){if(_.isUndefined(c)){if(!_.isUndefined(a))return r(void 0,a,f,h)}else return r(a,c,f,h)}function l(a,c){if(!_.isUndefined(c))return r(void 0,c)}function o(a,c){if(_.isUndefined(c)){if(!_.isUndefined(a))return r(void 0,a)}else return r(void 0,c)}function s(a,c,f){if(f in t)return r(a,c);if(f in e)return r(void 0,a)}const u={url:l,method:l,data:l,baseURL:o,transformRequest:o,transformResponse:o,paramsSerializer:o,timeout:o,timeoutMessage:o,withCredentials:o,withXSRFToken:o,adapter:o,responseType:o,xsrfCookieName:o,xsrfHeaderName:o,onUploadProgress:o,onDownloadProgress:o,decompress:o,maxContentLength:o,maxBodyLength:o,beforeRedirect:o,transport:o,httpAgent:o,httpsAgent:o,cancelToken:o,socketPath:o,responseEncoding:o,validateStatus:s,headers:(a,c,f)=>i(rm(a),rm(c),f,!0)};return _.forEach(Object.keys(Object.assign({},e,t)),function(c){const f=u[c]||i,h=f(e[c],t[c],c);_.isUndefined(h)&&f!==s||(n[c]=h)}),n}const P0=e=>{const t=jr({},e);let{data:n,withXSRFToken:r,xsrfHeaderName:i,xsrfCookieName:l,headers:o,auth:s}=t;t.headers=o=st.from(o),t.url=w0(C0(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),s&&o.set("Authorization","Basic "+btoa((s.username||"")+":"+(s.password?unescape(encodeURIComponent(s.password)):"")));let u;if(_.isFormData(n)){if($e.hasStandardBrowserEnv||$e.hasStandardBrowserWebWorkerEnv)o.setContentType(void 0);else if((u=o.getContentType())!==!1){const[a,...c]=u?u.split(";").map(f=>f.trim()).filter(Boolean):[];o.setContentType([a||"multipart/form-data",...c].join("; "))}}if($e.hasStandardBrowserEnv&&(r&&_.isFunction(r)&&(r=r(t)),r||r!==!1&&hO(t.url))){const a=i&&l&&pO.read(l);a&&o.set(i,a)}return t},gO=typeof XMLHttpRequest<"u",vO=gO&&function(e){return new Promise(function(n,r){const i=P0(e);let l=i.data;const o=st.from(i.headers).normalize();let{responseType:s,onUploadProgress:u,onDownloadProgress:a}=i,c,f,h,d,m;function v(){d&&d(),m&&m(),i.cancelToken&&i.cancelToken.unsubscribe(c),i.signal&&i.signal.removeEventListener("abort",c)}let x=new XMLHttpRequest;x.open(i.method.toUpperCase(),i.url,!0),x.timeout=i.timeout;function p(){if(!x)return;const g=st.from("getAllResponseHeaders"in x&&x.getAllResponseHeaders()),P={data:!s||s==="text"||s==="json"?x.responseText:x.response,status:x.status,statusText:x.statusText,headers:g,config:e,request:x};E0(function(T){n(T),v()},function(T){r(T),v()},P),x=null}"onloadend"in x?x.onloadend=p:x.onreadystatechange=function(){!x||x.readyState!==4||x.status===0&&!(x.responseURL&&x.responseURL.indexOf("file:")===0)||setTimeout(p)},x.onabort=function(){x&&(r(new G("Request aborted",G.ECONNABORTED,e,x)),x=null)},x.onerror=function(){r(new G("Network Error",G.ERR_NETWORK,e,x)),x=null},x.ontimeout=function(){let C=i.timeout?"timeout of "+i.timeout+"ms exceeded":"timeout exceeded";const P=i.transitional||x0;i.timeoutErrorMessage&&(C=i.timeoutErrorMessage),r(new G(C,P.clarifyTimeoutError?G.ETIMEDOUT:G.ECONNABORTED,e,x)),x=null},l===void 0&&o.setContentType(null),"setRequestHeader"in x&&_.forEach(o.toJSON(),function(C,P){x.setRequestHeader(P,C)}),_.isUndefined(i.withCredentials)||(x.withCredentials=!!i.withCredentials),s&&s!=="json"&&(x.responseType=i.responseType),a&&([h,m]=Ds(a,!0),x.addEventListener("progress",h)),u&&x.upload&&([f,d]=Ds(u),x.upload.addEventListener("progress",f),x.upload.addEventListener("loadend",d)),(i.cancelToken||i.signal)&&(c=g=>{x&&(r(!g||g.type?new Wi(null,e,x):g),x.abort(),x=null)},i.cancelToken&&i.cancelToken.subscribe(c),i.signal&&(i.signal.aborted?c():i.signal.addEventListener("abort",c)));const y=cO(i.url);if(y&&$e.protocols.indexOf(y)===-1){r(new G("Unsupported protocol "+y+":",G.ERR_BAD_REQUEST,e));return}x.send(l||null)})},wO=(e,t)=>{const{length:n}=e=e?e.filter(Boolean):[];if(t||n){let r=new AbortController,i;const l=function(a){if(!i){i=!0,s();const c=a instanceof Error?a:this.reason;r.abort(c instanceof G?c:new Wi(c instanceof Error?c.message:c))}};let o=t&&setTimeout(()=>{o=null,l(new G(`timeout ${t} of ms exceeded`,G.ETIMEDOUT))},t);const s=()=>{e&&(o&&clearTimeout(o),o=null,e.forEach(a=>{a.unsubscribe?a.unsubscribe(l):a.removeEventListener("abort",l)}),e=null)};e.forEach(a=>a.addEventListener("abort",l));const{signal:u}=r;return u.unsubscribe=()=>_.asap(s),u}},xO=function*(e,t){let n=e.byteLength;if(n<t){yield e;return}let r=0,i;for(;r<n;)i=r+t,yield e.slice(r,i),r=i},SO=async function*(e,t){for await(const n of kO(e))yield*xO(n,t)},kO=async function*(e){if(e[Symbol.asyncIterator]){yield*e;return}const t=e.getReader();try{for(;;){const{done:n,value:r}=await t.read();if(n)break;yield r}}finally{await t.cancel()}},im=(e,t,n,r)=>{const i=SO(e,t);let l=0,o,s=u=>{o||(o=!0,r&&r(u))};return new ReadableStream({async pull(u){try{const{done:a,value:c}=await i.next();if(a){s(),u.close();return}let f=c.byteLength;if(n){let h=l+=f;n(h)}u.enqueue(new Uint8Array(c))}catch(a){throw s(a),a}},cancel(u){return s(u),i.return()}},{highWaterMark:2})},mu=typeof fetch=="function"&&typeof Request=="function"&&typeof Response=="function",_0=mu&&typeof ReadableStream=="function",EO=mu&&(typeof TextEncoder=="function"?(e=>t=>e.encode(t))(new TextEncoder):async e=>new Uint8Array(await new Response(e).arrayBuffer())),T0=(e,...t)=>{try{return!!e(...t)}catch{return!1}},CO=_0&&T0(()=>{let e=!1;const t=new Request($e.origin,{body:new ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t}),lm=64*1024,Uc=_0&&T0(()=>_.isReadableStream(new Response("").body)),Fs={stream:Uc&&(e=>e.body)};mu&&(e=>{["text","arrayBuffer","blob","formData","stream"].forEach(t=>{!Fs[t]&&(Fs[t]=_.isFunction(e[t])?n=>n[t]():(n,r)=>{throw new G(`Response type '${t}' is not supported`,G.ERR_NOT_SUPPORT,r)})})})(new Response);const PO=async e=>{if(e==null)return 0;if(_.isBlob(e))return e.size;if(_.isSpecCompliantForm(e))return(await new Request($e.origin,{method:"POST",body:e}).arrayBuffer()).byteLength;if(_.isArrayBufferView(e)||_.isArrayBuffer(e))return e.byteLength;if(_.isURLSearchParams(e)&&(e=e+""),_.isString(e))return(await EO(e)).byteLength},_O=async(e,t)=>{const n=_.toFiniteNumber(e.getContentLength());return n??PO(t)},TO=mu&&(async e=>{let{url:t,method:n,data:r,signal:i,cancelToken:l,timeout:o,onDownloadProgress:s,onUploadProgress:u,responseType:a,headers:c,withCredentials:f="same-origin",fetchOptions:h}=P0(e);a=a?(a+"").toLowerCase():"text";let d=wO([i,l&&l.toAbortSignal()],o),m;const v=d&&d.unsubscribe&&(()=>{d.unsubscribe()});let x;try{if(u&&CO&&n!=="get"&&n!=="head"&&(x=await _O(c,r))!==0){let P=new Request(t,{method:"POST",body:r,duplex:"half"}),E;if(_.isFormData(r)&&(E=P.headers.get("content-type"))&&c.setContentType(E),P.body){const[T,R]=tm(x,Ds(nm(u)));r=im(P.body,lm,T,R)}}_.isString(f)||(f=f?"include":"omit");const p="credentials"in Request.prototype;m=new Request(t,{...h,signal:d,method:n.toUpperCase(),headers:c.normalize().toJSON(),body:r,duplex:"half",credentials:p?f:void 0});let y=await fetch(m);const g=Uc&&(a==="stream"||a==="response");if(Uc&&(s||g&&v)){const P={};["status","statusText","headers"].forEach(L=>{P[L]=y[L]});const E=_.toFiniteNumber(y.headers.get("content-length")),[T,R]=s&&tm(E,Ds(nm(s),!0))||[];y=new Response(im(y.body,lm,T,()=>{R&&R(),v&&v()}),P)}a=a||"text";let C=await Fs[_.findKey(Fs,a)||"text"](y,e);return!g&&v&&v(),await new Promise((P,E)=>{E0(P,E,{data:C,headers:st.from(y.headers),status:y.status,statusText:y.statusText,config:e,request:m})})}catch(p){throw v&&v(),p&&p.name==="TypeError"&&/fetch/i.test(p.message)?Object.assign(new G("Network Error",G.ERR_NETWORK,e,m),{cause:p.cause||p}):G.from(p,p&&p.code,e,m)}}),$c={http:$R,xhr:vO,fetch:TO};_.forEach($c,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});const om=e=>`- ${e}`,RO=e=>_.isFunction(e)||e===null||e===!1,R0={getAdapter:e=>{e=_.isArray(e)?e:[e];const{length:t}=e;let n,r;const i={};for(let l=0;l<t;l++){n=e[l];let o;if(r=n,!RO(n)&&(r=$c[(o=String(n)).toLowerCase()],r===void 0))throw new G(`Unknown adapter '${o}'`);if(r)break;i[o||"#"+l]=r}if(!r){const l=Object.entries(i).map(([s,u])=>`adapter ${s} `+(u===!1?"is not supported by the environment":"is not available in the build"));let o=t?l.length>1?`since :
91
  `+l.map(om).join(`
92
  `):" "+om(l[0]):"as no adapter specified";throw new G("There is no suitable adapter to dispatch the request "+o,"ERR_NOT_SUPPORT")}return r},adapters:$c};function fa(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new Wi(null,e)}function sm(e){return fa(e),e.headers=st.from(e.headers),e.data=ca.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),R0.getAdapter(e.adapter||so.adapter)(e).then(function(r){return fa(e),r.data=ca.call(e,e.transformResponse,r),r.headers=st.from(r.headers),r},function(r){return k0(r)||(fa(e),r&&r.response&&(r.response.data=ca.call(e,e.transformResponse,r.response),r.response.headers=st.from(r.response.headers))),Promise.reject(r)})}const O0="1.8.4",yu={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{yu[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});const um={};yu.transitional=function(t,n,r){function i(l,o){return"[Axios v"+O0+"] Transitional option '"+l+"'"+o+(r?". "+r:"")}return(l,o,s)=>{if(t===!1)throw new G(i(o," has been removed"+(n?" in "+n:"")),G.ERR_DEPRECATED);return n&&!um[o]&&(um[o]=!0,console.warn(i(o," has been deprecated since v"+n+" and will be removed in the near future"))),t?t(l,o,s):!0}};yu.spelling=function(t){return(n,r)=>(console.warn(`${r} is likely a misspelling of ${t}`),!0)};function OO(e,t,n){if(typeof e!="object")throw new G("options must be an object",G.ERR_BAD_OPTION_VALUE);const r=Object.keys(e);let i=r.length;for(;i-- >0;){const l=r[i],o=t[l];if(o){const s=e[l],u=s===void 0||o(s,l,e);if(u!==!0)throw new G("option "+l+" must be "+u,G.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new G("Unknown option "+l,G.ERR_BAD_OPTION)}}const Jo={assertOptions:OO,validators:yu},Gt=Jo.validators;let Or=class{constructor(t){this.defaults=t,this.interceptors={request:new Zp,response:new Zp}}async request(t,n){try{return await this._request(t,n)}catch(r){if(r instanceof Error){let i={};Error.captureStackTrace?Error.captureStackTrace(i):i=new Error;const l=i.stack?i.stack.replace(/^.+\n/,""):"";try{r.stack?l&&!String(r.stack).endsWith(l.replace(/^.+\n.+\n/,""))&&(r.stack+=`
93
+ `+l):r.stack=l}catch{}}throw r}}_request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=jr(this.defaults,n);const{transitional:r,paramsSerializer:i,headers:l}=n;r!==void 0&&Jo.assertOptions(r,{silentJSONParsing:Gt.transitional(Gt.boolean),forcedJSONParsing:Gt.transitional(Gt.boolean),clarifyTimeoutError:Gt.transitional(Gt.boolean)},!1),i!=null&&(_.isFunction(i)?n.paramsSerializer={serialize:i}:Jo.assertOptions(i,{encode:Gt.function,serialize:Gt.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),Jo.assertOptions(n,{baseUrl:Gt.spelling("baseURL"),withXsrfToken:Gt.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let o=l&&_.merge(l.common,l[n.method]);l&&_.forEach(["delete","get","head","post","put","patch","common"],m=>{delete l[m]}),n.headers=st.concat(o,l);const s=[];let u=!0;this.interceptors.request.forEach(function(v){typeof v.runWhen=="function"&&v.runWhen(n)===!1||(u=u&&v.synchronous,s.unshift(v.fulfilled,v.rejected))});const a=[];this.interceptors.response.forEach(function(v){a.push(v.fulfilled,v.rejected)});let c,f=0,h;if(!u){const m=[sm.bind(this),void 0];for(m.unshift.apply(m,s),m.push.apply(m,a),h=m.length,c=Promise.resolve(n);f<h;)c=c.then(m[f++],m[f++]);return c}h=s.length;let d=n;for(f=0;f<h;){const m=s[f++],v=s[f++];try{d=m(d)}catch(x){v.call(this,x);break}}try{c=sm.call(this,d)}catch(m){return Promise.reject(m)}for(f=0,h=a.length;f<h;)c=c.then(a[f++],a[f++]);return c}getUri(t){t=jr(this.defaults,t);const n=C0(t.baseURL,t.url,t.allowAbsoluteUrls);return w0(n,t.params,t.paramsSerializer)}};_.forEach(["delete","get","head","options"],function(t){Or.prototype[t]=function(n,r){return this.request(jr(r||{},{method:t,url:n,data:(r||{}).data}))}});_.forEach(["post","put","patch"],function(t){function n(r){return function(l,o,s){return this.request(jr(s||{},{method:t,headers:r?{"Content-Type":"multipart/form-data"}:{},url:l,data:o}))}}Or.prototype[t]=n(),Or.prototype[t+"Form"]=n(!0)});let bO=class b0{constructor(t){if(typeof t!="function")throw new TypeError("executor must be a function.");let n;this.promise=new Promise(function(l){n=l});const r=this;this.promise.then(i=>{if(!r._listeners)return;let l=r._listeners.length;for(;l-- >0;)r._listeners[l](i);r._listeners=null}),this.promise.then=i=>{let l;const o=new Promise(s=>{r.subscribe(s),l=s}).then(i);return o.cancel=function(){r.unsubscribe(l)},o},t(function(l,o,s){r.reason||(r.reason=new Wi(l,o,s),n(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;const n=this._listeners.indexOf(t);n!==-1&&this._listeners.splice(n,1)}toAbortSignal(){const t=new AbortController,n=r=>{t.abort(r)};return this.subscribe(n),t.signal.unsubscribe=()=>this.unsubscribe(n),t.signal}static source(){let t;return{token:new b0(function(i){t=i}),cancel:t}}};function NO(e){return function(n){return e.apply(null,n)}}function IO(e){return _.isObject(e)&&e.isAxiosError===!0}const Hc={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(Hc).forEach(([e,t])=>{Hc[t]=e});function N0(e){const t=new Or(e),n=u0(Or.prototype.request,t);return _.extend(n,Or.prototype,t,{allOwnKeys:!0}),_.extend(n,t,null,{allOwnKeys:!0}),n.create=function(i){return N0(jr(e,i))},n}const Se=N0(so);Se.Axios=Or;Se.CanceledError=Wi;Se.CancelToken=bO;Se.isCancel=k0;Se.VERSION=O0;Se.toFormData=pu;Se.AxiosError=G;Se.Cancel=Se.CanceledError;Se.all=function(t){return Promise.all(t)};Se.spread=NO;Se.isAxiosError=IO;Se.mergeConfig=jr;Se.AxiosHeaders=st;Se.formToJSON=e=>S0(_.isHTMLForm(e)?new FormData(e):e);Se.getAdapter=R0.getAdapter;Se.HttpStatusCode=Hc;Se.default=Se;const{Axios:YO,AxiosError:ZO,CanceledError:e2,isCancel:t2,CancelToken:n2,VERSION:r2,all:i2,Cancel:l2,isAxiosError:o2,spread:s2,toFormData:u2,AxiosHeaders:a2,HttpStatusCode:c2,formToJSON:f2,getAdapter:d2,mergeConfig:h2}=Se,I0="https://muryshev-generic-chatbot-backend.hf.space",pd=Se.create({baseURL:`${I0}`,timeout:6e5}),AO=e=>{const t=localStorage.getItem("authToken");return t&&(e.headers.Authorization=`Bearer ${t}`),e},LO=e=>e,DO=async e=>{var n;const t=e.message;return t.includes("409")&&(console.log("409"),D0.invalidateQueries({queryKey:["processing"]})),((n=e.response)==null?void 0:n.status)===401?(localStorage.removeItem("authToken"),window.location.href="/login"):!Se.isCancel(e)&&!t.includes("409")&&alert(`${t} Произошла ошибка`),Promise.reject(e)};pd.interceptors.request.use(AO);pd.interceptors.response.use(LO,DO);const A0=async({url:e,signal:t,...n},r=I0)=>{var o,s,u;const i=new AbortController,l=t||i.signal;try{console.log("Попытка отправки запроса");const a=await pd({url:`${r}${e}`,signal:l,...n});return console.log("Запрос отправлен, результат:",a),{data:a.data,headers:a.headers}}catch(a){if(Se.isCancel(a))return console.log("Запрос отменен"),{error:{status:"Cancelled",data:"Request was cancelled",notCauseError:!0}};const c=a;return console.log("Ошибка при отправке запроса"),{error:{status:(o=c.response)==null?void 0:o.status,data:(s=c.response)==null?void 0:s.data,headers:(u=c.response)==null?void 0:u.headers}}}finally{t||i.abort()}},FO=async e=>{const t=await A0({url:"/auth/login",method:"post",data:e});if("error"in t)throw new Error(`Ошибка авторизации: ${t.error.status}`);return t.data},zO=async()=>{const e=localStorage.getItem("authToken");return"current_user"in(await A0({url:"/auth/checktoken",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},method:"post"})).data},L0=b.createContext(void 0),MO=({children:e})=>{const[t,n]=b.useState(()=>!!localStorage.getItem("authToken")),r=rR({mutationFn:o=>FO(o),onSuccess:o=>{localStorage.setItem("authToken",o.access_token),n(!0)},onError:o=>{console.error("Login Error:",o)}}),i=async o=>{await r.mutateAsync(o)},l=()=>{localStorage.removeItem("authToken"),n(!1)};return D.jsx(L0.Provider,{value:{isAuthenticated:t,login:i,logout:l,isLoading:r.isPending,error:r.error},children:e})},gu=()=>{const e=b.useContext(L0);if(!e)throw new Error("useAuth must be used within an AuthProvider");return e},jO=()=>{const{logout:e}=gu();return D.jsx("button",{className:"logout-button",onClick:e,children:"Выйти"})},BO=({isVisible:e,toggleSidebar:t,sidebarRef:n})=>{const r=qg(),i=Es(m=>m.chat.chats),l=Es(m=>m.chat.activeChatId),[o,s]=b.useState(null),[u,a]=b.useState(""),c=()=>{const m={id:Date.now().toString(),name:`Чат ${i.length+1}`,history:[]};r(fT(m))},f=m=>{var v;o===m&&u.trim()?(r(hT({chatId:m,newName:u})),s(null),a("")):(s(m),a(((v=i.find(x=>x.id===m))==null?void 0:v.name)||""))},h=m=>{r(dT(m))},d=()=>{console.log("Hide button clicked"),t()};return D.jsxs("div",{ref:n,className:`chat-sidebar ${e?"visible":""}`,children:[D.jsxs("div",{className:"sidebar-header",children:[D.jsx("button",{onClick:c,children:"Новый чат"}),D.jsx("button",{className:"icon-button toggle",onClick:d,title:"Скрыть меню",children:D.jsx(kT,{})})]}),D.jsx("ul",{children:i.map(m=>D.jsxs("li",{className:m.id===l?"active":"",onClick:()=>r(Qv(m.id)),children:[o===m.id?D.jsx("input",{value:u,onChange:v=>a(v.target.value),onBlur:()=>f(m.id),onKeyDown:v=>v.key==="Enter"&&f(m.id),autoFocus:!0,className:"chat-input"}):D.jsx("span",{className:"chat-name",children:m.name}),D.jsxs("div",{className:"chat-actions",children:[D.jsx("button",{className:"icon-button rename",onClick:v=>{v.stopPropagation(),f(m.id)},title:"Переименовать",children:D.jsx(ET,{})}),D.jsx("button",{className:"icon-button delete",onClick:v=>{v.stopPropagation(),h(m.id)},title:"Удалить",children:D.jsx(CT,{})})]})]},m.id))}),D.jsx("div",{className:"sidebar-header",children:D.jsx(jO,{})})]})};class UO{constructor(){this.dbName="ChatDB",this.storeName="chats",this.db=null}async initDB(){return this.db?this.db:new Promise((t,n)=>{const r=indexedDB.open(this.dbName,1);r.onupgradeneeded=()=>{r.result.createObjectStore(this.storeName,{keyPath:"id"})},r.onsuccess=()=>{this.db=r.result,t(this.db)},r.onerror=()=>n(r.error)})}async getChats(){const t=await this.initDB();return new Promise((n,r)=>{const o=t.transaction(this.storeName,"readonly").objectStore(this.storeName).getAll();o.onsuccess=()=>n(o.result),o.onerror=()=>r(o.error)})}async saveChat(t){const n=await this.initDB();return new Promise((r,i)=>{const s=n.transaction(this.storeName,"readwrite").objectStore(this.storeName).put(t);s.onsuccess=()=>r(),s.onerror=()=>i(s.error)})}async deleteChat(t){const n=await this.initDB();return new Promise((r,i)=>{const s=n.transaction(this.storeName,"readwrite").objectStore(this.storeName).delete(t);s.onsuccess=()=>r(),s.onerror=()=>i(s.error)})}async renameChat(t,n){const i=(await this.getChats()).find(l=>l.id===t);i&&(i.name=n,await this.saveChat(i))}}const Ao=new UO,$O=()=>{const[e,t]=b.useState(""),[n,r]=b.useState(null),[i,l]=b.useState(!1),[o,s]=b.useState(!1),[u,a]=b.useState(window.innerWidth>1800),[c,f]=b.useState(!1),h=Es(N=>N.chat.chats),d=Es(N=>N.chat.activeChatId),m=h.find(N=>N.id===d),v=(m==null?void 0:m.history)||[],x=qg(),p=b.useRef(null),y=b.useRef(null),{logout:g,isAuthenticated:C}=gu(),P=Uf(),E=b.useRef(!1),T=b.useRef(null);b.useEffect(()=>{const N=$=>{const X=document.getElementsByClassName("sidebar-toggle-close").length>0?document.getElementsByClassName("sidebar-toggle-close")[0].contains($.target):!1;u&&T.current&&!T.current.contains($.target)&&!X&&a(!1)};return document.addEventListener("mousedown",N),()=>{document.removeEventListener("mousedown",N)}},[u]);const R=()=>{console.log("Toggling sidebar, current state:",u),a(N=>!N)},L=()=>{const N=document.querySelector(".messages");if(N){const $=N.getBoundingClientRect(),X=window.innerHeight;return $.bottom<=X+10}return!0},j=()=>{p.current&&(p.current.abort(),l(!1),s(!1),y.current=null,console.log("Generation stopped by user"))};b.useEffect(()=>{(async()=>{try{console.log("Loading chats from storage...");const $=await Ao.getChats(),X=$.length>0?$:[{id:Date.now().toString(),name:"Чат 1",history:[]}];x(sT(X)),f(!0),console.log("Chats loaded:",X)}catch($){console.error("Failed to load chats:",$),r("Не удалось загрузить чаты"),f(!0)}})()},[x]),b.useEffect(()=>{(async()=>{if(c)try{const X=(await Ao.getChats()).filter(Q=>!h.some(pe=>pe.id===Q.id));for(const Q of X)await Ao.deleteChat(Q.id),console.log("Deleted chat from storage:",Q.id);for(const Q of h)await Ao.saveChat(Q)}catch($){console.error("Failed to sync chats with storage:",$),r("Ошибка синхронизации чатов")}})()},[h,c]),b.useEffect(()=>{if(!C||!c||E.current){console.log("Waiting for initialization or already attempted resend...",{isAuthenticated:C,isChatsLoaded:c,hasAttemptedResend:E.current});return}const N=localStorage.getItem("pendingMessage");if(N)try{const{text:$,chatId:X}=JSON.parse(N);console.log("Pending message found:",{text:$,chatId:X}),h.some(Q=>Q.id===X)?(console.log("Resending pending message to chat:",X),x(Qv(X)),M($),localStorage.removeItem("pendingMessage")):(console.log("Chat not found, discarding pending message"),localStorage.removeItem("pendingMessage"),r("Чат для отложенного сообщения не найден"))}catch($){console.error("Failed to parse pending message:",$),localStorage.removeItem("pendingMessage"),r("Ошибка обработки отложенного сообщения")}finally{E.current=!0}else console.log("No pending message found"),E.current=!0},[C,c,h]),b.useEffect(()=>{if(n){const N=setTimeout(()=>r(null),5e3);return()=>clearTimeout(N)}},[n]);const M=async N=>{var pe;if(!N.trim()||i||!C||!d)return;t(""),l(!0),s(!1),console.log("Start request - isLoading:",i,"isGeneratingTokens:",o);const $="https://muryshev-generic-chatbot-backend.hf.space/llm/chat/stream",X=localStorage.getItem("authToken"),Q={role:"user",content:N,searchResults:"",searchEntities:[]};x(uT({chatId:d,message:Q})),y.current=d;try{const le=new AbortController;p.current=le;const z=setTimeout(()=>{le.abort(),r("Сервер временно недоступен")},6e4),H=await fetch($,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${X}`},body:JSON.stringify({history:[...v,Q]}),signal:le.signal});if(clearTimeout(z),!H.ok){if(H.status===401){console.log("Saving pending message:",N,"for chat:",d),localStorage.setItem("pendingMessage",JSON.stringify({text:N,chatId:d})),x(aT(d)),r("Сессия истекла. Пожалуйста, войдите заново."),g(),P("/login"),l(!1),y.current=null;return}throw new Error(`HTTP error! status: ${H.status}`)}const w=(pe=H.body)==null?void 0:pe.getReader();if(!w)throw new Error("Response body is not readable");const ee=new TextDecoder;let ie="",k="",Z=[...v,Q];for(;;){const{done:at,value:ae}=await w.read();if(at)break;ie+=ee.decode(ae,{stream:!0});const Qe=ie.split(`
94
 
95
  `);for(let ct=0;ct<Qe.length-1;ct++){const Et=Qe[ct].trim();if(Et.startsWith("data: ")){const Hr=Et.slice(6);try{const ze=JSON.parse(Hr),Vr=y.current;if(ze.event==="done"){x(No({chatId:Vr,history:Z})),l(!1),y.current=null,console.log("Done - isLoading:",i,"isGeneratingTokens:",o);break}else if(ze.event==="error"){r("Произошла непредвиденная ошибка во время генерации ответа. Попробуйте повторить запрос."),l(!1),y.current=null,console.error("SSE error:",ze.data);break}else if(ze.event==="debug")console.log("Debug data:",ze.data);else if(ze.event==="search_results")l(!0),Z=Z.map((Lt,un)=>un===Z.length-1&&Lt.role==="user"?{...Lt,searchResults:ze.data.text,searchEntities:ze.data.ids}:Lt),x(No({chatId:Vr,history:Z})),console.log("After search_results - isLoading:",i,"isGeneratingTokens:",o);else if(ze.event==="reasoning")console.log("reasoning"),l(!0),Z=Z.map((Lt,un)=>un===Z.length-1&&Lt.role==="user"?{...Lt,reasoning:ze.data.text}:Lt),x(No({chatId:Vr,history:Z}));else if(ze.event==="token"){o||(s(!0),console.log("Before first token - isLoading:",i,"isGeneratingTokens:",o)),k+=ze.data;const Lt=Z.findLastIndex(an=>an.role==="user"),un=Z.findIndex((an,Qr)=>an.role==="assistant"&&Qr>Lt);un>=0?Z=Z.map((an,Qr)=>Qr===un?{...an,content:k}:an):Z=[...Z,{role:"assistant",content:k,searchResults:"",searchEntities:[]}],x(No({chatId:Vr,history:Z}))}}catch(ze){console.error("Failed to parse SSE data:",ze),r("Ошибка обработки данных от сервера")}}}ie=Qe[Qe.length-1];const At=document.querySelector(".messages");if(At&&y.current===d){const ct=At.querySelectorAll("div"),Et=ct[ct.length-1];Et&&L()&&setTimeout(()=>{Et.scrollIntoView({behavior:"smooth",block:"start"})},0)}}}catch(le){console.error("Stream error:",le),l(!1),s(!1),y.current=null,le instanceof DOMException&&le.name==="AbortError"&&!p.current?r("Сервер временно недоступен"):le instanceof DOMException&&le.name==="AbortError"||r("Произошла ошибка при запросе")}finally{p.current=null}};return b.useEffect(()=>{const N=$=>{$.ctrlKey&&$.shiftKey&&$.key==="F8"&&($.preventDefault(),Iv("expert_mode")==="true"?(S_("expert_mode"),console.log("Expert mode disabled")):(x_("expert_mode","true"),console.log("Expert mode enabled")))};return window.addEventListener("keydown",N),()=>{window.removeEventListener("keydown",N)}},[]),D.jsx("div",{className:"app-container",children:D.jsxs("div",{className:"chat-layout",children:[D.jsx(BO,{isVisible:u,toggleSidebar:R,sidebarRef:T}),D.jsx("div",{className:"sidebar-toggle-wrapper",children:u?D.jsx("button",{className:"sidebar-toggle-close",onClick:R,title:"Скрыть меню",children:D.jsx(Bp,{})}):D.jsx("button",{className:"sidebar-toggle-open",onClick:R,title:"Показать меню",children:D.jsx(Bp,{})})}),D.jsxs("div",{className:"chat-content",children:[n&&D.jsx("div",{className:"error-toast",children:n}),D.jsxs("div",{className:"messages",children:[v.map((N,$)=>D.jsx(Tp,{role:N.role,content:N.content,searchResults:N.searchResults,reasoning:N.reasoning},$)),i&&!o&&y.current===d&&D.jsx(Tp,{role:"assistant",content:"",isLoading:!0,searchResults:""},"loading")]}),D.jsxs("div",{className:"input-area",children:[D.jsx(k_,{onSend:M,text:e,setText:t}),D.jsxs("div",{className:"buttons",children:[i?D.jsx("button",{className:"stop-button",onClick:j,children:"Остановить"}):D.jsx("button",{className:"send-button",onClick:()=>M(e),children:"Отправить"}),D.jsx("a",{href:"#",className:"clear-link",onClick:N=>{N.preventDefault(),x(cT(d))},children:"Очистить"})]})]})]})]})})},HO=q_({reducer:{chat:pT}}),VO=()=>D.jsx(bS,{store:HO,children:D.jsx($O,{})}),QO=()=>{const[e,t]=b.useState(""),[n,r]=b.useState(""),{login:i,isLoading:l,error:o}=gu(),s=Uf(),u=async a=>{a.preventDefault();try{await i({username:e,password:n}),s("/",{replace:!0})}catch{}};return D.jsx("div",{className:"login-page",children:D.jsxs("form",{onSubmit:u,children:[D.jsxs("div",{children:[D.jsx("label",{children:"Логин:"}),D.jsx("input",{type:"text",value:e,onChange:a=>t(a.target.value)})]}),D.jsxs("div",{children:[D.jsx("label",{children:"Пароль:"}),D.jsx("input",{type:"password",value:n,onChange:a=>r(a.target.value)})]}),o&&D.jsx("p",{className:"error",children:"Неверный логин или пароль"}),D.jsx("button",{type:"submit",disabled:l,children:l?"Вход...":"Войти"})]})})},WO=!1,qO=({children:e,checkInterval:t=WO})=>{const{isAuthenticated:n,logout:r}=gu(),i=Uf(),{isLoading:l,data:o,error:s}=nR({queryKey:["tokenValid"],queryFn:zO,enabled:n,refetchInterval:t,refetchOnWindowFocus:!1});return b.useEffect(()=>{(s||!n||o===!1)&&(console.error("Token validation error:",s),r(),i("/login",{replace:!0}))},[n,o,s,r,i]),l?D.jsx("div",{children:"Loading..."}):s||!n||o===!1?null:D.jsx(D.Fragment,{children:e})},D0=new jT;da.createRoot(document.getElementById("root")).render(D.jsx(wn.StrictMode,{children:D.jsx(VT,{client:D0,children:D.jsx(MO,{children:D.jsx(cS,{children:D.jsxs(sS,{children:[D.jsx(oc,{path:"/login",element:D.jsx(QO,{})}),D.jsx(oc,{path:"/",element:D.jsx(qO,{children:D.jsx(VO,{})})})]})})})})}));
dist/index.html CHANGED
@@ -4,7 +4,7 @@
4
  <meta charset="UTF-8" />
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
  <title>Чат бот</title>
7
- <script type="module" crossorigin src="/assets/index-CQM8MSM2.js"></script>
8
  <link rel="stylesheet" crossorigin href="/assets/index-B6WK63XH.css">
9
  </head>
10
  <body>
 
4
  <meta charset="UTF-8" />
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
  <title>Чат бот</title>
7
+ <script type="module" crossorigin src="/assets/index-DE9FQJMi.js"></script>
8
  <link rel="stylesheet" crossorigin href="/assets/index-B6WK63XH.css">
9
  </head>
10
  <body>