bariweb-widget 0.1.11 → 0.1.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bariweb.iife.js +176 -116
- package/dist/bariweb.js +623 -445
- package/package.json +1 -1
- package/dist/types/components/accordion/accordion-item.d.ts +0 -8
- package/dist/types/components/accordion/accordion.d.ts +0 -1
- package/dist/types/components/accordion/accordion.styles.d.ts +0 -1
- package/dist/types/components/button/button.d.ts +0 -8
- package/dist/types/components/button/button.styles.d.ts +0 -1
- package/dist/types/components/card/card.d.ts +0 -6
- package/dist/types/components/card/card.styles.d.ts +0 -1
- package/dist/types/controllers/a11y.controller.d.ts +0 -50
- package/dist/types/controllers/ai-a11y.controller.d.ts +0 -17
- package/dist/types/controllers/chat.controller.d.ts +0 -100
- package/dist/types/controllers/scanner.controller.d.ts +0 -1
- package/dist/types/controllers/tts.controller.d.ts +0 -11
- package/dist/types/index.d.ts +0 -1
- package/dist/types/lib/AdminUI.d.ts +0 -8
- package/dist/types/lib/Fingerprint.d.ts +0 -44
- package/dist/types/lib/Watcher.d.ts +0 -62
- package/dist/types/lib/api/client/client.gen.d.ts +0 -2
- package/dist/types/lib/api/client/index.d.ts +0 -8
- package/dist/types/lib/api/client/types.gen.d.ts +0 -117
- package/dist/types/lib/api/client/utils.gen.d.ts +0 -33
- package/dist/types/lib/api/client.gen.d.ts +0 -12
- package/dist/types/lib/api/core/auth.gen.d.ts +0 -18
- package/dist/types/lib/api/core/bodySerializer.gen.d.ts +0 -25
- package/dist/types/lib/api/core/params.gen.d.ts +0 -43
- package/dist/types/lib/api/core/pathSerializer.gen.d.ts +0 -33
- package/dist/types/lib/api/core/queryKeySerializer.gen.d.ts +0 -18
- package/dist/types/lib/api/core/serverSentEvents.gen.d.ts +0 -71
- package/dist/types/lib/api/core/types.gen.d.ts +0 -78
- package/dist/types/lib/api/core/utils.gen.d.ts +0 -19
- package/dist/types/lib/api/index.d.ts +0 -2
- package/dist/types/lib/api/sdk.gen.d.ts +0 -118
- package/dist/types/lib/api/types.gen.d.ts +0 -694
- package/dist/types/lib/icons.d.ts +0 -28
- package/dist/types/widget.d.ts +0 -67
- package/dist/types/widget.styles.d.ts +0 -1
package/dist/bariweb.iife.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
(function(){var e=Object.defineProperty,t=(e,t)=>()=>(e&&(t=e(e=0)),t),n=(t,n)=>{let r={};for(var i in t)e(r,i,{get:t[i],enumerable:!0});return n||e(r,Symbol.toStringTag,{value:`Module`}),r},r={bodySerializer:e=>JSON.stringify(e,(e,t)=>typeof t==`bigint`?t.toString():t)};Object.entries({$body_:`body`,$headers_:`headers`,$path_:`path`,$query_:`query`});var i=({onRequest:e,onSseError:t,onSseEvent:n,responseTransformer:r,responseValidator:i,sseDefaultRetryDelay:a,sseMaxRetryAttempts:o,sseMaxRetryDelay:s,sseSleepFn:c,url:l,...u})=>{let d,f=c??(e=>new Promise(t=>setTimeout(t,e)));return{stream:async function*(){let c=a??3e3,p=0,m=u.signal??new AbortController().signal;for(;!m.aborted;){p++;let a=u.headers instanceof Headers?u.headers:new Headers(u.headers);d!==void 0&&a.set(`Last-Event-ID`,d);try{let t={redirect:`follow`,...u,body:u.serializedBody,headers:a,signal:m},o=new Request(l,t);e&&(o=await e(l,t));let s=await(u.fetch??globalThis.fetch)(o);if(!s.ok)throw Error(`SSE failed: ${s.status} ${s.statusText}`);if(!s.body)throw Error(`No body in SSE response`);let f=s.body.pipeThrough(new TextDecoderStream).getReader(),p=``,
|
|
1
|
+
(function(){var e=Object.defineProperty,t=(e,t)=>()=>(e&&(t=e(e=0)),t),n=(t,n)=>{let r={};for(var i in t)e(r,i,{get:t[i],enumerable:!0});return n||e(r,Symbol.toStringTag,{value:`Module`}),r},r={bodySerializer:e=>JSON.stringify(e,(e,t)=>typeof t==`bigint`?t.toString():t)};Object.entries({$body_:`body`,$headers_:`headers`,$path_:`path`,$query_:`query`});var i=({onRequest:e,onSseError:t,onSseEvent:n,responseTransformer:r,responseValidator:i,sseDefaultRetryDelay:a,sseMaxRetryAttempts:o,sseMaxRetryDelay:s,sseSleepFn:c,url:l,...u})=>{let d,f=c??(e=>new Promise(t=>setTimeout(t,e)));return{stream:async function*(){let c=a??3e3,p=0,m=u.signal??new AbortController().signal;for(;!m.aborted;){p++;let a=u.headers instanceof Headers?u.headers:new Headers(u.headers);d!==void 0&&a.set(`Last-Event-ID`,d);try{let t={redirect:`follow`,...u,body:u.serializedBody,headers:a,signal:m},o=new Request(l,t);e&&(o=await e(l,t));let s=await(u.fetch??globalThis.fetch)(o);if(!s.ok)throw Error(`SSE failed: ${s.status} ${s.statusText}`);if(!s.body)throw Error(`No body in SSE response`);let f=s.body.pipeThrough(new TextDecoderStream).getReader(),p=``,h=()=>{try{f.cancel()}catch{}};m.addEventListener(`abort`,h);try{for(;;){let{done:e,value:t}=await f.read();if(e)break;p+=t,p=p.replace(/\r\n/g,`
|
|
2
2
|
`).replace(/\r/g,`
|
|
3
3
|
`);let a=p.split(`
|
|
4
4
|
|
|
5
5
|
`);p=a.pop()??``;for(let e of a){let t=e.split(`
|
|
6
6
|
`),a=[],o;for(let e of t)if(e.startsWith(`data:`))a.push(e.replace(/^data:\s*/,``));else if(e.startsWith(`event:`))o=e.replace(/^event:\s*/,``);else if(e.startsWith(`id:`))d=e.replace(/^id:\s*/,``);else if(e.startsWith(`retry:`)){let t=Number.parseInt(e.replace(/^retry:\s*/,``),10);Number.isNaN(t)||(c=t)}let s,l=!1;if(a.length){let e=a.join(`
|
|
7
|
-
`);try{s=JSON.parse(e),l=!0}catch{s=e}}l&&(i&&await i(s),r&&(s=await r(s))),n?.({data:s,event:o,id:d,retry:c}),a.length&&(yield s)}}}finally{m.removeEventListener(`abort`,ee),f.releaseLock()}break}catch(e){if(t?.(e),o!==void 0&&p>=o)break;await f(Math.min(c*2**(p-1),s??3e4))}}}()}},a=e=>{switch(e){case`label`:return`.`;case`matrix`:return`;`;case`simple`:return`,`;default:return`&`}},o=e=>{switch(e){case`form`:return`,`;case`pipeDelimited`:return`|`;case`spaceDelimited`:return`%20`;default:return`,`}},s=e=>{switch(e){case`label`:return`.`;case`matrix`:return`;`;case`simple`:return`,`;default:return`&`}},c=({allowReserved:e,explode:t,name:n,style:r,value:i})=>{if(!t){let t=(e?i:i.map(e=>encodeURIComponent(e))).join(o(r));switch(r){case`label`:return`.${t}`;case`matrix`:return`;${n}=${t}`;case`simple`:return t;default:return`${n}=${t}`}}let s=a(r),c=i.map(t=>r===`label`||r===`simple`?e?t:encodeURIComponent(t):l({allowReserved:e,name:n,value:t})).join(s);return r===`label`||r===`matrix`?s+c:c},l=({allowReserved:e,name:t,value:n})=>{if(n==null)return``;if(typeof n==`object`)throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${t}=${e?n:encodeURIComponent(n)}`},u=({allowReserved:e,explode:t,name:n,style:r,value:i,valueOnly:a})=>{if(i instanceof Date)return a?i.toISOString():`${n}=${i.toISOString()}`;if(r!==`deepObject`&&!t){let t=[];Object.entries(i).forEach(([n,r])=>{t=[...t,n,e?r:encodeURIComponent(r)]});let a=t.join(`,`);switch(r){case`form`:return`${n}=${a}`;case`label`:return`.${a}`;case`matrix`:return`;${n}=${a}`;default:return a}}let o=s(r),c=Object.entries(i).map(([t,i])=>l({allowReserved:e,name:r===`deepObject`?`${n}[${t}]`:t,value:i})).join(o);return r===`label`||r===`matrix`?o+c:c},d=/\{[^{}]+\}/g,f=({path:e,url:t})=>{let n=t,r=t.match(d);if(r)for(let t of r){let r=!1,i=t.substring(1,t.length-1),a=`simple`;i.endsWith(`*`)&&(r=!0,i=i.substring(0,i.length-1)),i.startsWith(`.`)?(i=i.substring(1),a=`label`):i.startsWith(`;`)&&(i=i.substring(1),a=`matrix`);let o=e[i];if(o==null)continue;if(Array.isArray(o)){n=n.replace(t,c({explode:r,name:i,style:a,value:o}));continue}if(typeof o==`object`){n=n.replace(t,u({explode:r,name:i,style:a,value:o,valueOnly:!0}));continue}if(a===`matrix`){n=n.replace(t,`;${l({name:i,value:o})}`);continue}let s=encodeURIComponent(a===`label`?`.${o}`:o);n=n.replace(t,s)}return n},p=({baseUrl:e,path:t,query:n,querySerializer:r,url:i})=>{let a=i.startsWith(`/`)?i:`/${i}`,o=(e??``)+a;t&&(o=f({path:t,url:o}));let s=n?r(n):``;return s.startsWith(`?`)&&(s=s.substring(1)),s&&(o+=`?${s}`),o};function m(e){let t=e.body!==void 0;if(t&&e.bodySerializer)return`serializedBody`in e?e.serializedBody!==void 0&&e.serializedBody!==``?e.serializedBody:null:e.body===``?null:e.body;if(t)return e.body}var ee=async(e,t)=>{let n=typeof t==`function`?await t(e):t;if(n)return e.scheme===`bearer`?`Bearer ${n}`:e.scheme===`basic`?`Basic ${btoa(n)}`:n},te=({parameters:e={},...t}={})=>n=>{let r=[];if(n&&typeof n==`object`)for(let i in n){let a=n[i];if(a==null)continue;let o=e[i]||t;if(Array.isArray(a)){let e=c({allowReserved:o.allowReserved,explode:!0,name:i,style:`form`,value:a,...o.array});e&&r.push(e)}else if(typeof a==`object`){let e=u({allowReserved:o.allowReserved,explode:!0,name:i,style:`deepObject`,value:a,...o.object});e&&r.push(e)}else{let e=l({allowReserved:o.allowReserved,name:i,value:a});e&&r.push(e)}}return r.join(`&`)},ne=e=>{if(!e)return`stream`;let t=e.split(`;`)[0]?.trim();if(t){if(t.startsWith(`application/json`)||t.endsWith(`+json`))return`json`;if(t===`multipart/form-data`)return`formData`;if([`application/`,`audio/`,`image/`,`video/`].some(e=>t.startsWith(e)))return`blob`;if(t.startsWith(`text/`))return`text`}},re=(e,t)=>t?!!(e.headers.has(t)||e.query?.[t]||e.headers.get(`Cookie`)?.includes(`${t}=`)):!1,ie=async({security:e,...t})=>{for(let n of e){if(re(t,n.name))continue;let e=await ee(n,t.auth);if(!e)continue;let r=n.name??`Authorization`;switch(n.in){case`query`:t.query||={},t.query[r]=e;break;case`cookie`:t.headers.append(`Cookie`,`${r}=${e}`);break;default:t.headers.set(r,e);break}}},ae=e=>p({baseUrl:e.baseUrl,path:e.path,query:e.query,querySerializer:typeof e.querySerializer==`function`?e.querySerializer:te(e.querySerializer),url:e.url}),oe=(e,t)=>{let n={...e,...t};return n.baseUrl?.endsWith(`/`)&&(n.baseUrl=n.baseUrl.substring(0,n.baseUrl.length-1)),n.headers=ce(e.headers,t.headers),n},se=e=>{let t=[];return e.forEach((e,n)=>{t.push([n,e])}),t},ce=(...e)=>{let t=new Headers;for(let n of e){if(!n)continue;let e=n instanceof Headers?se(n):Object.entries(n);for(let[n,r]of e)if(r===null)t.delete(n);else if(Array.isArray(r))for(let e of r)t.append(n,e);else r!==void 0&&t.set(n,typeof r==`object`?JSON.stringify(r):r)}return t},h=class{constructor(){this.fns=[]}clear(){this.fns=[]}eject(e){let t=this.getInterceptorIndex(e);this.fns[t]&&(this.fns[t]=null)}exists(e){let t=this.getInterceptorIndex(e);return!!this.fns[t]}getInterceptorIndex(e){return typeof e==`number`?this.fns[e]?e:-1:this.fns.indexOf(e)}update(e,t){let n=this.getInterceptorIndex(e);return this.fns[n]?(this.fns[n]=t,e):!1}use(e){return this.fns.push(e),this.fns.length-1}},le=()=>({error:new h,request:new h,response:new h}),ue=te({allowReserved:!1,array:{explode:!0,style:`form`},object:{explode:!0,style:`deepObject`}}),de={"Content-Type":`application/json`},fe=(e={})=>({...r,headers:de,parseAs:`auto`,querySerializer:ue,...e}),pe=((e={})=>{let t=oe(fe(),e),n=()=>({...t}),r=e=>(t=oe(t,e),n()),a=le(),o=async e=>{let n={...t,...e,fetch:e.fetch??t.fetch??globalThis.fetch,headers:ce(t.headers,e.headers),serializedBody:void 0};return n.security&&await ie({...n,security:n.security}),n.requestValidator&&await n.requestValidator(n),n.body!==void 0&&n.bodySerializer&&(n.serializedBody=n.bodySerializer(n.body)),(n.body===void 0||n.serializedBody===``)&&n.headers.delete(`Content-Type`),{opts:n,url:ae(n)}},s=async e=>{let{opts:t,url:n}=await o(e),r={redirect:`follow`,...t,body:m(t)},i=new Request(n,r);for(let e of a.request.fns)e&&(i=await e(i,t));let s=t.fetch,c;try{c=await s(i)}catch(e){let n=e;for(let r of a.error.fns)r&&(n=await r(e,void 0,i,t));if(n||={},t.throwOnError)throw n;return t.responseStyle===`data`?void 0:{error:n,request:i,response:void 0}}for(let e of a.response.fns)e&&(c=await e(c,i,t));let l={request:i,response:c};if(c.ok){let e=(t.parseAs===`auto`?ne(c.headers.get(`Content-Type`)):t.parseAs)??`json`;if(c.status===204||c.headers.get(`Content-Length`)===`0`){let n;switch(e){case`arrayBuffer`:case`blob`:case`text`:n=await c[e]();break;case`formData`:n=new FormData;break;case`stream`:n=c.body;break;default:n={};break}return t.responseStyle===`data`?n:{data:n,...l}}let n;switch(e){case`arrayBuffer`:case`blob`:case`formData`:case`text`:n=await c[e]();break;case`json`:{let e=await c.text();n=e?JSON.parse(e):{};break}case`stream`:return t.responseStyle===`data`?c.body:{data:c.body,...l}}return e===`json`&&(t.responseValidator&&await t.responseValidator(n),t.responseTransformer&&(n=await t.responseTransformer(n))),t.responseStyle===`data`?n:{data:n,...l}}let u=await c.text(),d;try{d=JSON.parse(u)}catch{}let f=d??u,p=f;for(let e of a.error.fns)e&&(p=await e(f,c,i,t));if(p||={},t.throwOnError)throw p;return t.responseStyle===`data`?void 0:{error:p,...l}},c=e=>t=>s({...t,method:e}),l=e=>async t=>{let{opts:n,url:r}=await o(t);return i({...n,body:n.body,headers:n.headers,method:e,onRequest:async(e,t)=>{let r=new Request(e,t);for(let e of a.request.fns)e&&(r=await e(r,n));return r},serializedBody:m(n),url:r})};return{buildUrl:e=>ae({...t,...e}),connect:c(`CONNECT`),delete:c(`DELETE`),get:c(`GET`),getConfig:n,head:c(`HEAD`),interceptors:a,options:c(`OPTIONS`),patch:c(`PATCH`),post:c(`POST`),put:c(`PUT`),request:s,setConfig:r,sse:{connect:l(`CONNECT`),delete:l(`DELETE`),get:l(`GET`),head:l(`HEAD`),options:l(`OPTIONS`),patch:l(`PATCH`),post:l(`POST`),put:l(`PUT`),trace:l(`TRACE`)},trace:c(`TRACE`)}})(fe({baseUrl:`http://localhost:8000`})),g=globalThis,me=g.ShadowRoot&&(g.ShadyCSS===void 0||g.ShadyCSS.nativeShadow)&&`adoptedStyleSheets`in Document.prototype&&`replace`in CSSStyleSheet.prototype,_=Symbol(),he=new WeakMap,ge=class{constructor(e,t,n){if(this._$cssResult$=!0,n!==_)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=e,this.t=t}get styleSheet(){let e=this.o,t=this.t;if(me&&e===void 0){let n=t!==void 0&&t.length===1;n&&(e=he.get(t)),e===void 0&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),n&&he.set(t,e))}return e}toString(){return this.cssText}},_e=e=>new ge(typeof e==`string`?e:e+``,void 0,_),ve=(e,...t)=>new ge(e.length===1?e[0]:t.reduce((t,n,r)=>t+(e=>{if(!0===e._$cssResult$)return e.cssText;if(typeof e==`number`)return e;throw Error(`Value passed to 'css' function must be a 'css' function result: `+e+`. Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.`)})(n)+e[r+1],e[0]),e,_),ye=(e,t)=>{if(me)e.adoptedStyleSheets=t.map(e=>e instanceof CSSStyleSheet?e:e.styleSheet);else for(let n of t){let t=document.createElement(`style`),r=g.litNonce;r!==void 0&&t.setAttribute(`nonce`,r),t.textContent=n.cssText,e.appendChild(t)}},be=me?e=>e:e=>e instanceof CSSStyleSheet?(e=>{let t=``;for(let n of e.cssRules)t+=n.cssText;return _e(t)})(e):e,{is:xe,defineProperty:Se,getOwnPropertyDescriptor:Ce,getOwnPropertyNames:we,getOwnPropertySymbols:Te,getPrototypeOf:Ee}=Object,v=globalThis,De=v.trustedTypes,Oe=De?De.emptyScript:``,ke=v.reactiveElementPolyfillSupport,y=(e,t)=>e,b={toAttribute(e,t){switch(t){case Boolean:e=e?Oe:null;break;case Object:case Array:e=e==null?e:JSON.stringify(e)}return e},fromAttribute(e,t){let n=e;switch(t){case Boolean:n=e!==null;break;case Number:n=e===null?null:Number(e);break;case Object:case Array:try{n=JSON.parse(e)}catch{n=null}}return n}},x=(e,t)=>!xe(e,t),Ae={attribute:!0,type:String,converter:b,reflect:!1,useDefault:!1,hasChanged:x};Symbol.metadata??=Symbol(`metadata`),v.litPropertyMetadata??=new WeakMap;var S=class extends HTMLElement{static addInitializer(e){this._$Ei(),(this.l??=[]).push(e)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(e,t=Ae){if(t.state&&(t.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(e)&&((t=Object.create(t)).wrapped=!0),this.elementProperties.set(e,t),!t.noAccessor){let n=Symbol(),r=this.getPropertyDescriptor(e,n,t);r!==void 0&&Se(this.prototype,e,r)}}static getPropertyDescriptor(e,t,n){let{get:r,set:i}=Ce(this.prototype,e)??{get(){return this[t]},set(e){this[t]=e}};return{get:r,set(t){let a=r?.call(this);i?.call(this,t),this.requestUpdate(e,a,n)},configurable:!0,enumerable:!0}}static getPropertyOptions(e){return this.elementProperties.get(e)??Ae}static _$Ei(){if(this.hasOwnProperty(y(`elementProperties`)))return;let e=Ee(this);e.finalize(),e.l!==void 0&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(y(`finalized`)))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(y(`properties`))){let e=this.properties,t=[...we(e),...Te(e)];for(let n of t)this.createProperty(n,e[n])}let e=this[Symbol.metadata];if(e!==null){let t=litPropertyMetadata.get(e);if(t!==void 0)for(let[e,n]of t)this.elementProperties.set(e,n)}this._$Eh=new Map;for(let[e,t]of this.elementProperties){let n=this._$Eu(e,t);n!==void 0&&this._$Eh.set(n,e)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(e){let t=[];if(Array.isArray(e)){let n=new Set(e.flat(1/0).reverse());for(let e of n)t.unshift(be(e))}else e!==void 0&&t.push(be(e));return t}static _$Eu(e,t){let n=t.attribute;return!1===n?void 0:typeof n==`string`?n:typeof e==`string`?e.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise(e=>this.enableUpdating=e),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach(e=>e(this))}addController(e){(this._$EO??=new Set).add(e),this.renderRoot!==void 0&&this.isConnected&&e.hostConnected?.()}removeController(e){this._$EO?.delete(e)}_$E_(){let e=new Map,t=this.constructor.elementProperties;for(let n of t.keys())this.hasOwnProperty(n)&&(e.set(n,this[n]),delete this[n]);e.size>0&&(this._$Ep=e)}createRenderRoot(){let e=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return ye(e,this.constructor.elementStyles),e}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(e=>e.hostConnected?.())}enableUpdating(e){}disconnectedCallback(){this._$EO?.forEach(e=>e.hostDisconnected?.())}attributeChangedCallback(e,t,n){this._$AK(e,n)}_$ET(e,t){let n=this.constructor.elementProperties.get(e),r=this.constructor._$Eu(e,n);if(r!==void 0&&!0===n.reflect){let i=(n.converter?.toAttribute===void 0?b:n.converter).toAttribute(t,n.type);this._$Em=e,i==null?this.removeAttribute(r):this.setAttribute(r,i),this._$Em=null}}_$AK(e,t){let n=this.constructor,r=n._$Eh.get(e);if(r!==void 0&&this._$Em!==r){let e=n.getPropertyOptions(r),i=typeof e.converter==`function`?{fromAttribute:e.converter}:e.converter?.fromAttribute===void 0?b:e.converter;this._$Em=r;let a=i.fromAttribute(t,e.type);this[r]=a??this._$Ej?.get(r)??a,this._$Em=null}}requestUpdate(e,t,n,r=!1,i){if(e!==void 0){let a=this.constructor;if(!1===r&&(i=this[e]),n??=a.getPropertyOptions(e),!((n.hasChanged??x)(i,t)||n.useDefault&&n.reflect&&i===this._$Ej?.get(e)&&!this.hasAttribute(a._$Eu(e,n))))return;this.C(e,t,n)}!1===this.isUpdatePending&&(this._$ES=this._$EP())}C(e,t,{useDefault:n,reflect:r,wrapped:i},a){n&&!(this._$Ej??=new Map).has(e)&&(this._$Ej.set(e,a??t??this[e]),!0!==i||a!==void 0)||(this._$AL.has(e)||(this.hasUpdated||n||(t=void 0),this._$AL.set(e,t)),!0===r&&this._$Em!==e&&(this._$Eq??=new Set).add(e))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(e){Promise.reject(e)}let e=this.scheduleUpdate();return e!=null&&await e,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??=this.createRenderRoot(),this._$Ep){for(let[e,t]of this._$Ep)this[e]=t;this._$Ep=void 0}let e=this.constructor.elementProperties;if(e.size>0)for(let[t,n]of e){let{wrapped:e}=n,r=this[t];!0!==e||this._$AL.has(t)||r===void 0||this.C(t,void 0,n,r)}}let e=!1,t=this._$AL;try{e=this.shouldUpdate(t),e?(this.willUpdate(t),this._$EO?.forEach(e=>e.hostUpdate?.()),this.update(t)):this._$EM()}catch(t){throw e=!1,this._$EM(),t}e&&this._$AE(t)}willUpdate(e){}_$AE(e){this._$EO?.forEach(e=>e.hostUpdated?.()),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(e)),this.updated(e)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(e){return!0}update(e){this._$Eq&&=this._$Eq.forEach(e=>this._$ET(e,this[e])),this._$EM()}updated(e){}firstUpdated(e){}};S.elementStyles=[],S.shadowRootOptions={mode:`open`},S[y(`elementProperties`)]=new Map,S[y(`finalized`)]=new Map,ke?.({ReactiveElement:S}),(v.reactiveElementVersions??=[]).push(`2.1.2`);var je=globalThis,Me=e=>e,C=je.trustedTypes,Ne=C?C.createPolicy(`lit-html`,{createHTML:e=>e}):void 0,Pe=`$lit$`,w=`lit$${Math.random().toFixed(9).slice(2)}$`,Fe=`?`+w,Ie=`<${Fe}>`,T=document,E=()=>T.createComment(``),D=e=>e===null||typeof e!=`object`&&typeof e!=`function`,Le=Array.isArray,Re=e=>Le(e)||typeof e?.[Symbol.iterator]==`function`,O=`[
|
|
8
|
-
\f\r]`,k=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,ze=/-->/g,Be=/>/g,A=RegExp(`>|${
|
|
7
|
+
`);try{s=JSON.parse(e),l=!0}catch{s=e}}l&&(i&&await i(s),r&&(s=await r(s))),n?.({data:s,event:o,id:d,retry:c}),a.length&&(yield s)}}}finally{m.removeEventListener(`abort`,h),f.releaseLock()}break}catch(e){if(t?.(e),o!==void 0&&p>=o)break;await f(Math.min(c*2**(p-1),s??3e4))}}}()}},a=e=>{switch(e){case`label`:return`.`;case`matrix`:return`;`;case`simple`:return`,`;default:return`&`}},o=e=>{switch(e){case`form`:return`,`;case`pipeDelimited`:return`|`;case`spaceDelimited`:return`%20`;default:return`,`}},s=e=>{switch(e){case`label`:return`.`;case`matrix`:return`;`;case`simple`:return`,`;default:return`&`}},c=({allowReserved:e,explode:t,name:n,style:r,value:i})=>{if(!t){let t=(e?i:i.map(e=>encodeURIComponent(e))).join(o(r));switch(r){case`label`:return`.${t}`;case`matrix`:return`;${n}=${t}`;case`simple`:return t;default:return`${n}=${t}`}}let s=a(r),c=i.map(t=>r===`label`||r===`simple`?e?t:encodeURIComponent(t):l({allowReserved:e,name:n,value:t})).join(s);return r===`label`||r===`matrix`?s+c:c},l=({allowReserved:e,name:t,value:n})=>{if(n==null)return``;if(typeof n==`object`)throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${t}=${e?n:encodeURIComponent(n)}`},u=({allowReserved:e,explode:t,name:n,style:r,value:i,valueOnly:a})=>{if(i instanceof Date)return a?i.toISOString():`${n}=${i.toISOString()}`;if(r!==`deepObject`&&!t){let t=[];Object.entries(i).forEach(([n,r])=>{t=[...t,n,e?r:encodeURIComponent(r)]});let a=t.join(`,`);switch(r){case`form`:return`${n}=${a}`;case`label`:return`.${a}`;case`matrix`:return`;${n}=${a}`;default:return a}}let o=s(r),c=Object.entries(i).map(([t,i])=>l({allowReserved:e,name:r===`deepObject`?`${n}[${t}]`:t,value:i})).join(o);return r===`label`||r===`matrix`?o+c:c},d=/\{[^{}]+\}/g,f=({path:e,url:t})=>{let n=t,r=t.match(d);if(r)for(let t of r){let r=!1,i=t.substring(1,t.length-1),a=`simple`;i.endsWith(`*`)&&(r=!0,i=i.substring(0,i.length-1)),i.startsWith(`.`)?(i=i.substring(1),a=`label`):i.startsWith(`;`)&&(i=i.substring(1),a=`matrix`);let o=e[i];if(o==null)continue;if(Array.isArray(o)){n=n.replace(t,c({explode:r,name:i,style:a,value:o}));continue}if(typeof o==`object`){n=n.replace(t,u({explode:r,name:i,style:a,value:o,valueOnly:!0}));continue}if(a===`matrix`){n=n.replace(t,`;${l({name:i,value:o})}`);continue}let s=encodeURIComponent(a===`label`?`.${o}`:o);n=n.replace(t,s)}return n},p=({baseUrl:e,path:t,query:n,querySerializer:r,url:i})=>{let a=i.startsWith(`/`)?i:`/${i}`,o=(e??``)+a;t&&(o=f({path:t,url:o}));let s=n?r(n):``;return s.startsWith(`?`)&&(s=s.substring(1)),s&&(o+=`?${s}`),o};function m(e){let t=e.body!==void 0;if(t&&e.bodySerializer)return`serializedBody`in e?e.serializedBody!==void 0&&e.serializedBody!==``?e.serializedBody:null:e.body===``?null:e.body;if(t)return e.body}var h=async(e,t)=>{let n=typeof t==`function`?await t(e):t;if(n)return e.scheme===`bearer`?`Bearer ${n}`:e.scheme===`basic`?`Basic ${btoa(n)}`:n},ee=({parameters:e={},...t}={})=>n=>{let r=[];if(n&&typeof n==`object`)for(let i in n){let a=n[i];if(a==null)continue;let o=e[i]||t;if(Array.isArray(a)){let e=c({allowReserved:o.allowReserved,explode:!0,name:i,style:`form`,value:a,...o.array});e&&r.push(e)}else if(typeof a==`object`){let e=u({allowReserved:o.allowReserved,explode:!0,name:i,style:`deepObject`,value:a,...o.object});e&&r.push(e)}else{let e=l({allowReserved:o.allowReserved,name:i,value:a});e&&r.push(e)}}return r.join(`&`)},te=e=>{if(!e)return`stream`;let t=e.split(`;`)[0]?.trim();if(t){if(t.startsWith(`application/json`)||t.endsWith(`+json`))return`json`;if(t===`multipart/form-data`)return`formData`;if([`application/`,`audio/`,`image/`,`video/`].some(e=>t.startsWith(e)))return`blob`;if(t.startsWith(`text/`))return`text`}},ne=(e,t)=>t?!!(e.headers.has(t)||e.query?.[t]||e.headers.get(`Cookie`)?.includes(`${t}=`)):!1,re=async({security:e,...t})=>{for(let n of e){if(ne(t,n.name))continue;let e=await h(n,t.auth);if(!e)continue;let r=n.name??`Authorization`;switch(n.in){case`query`:t.query||={},t.query[r]=e;break;case`cookie`:t.headers.append(`Cookie`,`${r}=${e}`);break;default:t.headers.set(r,e);break}}},ie=e=>p({baseUrl:e.baseUrl,path:e.path,query:e.query,querySerializer:typeof e.querySerializer==`function`?e.querySerializer:ee(e.querySerializer),url:e.url}),ae=(e,t)=>{let n={...e,...t};return n.baseUrl?.endsWith(`/`)&&(n.baseUrl=n.baseUrl.substring(0,n.baseUrl.length-1)),n.headers=se(e.headers,t.headers),n},oe=e=>{let t=[];return e.forEach((e,n)=>{t.push([n,e])}),t},se=(...e)=>{let t=new Headers;for(let n of e){if(!n)continue;let e=n instanceof Headers?oe(n):Object.entries(n);for(let[n,r]of e)if(r===null)t.delete(n);else if(Array.isArray(r))for(let e of r)t.append(n,e);else r!==void 0&&t.set(n,typeof r==`object`?JSON.stringify(r):r)}return t},ce=class{constructor(){this.fns=[]}clear(){this.fns=[]}eject(e){let t=this.getInterceptorIndex(e);this.fns[t]&&(this.fns[t]=null)}exists(e){let t=this.getInterceptorIndex(e);return!!this.fns[t]}getInterceptorIndex(e){return typeof e==`number`?this.fns[e]?e:-1:this.fns.indexOf(e)}update(e,t){let n=this.getInterceptorIndex(e);return this.fns[n]?(this.fns[n]=t,e):!1}use(e){return this.fns.push(e),this.fns.length-1}},le=()=>({error:new ce,request:new ce,response:new ce}),ue=ee({allowReserved:!1,array:{explode:!0,style:`form`},object:{explode:!0,style:`deepObject`}}),de={"Content-Type":`application/json`},fe=(e={})=>({...r,headers:de,parseAs:`auto`,querySerializer:ue,...e}),pe=((e={})=>{let t=ae(fe(),e),n=()=>({...t}),r=e=>(t=ae(t,e),n()),a=le(),o=async e=>{let n={...t,...e,fetch:e.fetch??t.fetch??globalThis.fetch,headers:se(t.headers,e.headers),serializedBody:void 0};return n.security&&await re({...n,security:n.security}),n.requestValidator&&await n.requestValidator(n),n.body!==void 0&&n.bodySerializer&&(n.serializedBody=n.bodySerializer(n.body)),(n.body===void 0||n.serializedBody===``)&&n.headers.delete(`Content-Type`),{opts:n,url:ie(n)}},s=async e=>{let{opts:t,url:n}=await o(e),r={redirect:`follow`,...t,body:m(t)},i=new Request(n,r);for(let e of a.request.fns)e&&(i=await e(i,t));let s=t.fetch,c;try{c=await s(i)}catch(e){let n=e;for(let r of a.error.fns)r&&(n=await r(e,void 0,i,t));if(n||={},t.throwOnError)throw n;return t.responseStyle===`data`?void 0:{error:n,request:i,response:void 0}}for(let e of a.response.fns)e&&(c=await e(c,i,t));let l={request:i,response:c};if(c.ok){let e=(t.parseAs===`auto`?te(c.headers.get(`Content-Type`)):t.parseAs)??`json`;if(c.status===204||c.headers.get(`Content-Length`)===`0`){let n;switch(e){case`arrayBuffer`:case`blob`:case`text`:n=await c[e]();break;case`formData`:n=new FormData;break;case`stream`:n=c.body;break;default:n={};break}return t.responseStyle===`data`?n:{data:n,...l}}let n;switch(e){case`arrayBuffer`:case`blob`:case`formData`:case`text`:n=await c[e]();break;case`json`:{let e=await c.text();n=e?JSON.parse(e):{};break}case`stream`:return t.responseStyle===`data`?c.body:{data:c.body,...l}}return e===`json`&&(t.responseValidator&&await t.responseValidator(n),t.responseTransformer&&(n=await t.responseTransformer(n))),t.responseStyle===`data`?n:{data:n,...l}}let u=await c.text(),d;try{d=JSON.parse(u)}catch{}let f=d??u,p=f;for(let e of a.error.fns)e&&(p=await e(f,c,i,t));if(p||={},t.throwOnError)throw p;return t.responseStyle===`data`?void 0:{error:p,...l}},c=e=>t=>s({...t,method:e}),l=e=>async t=>{let{opts:n,url:r}=await o(t);return i({...n,body:n.body,headers:n.headers,method:e,onRequest:async(e,t)=>{let r=new Request(e,t);for(let e of a.request.fns)e&&(r=await e(r,n));return r},serializedBody:m(n),url:r})};return{buildUrl:e=>ie({...t,...e}),connect:c(`CONNECT`),delete:c(`DELETE`),get:c(`GET`),getConfig:n,head:c(`HEAD`),interceptors:a,options:c(`OPTIONS`),patch:c(`PATCH`),post:c(`POST`),put:c(`PUT`),request:s,setConfig:r,sse:{connect:l(`CONNECT`),delete:l(`DELETE`),get:l(`GET`),head:l(`HEAD`),options:l(`OPTIONS`),patch:l(`PATCH`),post:l(`POST`),put:l(`PUT`),trace:l(`TRACE`)},trace:c(`TRACE`)}})(fe({baseUrl:`http://localhost:8000`})),g=globalThis,me=g.ShadowRoot&&(g.ShadyCSS===void 0||g.ShadyCSS.nativeShadow)&&`adoptedStyleSheets`in Document.prototype&&`replace`in CSSStyleSheet.prototype,_=Symbol(),he=new WeakMap,ge=class{constructor(e,t,n){if(this._$cssResult$=!0,n!==_)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=e,this.t=t}get styleSheet(){let e=this.o,t=this.t;if(me&&e===void 0){let n=t!==void 0&&t.length===1;n&&(e=he.get(t)),e===void 0&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),n&&he.set(t,e))}return e}toString(){return this.cssText}},_e=e=>new ge(typeof e==`string`?e:e+``,void 0,_),ve=(e,...t)=>new ge(e.length===1?e[0]:t.reduce((t,n,r)=>t+(e=>{if(!0===e._$cssResult$)return e.cssText;if(typeof e==`number`)return e;throw Error(`Value passed to 'css' function must be a 'css' function result: `+e+`. Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.`)})(n)+e[r+1],e[0]),e,_),ye=(e,t)=>{if(me)e.adoptedStyleSheets=t.map(e=>e instanceof CSSStyleSheet?e:e.styleSheet);else for(let n of t){let t=document.createElement(`style`),r=g.litNonce;r!==void 0&&t.setAttribute(`nonce`,r),t.textContent=n.cssText,e.appendChild(t)}},be=me?e=>e:e=>e instanceof CSSStyleSheet?(e=>{let t=``;for(let n of e.cssRules)t+=n.cssText;return _e(t)})(e):e,{is:xe,defineProperty:Se,getOwnPropertyDescriptor:Ce,getOwnPropertyNames:we,getOwnPropertySymbols:Te,getPrototypeOf:Ee}=Object,v=globalThis,De=v.trustedTypes,Oe=De?De.emptyScript:``,ke=v.reactiveElementPolyfillSupport,y=(e,t)=>e,b={toAttribute(e,t){switch(t){case Boolean:e=e?Oe:null;break;case Object:case Array:e=e==null?e:JSON.stringify(e)}return e},fromAttribute(e,t){let n=e;switch(t){case Boolean:n=e!==null;break;case Number:n=e===null?null:Number(e);break;case Object:case Array:try{n=JSON.parse(e)}catch{n=null}}return n}},Ae=(e,t)=>!xe(e,t),je={attribute:!0,type:String,converter:b,reflect:!1,useDefault:!1,hasChanged:Ae};Symbol.metadata??=Symbol(`metadata`),v.litPropertyMetadata??=new WeakMap;var x=class extends HTMLElement{static addInitializer(e){this._$Ei(),(this.l??=[]).push(e)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(e,t=je){if(t.state&&(t.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(e)&&((t=Object.create(t)).wrapped=!0),this.elementProperties.set(e,t),!t.noAccessor){let n=Symbol(),r=this.getPropertyDescriptor(e,n,t);r!==void 0&&Se(this.prototype,e,r)}}static getPropertyDescriptor(e,t,n){let{get:r,set:i}=Ce(this.prototype,e)??{get(){return this[t]},set(e){this[t]=e}};return{get:r,set(t){let a=r?.call(this);i?.call(this,t),this.requestUpdate(e,a,n)},configurable:!0,enumerable:!0}}static getPropertyOptions(e){return this.elementProperties.get(e)??je}static _$Ei(){if(this.hasOwnProperty(y(`elementProperties`)))return;let e=Ee(this);e.finalize(),e.l!==void 0&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(y(`finalized`)))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(y(`properties`))){let e=this.properties,t=[...we(e),...Te(e)];for(let n of t)this.createProperty(n,e[n])}let e=this[Symbol.metadata];if(e!==null){let t=litPropertyMetadata.get(e);if(t!==void 0)for(let[e,n]of t)this.elementProperties.set(e,n)}this._$Eh=new Map;for(let[e,t]of this.elementProperties){let n=this._$Eu(e,t);n!==void 0&&this._$Eh.set(n,e)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(e){let t=[];if(Array.isArray(e)){let n=new Set(e.flat(1/0).reverse());for(let e of n)t.unshift(be(e))}else e!==void 0&&t.push(be(e));return t}static _$Eu(e,t){let n=t.attribute;return!1===n?void 0:typeof n==`string`?n:typeof e==`string`?e.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise(e=>this.enableUpdating=e),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach(e=>e(this))}addController(e){(this._$EO??=new Set).add(e),this.renderRoot!==void 0&&this.isConnected&&e.hostConnected?.()}removeController(e){this._$EO?.delete(e)}_$E_(){let e=new Map,t=this.constructor.elementProperties;for(let n of t.keys())this.hasOwnProperty(n)&&(e.set(n,this[n]),delete this[n]);e.size>0&&(this._$Ep=e)}createRenderRoot(){let e=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return ye(e,this.constructor.elementStyles),e}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(e=>e.hostConnected?.())}enableUpdating(e){}disconnectedCallback(){this._$EO?.forEach(e=>e.hostDisconnected?.())}attributeChangedCallback(e,t,n){this._$AK(e,n)}_$ET(e,t){let n=this.constructor.elementProperties.get(e),r=this.constructor._$Eu(e,n);if(r!==void 0&&!0===n.reflect){let i=(n.converter?.toAttribute===void 0?b:n.converter).toAttribute(t,n.type);this._$Em=e,i==null?this.removeAttribute(r):this.setAttribute(r,i),this._$Em=null}}_$AK(e,t){let n=this.constructor,r=n._$Eh.get(e);if(r!==void 0&&this._$Em!==r){let e=n.getPropertyOptions(r),i=typeof e.converter==`function`?{fromAttribute:e.converter}:e.converter?.fromAttribute===void 0?b:e.converter;this._$Em=r;let a=i.fromAttribute(t,e.type);this[r]=a??this._$Ej?.get(r)??a,this._$Em=null}}requestUpdate(e,t,n,r=!1,i){if(e!==void 0){let a=this.constructor;if(!1===r&&(i=this[e]),n??=a.getPropertyOptions(e),!((n.hasChanged??Ae)(i,t)||n.useDefault&&n.reflect&&i===this._$Ej?.get(e)&&!this.hasAttribute(a._$Eu(e,n))))return;this.C(e,t,n)}!1===this.isUpdatePending&&(this._$ES=this._$EP())}C(e,t,{useDefault:n,reflect:r,wrapped:i},a){n&&!(this._$Ej??=new Map).has(e)&&(this._$Ej.set(e,a??t??this[e]),!0!==i||a!==void 0)||(this._$AL.has(e)||(this.hasUpdated||n||(t=void 0),this._$AL.set(e,t)),!0===r&&this._$Em!==e&&(this._$Eq??=new Set).add(e))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(e){Promise.reject(e)}let e=this.scheduleUpdate();return e!=null&&await e,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??=this.createRenderRoot(),this._$Ep){for(let[e,t]of this._$Ep)this[e]=t;this._$Ep=void 0}let e=this.constructor.elementProperties;if(e.size>0)for(let[t,n]of e){let{wrapped:e}=n,r=this[t];!0!==e||this._$AL.has(t)||r===void 0||this.C(t,void 0,n,r)}}let e=!1,t=this._$AL;try{e=this.shouldUpdate(t),e?(this.willUpdate(t),this._$EO?.forEach(e=>e.hostUpdate?.()),this.update(t)):this._$EM()}catch(t){throw e=!1,this._$EM(),t}e&&this._$AE(t)}willUpdate(e){}_$AE(e){this._$EO?.forEach(e=>e.hostUpdated?.()),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(e)),this.updated(e)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(e){return!0}update(e){this._$Eq&&=this._$Eq.forEach(e=>this._$ET(e,this[e])),this._$EM()}updated(e){}firstUpdated(e){}};x.elementStyles=[],x.shadowRootOptions={mode:`open`},x[y(`elementProperties`)]=new Map,x[y(`finalized`)]=new Map,ke?.({ReactiveElement:x}),(v.reactiveElementVersions??=[]).push(`2.1.2`);var S=globalThis,Me=e=>e,C=S.trustedTypes,Ne=C?C.createPolicy(`lit-html`,{createHTML:e=>e}):void 0,Pe=`$lit$`,w=`lit$${Math.random().toFixed(9).slice(2)}$`,Fe=`?`+w,Ie=`<${Fe}>`,T=document,E=()=>T.createComment(``),D=e=>e===null||typeof e!=`object`&&typeof e!=`function`,O=Array.isArray,Le=e=>O(e)||typeof e?.[Symbol.iterator]==`function`,Re=`[
|
|
8
|
+
\f\r]`,k=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,ze=/-->/g,Be=/>/g,A=RegExp(`>|${Re}(?:([^\\s"'>=/]+)(${Re}*=${Re}*(?:[^ \t\n\f\r"'\`<>=]|("|')|))|$)`,`g`),Ve=/'/g,He=/"/g,Ue=/^(?:script|style|textarea|title)$/i,j=(e=>(t,...n)=>({_$litType$:e,strings:t,values:n}))(1),M=Symbol.for(`lit-noChange`),N=Symbol.for(`lit-nothing`),We=new WeakMap,P=T.createTreeWalker(T,129);function Ge(e,t){if(!O(e)||!e.hasOwnProperty(`raw`))throw Error(`invalid template strings array`);return Ne===void 0?t:Ne.createHTML(t)}var Ke=(e,t)=>{let n=e.length-1,r=[],i,a=t===2?`<svg>`:t===3?`<math>`:``,o=k;for(let t=0;t<n;t++){let n=e[t],s,c,l=-1,u=0;for(;u<n.length&&(o.lastIndex=u,c=o.exec(n),c!==null);)u=o.lastIndex,o===k?c[1]===`!--`?o=ze:c[1]===void 0?c[2]===void 0?c[3]!==void 0&&(o=A):(Ue.test(c[2])&&(i=RegExp(`</`+c[2],`g`)),o=A):o=Be:o===A?c[0]===`>`?(o=i??k,l=-1):c[1]===void 0?l=-2:(l=o.lastIndex-c[2].length,s=c[1],o=c[3]===void 0?A:c[3]===`"`?He:Ve):o===He||o===Ve?o=A:o===ze||o===Be?o=k:(o=A,i=void 0);let d=o===A&&e[t+1].startsWith(`/>`)?` `:``;a+=o===k?n+Ie:l>=0?(r.push(s),n.slice(0,l)+Pe+n.slice(l)+w+d):n+w+(l===-2?t:d)}return[Ge(e,a+(e[n]||`<?>`)+(t===2?`</svg>`:t===3?`</math>`:``)),r]},F=class e{constructor({strings:t,_$litType$:n},r){let i;this.parts=[];let a=0,o=0,s=t.length-1,c=this.parts,[l,u]=Ke(t,n);if(this.el=e.createElement(l,r),P.currentNode=this.el.content,n===2||n===3){let e=this.el.content.firstChild;e.replaceWith(...e.childNodes)}for(;(i=P.nextNode())!==null&&c.length<s;){if(i.nodeType===1){if(i.hasAttributes())for(let e of i.getAttributeNames())if(e.endsWith(Pe)){let t=u[o++],n=i.getAttribute(e).split(w),r=/([.?@])?(.*)/.exec(t);c.push({type:1,index:a,name:r[2],strings:n,ctor:r[1]===`.`?Je:r[1]===`?`?Ye:r[1]===`@`?Xe:R}),i.removeAttribute(e)}else e.startsWith(w)&&(c.push({type:6,index:a}),i.removeAttribute(e));if(Ue.test(i.tagName)){let e=i.textContent.split(w),t=e.length-1;if(t>0){i.textContent=C?C.emptyScript:``;for(let n=0;n<t;n++)i.append(e[n],E()),P.nextNode(),c.push({type:2,index:++a});i.append(e[t],E())}}}else if(i.nodeType===8)if(i.data===Fe)c.push({type:2,index:a});else{let e=-1;for(;(e=i.data.indexOf(w,e+1))!==-1;)c.push({type:7,index:a}),e+=w.length-1}a++}}static createElement(e,t){let n=T.createElement(`template`);return n.innerHTML=e,n}};function I(e,t,n=e,r){if(t===M)return t;let i=r===void 0?n._$Cl:n._$Co?.[r],a=D(t)?void 0:t._$litDirective$;return i?.constructor!==a&&(i?._$AO?.(!1),a===void 0?i=void 0:(i=new a(e),i._$AT(e,n,r)),r===void 0?n._$Cl=i:(n._$Co??=[])[r]=i),i!==void 0&&(t=I(e,i._$AS(e,t.values),i,r)),t}var qe=class{constructor(e,t){this._$AV=[],this._$AN=void 0,this._$AD=e,this._$AM=t}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(e){let{el:{content:t},parts:n}=this._$AD,r=(e?.creationScope??T).importNode(t,!0);P.currentNode=r;let i=P.nextNode(),a=0,o=0,s=n[0];for(;s!==void 0;){if(a===s.index){let t;s.type===2?t=new L(i,i.nextSibling,this,e):s.type===1?t=new s.ctor(i,s.name,s.strings,this,e):s.type===6&&(t=new Ze(i,this,e)),this._$AV.push(t),s=n[++o]}a!==s?.index&&(i=P.nextNode(),a++)}return P.currentNode=T,r}p(e){let t=0;for(let n of this._$AV)n!==void 0&&(n.strings===void 0?n._$AI(e[t]):(n._$AI(e,n,t),t+=n.strings.length-2)),t++}},L=class e{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(e,t,n,r){this.type=2,this._$AH=N,this._$AN=void 0,this._$AA=e,this._$AB=t,this._$AM=n,this.options=r,this._$Cv=r?.isConnected??!0}get parentNode(){let e=this._$AA.parentNode,t=this._$AM;return t!==void 0&&e?.nodeType===11&&(e=t.parentNode),e}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(e,t=this){e=I(this,e,t),D(e)?e===N||e==null||e===``?(this._$AH!==N&&this._$AR(),this._$AH=N):e!==this._$AH&&e!==M&&this._(e):e._$litType$===void 0?e.nodeType===void 0?Le(e)?this.k(e):this._(e):this.T(e):this.$(e)}O(e){return this._$AA.parentNode.insertBefore(e,this._$AB)}T(e){this._$AH!==e&&(this._$AR(),this._$AH=this.O(e))}_(e){this._$AH!==N&&D(this._$AH)?this._$AA.nextSibling.data=e:this.T(T.createTextNode(e)),this._$AH=e}$(e){let{values:t,_$litType$:n}=e,r=typeof n==`number`?this._$AC(e):(n.el===void 0&&(n.el=F.createElement(Ge(n.h,n.h[0]),this.options)),n);if(this._$AH?._$AD===r)this._$AH.p(t);else{let e=new qe(r,this),n=e.u(this.options);e.p(t),this.T(n),this._$AH=e}}_$AC(e){let t=We.get(e.strings);return t===void 0&&We.set(e.strings,t=new F(e)),t}k(t){O(this._$AH)||(this._$AH=[],this._$AR());let n=this._$AH,r,i=0;for(let a of t)i===n.length?n.push(r=new e(this.O(E()),this.O(E()),this,this.options)):r=n[i],r._$AI(a),i++;i<n.length&&(this._$AR(r&&r._$AB.nextSibling,i),n.length=i)}_$AR(e=this._$AA.nextSibling,t){for(this._$AP?.(!1,!0,t);e!==this._$AB;){let t=Me(e).nextSibling;Me(e).remove(),e=t}}setConnected(e){this._$AM===void 0&&(this._$Cv=e,this._$AP?.(e))}},R=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(e,t,n,r,i){this.type=1,this._$AH=N,this._$AN=void 0,this.element=e,this.name=t,this._$AM=r,this.options=i,n.length>2||n[0]!==``||n[1]!==``?(this._$AH=Array(n.length-1).fill(new String),this.strings=n):this._$AH=N}_$AI(e,t=this,n,r){let i=this.strings,a=!1;if(i===void 0)e=I(this,e,t,0),a=!D(e)||e!==this._$AH&&e!==M,a&&(this._$AH=e);else{let r=e,o,s;for(e=i[0],o=0;o<i.length-1;o++)s=I(this,r[n+o],t,o),s===M&&(s=this._$AH[o]),a||=!D(s)||s!==this._$AH[o],s===N?e=N:e!==N&&(e+=(s??``)+i[o+1]),this._$AH[o]=s}a&&!r&&this.j(e)}j(e){e===N?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,e??``)}},Je=class extends R{constructor(){super(...arguments),this.type=3}j(e){this.element[this.name]=e===N?void 0:e}},Ye=class extends R{constructor(){super(...arguments),this.type=4}j(e){this.element.toggleAttribute(this.name,!!e&&e!==N)}},Xe=class extends R{constructor(e,t,n,r,i){super(e,t,n,r,i),this.type=5}_$AI(e,t=this){if((e=I(this,e,t,0)??N)===M)return;let n=this._$AH,r=e===N&&n!==N||e.capture!==n.capture||e.once!==n.once||e.passive!==n.passive,i=e!==N&&(n===N||r);r&&this.element.removeEventListener(this.name,this,n),i&&this.element.addEventListener(this.name,this,e),this._$AH=e}handleEvent(e){typeof this._$AH==`function`?this._$AH.call(this.options?.host??this.element,e):this._$AH.handleEvent(e)}},Ze=class{constructor(e,t,n){this.element=e,this.type=6,this._$AN=void 0,this._$AM=t,this.options=n}get _$AU(){return this._$AM._$AU}_$AI(e){I(this,e)}},Qe=S.litHtmlPolyfillSupport;Qe?.(F,L),(S.litHtmlVersions??=[]).push(`3.3.2`);var $e=(e,t,n)=>{let r=n?.renderBefore??t,i=r._$litPart$;if(i===void 0){let e=n?.renderBefore??null;r._$litPart$=i=new L(t.insertBefore(E(),e),e,void 0,n??{})}return i._$AI(e),i},z=globalThis,B=class extends x{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){let e=super.createRenderRoot();return this.renderOptions.renderBefore??=e.firstChild,e}update(e){let t=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(e),this._$Do=$e(t,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return M}};B._$litElement$=!0,B.finalized=!0,z.litElementHydrateSupport?.({LitElement:B});var et=z.litElementPolyfillSupport;et?.({LitElement:B}),(z.litElementVersions??=[]).push(`4.2.2`);var tt=e=>(t,n)=>{n===void 0?customElements.define(e,t):n.addInitializer(()=>{customElements.define(e,t)})},nt={attribute:!0,type:String,converter:b,reflect:!1,hasChanged:Ae},rt=(e=nt,t,n)=>{let{kind:r,metadata:i}=n,a=globalThis.litPropertyMetadata.get(i);if(a===void 0&&globalThis.litPropertyMetadata.set(i,a=new Map),r===`setter`&&((e=Object.create(e)).wrapped=!0),a.set(n.name,e),r===`accessor`){let{name:r}=n;return{set(n){let i=t.get.call(this);t.set.call(this,n),this.requestUpdate(r,i,e,!0,n)},init(t){return t!==void 0&&this.C(r,void 0,e,t),t}}}if(r===`setter`){let{name:r}=n;return function(n){let i=this[r];t.call(this,n),this.requestUpdate(r,i,e,!0,n)}}throw Error(`Unsupported decorator location: `+r)};function it(e){return(t,n)=>typeof n==`object`?rt(e,t,n):((e,t,n)=>{let r=t.hasOwnProperty(n);return t.constructor.createProperty(n,e),r?Object.getOwnPropertyDescriptor(t,n):void 0})(e,t,n)}function V(e){return it({...e,state:!0,attribute:!1})}var at=(e,t,n)=>(n.configurable=!0,n.enumerable=!0,Reflect.decorate&&typeof t!=`object`&&Object.defineProperty(e,t,n),n);function ot(e,t){return(n,r,i)=>{let a=t=>t.renderRoot?.querySelector(e)??null;if(t){let{get:e,set:t}=typeof r==`object`?n:i??(()=>{let e=Symbol();return{get(){return this[e]},set(t){this[e]=t}}})();return at(n,r,{get(){let n=e.call(this);return n===void 0&&(n=a(this),(n!==null||this.hasUpdated)&&t.call(this,n)),n}})}return at(n,r,{get(){return a(this)}})}}var st={ATTRIBUTE:1,CHILD:2,PROPERTY:3,BOOLEAN_ATTRIBUTE:4,EVENT:5,ELEMENT:6},ct=e=>(...t)=>({_$litDirective$:e,values:t}),lt=class{constructor(e){}get _$AU(){return this._$AM._$AU}_$AT(e,t,n){this._$Ct=e,this._$AM=t,this._$Ci=n}_$AS(e,t){return this.update(e,t)}update(e,t){return this.render(...t)}},H=class extends lt{constructor(e){if(super(e),this.it=N,e.type!==st.CHILD)throw Error(this.constructor.directiveName+`() can only be used in child bindings`)}render(e){if(e===N||e==null)return this._t=void 0,this.it=e;if(e===M)return e;if(typeof e!=`string`)throw Error(this.constructor.directiveName+`() called with a non-string value`);if(e===this.it)return this._t;this.it=e;let t=[e];return t.raw=t,this._t={_$litType$:this.constructor.resultType,strings:t,values:[]}}};H.directiveName=`unsafeHTML`,H.resultType=1;var ut=ct(H),U=e=>j`${ut(`
|
|
9
9
|
<svg
|
|
10
10
|
viewBox="0 0 24 24"
|
|
11
11
|
fill="none"
|
|
@@ -16,7 +16,7 @@
|
|
|
16
16
|
>
|
|
17
17
|
${e}
|
|
18
18
|
</svg>
|
|
19
|
-
`)}`,
|
|
19
|
+
`)}`,W={accessibility:U(`<circle cx="12" cy="4.5" r="2"/><path d="M4 9.5h16"/><path d="M12 6.5v6"/><path d="M9.5 20.5 12 12.5l2.5 8"/>`),chat:U(`<path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/>`),settings:U(`<path d="M10.325 4.317a1.724 1.724 0 0 1 3.35 0 1.724 1.724 0 0 0 2.573 1.066 1.724 1.724 0 0 1 2.305 2.305 1.724 1.724 0 0 0 1.066 2.573 1.724 1.724 0 0 1 0 3.35 1.724 1.724 0 0 0-1.066 2.573 1.724 1.724 0 0 1-2.305 2.305 1.724 1.724 0 0 0-2.573 1.066 1.724 1.724 0 0 1-3.35 0 1.724 1.724 0 0 0-2.573-1.066 1.724 1.724 0 0 1-2.305-2.305 1.724 1.724 0 0 0-1.066-2.573 1.724 1.724 0 0 1 0-3.35 1.724 1.724 0 0 0 1.066-2.573 1.724 1.724 0 0 1 2.305-2.305 1.724 1.724 0 0 0 2.573-1.066z"/><circle cx="12" cy="12" r="3"/>`),mic:U(`<path d="M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z"/><path d="M19 10v2a7 7 0 0 1-14 0v-2"/><line x1="12" y1="19" x2="12" y2="23"/><line x1="8" y1="23" x2="16" y2="23"/>`),volumeOn:U(`<polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"/><path d="M15.54 8.46a5 5 0 0 1 0 7.07"/><path d="M19.07 4.93a10 10 0 0 1 0 14.14"/>`),volumeOff:U(`<polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"/><line x1="23" y1="9" x2="17" y2="15"/><line x1="17" y1="9" x2="23" y2="15"/>`),shield:U(`<path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>`),close:U(`<path d="M18 6 6 18"/><path d="m6 6 12 12"/>`),languages:U(`<path d="m5 8 6 6"/><path d="m4 14 6-6 2-3"/><path d="M2 5h12"/><path d="M7 2h1"/><path d="m22 22-5-10-5 10"/><path d="M14 18h6"/>`),profiles:U(`<path d="M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/>`),textSize:U(`<polyline points="4 7 4 4 20 4 20 7"/><line x1="9" y1="20" x2="15" y2="20"/><line x1="12" y1="4" x2="12" y2="20"/>`),contrast:U(`<circle cx="12" cy="12" r="10"/><path d="M12 18a6 6 0 0 0 0-12v12z"/>`),grayscale:U(`<circle cx="12" cy="12" r="10"/><path d="M12 2v20"/><path d="M12 18a6 6 0 0 0 0-12"/><path d="M12 14a2 2 0 0 0 0-4"/>`),cursor:U(`<path d="M4 3l7 17 2.2-6.2L20 11 4 3z"/>`),screenReader:U(`<polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"/><path d="M15.54 8.46a5 5 0 0 1 0 7.07"/><path d="M19.07 4.93a10 10 0 0 1 0 14.14"/>`),visualImpair:U(`<path d="M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0z"/><circle cx="12" cy="12" r="3"/>`),seizureSafe:U(`<path d="M13 2L3 14h9l-1 8 10-12h-9l1-8z"/>`),cognitive:U(`<path d="M9.5 2A2.5 2.5 0 0 1 12 4.5v15a2.5 2.5 0 0 1-4.96.44 2.5 2.5 0 0 1-2.96-3.08 3 3 0 0 1-.34-5.58 2.5 2.5 0 0 1 1.32-4.24 2.5 2.5 0 0 1 4.44-2.54z"/><path d="M14.5 2A2.5 2.5 0 0 0 12 4.5v15a2.5 2.5 0 0 0 4.96.44 2.5 2.5 0 0 0 2.96-3.08 3 3 0 0 0 .34-5.58 2.5 2.5 0 0 0-1.32-4.24 2.5 2.5 0 0 0-4.44-2.54z"/>`),info:U(`<circle cx="12" cy="12" r="10"/><path d="M12 16v-4"/><path d="M12 8h.01"/>`),check:U(`<path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/>`),chevronDown:U(`<path d="m6 9 6 6 6-6"/>`),sun:U(`<circle cx="12" cy="12" r="4"/><path d="M12 2v2"/><path d="M12 20v2"/><path d="m4.93 4.93 1.41 1.41"/><path d="m17.66 17.66 1.41 1.41"/><path d="M2 12h2"/><path d="M20 12h2"/><path d="m6.34 17.66-1.41 1.41"/><path d="m19.07 4.93-1.41 1.41"/>`),moon:U(`<path d="M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9z"/>`),droplet:U(`<path d="M12 22a7 7 0 0 0 7-7c0-2-1-3.9-3-5.5s-3.5-4-4-6.5c-.5 2.5-2 4.9-4 6.5s-3 3.5-3 5.5a7 7 0 0 0 7 7z"/>`),refresh:U(`<path d="M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"/><path d="M21 3v5h-5"/><path d="M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"/><path d="M3 21v-5h5"/>`),send:U(`<line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/>`),code:U(`<polyline points="16 18 22 12 16 6"/><polyline points="8 6 2 12 8 18"/>`),palette:U(`<circle cx="13.5" cy="6.5" r=".5"/><circle cx="17.5" cy="10.5" r=".5"/><circle cx="8.5" cy="7.5" r=".5"/><circle cx="6.5" cy="12.5" r=".5"/><path d="M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10c.92 0 1.76-.74 1.76-1.67 0-.42-.15-.81-.42-1.15-.28-.33-.45-.78-.45-1.26 0-.93.74-1.67 1.67-1.67h1.91c2.97 0 5.53-2.56 5.53-5.53C22 6.5 17.5 2 12 2z"/>`),link:U(`<path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/>`),type:U(`<polyline points="4 7 4 4 20 4 20 7"/><line x1="9" y1="20" x2="15" y2="20"/><line x1="12" y1="4" x2="12" y2="20"/>`),mouse:U(`<path d="M15 6v6a3 3 0 0 1-6 0V6a3 3 0 0 1 6 0z"/><rect x="6" y="2" width="12" height="20" rx="6"/>`)},dt=ve`
|
|
20
20
|
:host {
|
|
21
21
|
display: block;
|
|
22
22
|
pointer-events: none;
|
|
@@ -187,6 +187,7 @@
|
|
|
187
187
|
color: var(--bw-primary-fg);
|
|
188
188
|
box-shadow: none;
|
|
189
189
|
}
|
|
190
|
+
.bw-tab svg { width: 14px; height: 14px; flex-shrink: 0; }
|
|
190
191
|
.bw-tab[active] svg { color: var(--bw-primary-fg); }
|
|
191
192
|
|
|
192
193
|
/* ─── Content area ─── */
|
|
@@ -624,6 +625,51 @@
|
|
|
624
625
|
gap: 8px;
|
|
625
626
|
}
|
|
626
627
|
|
|
628
|
+
.lang-row-icon {
|
|
629
|
+
width: 16px;
|
|
630
|
+
height: 16px;
|
|
631
|
+
display: inline-flex;
|
|
632
|
+
align-items: center;
|
|
633
|
+
justify-content: center;
|
|
634
|
+
flex-shrink: 0;
|
|
635
|
+
}
|
|
636
|
+
.lang-row-icon svg {
|
|
637
|
+
width: 16px;
|
|
638
|
+
height: 16px;
|
|
639
|
+
display: block;
|
|
640
|
+
}
|
|
641
|
+
|
|
642
|
+
.settings-actions {
|
|
643
|
+
margin: 0 14px 14px;
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
.reset-settings-btn {
|
|
647
|
+
width: 100%;
|
|
648
|
+
min-height: 44px;
|
|
649
|
+
padding: 10px 14px;
|
|
650
|
+
border-radius: var(--bw-radius-sm);
|
|
651
|
+
border: 1.5px solid var(--bw-border);
|
|
652
|
+
background: var(--bw-bg);
|
|
653
|
+
color: var(--bw-fg);
|
|
654
|
+
font-size: 13px;
|
|
655
|
+
font-weight: 600;
|
|
656
|
+
cursor: pointer;
|
|
657
|
+
display: inline-flex;
|
|
658
|
+
align-items: center;
|
|
659
|
+
justify-content: center;
|
|
660
|
+
gap: 8px;
|
|
661
|
+
transition: all 0.18s;
|
|
662
|
+
}
|
|
663
|
+
.reset-settings-btn:hover {
|
|
664
|
+
border-color: #ef4444;
|
|
665
|
+
color: #ef4444;
|
|
666
|
+
background: #fef2f2;
|
|
667
|
+
}
|
|
668
|
+
.reset-settings-btn svg {
|
|
669
|
+
width: 16px;
|
|
670
|
+
height: 16px;
|
|
671
|
+
}
|
|
672
|
+
|
|
627
673
|
.trigger svg {
|
|
628
674
|
width: 28px;
|
|
629
675
|
height: 28px;
|
|
@@ -671,7 +717,8 @@
|
|
|
671
717
|
}
|
|
672
718
|
@keyframes adminFadeIn { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: none; } }
|
|
673
719
|
|
|
674
|
-
.admin-overlay .admin-icon {
|
|
720
|
+
.admin-overlay .admin-icon { margin-bottom: 12px; color: var(--bw-primary); }
|
|
721
|
+
.admin-overlay .admin-icon svg { width: 32px; height: 32px; }
|
|
675
722
|
.admin-overlay h4 { font-size: 17px; font-weight: 700; margin: 0 0 6px; color: var(--bw-fg); }
|
|
676
723
|
.admin-overlay p { font-size: 13px; color: var(--bw-fg-muted); margin: 0 0 20px; }
|
|
677
724
|
.admin-overlay input {
|
|
@@ -702,7 +749,7 @@
|
|
|
702
749
|
}
|
|
703
750
|
.auth-error { color: #ef4444; font-size: 12px; margin: 0 0 12px; }
|
|
704
751
|
.admin-status { color: #059669; font-size: 14px; font-weight: 600; margin: 0 0 16px; }
|
|
705
|
-
`,
|
|
752
|
+
`,ft=`bw-a11y-settings-v2`,G={monochrome:!1,darkHighContrast:!1,brightHighContrast:!1,lowSaturation:!1,highSaturation:!1,contrastMode:!1,customBgHue:null,customHeaderHue:null,customContentHue:null,activeColorTab:`background`,textScale:1,highlightHeaders:!1,enlargeButtons:!1,textSpacing:!1,dyslexicFont:!1,focusVisualizer:!1,cursorMagnifier:!1,animationsDisabled:!1,linkHighlight:!1},pt=class{constructor(e){this.settings={...G},(this.host=e).addController(this),this._loadSettings()}hostConnected(){this._applySettings()}_loadSettings(){let e=localStorage.getItem(ft);if(e)try{let t=JSON.parse(e);this.settings={...G,...t}}catch(e){console.error(`BariWeb: Failed to parse a11y settings`,e)}}_saveSettings(){localStorage.setItem(ft,JSON.stringify(this.settings)),this._applySettings(),this.host.requestUpdate()}_ensureGlobalStyles(){let e=`bw-global-a11y-styles`,t=document.getElementById(e);t||(t=document.createElement(`style`),t.id=e,document.head.appendChild(t)),t.textContent=`
|
|
706
753
|
/* Global Filters */
|
|
707
754
|
html {
|
|
708
755
|
filter:
|
|
@@ -832,7 +879,7 @@
|
|
|
832
879
|
html[data-bw-has-custom-content] div:not(bw-widget *) {
|
|
833
880
|
color: var(--bw-custom-content) !important;
|
|
834
881
|
}
|
|
835
|
-
`}_applySettings(){let e=document.documentElement;this._ensureGlobalStyles(),e.style.setProperty(`--bw-grayscale`,this.settings.monochrome?`100%`:`0%`);let t=1;this.settings.lowSaturation&&(t=.3),this.settings.highSaturation&&(t=2.5),e.style.setProperty(`--bw-saturation`,t.toString()),this.settings.customBgHue===null?e.removeAttribute(`data-bw-has-custom-bg`):(e.style.setProperty(`--bw-custom-bg`,`hsl(${this.settings.customBgHue}, 50%, 95%)`),e.setAttribute(`data-bw-has-custom-bg`,``)),this.settings.customHeaderHue===null?e.removeAttribute(`data-bw-has-custom-header`):(e.style.setProperty(`--bw-custom-header`,`hsl(${this.settings.customHeaderHue}, 70%, 30%)`),e.setAttribute(`data-bw-has-custom-header`,``)),this.settings.customContentHue===null?e.removeAttribute(`data-bw-has-custom-content`):(e.style.setProperty(`--bw-custom-content`,`hsl(${this.settings.customContentHue}, 60%, 40%)`),e.setAttribute(`data-bw-has-custom-content`,``)),this.settings.textScale>1?e.style.fontSize=`${this.settings.textScale*100}%`:e.style.fontSize=``;let n={"data-bw-monochrome":this.settings.monochrome,"data-bw-dark-high-contrast":this.settings.darkHighContrast,"data-bw-bright-high-contrast":this.settings.brightHighContrast,"data-bw-contrast-mode":this.settings.contrastMode,"data-bw-text-spacing":this.settings.textSpacing,"data-bw-dyslexic":this.settings.dyslexicFont,"data-bw-focus-visualizer":this.settings.focusVisualizer,"data-bw-cursor-magnifier":this.settings.cursorMagnifier,"data-bw-no-animations":this.settings.animationsDisabled,"data-bw-link-highlight":this.settings.linkHighlight,"data-bw-highlight-headers":this.settings.highlightHeaders,"data-bw-enlarge-buttons":this.settings.enlargeButtons};Object.entries(n).forEach(([t,n])=>{n?e.setAttribute(t,``):e.removeAttribute(t)});let r=this.host;r&&r.style.setProperty(`--bw-font-scale`,this.settings.textScale.toString())}toggleMonochrome(){this.settings.monochrome=!this.settings.monochrome,this._saveSettings()}toggleDarkHighContrast(){this.settings.darkHighContrast=!this.settings.darkHighContrast,this.settings.darkHighContrast&&(this.settings.brightHighContrast=!1,this.settings.contrastMode=!1),this._saveSettings()}toggleBrightHighContrast(){this.settings.brightHighContrast=!this.settings.brightHighContrast,this.settings.brightHighContrast&&(this.settings.darkHighContrast=!1,this.settings.contrastMode=!1),this._saveSettings()}toggleLowSaturation(){this.settings.lowSaturation=!this.settings.lowSaturation,this.settings.lowSaturation&&(this.settings.highSaturation=!1),this._saveSettings()}toggleHighSaturation(){this.settings.highSaturation=!this.settings.highSaturation,this.settings.highSaturation&&(this.settings.lowSaturation=!1),this._saveSettings()}toggleContrastMode(){this.settings.contrastMode=!this.settings.contrastMode,this.settings.contrastMode&&(this.settings.darkHighContrast=!1,this.settings.brightHighContrast=!1),this._saveSettings()}setCustomHue(e){this.settings.activeColorTab===`background`?this.settings.customBgHue=e:this.settings.activeColorTab===`header`?this.settings.customHeaderHue=e:this.settings.customContentHue=e,this._saveSettings()}resetCustomColors(){this.settings.customBgHue=null,this.settings.customHeaderHue=null,this.settings.customContentHue=null,this._saveSettings()}toggleHighlightHeaders(){this.settings.highlightHeaders=!this.settings.highlightHeaders,this._saveSettings()}toggleEnlargeButtons(){this.settings.enlargeButtons=!this.settings.enlargeButtons,this._saveSettings()}incrementTextScale(){this.settings.textScale>=1.5?this.settings.textScale=1:this.settings.textScale=parseFloat((this.settings.textScale+.1).toFixed(1)),this._saveSettings()}toggleTextSpacing(){this.settings.textSpacing=!this.settings.textSpacing,this._saveSettings()}toggleDyslexicFont(){this.settings.dyslexicFont=!this.settings.dyslexicFont,this._saveSettings()}toggleFocusVisualizer(){this.settings.focusVisualizer=!this.settings.focusVisualizer,this._saveSettings()}toggleCursorMagnifier(){this.settings.cursorMagnifier=!this.settings.cursorMagnifier,this._saveSettings()}toggleAnimations(){this.settings.animationsDisabled=!this.settings.animationsDisabled,this._saveSettings()}toggleLinkHighlight(){this.settings.linkHighlight=!this.settings.linkHighlight,this._saveSettings()}reset(){this.settings={...U},this._saveSettings()}};function W(e){try{let t=new URL(e),n=t.pathname;n=n.replace(yt,`:id`),n=n.replace(bt,`/:id`),n=n.replace(xt,`/:slug`),n=n.replace(St,`/:id`);let r=new URLSearchParams;t.searchParams.forEach((e,t)=>{Ct.has(t)?r.set(`:${t}`,``):e.length<30&&!/^\d+$/.test(e)&&r.set(t,e)});let i=r.toString();return n.replace(/\/$/,``)+(i?`?${i}`:``)}catch{return e.replace(yt,`:id`).replace(/\/\d{1,20}(?=\/|$)/g,`/:id`).split(`?`)[0]}}function G(e){let t=[`dialog`,`tooltip`,`menu`,`listbox`,`alertdialog`],n=e;for(;n&&n!==document.body;){let e=n.getAttribute(`role`)||``;if(t.includes(e)||n.hasAttribute(`data-radix-popper-content-wrapper`)||n.hasAttribute(`data-floating-ui-portal`))return!0;let r=typeof n.className==`string`?n.className:``;if(/popover|tooltip|dropdown-menu|floating|overlay/i.test(r))return!0;n=n.parentElement}return!1}function gt(e){let t=[`li`,`article`,`tr`,`dd`],n=e.parentElement,r=0;for(;n&&n!==document.body&&r<8;){let e=n.tagName.toLowerCase();if(t.includes(e))return!0;let i=typeof n.className==`string`?n.className:``;if(/\b(card|item|tile|post|entry|product|row-item|list-item|feed-item|cell)\b/i.test(i)){let e=n.parentElement?.children;if(e&&e.length>2)return!0}let a=n.getAttribute(`role`)||``;if(a===`listitem`||a===`row`||a===`gridcell`)return!0;n=n.parentElement,r++}return!1}function _t(e){let t=e,n=(t.getAttribute(`aria-label`)||t.getAttribute(`title`)||t.innerText||t.getAttribute(`placeholder`)||``).trim().toLowerCase();return!n||n.length<2||n.length>40||/^[\d\s₸$€%.,\-+:()]+$/.test(n)||/^\d{1,2}[./]\d{1,2}/.test(n)||wt.has(n)?``:n.replace(/^[\p{Emoji}\s]+/u,``).trim().slice(0,30)}function vt(e){let t=5381;for(let n=0;n<e.length;n++)t=(t<<5)+t^e.charCodeAt(n);return(t>>>0).toString(16)}function K(){let e=[],t=W(window.location.href);e.push(`route:${t}`);let n=document.querySelector(`h1`);if(n){let t=n.innerText?.trim().toLowerCase();t&&t.length>1&&t.length<50&&!/\d{3,}/.test(t)&&e.push(`h1:${t.slice(0,30)}`)}let r=Array.from(document.querySelectorAll(`input:not([type="hidden"]):not([type="submit"]):not([type="radio"]):not([type="checkbox"]), textarea, select`)).slice(0,8);for(let t of r){if(G(t))continue;let n=t,r=(n.getAttribute(`name`)||n.getAttribute(`placeholder`)||n.getAttribute(`aria-label`)||``).toLowerCase().trim().slice(0,25);r&&r.length>1&&!wt.has(r)&&e.push(`field:${r}`)}let i=Array.from(document.querySelectorAll(`nav a, [role="navigation"] a`)).slice(0,6);for(let t of i){if(G(t))continue;let n=_t(t);n&&e.push(`nav:${n}`)}let a=document.querySelector(`main`)||document.querySelector(`[role="main"]`)||document.getElementById(`root`);return a&&Array.from(a.querySelectorAll(`button:not([aria-hidden="true"]), [role="button"]:not([aria-hidden="true"])`)).filter(e=>!G(e)&&!gt(e)).map(_t).filter(e=>e.length>1).reduce((e,t)=>e.includes(t)?e:[...e,t],[]).slice(0,3).forEach(t=>e.push(`btn:${t}`)),[...new Set(e)].sort().slice(0,15)}function q(){return`bw-${vt(K().join(`|`))}`}var yt,bt,xt,St,Ct,wt,Tt=t((()=>{yt=/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi,bt=/\/\d{1,20}(?=\/|$)/g,xt=/\/[a-z0-9]+(?:-[a-z0-9]+)*-\d+(?=\/|$)/g,St=/\/[0-9a-f]{8,}(?=\/|$)/gi,Ct=new Set([`id`,`userId`,`user_id`,`orderId`,`order_id`,`itemId`,`item_id`,`productId`,`product_id`,`token`,`key`,`ref`,`code`,`session`]),wt=new Set(`ok,ок,okay,close,закрыть,cancel,отмена,yes,da,no,нет,да,submit,отправить,back,назад,next,далее,more,ещё,еще,menu,меню,...,•,·,loading,загрузка,open,открыть,expand,collapse,toggle,sort`.split(`,`))}));function Et(e,t){let n=new Set([...e].filter(e=>t.has(e))),r=new Set([...e,...t]);return r.size===0?1:n.size/r.size}var Dt,J,Ot=t((()=>{Tt(),Dt=class{constructor(e=1500){this._observer=null,this._debounceTimer=null,this._lastTokens=new Set,this._lastUrl=``,this._callbacks=[],this._discoveryCallbacks=[],this._isDiscovering=!1,this.isAutoDiscoveryEnabled=!1,this._debounceMs=e}start(){this._observer||(this._lastTokens=new Set(K()),this._lastUrl=W(window.location.href),this._observer=new MutationObserver(()=>{this._debounceTimer&&clearTimeout(this._debounceTimer),this._debounceTimer=setTimeout(()=>this._onMutation(),this._debounceMs)}),this._observer.observe(document.body,{childList:!0,subtree:!0,attributes:!1,characterData:!1}))}stop(){this._observer?.disconnect(),this._observer=null,this._debounceTimer&&clearTimeout(this._debounceTimer)}onStateChange(e){this._callbacks.push(e)}onDiscovery(e){this._discoveryCallbacks.push(e)}get isDiscovering(){return this._isDiscovering}getLiveSnapshot(){let e=(e,t)=>{if(e.hasAttribute(`bw-private`)||e.hasAttribute(`data-bw-private`))return`[MASKED]`;if(!t)return t;let n=t.replace(/(?:\d[ \-]*?){13,16}/g,`****`);return n=n.replace(/\b\d{12}\b/g,`****`),n},t=Array.from(document.querySelectorAll(`h1, h2`)).map(t=>e(t,t.innerText?.trim()||``)).filter(Boolean).slice(0,3),n=Array.from(document.querySelectorAll(`button, a[href], [role="button"]`)).map(t=>{let n=t,r=e(n,(n.getAttribute(`aria-label`)||n.innerText||``).trim().slice(0,60));return{id:n.id||``,text:r}}).filter(e=>e.text.length>0).slice(0,30);return{url:window.location.href,headings:t,fingerprint:q(),elements:n}}async _onMutation(){if(document.readyState!==`complete`)return;let e=W(window.location.href),t=new Set(K());if(t.size<2)return;let n=q(),r=e!==this._lastUrl,i=Et(this._lastTokens,t);if(r||i<.55){let a=r?`URL: ${this._lastUrl} → ${e}`:`Sim: ${i.toFixed(2)}`;console.log(`[Watcher] Screen change (${a})`),this._lastUrl=e,this._lastTokens=t;let o=this.getLiveSnapshot();if(this.isAutoDiscoveryEnabled){let e=this._buildTypedTokens();this._discover(n,e).catch(()=>{})}this._callbacks.forEach(e=>e(o))}}_buildTypedTokens(){let e=new Set,t=[],n=(n,r)=>{let i=r.trim().slice(0,40);if(!i||i.length<2)return;let a=`${n}:${i}`;e.has(a)||(e.add(a),t.push(a))};return document.querySelectorAll(`button, [role="button"]`).forEach(e=>{let t=e.innerText?.trim();t&&n(`btn`,t)}),document.querySelectorAll(`a[href]`).forEach(e=>{let t=(e.getAttribute(`aria-label`)||e.innerText)?.trim();t&&n(`a`,t)}),document.querySelectorAll(`input:not([type=hidden]), textarea, select`).forEach(e=>{let t=e.placeholder||e.name;t&&n(`input`,t)}),t.slice(0,8)}async _discover(e,t){let n=localStorage.getItem(`bw_admin_token`);if(n){this._isDiscovering=!0;try{let r=await fetch(`http://localhost:8000/v1/training/discover`,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${n}`},body:JSON.stringify({fingerprint:e,tokens:t,page_url:window.location.href})});if(r.ok){let e=await r.json();console.log(`[Discovery] ${e.status} — ${e.label}`),this._discoveryCallbacks.forEach(t=>t(e))}else r.status===401?(console.warn(`[Discovery] Token expired — disabling auto-discovery`),localStorage.removeItem(`bw_admin_token`),this.isAutoDiscoveryEnabled=!1):console.warn(`[Discovery] Server error ${r.status}`)}catch(e){console.warn(`[Discovery] Network error`,e)}finally{this._isDiscovering=!1}}}async forceDiscovery(){let e=[...new Set(K())],t=q();await this._discover(t,e)}},J=new Dt(1500)}));Ot();var kt=`http://localhost:8000`,At=class{constructor(e){this.isFixing=!1,this.simplifyEnabled=!1,this.autoA11yEnabled=!1,this._onParagraphKeydown=e=>{if(this.simplifyEnabled&&(e.key===`Enter`||e.key===` `)&&e.target instanceof HTMLElement){if(e.target.closest(`bw-widget`)||e.target.closest(`.bw-ai-tooltip`))return;let t=e.target.tagName.toLowerCase();if([`p`,`span`,`div`,`li`,`article`,`h1`,`h2`,`h3`,`h4`,`h5`,`h6`].includes(t)){e.preventDefault(),e.stopPropagation();let t=e.target.getBoundingClientRect();this._triggerSimplify(e.target,t.left+window.scrollX,t.bottom+window.scrollY)}}},this._onParagraphClick=async e=>{if(!this.simplifyEnabled)return;let t=e.target;if(t.closest(`bw-widget`)||t.closest(`.bw-ai-tooltip`))return;let n=t.tagName.toLowerCase();if([`p`,`span`,`div`,`li`,`article`,`h1`,`h2`,`h3`,`h4`,`h5`,`h6`].includes(n)){let n=t.innerText?.trim();n&&n.length>20&&(e.preventDefault(),e.stopPropagation(),this._triggerSimplify(t,e.pageX,e.pageY))}},(this.host=e).addController(this),this.simplifyEnabled=localStorage.getItem(`bw-ai-simplify`)===`true`,this.autoA11yEnabled=localStorage.getItem(`bw-ai-autofix`)===`true`,J.onStateChange(()=>{this.autoA11yEnabled&&!this.isFixing&&this.fixMarkup()}),this.autoA11yEnabled&&setTimeout(()=>this.fixMarkup(),1e3)}toggleAutoA11y(){this.autoA11yEnabled=!this.autoA11yEnabled,localStorage.setItem(`bw-ai-autofix`,this.autoA11yEnabled?`true`:`false`),this.autoA11yEnabled&&!this.isFixing&&this.fixMarkup(),this.host.requestUpdate()}hostConnected(){}hostDisconnected(){this.simplifyEnabled&&(document.body.removeEventListener(`click`,this._onParagraphClick,{capture:!0}),document.body.classList.remove(`bw-simplify-mode`))}_announce(e){let t=document.getElementById(`bw-ai-announcer`);t||(t=document.createElement(`div`),t.id=`bw-ai-announcer`,t.setAttribute(`aria-live`,`polite`),t.setAttribute(`aria-atomic`,`true`),Object.assign(t.style,{position:`absolute`,width:`1px`,height:`1px`,padding:`0`,margin:`-1px`,overflow:`hidden`,clip:`rect(0, 0, 0, 0)`,whiteSpace:`nowrap`,border:`0`}),document.body.appendChild(t)),t.textContent=e}async fixMarkup(){this.isFixing=!0,this.host.requestUpdate();try{let e=[];if(document.querySelectorAll(`img:not([alt]), img[alt=""]`).forEach(t=>{t.hasAttribute(`data-bw-ai-id`)||t.setAttribute(`data-bw-ai-id`,`ai-img-`+Math.random().toString(36).substring(2,9)),e.push({id:t.getAttribute(`data-bw-ai-id`),html:t.outerHTML.substring(0,300)+(t.outerHTML.length>300?`...>`:``)})}),document.querySelectorAll(`button:not([aria-label]), a:not([aria-label]), [role="button"]:not([aria-label])`).forEach(t=>{if(t.tagName===`INPUT`)return;let n=t;n.innerText?.trim()||n.textContent?.trim()||(t.hasAttribute(`data-bw-ai-id`)||t.setAttribute(`data-bw-ai-id`,`ai-btn-`+Math.random().toString(36).substring(2,9)),e.push({id:t.getAttribute(`data-bw-ai-id`),html:t.outerHTML.substring(0,300)+(t.outerHTML.length>300?`...>`:``)}))}),e.length===0){console.log(`BariWeb AI: No broken elements found.`);return}console.log(`BariWeb AI: Found ${e.length} broken elements. Processing...`);let t=window.BariwebConfig?.clientId||``;for(let n=0;n<e.length;n+=10){let r=e.slice(n,n+10),i=await fetch(`${kt}/v1/widget/a11y/fix`,{method:`POST`,headers:{"Content-Type":`application/json`,"X-Client-ID":t},body:JSON.stringify({elements:r})});i.ok&&(await i.json()).forEach(e=>{let t=document.querySelector(`[data-bw-ai-id="${e.id}"]`);if(t&&e.value&&(e.attribute===`alt`||e.attribute===`aria-label`)){t.setAttribute(e.attribute,e.value);let n=t,r=n.style.outline;n.style.outline=`3px solid #10b981`,setTimeout(()=>{n.style.outline=r},2e3)}})}this._announce(`Режим для незрячих отработал. AI исправил ${e.length} элементов.`)}catch(e){console.error(`BariWeb AI: A11y Fix failed`,e),this._announce(`Произошла ошибка при исправлении элементов.`)}finally{this.isFixing=!1,this.host.requestUpdate()}}toggleSimplify(){if(this.simplifyEnabled=!this.simplifyEnabled,this.simplifyEnabled){if(document.body.addEventListener(`click`,this._onParagraphClick,{capture:!0}),document.body.addEventListener(`keydown`,this._onParagraphKeydown,{capture:!0}),document.querySelectorAll(`p, h1, h2, h3, h4, h5, h6, li, article`).forEach(e=>{!e.hasAttribute(`tabindex`)&&e.textContent?.trim().length>20&&(e.setAttribute(`tabindex`,`0`),e.classList.add(`bw-simplify-focusable`))}),document.documentElement.style.setProperty(`--bw-simplify-cursor`,`help`),!document.getElementById(`bw-simplify-mode-style`)){let e=document.createElement(`style`);e.id=`bw-simplify-mode-style`,e.textContent=`
|
|
882
|
+
`}_applySettings(){let e=document.documentElement;this._ensureGlobalStyles(),e.style.setProperty(`--bw-grayscale`,this.settings.monochrome?`100%`:`0%`);let t=1;this.settings.lowSaturation&&(t=.3),this.settings.highSaturation&&(t=2.5),e.style.setProperty(`--bw-saturation`,t.toString()),this.settings.customBgHue===null?e.removeAttribute(`data-bw-has-custom-bg`):(e.style.setProperty(`--bw-custom-bg`,`hsl(${this.settings.customBgHue}, 50%, 95%)`),e.setAttribute(`data-bw-has-custom-bg`,``)),this.settings.customHeaderHue===null?e.removeAttribute(`data-bw-has-custom-header`):(e.style.setProperty(`--bw-custom-header`,`hsl(${this.settings.customHeaderHue}, 70%, 30%)`),e.setAttribute(`data-bw-has-custom-header`,``)),this.settings.customContentHue===null?e.removeAttribute(`data-bw-has-custom-content`):(e.style.setProperty(`--bw-custom-content`,`hsl(${this.settings.customContentHue}, 60%, 40%)`),e.setAttribute(`data-bw-has-custom-content`,``)),this.settings.textScale>1?e.style.fontSize=`${this.settings.textScale*100}%`:e.style.fontSize=``;let n={"data-bw-monochrome":this.settings.monochrome,"data-bw-dark-high-contrast":this.settings.darkHighContrast,"data-bw-bright-high-contrast":this.settings.brightHighContrast,"data-bw-contrast-mode":this.settings.contrastMode,"data-bw-text-spacing":this.settings.textSpacing,"data-bw-dyslexic":this.settings.dyslexicFont,"data-bw-focus-visualizer":this.settings.focusVisualizer,"data-bw-cursor-magnifier":this.settings.cursorMagnifier,"data-bw-no-animations":this.settings.animationsDisabled,"data-bw-link-highlight":this.settings.linkHighlight,"data-bw-highlight-headers":this.settings.highlightHeaders,"data-bw-enlarge-buttons":this.settings.enlargeButtons};Object.entries(n).forEach(([t,n])=>{n?e.setAttribute(t,``):e.removeAttribute(t)});let r=this.host;r&&r.style.setProperty(`--bw-font-scale`,this.settings.textScale.toString())}toggleMonochrome(){this.settings.monochrome=!this.settings.monochrome,this._saveSettings()}toggleDarkHighContrast(){this.settings.darkHighContrast=!this.settings.darkHighContrast,this.settings.darkHighContrast&&(this.settings.brightHighContrast=!1,this.settings.contrastMode=!1),this._saveSettings()}toggleBrightHighContrast(){this.settings.brightHighContrast=!this.settings.brightHighContrast,this.settings.brightHighContrast&&(this.settings.darkHighContrast=!1,this.settings.contrastMode=!1),this._saveSettings()}toggleLowSaturation(){this.settings.lowSaturation=!this.settings.lowSaturation,this.settings.lowSaturation&&(this.settings.highSaturation=!1),this._saveSettings()}toggleHighSaturation(){this.settings.highSaturation=!this.settings.highSaturation,this.settings.highSaturation&&(this.settings.lowSaturation=!1),this._saveSettings()}toggleContrastMode(){this.settings.contrastMode=!this.settings.contrastMode,this.settings.contrastMode&&(this.settings.darkHighContrast=!1,this.settings.brightHighContrast=!1),this._saveSettings()}setCustomHue(e){this.settings.activeColorTab===`background`?this.settings.customBgHue=e:this.settings.activeColorTab===`header`?this.settings.customHeaderHue=e:this.settings.customContentHue=e,this._saveSettings()}resetCustomColors(){this.settings.customBgHue=null,this.settings.customHeaderHue=null,this.settings.customContentHue=null,this._saveSettings()}toggleHighlightHeaders(){this.settings.highlightHeaders=!this.settings.highlightHeaders,this._saveSettings()}toggleEnlargeButtons(){this.settings.enlargeButtons=!this.settings.enlargeButtons,this._saveSettings()}incrementTextScale(){this.settings.textScale>=1.5?this.settings.textScale=1:this.settings.textScale=parseFloat((this.settings.textScale+.1).toFixed(1)),this._saveSettings()}toggleTextSpacing(){this.settings.textSpacing=!this.settings.textSpacing,this._saveSettings()}toggleDyslexicFont(){this.settings.dyslexicFont=!this.settings.dyslexicFont,this._saveSettings()}toggleFocusVisualizer(){this.settings.focusVisualizer=!this.settings.focusVisualizer,this._saveSettings()}toggleCursorMagnifier(){this.settings.cursorMagnifier=!this.settings.cursorMagnifier,this._saveSettings()}toggleAnimations(){this.settings.animationsDisabled=!this.settings.animationsDisabled,this._saveSettings()}toggleLinkHighlight(){this.settings.linkHighlight=!this.settings.linkHighlight,this._saveSettings()}reset(){this.settings={...G},this._saveSettings()}};function K(e){try{let t=new URL(e),n=t.pathname;n=n.replace(vt,`:id`),n=n.replace(yt,`/:id`),n=n.replace(bt,`/:slug`),n=n.replace(xt,`/:id`);let r=new URLSearchParams;t.searchParams.forEach((e,t)=>{St.has(t)?r.set(`:${t}`,``):e.length<30&&!/^\d+$/.test(e)&&r.set(t,e)});let i=r.toString();return n.replace(/\/$/,``)+(i?`?${i}`:``)}catch{return e.replace(vt,`:id`).replace(/\/\d{1,20}(?=\/|$)/g,`/:id`).split(`?`)[0]}}function mt(e){let t=[`dialog`,`tooltip`,`menu`,`listbox`,`alertdialog`],n=e;for(;n&&n!==document.body;){let e=n.getAttribute(`role`)||``;if(t.includes(e)||n.hasAttribute(`data-radix-popper-content-wrapper`)||n.hasAttribute(`data-floating-ui-portal`))return!0;let r=typeof n.className==`string`?n.className:``;if(/popover|tooltip|dropdown-menu|floating|overlay/i.test(r))return!0;n=n.parentElement}return!1}function ht(e){let t=[`li`,`article`,`tr`,`dd`],n=e.parentElement,r=0;for(;n&&n!==document.body&&r<8;){let e=n.tagName.toLowerCase();if(t.includes(e))return!0;let i=typeof n.className==`string`?n.className:``;if(/\b(card|item|tile|post|entry|product|row-item|list-item|feed-item|cell)\b/i.test(i)){let e=n.parentElement?.children;if(e&&e.length>2)return!0}let a=n.getAttribute(`role`)||``;if(a===`listitem`||a===`row`||a===`gridcell`)return!0;n=n.parentElement,r++}return!1}function gt(e){let t=e,n=(t.getAttribute(`aria-label`)||t.getAttribute(`title`)||t.innerText||t.getAttribute(`placeholder`)||``).trim().toLowerCase();return!n||n.length<2||n.length>40||/^[\d\s₸$€%.,\-+:()]+$/.test(n)||/^\d{1,2}[./]\d{1,2}/.test(n)||Ct.has(n)?``:n.replace(/^[\p{Emoji}\s]+/u,``).trim().slice(0,30)}function _t(e){let t=5381;for(let n=0;n<e.length;n++)t=(t<<5)+t^e.charCodeAt(n);return(t>>>0).toString(16)}function q(){let e=[],t=K(window.location.href);e.push(`route:${t}`);let n=document.querySelector(`h1`);if(n){let t=n.innerText?.trim().toLowerCase();t&&t.length>1&&t.length<50&&!/\d{3,}/.test(t)&&e.push(`h1:${t.slice(0,30)}`)}let r=Array.from(document.querySelectorAll(`input:not([type="hidden"]):not([type="submit"]):not([type="radio"]):not([type="checkbox"]), textarea, select`)).slice(0,8);for(let t of r){if(mt(t))continue;let n=t,r=(n.getAttribute(`name`)||n.getAttribute(`placeholder`)||n.getAttribute(`aria-label`)||``).toLowerCase().trim().slice(0,25);r&&r.length>1&&!Ct.has(r)&&e.push(`field:${r}`)}let i=Array.from(document.querySelectorAll(`nav a, [role="navigation"] a`)).slice(0,6);for(let t of i){if(mt(t))continue;let n=gt(t);n&&e.push(`nav:${n}`)}let a=document.querySelector(`main`)||document.querySelector(`[role="main"]`)||document.getElementById(`root`);return a&&Array.from(a.querySelectorAll(`button:not([aria-hidden="true"]), [role="button"]:not([aria-hidden="true"])`)).filter(e=>!mt(e)&&!ht(e)).map(gt).filter(e=>e.length>1).reduce((e,t)=>e.includes(t)?e:[...e,t],[]).slice(0,3).forEach(t=>e.push(`btn:${t}`)),[...new Set(e)].sort().slice(0,15)}function J(){return`bw-${_t(q().join(`|`))}`}var vt,yt,bt,xt,St,Ct,wt=t((()=>{vt=/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi,yt=/\/\d{1,20}(?=\/|$)/g,bt=/\/[a-z0-9]+(?:-[a-z0-9]+)*-\d+(?=\/|$)/g,xt=/\/[0-9a-f]{8,}(?=\/|$)/gi,St=new Set([`id`,`userId`,`user_id`,`orderId`,`order_id`,`itemId`,`item_id`,`productId`,`product_id`,`token`,`key`,`ref`,`code`,`session`]),Ct=new Set(`ok,ок,okay,close,закрыть,cancel,отмена,yes,da,no,нет,да,submit,отправить,back,назад,next,далее,more,ещё,еще,menu,меню,...,•,·,loading,загрузка,open,открыть,expand,collapse,toggle,sort`.split(`,`))}));function Tt(e,t){let n=new Set([...e].filter(e=>t.has(e))),r=new Set([...e,...t]);return r.size===0?1:n.size/r.size}var Et,Y,Dt=t((()=>{wt(),Et=class{constructor(e=1500){this._observer=null,this._debounceTimer=null,this._lastTokens=new Set,this._lastUrl=``,this._callbacks=[],this._discoveryCallbacks=[],this._isDiscovering=!1,this.isAutoDiscoveryEnabled=!1,this._debounceMs=e}start(){this._observer||(this._lastTokens=new Set(q()),this._lastUrl=K(window.location.href),this._observer=new MutationObserver(()=>{this._debounceTimer&&clearTimeout(this._debounceTimer),this._debounceTimer=setTimeout(()=>this._onMutation(),this._debounceMs)}),this._observer.observe(document.body,{childList:!0,subtree:!0,attributes:!1,characterData:!1}))}stop(){this._observer?.disconnect(),this._observer=null,this._debounceTimer&&clearTimeout(this._debounceTimer)}onStateChange(e){this._callbacks.push(e)}onDiscovery(e){this._discoveryCallbacks.push(e)}get isDiscovering(){return this._isDiscovering}getLiveSnapshot(){let e=(e,t)=>{if(e.hasAttribute(`bw-private`)||e.hasAttribute(`data-bw-private`))return`[MASKED]`;if(!t)return t;let n=t.replace(/(?:\d[ \-]*?){13,16}/g,`****`);return n=n.replace(/\b\d{12}\b/g,`****`),n},t=Array.from(document.querySelectorAll(`h1, h2`)).map(t=>e(t,t.innerText?.trim()||``)).filter(Boolean).slice(0,3),n=Array.from(document.querySelectorAll(`button, a[href], [role="button"]`)).map(t=>{let n=t,r=e(n,(n.getAttribute(`aria-label`)||n.innerText||``).trim().slice(0,60));return{id:n.id||``,text:r}}).filter(e=>e.text.length>0).slice(0,30);return{url:window.location.href,headings:t,fingerprint:J(),elements:n}}async _onMutation(){if(document.readyState!==`complete`)return;let e=K(window.location.href),t=new Set(q());if(t.size<2)return;let n=J(),r=e!==this._lastUrl,i=Tt(this._lastTokens,t);if(r||i<.55){let a=r?`URL: ${this._lastUrl} → ${e}`:`Sim: ${i.toFixed(2)}`;console.log(`[Watcher] Screen change (${a})`),this._lastUrl=e,this._lastTokens=t;let o=this.getLiveSnapshot();if(this.isAutoDiscoveryEnabled){let e=this._buildTypedTokens();this._discover(n,e).catch(()=>{})}this._callbacks.forEach(e=>e(o))}}_buildTypedTokens(){let e=new Set,t=[],n=(n,r)=>{let i=r.trim().slice(0,40);if(!i||i.length<2)return;let a=`${n}:${i}`;e.has(a)||(e.add(a),t.push(a))};return document.querySelectorAll(`button, [role="button"]`).forEach(e=>{let t=e.innerText?.trim();t&&n(`btn`,t)}),document.querySelectorAll(`a[href]`).forEach(e=>{let t=(e.getAttribute(`aria-label`)||e.innerText)?.trim();t&&n(`a`,t)}),document.querySelectorAll(`input:not([type=hidden]), textarea, select`).forEach(e=>{let t=e.placeholder||e.name;t&&n(`input`,t)}),t.slice(0,8)}async _discover(e,t){let n=localStorage.getItem(`bw_admin_token`);if(n){this._isDiscovering=!0;try{let r=await fetch(`http://localhost:8000/v1/training/discover`,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${n}`},body:JSON.stringify({fingerprint:e,tokens:t,page_url:window.location.href})});if(r.ok){let e=await r.json();console.log(`[Discovery] ${e.status} — ${e.label}`),this._discoveryCallbacks.forEach(t=>t(e))}else r.status===401?(console.warn(`[Discovery] Token expired — disabling auto-discovery`),localStorage.removeItem(`bw_admin_token`),this.isAutoDiscoveryEnabled=!1):console.warn(`[Discovery] Server error ${r.status}`)}catch(e){console.warn(`[Discovery] Network error`,e)}finally{this._isDiscovering=!1}}}async forceDiscovery(){let e=[...new Set(q())],t=J();await this._discover(t,e)}},Y=new Et(1500)}));Dt();var Ot=`http://localhost:8000`,kt=class{constructor(e){this.isFixing=!1,this.simplifyEnabled=!1,this.autoA11yEnabled=!1,this._onParagraphKeydown=e=>{if(this.simplifyEnabled&&(e.key===`Enter`||e.key===` `)&&e.target instanceof HTMLElement){if(e.target.closest(`bw-widget`)||e.target.closest(`.bw-ai-tooltip`))return;let t=e.target.tagName.toLowerCase();if([`p`,`span`,`div`,`li`,`article`,`h1`,`h2`,`h3`,`h4`,`h5`,`h6`].includes(t)){e.preventDefault(),e.stopPropagation();let t=e.target.getBoundingClientRect();this._triggerSimplify(e.target,t.left+window.scrollX,t.bottom+window.scrollY)}}},this._onParagraphClick=async e=>{if(!this.simplifyEnabled)return;let t=e.target;if(t.closest(`bw-widget`)||t.closest(`.bw-ai-tooltip`))return;let n=t.tagName.toLowerCase();if([`p`,`span`,`div`,`li`,`article`,`h1`,`h2`,`h3`,`h4`,`h5`,`h6`].includes(n)){let n=t.innerText?.trim();n&&n.length>20&&(e.preventDefault(),e.stopPropagation(),this._triggerSimplify(t,e.pageX,e.pageY))}},(this.host=e).addController(this),this.simplifyEnabled=localStorage.getItem(`bw-ai-simplify`)===`true`,this.autoA11yEnabled=localStorage.getItem(`bw-ai-autofix`)===`true`,Y.onStateChange(()=>{this.autoA11yEnabled&&!this.isFixing&&this.fixMarkup()}),this.autoA11yEnabled&&setTimeout(()=>this.fixMarkup(),1e3)}toggleAutoA11y(){this.autoA11yEnabled=!this.autoA11yEnabled,localStorage.setItem(`bw-ai-autofix`,this.autoA11yEnabled?`true`:`false`),this.autoA11yEnabled&&!this.isFixing&&this.fixMarkup(),this.host.requestUpdate()}hostConnected(){}hostDisconnected(){this.simplifyEnabled&&(document.body.removeEventListener(`click`,this._onParagraphClick,{capture:!0}),document.body.classList.remove(`bw-simplify-mode`))}_announce(e){let t=document.getElementById(`bw-ai-announcer`);t||(t=document.createElement(`div`),t.id=`bw-ai-announcer`,t.setAttribute(`aria-live`,`polite`),t.setAttribute(`aria-atomic`,`true`),Object.assign(t.style,{position:`absolute`,width:`1px`,height:`1px`,padding:`0`,margin:`-1px`,overflow:`hidden`,clip:`rect(0, 0, 0, 0)`,whiteSpace:`nowrap`,border:`0`}),document.body.appendChild(t)),t.textContent=e}async fixMarkup(){this.isFixing=!0,this.host.requestUpdate();try{let e=[];if(document.querySelectorAll(`img:not([alt]), img[alt=""]`).forEach(t=>{t.hasAttribute(`data-bw-ai-id`)||t.setAttribute(`data-bw-ai-id`,`ai-img-`+Math.random().toString(36).substring(2,9)),e.push({id:t.getAttribute(`data-bw-ai-id`),html:t.outerHTML.substring(0,300)+(t.outerHTML.length>300?`...>`:``)})}),document.querySelectorAll(`button:not([aria-label]), a:not([aria-label]), [role="button"]:not([aria-label])`).forEach(t=>{if(t.tagName===`INPUT`)return;let n=t;n.innerText?.trim()||n.textContent?.trim()||(t.hasAttribute(`data-bw-ai-id`)||t.setAttribute(`data-bw-ai-id`,`ai-btn-`+Math.random().toString(36).substring(2,9)),e.push({id:t.getAttribute(`data-bw-ai-id`),html:t.outerHTML.substring(0,300)+(t.outerHTML.length>300?`...>`:``)}))}),e.length===0){console.log(`BariWeb AI: No broken elements found.`);return}console.log(`BariWeb AI: Found ${e.length} broken elements. Processing...`);let t=window.BariwebConfig?.clientId||``;for(let n=0;n<e.length;n+=10){let r=e.slice(n,n+10),i=await fetch(`${Ot}/v1/widget/a11y/fix`,{method:`POST`,headers:{"Content-Type":`application/json`,"X-Client-ID":t},body:JSON.stringify({elements:r})});i.ok&&(await i.json()).forEach(e=>{let t=document.querySelector(`[data-bw-ai-id="${e.id}"]`);if(t&&e.value&&(e.attribute===`alt`||e.attribute===`aria-label`)){t.setAttribute(e.attribute,e.value);let n=t,r=n.style.outline;n.style.outline=`3px solid #10b981`,setTimeout(()=>{n.style.outline=r},2e3)}})}this._announce(`Режим для незрячих отработал. AI исправил ${e.length} элементов.`)}catch(e){console.error(`BariWeb AI: A11y Fix failed`,e),this._announce(`Произошла ошибка при исправлении элементов.`)}finally{this.isFixing=!1,this.host.requestUpdate()}}toggleSimplify(){if(this.simplifyEnabled=!this.simplifyEnabled,this.simplifyEnabled){if(document.body.addEventListener(`click`,this._onParagraphClick,{capture:!0}),document.body.addEventListener(`keydown`,this._onParagraphKeydown,{capture:!0}),document.querySelectorAll(`p, h1, h2, h3, h4, h5, h6, li, article`).forEach(e=>{!e.hasAttribute(`tabindex`)&&e.textContent?.trim().length>20&&(e.setAttribute(`tabindex`,`0`),e.classList.add(`bw-simplify-focusable`))}),document.documentElement.style.setProperty(`--bw-simplify-cursor`,`help`),!document.getElementById(`bw-simplify-mode-style`)){let e=document.createElement(`style`);e.id=`bw-simplify-mode-style`,e.textContent=`
|
|
836
883
|
body.bw-simplify-mode *:hover {
|
|
837
884
|
cursor: help !important;
|
|
838
885
|
background-color: rgba(168, 85, 247, 0.1) !important;
|
|
@@ -917,7 +964,7 @@
|
|
|
917
964
|
<div class="bw-ai-tooltip-content" role="status" aria-live="polite">
|
|
918
965
|
Ожидаем ответ от ИИ...
|
|
919
966
|
</div>
|
|
920
|
-
`,document.body.appendChild(i),i.style.left=`${Math.max(10,t-160)}px`,i.style.top=`${n+20}px`;let a=e.style.outline,o=e.style.backgroundColor;e.style.outline=`2px dashed #a855f7`,e.style.backgroundColor=`rgba(168, 85, 247, 0.05)`,i.querySelector(`.bw-ai-tooltip-close`)?.addEventListener(`click`,()=>{i.remove(),e.style.outline=a,e.style.backgroundColor=o});try{let e=window.BariwebConfig?.clientId||``,t=await fetch(`${kt}/v1/widget/a11y/simplify`,{method:`POST`,headers:{"Content-Type":`application/json`,"X-Client-ID":e},body:JSON.stringify({text:r})});if(t.ok){let e=await t.json();if(e.text)i.classList.remove(`bw-ai-tooltip-loading`),i.querySelector(`.bw-ai-tooltip-content`).innerHTML=e.text,i.focus();else throw Error(`Empty response`)}else throw Error(`Server error`)}catch(e){console.error(`BariWeb AI: Simplify failed`,e),i.classList.remove(`bw-ai-tooltip-loading`),i.querySelector(`.bw-ai-tooltip-content`).innerHTML=`<span style="color:#ef4444; font-size:13px;">Ошибка создания упрощенного текста. Попробуйте еще раз.</span>`,i.focus()}}},jt=`bw-tts-enabled-v1`,Mt=class{constructor(){this.enabled=!0,this.enabled=this.loadEnabled()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e;try{localStorage.setItem(jt,e?`1`:`0`)}catch{}e||this.stop()}stop(){`speechSynthesis`in window&&window.speechSynthesis.cancel()}speak(e){if(!this.enabled||!(`speechSynthesis`in window))return;let t=(e||``).trim();if(t)try{window.speechSynthesis.cancel();let e=new SpeechSynthesisUtterance(t),n=this.detectLanguage(t);e.lang=n;let r=this.pickVoice(n);r&&(e.voice=r),e.rate=1,e.pitch=1,window.speechSynthesis.speak(e)}catch(e){console.warn(`TTS speak failed`,e)}}loadEnabled(){try{let e=localStorage.getItem(jt);return e===null?!0:e!==`0`}catch{return!0}}detectLanguage(e){let t=e.toLowerCase();return/[әіңғүұқөһ]/i.test(t)?`kk-KZ`:/[а-яё]/i.test(t)?`ru-RU`:/[a-z]/i.test(t)?`en-US`:`ru-RU`}pickVoice(e){if(!(`speechSynthesis`in window))return null;let t=window.speechSynthesis.getVoices();if(!t||t.length===0)return null;let n=e.split(`-`)[0].toLowerCase();return t.find(t=>t.lang.toLowerCase()===e.toLowerCase())||t.find(e=>e.lang.toLowerCase().startsWith(n))||t[0]||null}};Tt();var Nt=`http://localhost:8000`,Pt=5,Ft=[/(submit|отправить|оплатить|сгенерировать|сохранить|перевести|подтвердит|купить|удалить|delete|pay|purchase|buy|send|transfer|confirm|place.?order|checkout|remove|drop|unsubscribe|sign.?out|выйти|уволить)/i];function It(e){if(e.type!==`click_element`||!e.element_id)return!1;let t=document.getElementById(e.element_id);if(!t)return!1;if(t.getAttribute(`type`)===`submit`||t.tagName.toLowerCase()===`button`&&t.closest(`form`)!==null&&t.getAttribute(`type`)!==`button`)return!0;let n=[t.textContent?.trim()||``,t.getAttribute(`aria-label`)||``,t.getAttribute(`title`)||``,t.getAttribute(`name`)||``,t.getAttribute(`value`)||``].join(` `);return Ft.some(e=>e.test(n))}var Lt=class{constructor(e){this.messages=[],this.isLoading=!1,this.error=null,this._tts=new Mt,this._voiceMode=!1,this.pendingConfirmation=null,(this.host=e).addController(this),this._loadMessages()}hostConnected(){}hostDisconnected(){this._tts.stop()}_loadMessages(){try{let e=sessionStorage.getItem(`bw-chat-history`);e&&(this.messages=JSON.parse(e),this.messages.length>0&&typeof this.host.setOpen==`function`&&setTimeout(()=>this.host.setOpen(!0),100));let t=sessionStorage.getItem(`bw-auto-resume`);if(t===`true`||t===`verify-only`){sessionStorage.removeItem(`bw-auto-resume`);let e=t===`verify-only`?`Страница загрузилась после отправки формы. Проверь новый DOM: если авторизация прошла успешно (нет формы входа, есть контент приложения) — сообщи об успехе. НЕ нажимай ничего снова.`:`Страница загрузилась. Продолжай выполнение задачи с учетом нового контекста и DOM.`;setTimeout(()=>{this._agentStep(e)},1e3)}}catch(e){console.error(`Failed to load chat history`,e)}}_saveMessages(){try{sessionStorage.setItem(`bw-chat-history`,JSON.stringify(this.messages))}catch(e){console.error(`Failed to save chat history`,e)}}gatherContext(){let e=window.location.href,t=document.body?.innerText?.slice(0,3e3)??``,n=Array.from(document.querySelectorAll(`a[href], button, [role="button"], input:not([type="hidden"]), textarea, select`)).filter(e=>!e.hasAttribute(`bw-private`)).map(e=>{let t=e,n=t.tagName.toLowerCase(),r=n===`input`||n===`textarea`||n===`select`,i=t.getAttribute(`type`)||(n===`input`?`text`:n===`button`?`button`:n),a=t.getAttribute(`name`)||``,o=t.getAttribute(`placeholder`)||``,s=r?(t.value||``).slice(0,80):``;s&&=(s=s.replace(/\b\d{13,19}\b/g,e=>e.slice(0,4)+` **** **** `+e.slice(-4)),s.replace(/\b\d{12}\b/g,`**** **** ****`));let c=t.id&&!t.getAttribute(`data-bw-auto`)?t.id:t.getAttribute(`data-id`)||t.getAttribute(`data-testid`)||``;if(!c){let e=`${n}|${i}|${a}|${o}|${(t.className||``).toString().replace(/\s+/g,`-`).slice(0,40)}|${t.href||``}|${(t.textContent||``).trim().slice(0,30)}|${t.parentElement?.tagName?.toLowerCase()||`root`}`,r=5381;for(let t=0;t<e.length;t++)r=(r<<5)+r^e.charCodeAt(t);c=`bw-${(r>>>0).toString(16)}`,t.id=c,t.setAttribute(`data-bw-auto`,`true`)}let l=t.getAttribute(`aria-label`)||``;if(!l&&c){let e=document.querySelector(`label[for="${c}"]`);e&&(l=e.textContent?.trim()||``)}if(!l){let e=t.parentElement;for(;e&&e.tagName.toLowerCase()!==`form`&&e.tagName.toLowerCase()!==`body`;){if(e.tagName.toLowerCase()===`label`){l=(e.textContent||``).replace(t.textContent||``,``).trim();break}e=e.parentElement}}if(l||=(t.textContent||``).trim().slice(0,80),l||=t.getAttribute(`title`)||``,!l&&o&&(l=o),!l&&n===`button`){let e=t.querySelector(`svg`);if(e&&typeof e.className?.baseVal==`string`){let t=e.className.baseVal.match(/lucide-([a-z0-9\-]+)/);l=t?`[icon:${t[1]}]`:`[icon]`}else l=`[btn:${(t.className||``).toString().slice(0,30)}]`}return{id:c,label:l.trim(),tag:n,type:i,name:a,placeholder:o,value:s}}).filter(e=>e.label.length>0||(e.placeholder??``).length>0||(e.name??``).length>0).slice(0,100).map(e=>`[`+[e.tag,e.type||``,e.id,e.name||``,e.placeholder||``,e.value||``,e.label].join(`|`)+`]`).join(``),r=t;return r=r.replace(/\b\d{13,19}\b/g,`**** **** **** ****`),r=r.replace(/\b\d{12}\b/g,`**** **** ****`),{page_text:r,elements:n,page_url:e}}executeAction(e){if(e.type===`click_element`&&e.element_id){let t=document.getElementById(e.element_id);if(t){if(t.tagName.toLowerCase()===`a`&&t.href){let n=t.href;return new URL(n,window.location.origin).origin===window.location.origin&&sessionStorage.setItem(`bw-auto-resume`,`true`),t.click(),{result:`✅ Нажал на "${t.textContent?.trim()||e.element_id}"`,causesNavigation:!0}}return t.getAttribute(`type`)===`submit`||t.tagName.toLowerCase()===`button`&&t.closest(`form`)!==null&&t.getAttribute(`type`)!==`button`?(sessionStorage.setItem(`bw-auto-resume`,`verify-only`),t.click(),{result:`✅ Нажал на "${t.textContent?.trim()||e.element_id}"`,causesNavigation:!0}):(t.click(),{result:`✅ Нажал на "${t.textContent?.trim()||e.element_id}"`,causesNavigation:!1})}return{result:`⚠️ Элемент "${e.element_id}" не найден.`,causesNavigation:!1}}if(e.type===`navigate`&&e.url)return sessionStorage.setItem(`bw-auto-resume`,`true`),window.location.href=e.url,{result:`🔀 Перехожу на ${e.url}...`,causesNavigation:!0};if(e.type===`input_text`&&e.element_id&&e.value!==void 0){let t=document.getElementById(e.element_id);if(t){let n=Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype,`value`)?.set,r=Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,`value`)?.set;return t.tagName.toLowerCase()===`textarea`&&r?r.call(t,e.value):n?n.call(t,e.value):t.value=e.value,t.dispatchEvent(new Event(`input`,{bubbles:!0})),t.dispatchEvent(new Event(`change`,{bubbles:!0})),{result:`⌨️ Ввел текст "${e.value}" в поле.`,causesNavigation:!1}}return{result:`⚠️ Поле ввода "${e.element_id}" не найдено.`,causesNavigation:!1}}return e.type===`continue`?{result:`🔄 Анализирую страницу...`,causesNavigation:!1}:{result:`⚠️ Неизвестное действие.`,causesNavigation:!1}}async _callAPI(e){let{page_text:t,elements:n,page_url:r}=this.gatherContext(),i=q(),a=this.host.clientId||window.__BARIWEB_CLIENT_ID__||``,o=null;try{let e=await fetch(`${Nt}/v1/training/match-screen`,{method:`POST`,headers:{"Content-Type":`application/json`,"X-Client-ID":a},body:JSON.stringify({fingerprint:i})});if(e.ok){let t=await e.json();t.matched&&(o=t.label)}}catch(e){console.warn(`Failed to match screen fingerprint`,e)}let s=await fetch(`${Nt}/v1/chat`,{method:`POST`,headers:{"Content-Type":`application/json`,"X-Client-ID":a},body:JSON.stringify({query:e,history:this._compressedHistory(),page_text:t,elements:n,page_url:r,screen_label:o,screen_fingerprint:i})});if(!s.ok)throw Error(`HTTP ${s.status}: ${s.statusText}`);let c=await s.json();if(c.text&&c.text.trimStart().startsWith(`{`))try{let e=JSON.parse(c.text);e.text&&(c.text=e.text,e.action&&!c.action&&(c.action=e.action))}catch{c.text=c.text.replace(/^\{"text"\s*:\s*"/,``).replace(/",?\s*"action".*$/,``)}return c}_compressedHistory(){let e=this.messages.map(e=>({role:e.role,text:e.text}));if(e.length<=3)return e;let t=-1;for(let n=e.length-1;n>=0;n--)if(e[n].role===`user`){t=n;break}return t===-1?e.slice(-3):[e[t],...e.slice(t+1).filter(e=>e.role===`assistant`).slice(-2)]}async _agentLoop(e,t,n=!1){if(this.isLoading)return;this.isLoading=!0,this.error=null,this._voiceMode=n,t&&(this.messages=[...this.messages,{role:`user`,text:e,timestamp:Date.now()}],this._saveMessages()),this.host.requestUpdate();let r=e,i=0;try{for(;i<Pt;){i++;let e=await this._callAPI(r),t=e.text;if(e.action){if(It(e.action)){let t=document.getElementById(e.action.element_id||``)?.textContent?.trim()||e.action.element_id||`кнопку`;this.pendingConfirmation={text:`${e.text}\n\n⚠️ Нажать «${t}»?`,action:e.action,currentQuery:r,step:i},this.messages=[...this.messages,{role:`assistant`,text:`${e.text}\n\n🛑 **Подтвердите действие:** нажать «${t}»?`,timestamp:Date.now()}],this._saveMessages(),this._voiceMode&&this._tts.speak(e.text),this.isLoading=!1,this.host.requestUpdate();return}let n=this.gatherContext().page_text,{result:a,causesNavigation:o}=this.executeAction(e.action);if(e.action.type===`continue`){this.messages=[...this.messages,{role:`assistant`,text:`🔄 Анализирую...`,timestamp:Date.now()}],this._saveMessages(),this._voiceMode&&this._tts.speak(`Анализирую...`),this.host.requestUpdate(),await this._waitForDom(800),r=`Страница обновилась. Продолжай задачу, прочитай DOM.`;continue}if(t=`${e.text}\n${a}`,o){this.messages=[...this.messages,{role:`assistant`,text:t,timestamp:Date.now()}],this._saveMessages(),this._voiceMode&&this._tts.speak(t),this.host.requestUpdate(),await this._waitForDom(1500);let e=sessionStorage.getItem(`bw-auto-resume`);if(e===`true`||e===`verify-only`){sessionStorage.removeItem(`bw-auto-resume`),r=e===`verify-only`?`Страница загрузилась после отправки формы (SPA навигация). Проверь новый DOM: если задача выполнена — сообщи об успехе. НЕ нажимай ничего снова.`:`Страница загрузилась (SPA навигация). Продолжай задачу, прочитай новый DOM.`;continue}break}this.messages=[...this.messages,{role:`assistant`,text:t,timestamp:Date.now()}],this._saveMessages(),this._voiceMode&&this._tts.speak(t),this.host.requestUpdate(),e.action.type===`input_text`&&e.action.element_id?(await this._waitForDom(800),r=(document.getElementById(e.action.element_id)?.value??``).length>0?`✅ Поле заполнено. Переходи к СЛЕДУЮЩЕМУ незаполненному полю или нажми кнопку отправки. НЕ повторяй ввод.`:`⚠️ Поле не получило значение. Попробуй ввести снова в id="${e.action.element_id}".`):(await this._waitForDom(800),r=n===this.gatherContext().page_text?`⚠️ Страница не изменилась. Возможно кнопка не сработала. Проверь DOM.`:`Действие выполнено. Если задача готова — сообщи. Иначе продолжай.`);continue}this.messages=[...this.messages,{role:`assistant`,text:t,timestamp:Date.now()}],this._saveMessages(),this._voiceMode&&this._tts.speak(t);break}}catch(e){this.error=e.message??`Ошибка соединения`,this.messages=[...this.messages,{role:`assistant`,text:`❌ Ошибка: ${this.error}`,timestamp:Date.now()}],this._saveMessages(),this._voiceMode&&this._tts.speak(`Ошибка: ${this.error}`)}finally{this.isLoading=!1,this.host.requestUpdate()}}async confirmAction(){if(!this.pendingConfirmation)return;let{action:e}=this.pendingConfirmation;this.pendingConfirmation=null,this.messages=[...this.messages,{role:`user`,text:`✅ Подтверждаю`,timestamp:Date.now()}],this._saveMessages(),this.host.requestUpdate();let{result:t,causesNavigation:n}=this.executeAction(e);this.messages=[...this.messages,{role:`assistant`,text:t,timestamp:Date.now()}],this._saveMessages(),this._voiceMode&&this._tts.speak(t),this.host.requestUpdate(),!n&&(await this._waitForDom(1200),await this._agentStep(`Действие подтверждено и выполнено. Проверь результат в DOM.`))}cancelAction(){this.pendingConfirmation&&(this.pendingConfirmation=null,this.messages=[...this.messages,{role:`user`,text:`❌ Отмена`,timestamp:Date.now()},{role:`assistant`,text:`🚫 Действие отменено. Чем ещё могу помочь?`,timestamp:Date.now()}],this._saveMessages(),this._voiceMode&&this._tts.speak(`Действие отменено. Чем ещё могу помочь?`),this.host.requestUpdate())}_waitForDom(e){return new Promise(t=>setTimeout(t,e))}async sendMessage(e,t=!1){!e.trim()||this.isLoading||(await this._agentLoop(e,!0,t),this.host.updateComplete?.then(()=>{let e=this.host.renderRoot?.querySelector(`.chat-messages`);e&&(e.scrollTop=e.scrollHeight)}))}async _agentStep(e){await this._agentLoop(e,!1,this._voiceMode),this.host.updateComplete?.then(()=>{let e=this.host.renderRoot?.querySelector(`.chat-messages`);e&&(e.scrollTop=e.scrollHeight)})}clearMessages(){this.messages=[],this.error=null,this.pendingConfirmation=null,this._saveMessages(),this.host.requestUpdate()}isTtsEnabled(){return this._tts.isEnabled()}setTtsEnabled(e){this._tts.setEnabled(e),this.host.requestUpdate()}async transcribeAudio(e,t){let n=this.host.clientId||window.__BARIWEB_CLIENT_ID__||``,r=new FormData;r.append(`language_mode`,t),r.append(`audio`,e,`speech.wav`);let i=await fetch(`${Nt}/v1/stt/transcribe`,{method:`POST`,headers:{"X-Client-ID":n},body:r});if(!i.ok){let e=`HTTP ${i.status}`;try{e=(await i.json())?.detail||e}catch{}throw Error(e)}return await i.json()}};function Y(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a}var Rt=n({initAdminMode:()=>Ht,mountAdminPanel:()=>Vt});function zt(){if(!X)return;let e=K(),t=q(),n=Z?.is_trained===!0,r=Z&&!Z.is_trained,i=Z?.label||null,a=Z?.description||null,o=n?`active`:r?`draft`:`idle`,s=n?`trained`:r?`draft`:`idle`,c=n?`✅ Обучено`:r?`📝 Черновик (не подтверждено)`:`🔍 Сканирование...`,l=X.querySelector(`#bw-admin-panel`);l&&(l.className=n?`trained`:`discovering`,l.id=`bw-admin-panel`,n&&l.classList.add(`trained`));let u=X.querySelector(`#bw-panel-content`);u&&(u.innerHTML=`
|
|
967
|
+
`,document.body.appendChild(i),i.style.left=`${Math.max(10,t-160)}px`,i.style.top=`${n+20}px`;let a=e.style.outline,o=e.style.backgroundColor;e.style.outline=`2px dashed #a855f7`,e.style.backgroundColor=`rgba(168, 85, 247, 0.05)`,i.querySelector(`.bw-ai-tooltip-close`)?.addEventListener(`click`,()=>{i.remove(),e.style.outline=a,e.style.backgroundColor=o});try{let e=window.BariwebConfig?.clientId||``,t=await fetch(`${Ot}/v1/widget/a11y/simplify`,{method:`POST`,headers:{"Content-Type":`application/json`,"X-Client-ID":e},body:JSON.stringify({text:r})});if(t.ok){let e=await t.json();if(e.text)i.classList.remove(`bw-ai-tooltip-loading`),i.querySelector(`.bw-ai-tooltip-content`).innerHTML=e.text,i.focus();else throw Error(`Empty response`)}else throw Error(`Server error`)}catch(e){console.error(`BariWeb AI: Simplify failed`,e),i.classList.remove(`bw-ai-tooltip-loading`),i.querySelector(`.bw-ai-tooltip-content`).innerHTML=`<span style="color:#ef4444; font-size:13px;">Ошибка создания упрощенного текста. Попробуйте еще раз.</span>`,i.focus()}}},At=`bw-tts-enabled-v1`,jt=class{constructor(){this.enabled=!0,this.enabled=this.loadEnabled(),`speechSynthesis`in window&&(window.speechSynthesis.getVoices(),window.speechSynthesis.onvoiceschanged=()=>{window.speechSynthesis.getVoices()})}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e;try{localStorage.setItem(At,e?`1`:`0`)}catch{}e||this.stop()}stop(){`speechSynthesis`in window&&window.speechSynthesis.cancel()}speak(e){if(!this.enabled||!(`speechSynthesis`in window))return;let t=(e||``).trim();if(t)try{window.speechSynthesis.resume(),window.speechSynthesis.cancel();let e=new SpeechSynthesisUtterance(t),n=this.detectLanguage(t);e.lang=n;let r=this.pickVoice(n);r&&(e.voice=r),e.rate=1,e.pitch=1,e.volume=1,window.speechSynthesis.speak(e)}catch(e){console.warn(`TTS speak failed`,e)}}loadEnabled(){try{let e=localStorage.getItem(At);return e===null?!0:e!==`0`}catch{return!0}}detectLanguage(e){return/[\u04D8\u04D9\u0492\u0493\u04AE\u04AF\u049A\u049B\u04E8\u04E9\u04BA\u04BB\u0406\u0456\u04A2\u04A3]/u.test(e)?`kk-KZ`:/[\u0400-\u04FF]/u.test(e)?`ru-RU`:/[a-z]/i.test(e)?`en-US`:`ru-RU`}pickVoice(e){if(!(`speechSynthesis`in window))return null;let t=window.speechSynthesis.getVoices();if(!t||t.length===0)return null;let n=e.split(`-`)[0].toLowerCase();return t.find(t=>t.lang.toLowerCase()===e.toLowerCase())||t.find(e=>e.lang.toLowerCase().startsWith(n))||t[0]||null}};wt();var Mt=`http://localhost:8000`,Nt=5,Pt=[/(submit|отправить|оплатить|сгенерировать|сохранить|перевести|подтвердит|купить|удалить|delete|pay|purchase|buy|send|transfer|confirm|place.?order|checkout|remove|drop|unsubscribe|sign.?out|выйти|уволить)/i];function Ft(e){if(e.type!==`click_element`||!e.element_id)return!1;let t=document.getElementById(e.element_id);if(!t)return!1;if(t.getAttribute(`type`)===`submit`||t.tagName.toLowerCase()===`button`&&t.closest(`form`)!==null&&t.getAttribute(`type`)!==`button`)return!0;let n=[t.textContent?.trim()||``,t.getAttribute(`aria-label`)||``,t.getAttribute(`title`)||``,t.getAttribute(`name`)||``,t.getAttribute(`value`)||``].join(` `);return Pt.some(e=>e.test(n))}var It=class{constructor(e){this.messages=[],this.isLoading=!1,this.error=null,this._tts=new jt,this._voiceMode=!1,this.pendingConfirmation=null,(this.host=e).addController(this),this._loadMessages()}hostConnected(){}hostDisconnected(){this._tts.stop()}_shouldSpeak(){return this._voiceMode||this._tts.isEnabled()}_loadMessages(){try{let e=sessionStorage.getItem(`bw-chat-history`);e&&(this.messages=JSON.parse(e),this.messages.length>0&&typeof this.host.setOpen==`function`&&setTimeout(()=>this.host.setOpen(!0),100));let t=sessionStorage.getItem(`bw-auto-resume`);if(t===`true`||t===`verify-only`){sessionStorage.removeItem(`bw-auto-resume`);let e=t===`verify-only`?`Страница загрузилась после отправки формы. Проверь новый DOM: если авторизация прошла успешно (нет формы входа, есть контент приложения) — сообщи об успехе. НЕ нажимай ничего снова.`:`Страница загрузилась. Продолжай выполнение задачи с учетом нового контекста и DOM.`;setTimeout(()=>{this._agentStep(e)},1e3)}}catch(e){console.error(`Failed to load chat history`,e)}}_saveMessages(){try{sessionStorage.setItem(`bw-chat-history`,JSON.stringify(this.messages))}catch(e){console.error(`Failed to save chat history`,e)}}gatherContext(){let e=window.location.href,t=document.body?.innerText?.slice(0,3e3)??``,n=Array.from(document.querySelectorAll(`a[href], button, [role="button"], input:not([type="hidden"]), textarea, select`)).filter(e=>!e.hasAttribute(`bw-private`)).map(e=>{let t=e,n=t.tagName.toLowerCase(),r=n===`input`||n===`textarea`||n===`select`,i=t.getAttribute(`type`)||(n===`input`?`text`:n===`button`?`button`:n),a=t.getAttribute(`name`)||``,o=t.getAttribute(`placeholder`)||``,s=r?(t.value||``).slice(0,80):``;s&&=(s=s.replace(/\b\d{13,19}\b/g,e=>e.slice(0,4)+` **** **** `+e.slice(-4)),s.replace(/\b\d{12}\b/g,`**** **** ****`));let c=t.id&&!t.getAttribute(`data-bw-auto`)?t.id:t.getAttribute(`data-id`)||t.getAttribute(`data-testid`)||``;if(!c){let e=`${n}|${i}|${a}|${o}|${(t.className||``).toString().replace(/\s+/g,`-`).slice(0,40)}|${t.href||``}|${(t.textContent||``).trim().slice(0,30)}|${t.parentElement?.tagName?.toLowerCase()||`root`}`,r=5381;for(let t=0;t<e.length;t++)r=(r<<5)+r^e.charCodeAt(t);c=`bw-${(r>>>0).toString(16)}`,t.id=c,t.setAttribute(`data-bw-auto`,`true`)}let l=t.getAttribute(`aria-label`)||``;if(!l&&c){let e=document.querySelector(`label[for="${c}"]`);e&&(l=e.textContent?.trim()||``)}if(!l){let e=t.parentElement;for(;e&&e.tagName.toLowerCase()!==`form`&&e.tagName.toLowerCase()!==`body`;){if(e.tagName.toLowerCase()===`label`){l=(e.textContent||``).replace(t.textContent||``,``).trim();break}e=e.parentElement}}if(l||=(t.textContent||``).trim().slice(0,80),l||=t.getAttribute(`title`)||``,!l&&o&&(l=o),!l&&n===`button`){let e=t.querySelector(`svg`);if(e&&typeof e.className?.baseVal==`string`){let t=e.className.baseVal.match(/lucide-([a-z0-9\-]+)/);l=t?`[icon:${t[1]}]`:`[icon]`}else l=`[btn:${(t.className||``).toString().slice(0,30)}]`}return{id:c,label:l.trim(),tag:n,type:i,name:a,placeholder:o,value:s}}).filter(e=>e.label.length>0||(e.placeholder??``).length>0||(e.name??``).length>0).slice(0,100).map(e=>`[`+[e.tag,e.type||``,e.id,e.name||``,e.placeholder||``,e.value||``,e.label].join(`|`)+`]`).join(``),r=t;return r=r.replace(/\b\d{13,19}\b/g,`**** **** **** ****`),r=r.replace(/\b\d{12}\b/g,`**** **** ****`),{page_text:r,elements:n,page_url:e}}executeAction(e){if(e.type===`click_element`&&e.element_id){let t=document.getElementById(e.element_id);if(t){if(t.tagName.toLowerCase()===`a`&&t.href){let n=t.href;return new URL(n,window.location.origin).origin===window.location.origin&&sessionStorage.setItem(`bw-auto-resume`,`true`),t.click(),{result:`✅ Нажал на "${t.textContent?.trim()||e.element_id}"`,causesNavigation:!0}}return t.getAttribute(`type`)===`submit`||t.tagName.toLowerCase()===`button`&&t.closest(`form`)!==null&&t.getAttribute(`type`)!==`button`?(sessionStorage.setItem(`bw-auto-resume`,`verify-only`),t.click(),{result:`✅ Нажал на "${t.textContent?.trim()||e.element_id}"`,causesNavigation:!0}):(t.click(),{result:`✅ Нажал на "${t.textContent?.trim()||e.element_id}"`,causesNavigation:!1})}return{result:`⚠️ Элемент "${e.element_id}" не найден.`,causesNavigation:!1}}if(e.type===`navigate`&&e.url)return sessionStorage.setItem(`bw-auto-resume`,`true`),window.location.href=e.url,{result:`🔀 Перехожу на ${e.url}...`,causesNavigation:!0};if(e.type===`input_text`&&e.element_id&&e.value!==void 0){let t=document.getElementById(e.element_id);if(t){let n=Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype,`value`)?.set,r=Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,`value`)?.set;return t.tagName.toLowerCase()===`textarea`&&r?r.call(t,e.value):n?n.call(t,e.value):t.value=e.value,t.dispatchEvent(new Event(`input`,{bubbles:!0})),t.dispatchEvent(new Event(`change`,{bubbles:!0})),{result:`⌨️ Ввел текст "${e.value}" в поле.`,causesNavigation:!1}}return{result:`⚠️ Поле ввода "${e.element_id}" не найдено.`,causesNavigation:!1}}return e.type===`continue`?{result:`🔄 Анализирую страницу...`,causesNavigation:!1}:{result:`⚠️ Неизвестное действие.`,causesNavigation:!1}}async _callAPI(e){let{page_text:t,elements:n,page_url:r}=this.gatherContext(),i=J(),a=this.host.clientId||window.__BARIWEB_CLIENT_ID__||``,o=null;try{let e=await fetch(`${Mt}/v1/training/match-screen`,{method:`POST`,headers:{"Content-Type":`application/json`,"X-Client-ID":a},body:JSON.stringify({fingerprint:i})});if(e.ok){let t=await e.json();t.matched&&(o=t.label)}}catch(e){console.warn(`Failed to match screen fingerprint`,e)}let s=await fetch(`${Mt}/v1/chat`,{method:`POST`,headers:{"Content-Type":`application/json`,"X-Client-ID":a},body:JSON.stringify({query:e,history:this._compressedHistory(),page_text:t,elements:n,page_url:r,screen_label:o,screen_fingerprint:i})});if(!s.ok)throw Error(`HTTP ${s.status}: ${s.statusText}`);let c=await s.json();if(c.text&&c.text.trimStart().startsWith(`{`))try{let e=JSON.parse(c.text);e.text&&(c.text=e.text,e.action&&!c.action&&(c.action=e.action))}catch{c.text=c.text.replace(/^\{"text"\s*:\s*"/,``).replace(/",?\s*"action".*$/,``)}return c}_compressedHistory(){let e=this.messages.map(e=>({role:e.role,text:e.text}));if(e.length<=3)return e;let t=-1;for(let n=e.length-1;n>=0;n--)if(e[n].role===`user`){t=n;break}return t===-1?e.slice(-3):[e[t],...e.slice(t+1).filter(e=>e.role===`assistant`).slice(-2)]}async _agentLoop(e,t,n=!1){if(this.isLoading)return;this.isLoading=!0,this.error=null,this._voiceMode=n,t&&(this.messages=[...this.messages,{role:`user`,text:e,timestamp:Date.now()}],this._saveMessages()),this.host.requestUpdate();let r=e,i=0;try{for(;i<Nt;){i++;let e=await this._callAPI(r),t=e.text;if(e.action){if(Ft(e.action)){let t=document.getElementById(e.action.element_id||``)?.textContent?.trim()||e.action.element_id||`кнопку`;this.pendingConfirmation={text:`${e.text}\n\n⚠️ Нажать «${t}»?`,action:e.action,currentQuery:r,step:i},this.messages=[...this.messages,{role:`assistant`,text:`${e.text}\n\n🛑 **Подтвердите действие:** нажать «${t}»?`,timestamp:Date.now()}],this._saveMessages(),this._shouldSpeak()&&this._tts.speak(e.text),this.isLoading=!1,this.host.requestUpdate();return}let n=this.gatherContext().page_text,{result:a,causesNavigation:o}=this.executeAction(e.action);if(e.action.type===`continue`){this.messages=[...this.messages,{role:`assistant`,text:`🔄 Анализирую...`,timestamp:Date.now()}],this._saveMessages(),this._shouldSpeak()&&this._tts.speak(`Анализирую...`),this.host.requestUpdate(),await this._waitForDom(800),r=`Страница обновилась. Продолжай задачу, прочитай DOM.`;continue}if(t=`${e.text}\n${a}`,o){this.messages=[...this.messages,{role:`assistant`,text:t,timestamp:Date.now()}],this._saveMessages(),this._shouldSpeak()&&this._tts.speak(t),this.host.requestUpdate(),await this._waitForDom(1500);let e=sessionStorage.getItem(`bw-auto-resume`);if(e===`true`||e===`verify-only`){sessionStorage.removeItem(`bw-auto-resume`),r=e===`verify-only`?`Страница загрузилась после отправки формы (SPA навигация). Проверь новый DOM: если задача выполнена — сообщи об успехе. НЕ нажимай ничего снова.`:`Страница загрузилась (SPA навигация). Продолжай задачу, прочитай новый DOM.`;continue}break}this.messages=[...this.messages,{role:`assistant`,text:t,timestamp:Date.now()}],this._saveMessages(),this._shouldSpeak()&&this._tts.speak(t),this.host.requestUpdate(),e.action.type===`input_text`&&e.action.element_id?(await this._waitForDom(800),r=(document.getElementById(e.action.element_id)?.value??``).length>0?`✅ Поле заполнено. Переходи к СЛЕДУЮЩЕМУ незаполненному полю или нажми кнопку отправки. НЕ повторяй ввод.`:`⚠️ Поле не получило значение. Попробуй ввести снова в id="${e.action.element_id}".`):(await this._waitForDom(800),r=n===this.gatherContext().page_text?`⚠️ Страница не изменилась. Возможно кнопка не сработала. Проверь DOM.`:`Действие выполнено. Если задача готова — сообщи. Иначе продолжай.`);continue}this.messages=[...this.messages,{role:`assistant`,text:t,timestamp:Date.now()}],this._saveMessages(),this._shouldSpeak()&&this._tts.speak(t);break}}catch(e){this.error=e.message??`Ошибка соединения`,this.messages=[...this.messages,{role:`assistant`,text:`❌ Ошибка: ${this.error}`,timestamp:Date.now()}],this._saveMessages(),this._shouldSpeak()&&this._tts.speak(`Ошибка: ${this.error}`)}finally{this.isLoading=!1,this.host.requestUpdate()}}async confirmAction(){if(!this.pendingConfirmation)return;let{action:e}=this.pendingConfirmation;this.pendingConfirmation=null,this.messages=[...this.messages,{role:`user`,text:`✅ Подтверждаю`,timestamp:Date.now()}],this._saveMessages(),this.host.requestUpdate();let{result:t,causesNavigation:n}=this.executeAction(e);this.messages=[...this.messages,{role:`assistant`,text:t,timestamp:Date.now()}],this._saveMessages(),this._shouldSpeak()&&this._tts.speak(t),this.host.requestUpdate(),!n&&(await this._waitForDom(1200),await this._agentStep(`Действие подтверждено и выполнено. Проверь результат в DOM.`))}cancelAction(){this.pendingConfirmation&&(this.pendingConfirmation=null,this.messages=[...this.messages,{role:`user`,text:`❌ Отмена`,timestamp:Date.now()},{role:`assistant`,text:`🚫 Действие отменено. Чем ещё могу помочь?`,timestamp:Date.now()}],this._saveMessages(),this._shouldSpeak()&&this._tts.speak(`Действие отменено. Чем ещё могу помочь?`),this.host.requestUpdate())}_waitForDom(e){return new Promise(t=>setTimeout(t,e))}async sendMessage(e,t=!1){!e.trim()||this.isLoading||(await this._agentLoop(e,!0,t),this.host.updateComplete?.then(()=>{let e=this.host.renderRoot?.querySelector(`.chat-messages`);e&&(e.scrollTop=e.scrollHeight)}))}async _agentStep(e){await this._agentLoop(e,!1,this._voiceMode),this.host.updateComplete?.then(()=>{let e=this.host.renderRoot?.querySelector(`.chat-messages`);e&&(e.scrollTop=e.scrollHeight)})}clearMessages(){this.messages=[],this.error=null,this.pendingConfirmation=null,this._saveMessages(),this.host.requestUpdate()}isTtsEnabled(){return this._tts.isEnabled()}setTtsEnabled(e){this._tts.setEnabled(e),this.host.requestUpdate()}async transcribeAudio(e,t){let n=this.host.clientId||window.__BARIWEB_CLIENT_ID__||``,r=new FormData;r.append(`language_mode`,t),r.append(`audio`,e,`speech.wav`);let i=await fetch(`${Mt}/v1/stt/transcribe`,{method:`POST`,headers:{"X-Client-ID":n},body:r});if(!i.ok){let e=`HTTP ${i.status}`;try{e=(await i.json())?.detail||e}catch{}throw Error(e)}return await i.json()}};function X(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a}var Lt=n({initAdminMode:()=>Vt,mountAdminPanel:()=>Bt});function Rt(){if(!Z)return;let e=q(),t=J(),n=Q?.is_trained===!0,r=Q&&!Q.is_trained,i=Q?.label||null,a=Q?.description||null,o=n?`active`:r?`draft`:`idle`,s=n?`trained`:r?`draft`:`idle`,c=n?`✅ Обучено`:r?`📝 Черновик (не подтверждено)`:`🔍 Сканирование...`,l=Z.querySelector(`#bw-admin-panel`);l&&(l.className=n?`trained`:`discovering`,l.id=`bw-admin-panel`,n&&l.classList.add(`trained`));let u=Z.querySelector(`#bw-panel-content`);u&&(u.innerHTML=`
|
|
921
968
|
<div class="bw-status-box ${n?`trained`:r?`draft`:``}">
|
|
922
969
|
<div class="bw-status-indicator">
|
|
923
970
|
<span class="bw-status-dot ${o}"></span>
|
|
@@ -937,8 +984,8 @@
|
|
|
937
984
|
<div class="spinner"></div>
|
|
938
985
|
🤖 Система обучается в фоновом режиме...
|
|
939
986
|
</div>
|
|
940
|
-
`,u.querySelectorAll(`.bw-token-tag`).forEach(e=>{let t=e;t.onmouseenter=()=>
|
|
941
|
-
<style>${
|
|
987
|
+
`,u.querySelectorAll(`.bw-token-tag`).forEach(e=>{let t=e;t.onmouseenter=()=>zt(t.dataset.token||``),t.onmouseleave=()=>document.querySelectorAll(`.bw-highlight-rect`).forEach(e=>e.remove())}))}function zt(e){document.querySelectorAll(`.bw-highlight-rect`).forEach(e=>e.remove());let t=document.createTreeWalker(document.body,NodeFilter.SHOW_ELEMENT),n;for(;n=t.nextNode();)if((n.innerText||``).toLowerCase()===e.toLowerCase()&&n.offsetWidth>0){let e=n.getBoundingClientRect(),t=document.createElement(`div`);t.className=`bw-highlight-rect`,t.style.top=`${e.top+window.scrollY}px`,t.style.left=`${e.left+window.scrollX}px`,t.style.width=`${e.width}px`,t.style.height=`${e.height}px`,document.body.appendChild(t)}}async function Bt(){if(Z)return;let e=document.createElement(`div`);e.id=`bw-admin-wrapper`,e.innerHTML=`
|
|
988
|
+
<style>${Ht}</style>
|
|
942
989
|
<div id="bw-admin-panel">
|
|
943
990
|
<div class="bw-panel-header">
|
|
944
991
|
<span class="bw-panel-title">🧠 Discovery Mode</span>
|
|
@@ -946,7 +993,7 @@
|
|
|
946
993
|
</div>
|
|
947
994
|
<div id="bw-panel-content"></div>
|
|
948
995
|
</div>
|
|
949
|
-
`,document.body.appendChild(e),
|
|
996
|
+
`,document.body.appendChild(e),Z=e;let t=e.querySelector(`#bw-admin-close`);t.onclick=()=>{Z?.remove(),Z=null},Y.onDiscovery(e=>{Q=e,Rt()}),Rt(),await Y.forceDiscovery()}function Vt(){Bt()}var Ht,Z,Q,Ut=t((()=>{Dt(),wt(),Ht=`
|
|
950
997
|
#bw-admin-panel {
|
|
951
998
|
position: fixed;
|
|
952
999
|
bottom: 160px;
|
|
@@ -1113,51 +1160,60 @@
|
|
|
1113
1160
|
border-radius: 4px;
|
|
1114
1161
|
transition: all 0.15s ease-out;
|
|
1115
1162
|
}
|
|
1116
|
-
`,X=null,Z=null}));Ot();var Gt=`bw-stt-lang-v1`,Kt=200,qt=.015,Jt=1200,Yt=2e4,Xt=350,Q={kz:{langLabel:`Тану және виджет тілі`,langKz:`Қазақша`,langRu:`Орысша`,langEn:`Ағылшынша`,chatTab:`💬 Чат`,settingsTab:`♿ Баптаулар`,brandSub:`Инклюзия`,madeIn:`Қазақстанда жасалған 🇰🇿`,voiceBtnInit:`Дауыс`,voiceBtnRec:`Жазылуда...`,micBannerRec:`🎙️ Тыңдаудамын... (тыныштық болса тоқтаймын)`,micBannerWait:`⏳ Сөзді тану...`,micBannerErr:`⚠️`,micAriaL:`Голостық енгізуді қосу (жазу үшін ұстап тұрыңыз)`,inputAriaL:`Хабарламаны енгізу өрісі`,inputPl:`Хабарлама енгізіңіз...`,ttsAriaOn:`Жауапты дыбыстауды өшіру`,ttsAriaOff:`Жауапты дыбыстауды қосу`,sendAria:`Хабарлама жіберу`,onPage:`Бетте:`,emptyChatTitle:`Сіздің көмекшіңіз`,emptyChatSub:`Тапсырманы сипаттаңыз — мен қажетті түймелерді тауып, өрістерді сіз үшін толтырамын.`,confirmAction:`✅ Әрекетті растау`,cancelAction:`Болдырмау`,textScale:`Мәтін өлшемі`,monochrome:`А/Қ`,monochromeVal:`Монохром`,contrast:`Контраст`,contrastVal:`Қараңғы`,links:`Сілтемелер`,linksVal:`Ерекшелеу`,spacing:`Аралық`,spacingVal:`Үлкейту`,font:`Қаріп`,fontVal:`Дислексия`,cursor:`Курсор`,cursorVal:`Үлкейту`,colorSettingsTitle:`Түс баптаулары`,colorBg:`Фон`,colorHeader:`Бас киім`,colorText:`Мәтін`,aiSimplifyTitle:`AI Мәтінді оңтайландыру`,aiBlindTitle:`Зағиптар режимі (AI)`,on:`ҚОСУЛЫ`,off:`ӨШІРУЛІ`,closeAria:`Жабу`},ru:{langLabel:`Язык распознавания и виджета`,langKz:`Казахский`,langRu:`Русский`,langEn:`Английский`,chatTab:`💬 Чат`,settingsTab:`♿ Настройки`,brandSub:`Инклюзия`,madeIn:`Сделано в Казахстане 🇰🇿`,voiceBtnInit:`Нажмите`,voiceBtnRec:`Запись...`,micBannerRec:`🎙️ Слушаю... (остановлюсь по тишине)`,micBannerWait:`⏳ Распознаю речь...`,micBannerErr:`⚠️`,micAriaL:`Включить голосовой ввод (удерживайте для записи)`,inputAriaL:`Текстовое поле ввода сообщения`,inputPl:`Введите сообщение...`,ttsAriaOn:`Выключить озвучку ответа`,ttsAriaOff:`Включить озвучку ответа`,sendAria:`Отправить сообщение`,onPage:`На странице:`,emptyChatTitle:`Ваш помощник`,emptyChatSub:`Опишите задачу — я найду нужные кнопки и заполню поля за вас.`,confirmAction:`✅ Подтвердить действие`,cancelAction:`Отменить`,textScale:`Размер текста`,monochrome:`Ч/Б`,monochromeVal:`Монохром`,contrast:`Контраст`,contrastVal:`Тёмный`,links:`Ссылки`,linksVal:`Выделить`,spacing:`Отступы`,spacingVal:`Увеличить`,font:`Шрифт`,fontVal:`Дислексия`,cursor:`Курсор`,cursorVal:`Увеличить`,colorSettingsTitle:`Настройка цвета`,colorBg:`Фон`,colorHeader:`Шапка`,colorText:`Текст`,aiSimplifyTitle:`AI Упрощение текста`,aiBlindTitle:`Режим для незрячих (AI)`,on:`ВКЛ`,off:`ВЫКЛ`,closeAria:`Закрыть`},en:{langLabel:`Widget & Recognition Language`,langKz:`Kazakh`,langRu:`Russian`,langEn:`English`,chatTab:`💬 Chat`,settingsTab:`♿ Settings`,brandSub:`Inclusion`,madeIn:`Made in Kazakhstan 🇰🇿`,voiceBtnInit:`Press`,voiceBtnRec:`Recording...`,micBannerRec:`🎙️ Listening... (stops on silence)`,micBannerWait:`⏳ Recognizing...`,micBannerErr:`⚠️`,micAriaL:`Enable voice input (hold to record)`,inputAriaL:`Text input field`,inputPl:`Type a message...`,ttsAriaOn:`Disable answer TTS`,ttsAriaOff:`Enable answer TTS`,sendAria:`Send message`,onPage:`On page:`,emptyChatTitle:`Your Assistant`,emptyChatSub:`Describe the task — I will find buttons and fill fields for you.`,confirmAction:`✅ Confirm Action`,cancelAction:`Cancel`,textScale:`Text size`,monochrome:`B/W`,monochromeVal:`Monochrome`,contrast:`Contrast`,contrastVal:`Dark`,links:`Links`,linksVal:`Highlight`,spacing:`Spacing`,spacingVal:`Increase`,font:`Font`,fontVal:`Dyslexia`,cursor:`Cursor`,cursorVal:`Increase`,colorSettingsTitle:`Color Settings`,colorBg:`Bg`,colorHeader:`Header`,colorText:`Text`,aiSimplifyTitle:`AI Text Simplification`,aiBlindTitle:`Blind Mode (AI)`,on:`ON`,off:`OFF`,closeAria:`Close`}},$=class extends R{static{this.styles=[pt]}constructor(){super(),this._a11y=new ht(this),this._aiA11y=new At(this),this._chat=new Lt(this),this.clientId=``,this._isOpen=!1,this._activeTab=`chat`,this._inputValue=``,this._isAdmin=!1,this._adminPassword=``,this._authError=``,this._currentScreenLabel=``,this._sttState=`idle`,this._sttLanguageMode=`ru`,this._sttError=``,this._adminClickCount=0,this._showAdminLogin=!1,this._mediaStream=null,this._audioContext=null,this._analyser=null,this._scriptProcessor=null,this._pcmChunks=[],this._sampleRate=44100,this._recordingStartTs=0,this._silenceStartedTs=null,this._silenceIntervalId=null,this._maxDurationTimeoutId=null,this._adminClickTimer=null,this._handleGlobalKeydown=e=>{this._isOpen&&e.altKey&&e.code===`KeyV`&&(e.preventDefault(),this._toggleVoice())};try{let e=localStorage.getItem(Gt);(e===`kz`||e===`ru`||e===`en`)&&(this._sttLanguageMode=e)}catch{}this._checkAuthStatus()}_setSttLanguageMode(e){this._sttLanguageMode=e;try{localStorage.setItem(Gt,e)}catch{}}async _checkAuthStatus(){let e=localStorage.getItem(`bw_admin_token`);if(e)try{(await fetch(`http://localhost:8000/auth/login/widget/verify`,{headers:{Authorization:`Bearer ${e}`}})).ok?(this._isAdmin=!0,this._loadAdminUI()):localStorage.removeItem(`bw_admin_token`)}catch{try{let t=JSON.parse(atob(e.split(`.`)[1]));t.exp*1e3>Date.now()&&t.role===`admin`?(this._isAdmin=!0,this._loadAdminUI()):localStorage.removeItem(`bw_admin_token`)}catch{localStorage.removeItem(`bw_admin_token`)}}}async _loadAdminUI(){try{let{initAdminMode:e}=await Promise.resolve().then(()=>(Wt(),Rt));e(),J.isAutoDiscoveryEnabled=!0}catch(e){console.error(`Admin UI load failed`,e)}}async _handleAdminLogin(){if(this._authError=``,!this.clientId){this._authError=`Client ID not configured`;return}try{let e=await fetch(`http://localhost:8000/auth/login/widget`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({client_public_id:this.clientId,admin_key:this._adminPassword})});if(e.ok){let{access_token:t}=await e.json();localStorage.setItem(`bw_admin_token`,t),this._isAdmin=!0,this._showAdminLogin=!1,this._loadAdminUI()}else this._authError=(await e.json().catch(()=>({}))).detail||`Invalid admin key`}catch{this._authError=`Connection failed`}}_handleAdminLogout(){localStorage.removeItem(`bw_admin_token`),this._isAdmin=!1,this._adminPassword=``,this._showAdminLogin=!1,J.isAutoDiscoveryEnabled=!1,document.querySelector(`#bw-admin-wrapper`)?.remove()}_handleLogoClick(){this._adminClickCount++,this._adminClickCount>=5&&(this._showAdminLogin=!this._showAdminLogin,this._adminClickCount=0),this._adminClickTimer&&clearTimeout(this._adminClickTimer),this._adminClickTimer=setTimeout(()=>{this._adminClickCount=0},2e3)}connectedCallback(){super.connectedCallback(),J.start(),J.onStateChange(async e=>{try{let t=await fetch(`http://localhost:8000/v1/training/match-screen`,{method:`POST`,headers:{"Content-Type":`application/json`,"X-Client-ID":this.clientId||window.__BARIWEB_CLIENT_ID__||``},body:JSON.stringify({fingerprint:e.fingerprint})});if(t.ok){let e=await t.json();this._currentScreenLabel=e.matched?e.label:``}}catch{}}),window.addEventListener(`keydown`,this._handleGlobalKeydown)}disconnectedCallback(){super.disconnectedCallback(),J.stop(),this._cleanupRecording(),window.removeEventListener(`keydown`,this._handleGlobalKeydown)}_beep(e){let t=new(window.AudioContext||window.webkitAudioContext),n=t.createOscillator(),r=t.createGain();n.type=`sine`,n.frequency.setValueAtTime(e,t.currentTime),r.gain.setValueAtTime(.1,t.currentTime),r.gain.exponentialRampToValueAtTime(1e-5,t.currentTime+.1),n.connect(r),r.connect(t.destination),n.start(),n.stop(t.currentTime+.1)}_toggle(){this._isOpen=!this._isOpen}setOpen(e){this._isOpen=e}_setTab(e){this._activeTab=e}_handleInput(e){this._inputValue=e.target.value}_handleKeydown(e){e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),this._handleSend()),e.code===`Space`&&e.target.tagName!==`INPUT`&&(e.preventDefault(),this._sttState===`idle`&&this._startRecording())}async _handleSend(){let e=this._inputValue.trim();!e||this._chat.isLoading||this._sttState!==`idle`||(this._inputValue=``,await this._chat.sendMessage(e,!1),this._scrollMessages())}_scrollMessages(){this.updateComplete.then(()=>{this._messagesEl&&(this._messagesEl.scrollTop=this._messagesEl.scrollHeight)})}_getCurrentHue(){let e=this._a11y.settings;return e.activeColorTab===`background`?e.customBgHue||0:e.activeColorTab===`header`?e.customHeaderHue||0:e.customContentHue||0}_clearSttTimers(){this._silenceIntervalId!==null&&(window.clearInterval(this._silenceIntervalId),this._silenceIntervalId=null),this._maxDurationTimeoutId!==null&&(window.clearTimeout(this._maxDurationTimeoutId),this._maxDurationTimeoutId=null)}_cleanupRecording(){this._clearSttTimers(),this._analyser=null,this._scriptProcessor&&=(this._scriptProcessor.disconnect(),this._scriptProcessor.onaudioprocess=null,null),this._audioContext&&=(this._audioContext.close().catch(()=>{}),null),this._mediaStream&&=(this._mediaStream.getTracks().forEach(e=>e.stop()),null),this._pcmChunks=[],this._silenceStartedTs=null}async _toggleVoice(){if(this._sttState!==`processing`){if(this._sttState===`recording`){this._stopRecording();return}await this._startRecording()}}async _startRecording(){if(!navigator.mediaDevices?.getUserMedia){this._sttState=`error`,this._sttError=`Микрофон не поддерживается.`;return}try{this._cleanupRecording(),this._sttError=``;let e=await navigator.mediaDevices.getUserMedia({audio:!0});this._mediaStream=e,this._pcmChunks=[],this._recordingStartTs=Date.now(),this._silenceStartedTs=null,this._audioContext=new AudioContext,this._sampleRate=this._audioContext.sampleRate;let t=this._audioContext.createMediaStreamSource(e);this._analyser=this._audioContext.createAnalyser(),this._analyser.fftSize=2048,t.connect(this._analyser),this._scriptProcessor=this._audioContext.createScriptProcessor(4096,1,1),t.connect(this._scriptProcessor),this._scriptProcessor.connect(this._audioContext.destination),this._scriptProcessor.onaudioprocess=e=>{this._sttState===`recording`&&(this._pcmChunks.push(new Float32Array(e.inputBuffer.getChannelData(0))),e.outputBuffer.getChannelData(0).fill(0))},this._sttState=`recording`,this._beep(880),this._maxDurationTimeoutId=window.setTimeout(()=>{this._sttState===`recording`&&this._stopRecording()},Yt);let n=new Uint8Array(this._analyser.fftSize);this._silenceIntervalId=window.setInterval(()=>{if(!this._analyser||this._sttState!==`recording`)return;this._analyser.getByteTimeDomainData(n);let e=0;for(let t=0;t<n.length;t++){let r=(n[t]-128)/128;e+=r*r}Math.sqrt(e/n.length)<qt?this._silenceStartedTs?Date.now()-this._silenceStartedTs>=Jt&&this._stopRecording():this._silenceStartedTs=Date.now():this._silenceStartedTs=null},Kt)}catch{this._sttState=`error`,this._sttError=`Нет доступа к микрофону.`,this._cleanupRecording()}}_stopRecording(){this._sttState===`recording`&&(this._clearSttTimers(),this._sttState=`processing`,this._beep(440),this._finalizeRecording().catch(e=>{this._sttState=`error`,this._sttError=e?.message||`Ошибка обработки.`}))}async _finalizeRecording(){let e=Date.now()-this._recordingStartTs,t=this._pcmChunks.reduce((e,t)=>e+t.length,0),n=new Float32Array(t),r=0;for(let e of this._pcmChunks)n.set(e,r),r+=e.length;let i=this._encodeWav(n,this._sampleRate);if(this._cleanupRecording(),e<Xt||i.size===0){this._sttState=`error`,this._sttError=`Слишком короткая запись.`;return}try{let e=(await this._chat.transcribeAudio(i,this._sttLanguageMode)).text?.trim();if(!e){this._sttState=`error`,this._sttError=`Речь не распознана.`;return}await this._chat.sendMessage(e,!0),this._sttState=`idle`,this._sttError=``,this._inputValue=``,this._scrollMessages()}catch(e){this._sttState=`error`,this._sttError=e?.message||`Ошибка распознавания.`}}_encodeWav(e,t){let n=t*2,r=e.length*2,i=new ArrayBuffer(44+r),a=new DataView(i),o=(e,t)=>{for(let n=0;n<t.length;n++)a.setUint8(e+n,t.charCodeAt(n))};o(0,`RIFF`),a.setUint32(4,36+r,!0),o(8,`WAVE`),o(12,`fmt `),a.setUint32(16,16,!0),a.setUint16(20,1,!0),a.setUint16(22,1,!0),a.setUint32(24,t,!0),a.setUint32(28,n,!0),a.setUint16(32,2,!0),a.setUint16(34,16,!0),o(36,`data`),a.setUint32(40,r,!0);let s=44;for(let t=0;t<e.length;t++){let n=Math.max(-1,Math.min(1,e[t]));a.setInt16(s,n<0?n*32768:n*32767,!0),s+=2}return new Blob([i],{type:`audio/wav`})}_vibrate(){`vibrate`in navigator&&navigator.vibrate(20)}_renderChatTab(){let e=Q[this._sttLanguageMode],t=this._chat.messages,n=this._chat.isLoading,r=this._chat.pendingConfirmation,i=n||this._sttState!==`idle`;return j`
|
|
1163
|
+
`,Z=null,Q=null}));Dt();var Wt=`bw-stt-lang-v1`,Gt=200,Kt=.015,qt=1200,Jt=2e4,Yt=350,Xt={ru:{announceVoiceInputAvailable:`Голосовой ввод доступен. Кнопка в нижнем правом углу.`,announceWidgetOpened:`Виджет открыт.`,announceSwitchedToChat:`Переход в чат. Голосовой ввод доступен.`,errorMicNotSupported:`Микрофон не поддерживается.`,errorNoMicAccess:`Нет доступа к микрофону.`,errorProcessing:`Ошибка обработки.`,errorTooShort:`Слишком короткая запись.`,errorSpeechNotRecognized:`Речь не распознана.`,errorRecognition:`Ошибка распознавания.`,screenLabelPrefix:`На странице:`,chatEmptyTitle:`Ваш помощник`,chatEmptySub:`Опишите задачу — я найду нужные кнопки и заполню поля за вас.`,confirmAction:`Подтвердить действие`,cancel:`Отменить`,listening:`Слушаю... (остановлюсь по тишине)`,recognizingSpeech:`Распознаю речь...`,micAria:`Включить голосовой ввод (удерживайте для записи)`,inputPlaceholder:`Введите сообщение...`,inputAria:`Текстовое поле ввода сообщения`,ttsDisableAria:`Выключить озвучку ответа`,ttsEnableAria:`Включить озвучку ответа`,sendAria:`Отправить сообщение`,tileTextSize:`Размер текста`,tileMonochrome:`Ч/Б`,valueMonochrome:`Монохром`,tileContrast:`Контраст`,valueDark:`Тёмный`,tileLinks:`Ссылки`,valueHighlight:`Выделить`,tileSpacing:`Отступы`,valueEnlarge:`Увеличить`,tileFont:`Шрифт`,valueDyslexia:`Дислексия`,tileCursor:`Курсор`,tileVoice:`Голос`,valueRecording:`Запись...`,valuePress:`Нажмите`,colorSetup:`Настройка цвета`,tabBackground:`Фон`,tabHeader:`Шапка`,tabText:`Текст`,decrease:`Уменьшить`,hue:`Оттенок`,increase:`Увеличить`,recognitionLanguage:`Язык`,changeRecognitionLanguage:`Изменить язык распознавания`,languageAuto:`Автоопределение`,languageKz:`Казахский`,languageRu:`Русский`,languageEn:`Английский`,aiSimplify:`AI Упрощение текста`,aiBlindMode:`Режим для незрячих (AI)`,on:`ВКЛ`,off:`ВЫКЛ`,resetSettings:`Сбросить настройки`,adminMode:`Режим администратора`,adminAccess:`Admin доступ`,adminLoggedIn:`Вы вошли как администратор`,adminLogout:`Выйти из аккаунта`,adminPrompt:`Введите ключ для активации режима обучения`,adminLogin:`Войти`,close:`Закрыть`,inclusion:`Инклюзия`,tabChat:`Чат`,tabSettings:`Настройки`,madeInKazakhstan:`Сделано в Казахстане 🇰🇿`,closeWidgetAria:`Закрыть`,widgetDialogAria:`BariWeb Accessibility Widget`,triggerAria:`Открыть/Закрыть меню доступности`,adminKeyPlaceholder:`Admin Key`},kz:{announceVoiceInputAvailable:`Дауыстық енгізу қолжетімді. Түйме төменгі оң жақ бұрышта.`,announceWidgetOpened:`Виджет ашылды.`,announceSwitchedToChat:`Чатқа ауысты. Дауыстық енгізу қолжетімді.`,errorMicNotSupported:`Микрофонға қолдау жоқ.`,errorNoMicAccess:`Микрофонға рұқсат жоқ.`,errorProcessing:`Өңдеу қатесі.`,errorTooShort:`Жазба тым қысқа.`,errorSpeechNotRecognized:`Сөйлеу танылмады.`,errorRecognition:`Тану қатесі.`,screenLabelPrefix:`Бетте:`,chatEmptyTitle:`Сіздің көмекшіңіз`,chatEmptySub:`Міндетті сипаттаңыз — мен керек батырмаларды тауып, өрістерді толтырамын.`,confirmAction:`Әрекетті растау`,cancel:`Бас тарту`,listening:`Тыңдап тұрмын... (үнсіздікте тоқтаймын)`,recognizingSpeech:`Сөйлеуді танып жатырмын...`,micAria:`Дауыстық енгізуді қосу (жазу үшін ұстап тұрыңыз)`,inputPlaceholder:`Хабарлама енгізіңіз...`,inputAria:`Хабарлама енгізу өрісі`,ttsDisableAria:`Жауап дауысын өшіру`,ttsEnableAria:`Жауап дауысын қосу`,sendAria:`Хабарламаны жіберу`,tileTextSize:`Мәтін өлшемі`,tileMonochrome:`Қ/А`,valueMonochrome:`Монохром`,tileContrast:`Контраст`,valueDark:`Қою`,tileLinks:`Сілтемелер`,valueHighlight:`Белгілеу`,tileSpacing:`Аралықтар`,valueEnlarge:`Үлкейту`,tileFont:`Қаріп`,valueDyslexia:`Дислексия`,tileCursor:`Курсор`,tileVoice:`Дауыс`,valueRecording:`Жазып жатыр...`,valuePress:`Басыңыз`,colorSetup:`Түсті баптау`,tabBackground:`Фон`,tabHeader:`Тақырып`,tabText:`Мәтін`,decrease:`Азайту`,hue:`Реңк`,increase:`Көбейту`,recognitionLanguage:`Тіл`,changeRecognitionLanguage:`Тану тілін өзгерту`,languageAuto:`Автоанықтау`,languageKz:`Қазақша`,languageRu:`Орысша`,languageEn:`Ағылшынша`,aiSimplify:`AI мәтінді жеңілдету`,aiBlindMode:`Көру қабілеті нашарларға режим (AI)`,on:`ҚОС`,off:`ӨШІК`,resetSettings:`Баптауларды қалпына келтіру`,adminMode:`Әкімші режимі`,adminAccess:`Admin қолжетімділігі`,adminLoggedIn:`Сіз әкімші ретінде кірдіңіз`,adminLogout:`Аккаунттан шығу`,adminPrompt:`Оқыту режимін қосу үшін кілт енгізіңіз`,adminLogin:`Кіру`,close:`Жабу`,inclusion:`Инклюзия`,tabChat:`Чат`,tabSettings:`Баптаулар`,madeInKazakhstan:`Қазақстанда жасалған 🇰🇿`,closeWidgetAria:`Жабу`,widgetDialogAria:`BariWeb қолжетімділік виджеті`,triggerAria:`Қолжетімділік мәзірін ашу/жабу`,adminKeyPlaceholder:`Admin Key`},en:{announceVoiceInputAvailable:`Voice input is available. The button is in the bottom-right corner.`,announceWidgetOpened:`Widget opened.`,announceSwitchedToChat:`Switched to chat. Voice input is available.`,errorMicNotSupported:`Microphone is not supported.`,errorNoMicAccess:`No access to microphone.`,errorProcessing:`Processing error.`,errorTooShort:`Recording is too short.`,errorSpeechNotRecognized:`Speech was not recognized.`,errorRecognition:`Recognition error.`,screenLabelPrefix:`On page:`,chatEmptyTitle:`Your assistant`,chatEmptySub:`Describe your task — I will find the right buttons and fill fields for you.`,confirmAction:`Confirm action`,cancel:`Cancel`,listening:`Listening... (will stop on silence)`,recognizingSpeech:`Recognizing speech...`,micAria:`Enable voice input (hold to record)`,inputPlaceholder:`Type a message...`,inputAria:`Message input field`,ttsDisableAria:`Disable answer voice`,ttsEnableAria:`Enable answer voice`,sendAria:`Send message`,tileTextSize:`Text size`,tileMonochrome:`B/W`,valueMonochrome:`Monochrome`,tileContrast:`Contrast`,valueDark:`Dark`,tileLinks:`Links`,valueHighlight:`Highlight`,tileSpacing:`Spacing`,valueEnlarge:`Enlarge`,tileFont:`Font`,valueDyslexia:`Dyslexia`,tileCursor:`Cursor`,tileVoice:`Voice`,valueRecording:`Recording...`,valuePress:`Press`,colorSetup:`Color setup`,tabBackground:`Background`,tabHeader:`Header`,tabText:`Text`,decrease:`Decrease`,hue:`Hue`,increase:`Increase`,recognitionLanguage:`Language`,changeRecognitionLanguage:`Change recognition language`,languageAuto:`Auto detect`,languageKz:`Kazakh`,languageRu:`Russian`,languageEn:`English`,aiSimplify:`AI text simplification`,aiBlindMode:`Blind mode (AI)`,on:`ON`,off:`OFF`,resetSettings:`Reset settings`,adminMode:`Administrator mode`,adminAccess:`Admin access`,adminLoggedIn:`You are logged in as administrator`,adminLogout:`Log out`,adminPrompt:`Enter key to activate training mode`,adminLogin:`Log in`,close:`Close`,inclusion:`Inclusion`,tabChat:`Chat`,tabSettings:`Settings`,madeInKazakhstan:`Made in Kazakhstan 🇰🇿`,closeWidgetAria:`Close`,widgetDialogAria:`BariWeb Accessibility Widget`,triggerAria:`Open/close accessibility menu`,adminKeyPlaceholder:`Admin Key`}},$=class extends B{static{this.styles=[dt]}constructor(){super(),this._a11y=new pt(this),this._aiA11y=new kt(this),this._chat=new It(this),this.clientId=``,this._isOpen=!1,this._activeTab=`chat`,this._inputValue=``,this._isAdmin=!1,this._adminPassword=``,this._authError=``,this._currentScreenLabel=``,this._sttState=`idle`,this._sttLanguageMode=`auto`,this._sttError=``,this._adminClickCount=0,this._showAdminLogin=!1,this._mediaStream=null,this._audioContext=null,this._analyser=null,this._scriptProcessor=null,this._pcmChunks=[],this._sampleRate=44100,this._recordingStartTs=0,this._silenceStartedTs=null,this._silenceIntervalId=null,this._maxDurationTimeoutId=null,this._adminClickTimer=null,this._handleGlobalKeydown=e=>{this._isOpen&&e.altKey&&e.code===`KeyV`&&(e.preventDefault(),this._toggleVoice())};try{let e=localStorage.getItem(Wt);(e===`auto`||e===`kz`||e===`ru`||e===`en`)&&(this._sttLanguageMode=e)}catch{}this._checkAuthStatus()}_setSttLanguageMode(e){this._sttLanguageMode=e;try{localStorage.setItem(Wt,e)}catch{}}_uiLang(){return this._sttLanguageMode===`kz`?`kz`:this._sttLanguageMode===`en`?`en`:`ru`}_t(e){return Xt[this._uiLang()][e]??Xt.ru[e]??e}async _checkAuthStatus(){let e=localStorage.getItem(`bw_admin_token`);if(e)try{(await fetch(`http://localhost:8000/auth/login/widget/verify`,{headers:{Authorization:`Bearer ${e}`}})).ok?(this._isAdmin=!0,this._loadAdminUI()):localStorage.removeItem(`bw_admin_token`)}catch{try{let t=JSON.parse(atob(e.split(`.`)[1]));t.exp*1e3>Date.now()&&t.role===`admin`?(this._isAdmin=!0,this._loadAdminUI()):localStorage.removeItem(`bw_admin_token`)}catch{localStorage.removeItem(`bw_admin_token`)}}}async _loadAdminUI(){try{let{initAdminMode:e}=await Promise.resolve().then(()=>(Ut(),Lt));e(),Y.isAutoDiscoveryEnabled=!0}catch(e){console.error(`Admin UI load failed`,e)}}async _handleAdminLogin(){if(this._authError=``,!this.clientId){this._authError=`Client ID not configured`;return}try{let e=await fetch(`http://localhost:8000/auth/login/widget`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({client_public_id:this.clientId,admin_key:this._adminPassword})});if(e.ok){let{access_token:t}=await e.json();localStorage.setItem(`bw_admin_token`,t),this._isAdmin=!0,this._showAdminLogin=!1,this._loadAdminUI()}else this._authError=(await e.json().catch(()=>({}))).detail||`Invalid admin key`}catch{this._authError=`Connection failed`}}_handleAdminLogout(){localStorage.removeItem(`bw_admin_token`),this._isAdmin=!1,this._adminPassword=``,this._showAdminLogin=!1,Y.isAutoDiscoveryEnabled=!1,document.querySelector(`#bw-admin-wrapper`)?.remove()}_handleLogoClick(){this._adminClickCount++,this._adminClickCount>=5&&(this._showAdminLogin=!this._showAdminLogin,this._adminClickCount=0),this._adminClickTimer&&clearTimeout(this._adminClickTimer),this._adminClickTimer=setTimeout(()=>{this._adminClickCount=0},2e3)}connectedCallback(){super.connectedCallback(),Y.start(),Y.onStateChange(async e=>{try{let t=await fetch(`http://localhost:8000/v1/training/match-screen`,{method:`POST`,headers:{"Content-Type":`application/json`,"X-Client-ID":this.clientId||window.__BARIWEB_CLIENT_ID__||``},body:JSON.stringify({fingerprint:e.fingerprint})});if(t.ok){let e=await t.json();this._currentScreenLabel=e.matched?e.label:``}}catch{}}),window.addEventListener(`keydown`,this._handleGlobalKeydown)}disconnectedCallback(){super.disconnectedCallback(),Y.stop(),this._cleanupRecording(),window.removeEventListener(`keydown`,this._handleGlobalKeydown)}_announce(e){if(`speechSynthesis`in window){let t=new SpeechSynthesisUtterance(e);t.lang=this._uiLang()===`kz`?`kk-KZ`:this._uiLang()===`en`?`en-US`:`ru-RU`,window.speechSynthesis.speak(t)}}_beep(e){try{let t=new(window.AudioContext||window.webkitAudioContext),n=t.createOscillator(),r=t.createGain();n.type=`sine`,n.frequency.setValueAtTime(e,t.currentTime),r.gain.setValueAtTime(.1,t.currentTime),r.gain.exponentialRampToValueAtTime(1e-5,t.currentTime+.1),n.connect(r),r.connect(t.destination),n.start(),n.stop(t.currentTime+.1)}catch{}}_toggle(){this._isOpen=!this._isOpen,this._isOpen&&(setTimeout(()=>this._announce(this._t(`announceVoiceInputAvailable`)),500),this._scrollMessages())}setOpen(e){this._isOpen=e,e&&(this._announce(this._t(`announceWidgetOpened`)),this._scrollMessages())}_setTab(e){this._activeTab=e,e===`chat`&&(this._announce(this._t(`announceSwitchedToChat`)),this._scrollMessages(),setTimeout(()=>{this.renderRoot?.querySelector(`#bw-voice-btn`)?.focus()},300))}_handleInput(e){this._inputValue=e.target.value}_handleKeydown(e){e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),this._handleSend()),e.code===`Space`&&e.target.tagName!==`INPUT`&&(e.preventDefault(),this._sttState===`idle`&&this._startRecording())}async _handleSend(){let e=this._inputValue.trim();if(!e||this._chat.isLoading||this._sttState!==`idle`)return;this._inputValue=``;let t=this._chat.sendMessage(e,!1);this._scrollMessages(),await t,this._scrollMessages()}_scrollMessages(){this.updateComplete.then(()=>{this._messagesEl&&(this._messagesEl.scrollTop=this._messagesEl.scrollHeight)})}_getCurrentHue(){let e=this._a11y.settings;return e.activeColorTab===`background`?e.customBgHue||0:e.activeColorTab===`header`?e.customHeaderHue||0:e.customContentHue||0}_resetWidgetSettings(){this._a11y.reset(),this._aiA11y.simplifyEnabled&&this._aiA11y.toggleSimplify(),this._aiA11y.autoA11yEnabled&&this._aiA11y.toggleAutoA11y(),this._setSttLanguageMode(`auto`),this.requestUpdate()}_clearSttTimers(){this._silenceIntervalId!==null&&(window.clearInterval(this._silenceIntervalId),this._silenceIntervalId=null),this._maxDurationTimeoutId!==null&&(window.clearTimeout(this._maxDurationTimeoutId),this._maxDurationTimeoutId=null)}_cleanupRecording(){this._clearSttTimers(),this._analyser=null,this._scriptProcessor&&=(this._scriptProcessor.disconnect(),this._scriptProcessor.onaudioprocess=null,null),this._audioContext&&=(this._audioContext.close().catch(()=>{}),null),this._mediaStream&&=(this._mediaStream.getTracks().forEach(e=>e.stop()),null),this._pcmChunks=[],this._silenceStartedTs=null}async _toggleVoice(){if(this._sttState!==`processing`){if(this._sttState===`recording`){this._stopRecording();return}await this._startRecording()}}async _startRecording(){if(!navigator.mediaDevices?.getUserMedia){this._sttState=`error`,this._sttError=this._t(`errorMicNotSupported`);return}try{this._cleanupRecording(),this._sttError=``;let e=await navigator.mediaDevices.getUserMedia({audio:!0});this._mediaStream=e,this._pcmChunks=[],this._recordingStartTs=Date.now(),this._silenceStartedTs=null,this._audioContext=new AudioContext,this._sampleRate=this._audioContext.sampleRate;let t=this._audioContext.createMediaStreamSource(e);this._analyser=this._audioContext.createAnalyser(),this._analyser.fftSize=2048,t.connect(this._analyser),this._scriptProcessor=this._audioContext.createScriptProcessor(4096,1,1),t.connect(this._scriptProcessor),this._scriptProcessor.connect(this._audioContext.destination),this._scriptProcessor.onaudioprocess=e=>{this._sttState===`recording`&&(this._pcmChunks.push(new Float32Array(e.inputBuffer.getChannelData(0))),e.outputBuffer.getChannelData(0).fill(0))},this._sttState=`recording`,this._beep(880),this._maxDurationTimeoutId=window.setTimeout(()=>{this._sttState===`recording`&&this._stopRecording()},Jt);let n=new Uint8Array(this._analyser.fftSize);this._silenceIntervalId=window.setInterval(()=>{if(!this._analyser||this._sttState!==`recording`)return;this._analyser.getByteTimeDomainData(n);let e=0;for(let t=0;t<n.length;t++){let r=(n[t]-128)/128;e+=r*r}Math.sqrt(e/n.length)<Kt?this._silenceStartedTs?Date.now()-this._silenceStartedTs>=qt&&this._stopRecording():this._silenceStartedTs=Date.now():this._silenceStartedTs=null},Gt)}catch{this._sttState=`error`,this._sttError=this._t(`errorNoMicAccess`),this._cleanupRecording()}}_stopRecording(){this._sttState===`recording`&&(this._clearSttTimers(),this._sttState=`processing`,this._beep(440),this._finalizeRecording().catch(e=>{this._sttState=`error`,this._sttError=e?.message||this._t(`errorProcessing`)}))}async _finalizeRecording(){let e=Date.now()-this._recordingStartTs,t=this._pcmChunks.reduce((e,t)=>e+t.length,0),n=new Float32Array(t),r=0;for(let e of this._pcmChunks)n.set(e,r),r+=e.length;let i=this._encodeWav(n,this._sampleRate);if(this._cleanupRecording(),e<Yt||i.size===0){this._sttState=`error`,this._sttError=this._t(`errorTooShort`);return}try{let e=(await this._chat.transcribeAudio(i,this._sttLanguageMode)).text?.trim();if(!e){this._sttState=`error`,this._sttError=this._t(`errorSpeechNotRecognized`);return}await this._chat.sendMessage(e,!0),this._sttState=`idle`,this._sttError=``,this._inputValue=``,this._scrollMessages()}catch(e){this._sttState=`error`,this._sttError=e?.message||this._t(`errorRecognition`)}}_encodeWav(e,t){let n=t*2,r=e.length*2,i=new ArrayBuffer(44+r),a=new DataView(i),o=(e,t)=>{for(let n=0;n<t.length;n++)a.setUint8(e+n,t.charCodeAt(n))};o(0,`RIFF`),a.setUint32(4,36+r,!0),o(8,`WAVE`),o(12,`fmt `),a.setUint32(16,16,!0),a.setUint16(20,1,!0),a.setUint16(22,1,!0),a.setUint32(24,t,!0),a.setUint32(28,n,!0),a.setUint16(32,2,!0),a.setUint16(34,16,!0),o(36,`data`),a.setUint32(40,r,!0);let s=44;for(let t=0;t<e.length;t++){let n=Math.max(-1,Math.min(1,e[t]));a.setInt16(s,n<0?n*32768:n*32767,!0),s+=2}return new Blob([i],{type:`audio/wav`})}_vibrate(){`vibrate`in navigator&&navigator.vibrate(20)}_renderChatTab(){let e=this._chat.messages,t=this._chat.isLoading,n=this._chat.pendingConfirmation,r=t||this._sttState===`processing`,i=e=>this._t(e);return j`
|
|
1117
1164
|
<div class="chat-messages" id="bw-chat-messages">
|
|
1118
1165
|
${this._currentScreenLabel?j`
|
|
1119
1166
|
<div class="screen-label-badge">
|
|
1120
1167
|
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" width="12" height="12"><polyline points="20 6 9 17 4 12"/></svg>
|
|
1121
|
-
${
|
|
1168
|
+
${i(`screenLabelPrefix`)} <strong>${this._currentScreenLabel}</strong>
|
|
1122
1169
|
</div>
|
|
1123
1170
|
`:``}
|
|
1124
1171
|
|
|
1125
|
-
${
|
|
1172
|
+
${e.length===0?j`
|
|
1126
1173
|
<div class="chat-empty">
|
|
1127
|
-
${
|
|
1128
|
-
<p class="chat-empty-title">${
|
|
1129
|
-
<p class="chat-empty-sub">${
|
|
1174
|
+
${W.accessibility}
|
|
1175
|
+
<p class="chat-empty-title">${i(`chatEmptyTitle`)}</p>
|
|
1176
|
+
<p class="chat-empty-sub">${i(`chatEmptySub`)}</p>
|
|
1130
1177
|
</div>
|
|
1131
|
-
`:
|
|
1178
|
+
`:e.map(e=>{if(e.role===`assistant`&&(e.text.includes(`✅`)||e.text.includes(`⌨️`)||e.text.includes(`🔄`))){let t=e.text.split(`
|
|
1179
|
+
`)[0];return j`
|
|
1132
1180
|
<details class="system-log">
|
|
1133
|
-
<summary class="system-log-header"
|
|
1134
|
-
|
|
1181
|
+
<summary class="system-log-header">
|
|
1182
|
+
${W.code} <span>${t}</span>
|
|
1183
|
+
</summary>
|
|
1135
1184
|
<div class="system-log-details">${e.text}</div>
|
|
1136
|
-
</details
|
|
1185
|
+
</details>
|
|
1186
|
+
`}return j`
|
|
1187
|
+
<div class="chat-bubble ${e.role}">
|
|
1188
|
+
${e.text}
|
|
1189
|
+
</div>
|
|
1190
|
+
`})}
|
|
1137
1191
|
|
|
1138
|
-
${
|
|
1192
|
+
${t?j`
|
|
1139
1193
|
<div class="typing-indicator">
|
|
1140
|
-
<div class="typing-dot"></div
|
|
1141
|
-
|
|
1194
|
+
<div class="typing-dot"></div>
|
|
1195
|
+
<div class="typing-dot"></div>
|
|
1196
|
+
<div class="typing-dot"></div>
|
|
1197
|
+
</div>
|
|
1198
|
+
`:``}
|
|
1142
1199
|
</div>
|
|
1143
1200
|
|
|
1144
|
-
${
|
|
1201
|
+
${n?j`
|
|
1145
1202
|
<div class="confirm-panel">
|
|
1146
1203
|
<button class="btn-confirm" @click=${()=>this._chat.confirmAction()} id="bw-confirm-action">
|
|
1147
|
-
${
|
|
1204
|
+
${i(`confirmAction`)}
|
|
1148
1205
|
</button>
|
|
1149
1206
|
<button class="btn-cancel" @click=${()=>this._chat.cancelAction()} id="bw-cancel-action">
|
|
1150
|
-
${
|
|
1207
|
+
${i(`cancel`)}
|
|
1151
1208
|
</button>
|
|
1152
1209
|
</div>
|
|
1153
1210
|
`:j`
|
|
1154
1211
|
<div class="chat-input-area">
|
|
1155
1212
|
${this._sttState===`idle`?``:j`
|
|
1156
1213
|
<div class="stt-banner ${this._sttState}">
|
|
1157
|
-
${this._sttState===`recording
|
|
1214
|
+
${this._sttState===`recording`?`REC: ${i(`listening`)}`:this._sttState===`processing`?`... ${i(`recognizingSpeech`)}`:`! ${this._sttError}`}
|
|
1158
1215
|
</div>`}
|
|
1159
1216
|
<div class="chat-input-row">
|
|
1160
|
-
<!-- 🎙️ Primary Mic Button (Large Target Size) -->
|
|
1161
1217
|
<button class="chat-icon-btn ${this._sttState===`recording`?`recording`:``}"
|
|
1162
1218
|
@mouseenter=${this._vibrate}
|
|
1163
1219
|
@focus=${this._vibrate}
|
|
@@ -1165,166 +1221,172 @@
|
|
|
1165
1221
|
@mouseup=${this._stopRecording}
|
|
1166
1222
|
@touchstart=${e=>{e.preventDefault(),this._startRecording(),this._vibrate()}}
|
|
1167
1223
|
@touchend=${e=>{e.preventDefault(),this._stopRecording()}}
|
|
1168
|
-
@click=${this._toggleVoice}
|
|
1169
|
-
?disabled=${this._sttState===`processing`||
|
|
1170
|
-
id="bw-voice-btn"
|
|
1171
|
-
aria-label
|
|
1172
|
-
${
|
|
1224
|
+
@click=${this._toggleVoice}
|
|
1225
|
+
?disabled=${this._sttState===`processing`||t}
|
|
1226
|
+
id="bw-voice-btn"
|
|
1227
|
+
aria-label=${i(`micAria`)}>
|
|
1228
|
+
${W.mic}
|
|
1173
1229
|
</button>
|
|
1174
1230
|
|
|
1175
1231
|
<input
|
|
1176
1232
|
class="chat-input"
|
|
1177
1233
|
type="text"
|
|
1178
|
-
placeholder
|
|
1234
|
+
placeholder=${i(`inputPlaceholder`)}
|
|
1179
1235
|
.value=${this._inputValue}
|
|
1180
1236
|
@input=${this._handleInput}
|
|
1181
1237
|
@keydown=${this._handleKeydown}
|
|
1182
|
-
?disabled=${
|
|
1238
|
+
?disabled=${r}
|
|
1183
1239
|
id="bw-chat-input"
|
|
1184
|
-
aria-label
|
|
1240
|
+
aria-label=${i(`inputAria`)}
|
|
1185
1241
|
/>
|
|
1186
1242
|
|
|
1187
|
-
|
|
1243
|
+
<button class="chat-icon-btn ${this._chat.isTtsEnabled()?`tts-on`:``}"
|
|
1244
|
+
@click=${()=>{this._chat.setTtsEnabled(!this._chat.isTtsEnabled()),this.requestUpdate()}}
|
|
1245
|
+
id="bw-tts-btn"
|
|
1246
|
+
aria-label=${this._chat.isTtsEnabled()?i(`ttsDisableAria`):i(`ttsEnableAria`)}>
|
|
1247
|
+
${this._chat.isTtsEnabled()?W.volumeOn:W.volumeOff}
|
|
1248
|
+
</button>
|
|
1249
|
+
|
|
1188
1250
|
<button class="chat-send-btn" @click=${this._handleSend}
|
|
1189
|
-
?disabled=${!this._inputValue.trim()||
|
|
1190
|
-
id="bw-send-btn"
|
|
1191
|
-
aria-label
|
|
1192
|
-
${
|
|
1251
|
+
?disabled=${!this._inputValue.trim()||r}
|
|
1252
|
+
id="bw-send-btn"
|
|
1253
|
+
aria-label=${i(`sendAria`)}>
|
|
1254
|
+
${W.send}
|
|
1193
1255
|
</button>
|
|
1194
1256
|
</div>
|
|
1195
1257
|
</div>
|
|
1196
1258
|
`}
|
|
1197
|
-
`}_renderA11yTab(){let e=
|
|
1259
|
+
`}_renderA11yTab(){let e=this._a11y.settings,t=e=>this._t(e);return j`
|
|
1198
1260
|
<div class="a11y-scroller">
|
|
1199
|
-
|
|
1200
|
-
<!-- Language config mapped to TOP of settings tab -->
|
|
1201
|
-
<div style="padding: 16px 16px 0;">
|
|
1202
|
-
<div style="display: flex; align-items: center; justify-content: space-between; padding: 12px; background: var(--bw-bg-subtle, #f8fafc); border-radius: var(--bw-radius, 14px); margin-bottom: 0px;">
|
|
1203
|
-
<div style="display: flex; align-items: center; gap: 10px; font-weight: 600; font-size: 14px; color: var(--bw-fg, #1e293b);">
|
|
1204
|
-
${H.languages} ${e.langLabel}
|
|
1205
|
-
</div>
|
|
1206
|
-
<select style="height: 34px; padding: 0 8px; border: 1px solid var(--bw-primary, #6d28d9); border-radius: 8px; background: rgba(109, 40, 217, 0.05); color: var(--bw-primary, #6d28d9); cursor: pointer; outline: none; font-size: 13px; font-weight: 600;"
|
|
1207
|
-
.value=${this._sttLanguageMode}
|
|
1208
|
-
@change=${e=>{this._setSttLanguageMode(e.target.value),this.requestUpdate()}}
|
|
1209
|
-
aria-label="${e.langLabel}">
|
|
1210
|
-
<option value="kz">${Q.kz.langKz}</option>
|
|
1211
|
-
<option value="ru">${Q.ru.langRu}</option>
|
|
1212
|
-
<option value="en">${Q.en.langEn}</option>
|
|
1213
|
-
</select>
|
|
1214
|
-
</div>
|
|
1215
|
-
</div>
|
|
1216
|
-
|
|
1217
1261
|
<div class="settings-grid">
|
|
1218
|
-
${
|
|
1262
|
+
${[{id:`bw-tile-textscale`,icon:W.textSize,label:t(`tileTextSize`),value:`${Math.round(e.textScale*100)}%`,active:e.textScale>1,action:()=>this._a11y.incrementTextScale()},{id:`bw-tile-monochrome`,icon:W.palette,label:t(`tileMonochrome`),value:t(`valueMonochrome`),active:e.monochrome,action:()=>this._a11y.toggleMonochrome()},{id:`bw-tile-contrast`,icon:W.sun,label:t(`tileContrast`),value:t(`valueDark`),active:e.darkHighContrast,action:()=>this._a11y.toggleDarkHighContrast()},{id:`bw-tile-links`,icon:W.link,label:t(`tileLinks`),value:t(`valueHighlight`),active:e.linkHighlight,action:()=>this._a11y.toggleLinkHighlight()},{id:`bw-tile-spacing`,icon:W.type,label:t(`tileSpacing`),value:t(`valueEnlarge`),active:e.textSpacing,action:()=>this._a11y.toggleTextSpacing()},{id:`bw-tile-font`,icon:W.type,label:t(`tileFont`),value:t(`valueDyslexia`),active:e.dyslexicFont,action:()=>this._a11y.toggleDyslexicFont()},{id:`bw-tile-cursor`,icon:W.mouse,label:t(`tileCursor`),value:t(`valueEnlarge`),active:e.cursorMagnifier,action:()=>this._a11y.toggleCursorMagnifier()},{id:`bw-tile-voice`,icon:null,label:t(`tileVoice`),value:this._sttState===`recording`?t(`valueRecording`):t(`valuePress`),active:this._sttState===`recording`,action:()=>this._toggleVoice()}].map(e=>j`
|
|
1219
1263
|
<button class="settings-card" ?active=${e.active} @click=${e.action} id=${e.id}
|
|
1220
1264
|
aria-pressed=${e.active?`true`:`false`} aria-label=${e.label}>
|
|
1221
|
-
${e.icon||
|
|
1265
|
+
${e.icon||W.mic}
|
|
1222
1266
|
<span class="settings-card-label">${e.label}</span>
|
|
1223
1267
|
<span class="settings-card-value">${e.value}</span>
|
|
1224
|
-
${e.active?j`<span class="active-badge">${
|
|
1268
|
+
${e.active?j`<span class="active-badge">${W.check}</span>`:``}
|
|
1225
1269
|
</button>
|
|
1226
1270
|
`)}
|
|
1227
1271
|
</div>
|
|
1228
1272
|
|
|
1229
1273
|
<div class="color-section">
|
|
1230
1274
|
<div class="color-section-header">
|
|
1231
|
-
${
|
|
1232
|
-
<h4 class="color-section-title">${
|
|
1275
|
+
${W.droplet}
|
|
1276
|
+
<h4 class="color-section-title">${t(`colorSetup`)}</h4>
|
|
1233
1277
|
</div>
|
|
1234
1278
|
<div class="color-tabs">
|
|
1235
|
-
<button class="color-tab" ?active=${
|
|
1236
|
-
@click=${()=>{
|
|
1237
|
-
<button class="color-tab" ?active=${
|
|
1238
|
-
@click=${()=>{
|
|
1239
|
-
<button class="color-tab" ?active=${
|
|
1240
|
-
@click=${()=>{
|
|
1279
|
+
<button class="color-tab" ?active=${e.activeColorTab===`background`}
|
|
1280
|
+
@click=${()=>{e.activeColorTab=`background`,this.requestUpdate()}}>${t(`tabBackground`)}</button>
|
|
1281
|
+
<button class="color-tab" ?active=${e.activeColorTab===`header`}
|
|
1282
|
+
@click=${()=>{e.activeColorTab=`header`,this.requestUpdate()}}>${t(`tabHeader`)}</button>
|
|
1283
|
+
<button class="color-tab" ?active=${e.activeColorTab===`content`}
|
|
1284
|
+
@click=${()=>{e.activeColorTab=`content`,this.requestUpdate()}}>${t(`tabText`)}</button>
|
|
1241
1285
|
</div>
|
|
1242
1286
|
<div class="hue-row">
|
|
1243
|
-
<button class="hue-step-btn" @click=${()=>this._a11y.setCustomHue((this._getCurrentHue()-15+360)%360)} aria-label
|
|
1287
|
+
<button class="hue-step-btn" @click=${()=>this._a11y.setCustomHue((this._getCurrentHue()-15+360)%360)} aria-label=${t(`decrease`)}>-</button>
|
|
1244
1288
|
<input type="range" class="hue-slider" min="0" max="360"
|
|
1245
1289
|
.value=${String(this._getCurrentHue())}
|
|
1246
1290
|
@input=${e=>this._a11y.setCustomHue(parseInt(e.target.value))}
|
|
1247
|
-
aria-label
|
|
1248
|
-
<button class="hue-step-btn" @click=${()=>this._a11y.setCustomHue((this._getCurrentHue()+15)%360)} aria-label
|
|
1291
|
+
aria-label=${t(`hue`)} />
|
|
1292
|
+
<button class="hue-step-btn" @click=${()=>this._a11y.setCustomHue((this._getCurrentHue()+15)%360)} aria-label=${t(`increase`)}>+</button>
|
|
1249
1293
|
</div>
|
|
1250
1294
|
</div>
|
|
1251
1295
|
|
|
1252
|
-
<div class="ai-tools-section"
|
|
1296
|
+
<div class="ai-tools-section">
|
|
1297
|
+
<div style="display: flex; align-items: center; justify-content: space-between; padding: 12px; background: var(--bw-bg-subtle, #f8fafc); border-radius: var(--bw-radius, 14px); margin-bottom: 12px;">
|
|
1298
|
+
<div class="lang-row-label" style="display: flex; align-items: center; gap: 10px; font-weight: 600; font-size: 14px; color: var(--bw-fg, #1e293b);">
|
|
1299
|
+
<span class="lang-row-icon">${W.languages}</span>${t(`recognitionLanguage`)}
|
|
1300
|
+
</div>
|
|
1301
|
+
<select style="height: 34px; padding: 0 8px; border: 1px solid var(--bw-border); border-radius: 8px; background: #fff; cursor: pointer; outline: none; font-size: 13px;"
|
|
1302
|
+
.value=${this._sttLanguageMode}
|
|
1303
|
+
@change=${e=>{this._setSttLanguageMode(e.target.value),this.requestUpdate()}}
|
|
1304
|
+
aria-label=${t(`changeRecognitionLanguage`)}>
|
|
1305
|
+
<option value="auto">${t(`languageAuto`)}</option>
|
|
1306
|
+
<option value="kz">${t(`languageKz`)}</option>
|
|
1307
|
+
<option value="ru">${t(`languageRu`)}</option>
|
|
1308
|
+
<option value="en">${t(`languageEn`)}</option>
|
|
1309
|
+
</select>
|
|
1310
|
+
</div>
|
|
1311
|
+
|
|
1253
1312
|
<button class="ai-tool-btn ${this._aiA11y.simplifyEnabled?`active`:``}"
|
|
1254
1313
|
@click=${()=>this._aiA11y.toggleSimplify()} id="bw-ai-simplify">
|
|
1255
|
-
${
|
|
1256
|
-
<span class="ai-tool-btn-label">${
|
|
1314
|
+
${W.textSize}
|
|
1315
|
+
<span class="ai-tool-btn-label">${t(`aiSimplify`)}</span>
|
|
1257
1316
|
<span class="ai-tool-badge ${this._aiA11y.simplifyEnabled?`on`:``}">
|
|
1258
|
-
${this._aiA11y.simplifyEnabled?
|
|
1317
|
+
${this._aiA11y.simplifyEnabled?t(`on`):t(`off`)}
|
|
1259
1318
|
</span>
|
|
1260
1319
|
</button>
|
|
1261
|
-
|
|
1320
|
+
|
|
1262
1321
|
<button class="ai-tool-btn ${this._aiA11y.autoA11yEnabled?`active`:``}"
|
|
1263
|
-
@click=${()=>this._aiA11y.toggleAutoA11y()}
|
|
1322
|
+
@click=${()=>this._aiA11y.toggleAutoA11y()}
|
|
1264
1323
|
id="bw-ai-fix">
|
|
1265
|
-
${
|
|
1266
|
-
<span class="ai-tool-btn-label">${
|
|
1324
|
+
${W.accessibility}
|
|
1325
|
+
<span class="ai-tool-btn-label">${t(`aiBlindMode`)}</span>
|
|
1267
1326
|
<span class="ai-tool-badge ${this._aiA11y.autoA11yEnabled?`on`:``}">
|
|
1268
|
-
${this._aiA11y.autoA11yEnabled?
|
|
1327
|
+
${this._aiA11y.autoA11yEnabled?t(`on`):t(`off`)}
|
|
1269
1328
|
</span>
|
|
1270
1329
|
</button>
|
|
1271
1330
|
</div>
|
|
1331
|
+
|
|
1332
|
+
<div class="settings-actions">
|
|
1333
|
+
<button class="reset-settings-btn" @click=${this._resetWidgetSettings} id="bw-reset-settings-btn">
|
|
1334
|
+
${W.refresh}
|
|
1335
|
+
${t(`resetSettings`)}
|
|
1336
|
+
</button>
|
|
1337
|
+
</div>
|
|
1272
1338
|
</div>
|
|
1273
|
-
`}_renderAdminOverlay(){return this.
|
|
1339
|
+
`}_renderAdminOverlay(){if(!this._showAdminLogin)return``;let e=e=>this._t(e);return j`
|
|
1274
1340
|
<div class="admin-overlay">
|
|
1275
|
-
<div class="admin-icon"
|
|
1276
|
-
<h4>${this._isAdmin
|
|
1341
|
+
<div class="admin-icon">${W.shield}</div>
|
|
1342
|
+
<h4>${this._isAdmin?e(`adminMode`):e(`adminAccess`)}</h4>
|
|
1277
1343
|
${this._isAdmin?j`
|
|
1278
|
-
<p class="admin-status"
|
|
1279
|
-
<button class="admin-logout-btn" @click=${this._handleAdminLogout}
|
|
1344
|
+
<p class="admin-status">${e(`adminLoggedIn`)}</p>
|
|
1345
|
+
<button class="admin-logout-btn" @click=${this._handleAdminLogout}>${e(`adminLogout`)}</button>
|
|
1280
1346
|
`:j`
|
|
1281
|
-
<p
|
|
1282
|
-
<input type="password" placeholder
|
|
1347
|
+
<p>${e(`adminPrompt`)}</p>
|
|
1348
|
+
<input type="password" placeholder=${e(`adminKeyPlaceholder`)}
|
|
1283
1349
|
.value=${this._adminPassword}
|
|
1284
1350
|
@input=${e=>{this._adminPassword=e.target.value}}
|
|
1285
1351
|
@keydown=${e=>{e.key===`Enter`&&this._handleAdminLogin()}} />
|
|
1286
|
-
${this._authError?j`<
|
|
1287
|
-
<button class="admin-login-btn" @click=${this._handleAdminLogin}
|
|
1352
|
+
${this._authError?j`<div class="auth-error">${this._authError}</div>`:``}
|
|
1353
|
+
<button class="admin-login-btn" @click=${this._handleAdminLogin}>${e(`adminLogin`)}</button>
|
|
1288
1354
|
`}
|
|
1289
1355
|
<button class="admin-close-btn" @click=${()=>{this._showAdminLogin=!1,this._authError=``}}>
|
|
1290
|
-
|
|
1356
|
+
${e(`close`)}
|
|
1291
1357
|
</button>
|
|
1292
1358
|
</div>
|
|
1293
|
-
|
|
1359
|
+
`}render(){let e=e=>this._t(e);return j`
|
|
1294
1360
|
<div class="widget-container">
|
|
1295
|
-
<!-- Panel -->
|
|
1296
1361
|
<div class="bw-panel ${this._isOpen?`panel-visible`:`panel-hidden`}"
|
|
1297
|
-
role="dialog" aria-modal="true" aria-label
|
|
1362
|
+
role="dialog" aria-modal="true" aria-label=${e(`widgetDialogAria`)}>
|
|
1298
1363
|
|
|
1299
|
-
<!-- Header -->
|
|
1300
1364
|
<div class="bw-header">
|
|
1301
1365
|
<div class="header-branding" @click=${this._handleLogoClick} id="bw-logo">
|
|
1302
|
-
${
|
|
1366
|
+
${W.accessibility}
|
|
1303
1367
|
<div class="header-branding-text">
|
|
1304
1368
|
<span class="header-brand-name">BariWeb</span>
|
|
1305
|
-
<span class="header-brand-sub">${e
|
|
1369
|
+
<span class="header-brand-sub">${e(`inclusion`)}</span>
|
|
1306
1370
|
</div>
|
|
1307
1371
|
</div>
|
|
1308
|
-
<button class="close-btn" @click=${this._toggle} aria-label
|
|
1309
|
-
${
|
|
1372
|
+
<button class="close-btn" @click=${this._toggle} aria-label=${e(`closeWidgetAria`)} id="bw-close">
|
|
1373
|
+
${W.close}
|
|
1310
1374
|
</button>
|
|
1311
1375
|
</div>
|
|
1312
1376
|
|
|
1313
|
-
<!-- Tabs -->
|
|
1314
1377
|
<div class="bw-tabs" role="tablist">
|
|
1315
1378
|
<button class="bw-tab" ?active=${this._activeTab===`chat`}
|
|
1316
1379
|
@click=${()=>this._setTab(`chat`)} role="tab"
|
|
1317
|
-
aria-selected=${this._activeTab===`chat`} id="bw-tab-chat">
|
|
1318
|
-
${
|
|
1380
|
+
aria-selected=${this._activeTab===`chat`?`true`:`false`} id="bw-tab-chat">
|
|
1381
|
+
${W.chat} ${e(`tabChat`)}
|
|
1319
1382
|
</button>
|
|
1320
1383
|
<button class="bw-tab" ?active=${this._activeTab===`a11y`}
|
|
1321
1384
|
@click=${()=>this._setTab(`a11y`)} role="tab"
|
|
1322
|
-
aria-selected=${this._activeTab===`a11y`} id="bw-tab-settings">
|
|
1323
|
-
${
|
|
1385
|
+
aria-selected=${this._activeTab===`a11y`?`true`:`false`} id="bw-tab-settings">
|
|
1386
|
+
${W.settings} ${e(`tabSettings`)}
|
|
1324
1387
|
</button>
|
|
1325
1388
|
</div>
|
|
1326
1389
|
|
|
1327
|
-
<!-- Content -->
|
|
1328
1390
|
<div class="bw-content">
|
|
1329
1391
|
<div class="tab-panel" ?active=${this._activeTab===`chat`} role="tabpanel">
|
|
1330
1392
|
${this._renderChatTab()}
|
|
@@ -1335,20 +1397,18 @@
|
|
|
1335
1397
|
${this._renderAdminOverlay()}
|
|
1336
1398
|
</div>
|
|
1337
1399
|
|
|
1338
|
-
<!-- Footer -->
|
|
1339
1400
|
<div class="bw-footer" @click=${this._handleLogoClick}>
|
|
1340
1401
|
<div class="footer-brand">
|
|
1341
|
-
${
|
|
1402
|
+
${W.accessibility} BariWeb
|
|
1342
1403
|
</div>
|
|
1343
|
-
<span>${e
|
|
1404
|
+
<span>${e(`madeInKazakhstan`)}</span>
|
|
1344
1405
|
</div>
|
|
1345
1406
|
</div>
|
|
1346
1407
|
|
|
1347
|
-
<!-- FAB Trigger -->
|
|
1348
1408
|
<button class="trigger" @click=${this._toggle}
|
|
1349
|
-
aria-expanded=${this._isOpen} aria-label
|
|
1350
|
-
id="bw-trigger" style="position:fixed; bottom:24px; left:24px; width:60px; height:60px; border-radius:50%; background:var(--bw-primary
|
|
1351
|
-
${this._isOpen?
|
|
1409
|
+
aria-expanded=${this._isOpen} aria-label=${e(`triggerAria`)}
|
|
1410
|
+
id="bw-trigger" style="position:fixed; bottom:24px; left:24px; width:60px; height:60px; border-radius:50%; background:var(--bw-primary,#6d28d9); color:var(--bw-primary-fg, #05050a); border:none; cursor:pointer; display:flex; align-items:center; justify-content:center; pointer-events:auto; box-shadow:0 4px 20px rgba(0,0,0,0.3); transition: transform 0.3s cubic-bezier(0.34,1.56,0.64,1), opacity 0.2s;">
|
|
1411
|
+
${this._isOpen?W.close:W.accessibility}
|
|
1352
1412
|
</button>
|
|
1353
1413
|
</div>
|
|
1354
|
-
`}};
|
|
1414
|
+
`}};X([it({type:String,attribute:`client-id`})],$.prototype,`clientId`,void 0),X([V()],$.prototype,`_isOpen`,void 0),X([V()],$.prototype,`_activeTab`,void 0),X([V()],$.prototype,`_inputValue`,void 0),X([V()],$.prototype,`_isAdmin`,void 0),X([V()],$.prototype,`_adminPassword`,void 0),X([V()],$.prototype,`_authError`,void 0),X([V()],$.prototype,`_currentScreenLabel`,void 0),X([V()],$.prototype,`_sttState`,void 0),X([V()],$.prototype,`_sttLanguageMode`,void 0),X([V()],$.prototype,`_sttError`,void 0),X([V()],$.prototype,`_adminClickCount`,void 0),X([V()],$.prototype,`_showAdminLogin`,void 0),X([ot(`.chat-messages`)],$.prototype,`_messagesEl`,void 0),$=X([tt(`bw-widget`)],$);var Zt=()=>{let e=document.querySelector(`bw-widget`)?.getAttribute(`client-id`);if(e)return e;let t=(document.currentScript||document.querySelector(`script[src*="bariweb"]`))?.getAttribute(`data-client-id`);return t||=document.querySelector(`script[data-client-id]`)?.getAttribute(`data-client-id`)||``,t||window.__BARIWEB_CLIENT_ID__||``},Qt=Zt();window.__BARIWEB_CLIENT_ID__=Qt,pe.setConfig({baseUrl:`http://localhost:8000`}),pe.interceptors.request.use(e=>{let t=Zt();return e.headers.set(`X-Client-ID`,t),e})})();
|