makethisbetter 1.28.6 → 1.28.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,5 +1,5 @@
1
1
  <p align="center">
2
- <img src="https://makethisbetter.dev/icon.svg" width="80" height="80" alt="Make This Better">
2
+ <img src="assets/logo.png" width="80" height="80" alt="Make This Better">
3
3
  </p>
4
4
 
5
5
  <h1 align="center">Make This Better</h1>
@@ -62,11 +62,11 @@
62
62
  <div class="mtb-chat-finalize-message">${d(this.i18n.error.finalize_message)}</div>
63
63
  ${t?`<button class="mtb-chat-finalize-retry" type="button">${d(this.i18n.clarify.retry)}</button>`:""}
64
64
  <button class="mtb-chat-finalize-close" type="button">${d(this.i18n.success.close)}</button>
65
- `,t&&e.querySelector(".mtb-chat-finalize-retry").addEventListener("click",()=>{const r=e.querySelector(".mtb-chat-finalize-retry");r.disabled=!0,r.innerHTML='<span class="mtb-chat-finalize-spinner" aria-label="Retrying"></span>',t()}),e.querySelector(".mtb-chat-finalize-close").addEventListener("click",()=>this.opts.onCancel())}showFinalizeSuccess(){this.state="done",this.renderSuccess()}attachHandoff(){const t=this.el.querySelector(".mtb-chat-success");if(!t)return;this.i18n.success;const e=this.opts.resolveBoardLink?.(),r=t.querySelector(".mtb-chat-success-link-pending");e&&r&&(r.classList.remove("mtb-chat-success-link-pending"),r.addEventListener("click",s=>{s.preventDefault(),e()}));const n=this.opts.resolveEmailCapture?.();n&&!t.querySelector(".mtb-chat-email-card")?(this.autoCloseTimer&&(clearTimeout(this.autoCloseTimer),this.autoCloseTimer=null),t.classList.remove("mtb-chat-success-simple"),t.appendChild(this.buildEmailCard(n))):this.finalized&&!n&&!this.autoCloseTimer&&!t.querySelector(".mtb-chat-email-card")&&(this.autoCloseTimer=setTimeout(()=>this.destroy(),Rt))}finalizeInBackground(){Promise.resolve(this.opts.onFinalize()).then(()=>{this.finalized=!0,this.attachHandoff()}).catch(()=>{})}buildEmailCard(t){const e=this.i18n.success,r=document.createElement("div");r.className="mtb-chat-email-card";const n=document.createElement("div");n.className="mtb-chat-email-row";const s=document.createElement("div");s.className="mtb-chat-email-field";const o=document.createElement("input");o.className="mtb-chat-email-input",o.type="email",o.placeholder=e.email_cta,s.appendChild(o);const a=document.createElement("button");a.className="mtb-chat-email-submit",a.type="button",a.textContent=e.notify,a.disabled=!0;const l=async()=>{const c=o.value.trim();if(!c)return;if(a.disabled=!0,o.disabled=!0,await t.onSubmit(c)){const b=document.createElement("div");b.className="mtb-chat-email-note",b.textContent=e.email_saved,r.replaceChildren(b),this.autoCloseTimer=setTimeout(()=>this.destroy(),Rt);return}o.disabled=!1,a.disabled=!1;const u=r.querySelector(".mtb-chat-email-error")??document.createElement("div");u.className="mtb-chat-email-error",u.textContent=e.email_error,r.appendChild(u)};return o.addEventListener("input",()=>{a.disabled=!o.value.trim()}),o.addEventListener("keydown",c=>{c.key==="Enter"&&o.value.trim()&&l()}),a.addEventListener("click",()=>void l()),n.appendChild(s),n.appendChild(a),r.appendChild(n),r}appendUserBubble(t){const e=document.createElement("div");e.className="mtb-chat-bubble mtb-chat-bubble-user",e.textContent=t,this.messagesEl.appendChild(e),this.messagesEl.scrollTop=this.messagesEl.scrollHeight,this.inputEl.value="",this.sendBtn.disabled=!0}startStreamingBubble(){const t=document.createElement("div");t.className="mtb-chat-ai-row",t.innerHTML=`<div class="mtb-chat-avatar">${q}</div><div class="mtb-chat-bubble mtb-chat-bubble-ai"></div>`,this.messagesEl.appendChild(t),this.streamingBubbleEl=t.querySelector(".mtb-chat-bubble-ai")}appendStreamDelta(t){this.streamingBubbleEl&&(this.streamingBubbleEl.textContent=(this.streamingBubbleEl.textContent??"")+t,this.messagesEl.scrollTop=this.messagesEl.scrollHeight)}endStreamingBubble(){this.streamingBubbleEl=null}appendAiBubble(t){const e=document.createElement("div");e.className="mtb-chat-ai-row",e.innerHTML=`<div class="mtb-chat-avatar">${q}</div><div class="mtb-chat-bubble mtb-chat-bubble-ai"></div>`,e.querySelector(".mtb-chat-bubble-ai").textContent=t,this.messagesEl.appendChild(e),this.messagesEl.scrollTop=this.messagesEl.scrollHeight}renderSuggestions(t){if(this.clearSuggestions(),!t?.length)return;const e=document.createElement("div");e.className="mtb-chat-suggestions";for(const r of t){const n=document.createElement("button");n.className="mtb-chat-sg",n.type="button",n.textContent=r,n.addEventListener("click",()=>{this.inputEl.value=r,this.sendBtn.disabled=!1,this.inputEl.focus({preventScroll:!0})}),e.appendChild(n)}this.messagesEl.appendChild(e),this.messagesEl.scrollTop=this.messagesEl.scrollHeight}clearSuggestions(){this.messagesEl.querySelector(".mtb-chat-suggestions")?.remove()}showThinking(){if(this.messagesEl.querySelector(".mtb-chat-thinking"))return;const t=document.createElement("div");t.className="mtb-chat-ai-row mtb-chat-thinking",t.innerHTML=`<div class="mtb-chat-avatar">${q}</div><div class="mtb-chat-dots"><span></span><span></span><span></span></div>`,this.messagesEl.appendChild(t),this.messagesEl.scrollTop=this.messagesEl.scrollHeight}removeThinking(){this.messagesEl.querySelector(".mtb-chat-thinking")?.remove()}showRetryableError(t,e){this.clearError();const r=document.createElement("div");r.className="mtb-chat-error-row";const n=document.createElement("span");n.className="mtb-chat-error-text",n.textContent=t;const s=document.createElement("button");s.className="mtb-chat-error-retry",s.type="button",s.textContent=this.i18n.clarify.retry,s.addEventListener("click",e),r.appendChild(n),r.appendChild(s),this.messagesEl.appendChild(r),this.messagesEl.scrollTop=this.messagesEl.scrollHeight}clearError(){this.messagesEl.querySelectorAll(".mtb-chat-error-row").forEach(t=>t.remove())}showSkip(){if(this.actionsEl.querySelector(".mtb-chat-skip"))return;const t=document.createElement("button");t.className="mtb-chat-skip",t.type="button",t.title=this.i18n.clarify.skip,t.textContent=this.i18n.clarify.skip_short,t.addEventListener("click",()=>this.skipAndSend()),this.actionsEl.insertBefore(t,this.sendBtn)}skipAndSend(){this.hideSkip(),this.state="done",this.setComposerDisabled(!0),this.renderSuccess(),this.finalizeInBackground()}hideSkip(){this.actionsEl?.querySelector(".mtb-chat-skip")?.remove()}hideCapture(){this.actionsEl.querySelector(".mtb-chat-screenshot")?.remove(),this.actionsEl.querySelector(".mtb-chat-attachment")?.remove()}setComposerDisabled(t){this.inputEl.disabled=t,this.sendBtn.disabled=t,this.composerEl.classList.toggle("mtb-chat-composer-disabled",t)}positionCard(t,e,r,n){const s=hi(n),{vw:o,vh:a,minLeft:l,maxRight:c}=s,h=Q,u=8,b=di(mi,s),k=(this.el.offsetHeight||280)+80;let f,m;const lt=r&&r.width<o*.6&&r.height<a*.6;r&&lt?(f=r.left,m=r.bottom+u,m+k>a-h&&(m=r.top-k-u),m<h&&(m=Math.min(r.bottom+u,a-k-h))):(f=t+12,m=e+12),f+b>c&&(f=c-b),f<l&&(f=l),m<h&&(m=h),m+k>a-h&&(m=a-k-h),m<h&&(m=h),this.el.style.left=`${f}px`,this.el.style.top=`${m}px`,this.el.style.maxHeight=`${a-m-h}px`}submit(t){this.sendMessage(t)}sessionId(){return this.session?.id??null}destroy(){this.clarifyAbort?.abort(),this.autoCloseTimer&&clearTimeout(this.autoCloseTimer),window.removeEventListener("keydown",this.handleEscape),this.sheet.release(),this.focusTrap.release(),this.el.remove(),this.focusTrap.restoreFocus()}}const wi=5e3,yi='<svg width="20" height="20" viewBox="0 0 20 20" fill="currentColor"><path d="M8.1 14.6L3.8 10.3l1.5-1.5 2.8 2.8 6.6-6.6 1.5 1.5z"/></svg>';class xi{constructor(t,e,r,n){const s=e.success,o=n?.skipFollowup?s.title_no_ai:s.title;this.el=t.el("div","mtb-chat mtb-chat-receipt"),this.el.setAttribute("role","dialog"),this.el.setAttribute("aria-modal","true"),this.el.setAttribute("aria-label",o);const a=document.createElement("div");a.className="mtb-chat-success mtb-chat-success-simple";const l=document.createElement("div");l.className="mtb-chat-success-icon",l.innerHTML=yi,a.appendChild(l);const c=document.createElement("div");if(c.className="mtb-chat-success-title",c.textContent=o,a.appendChild(c),n?.onViewFeedback){const h=document.createElement("a");h.className="mtb-chat-success-link",h.href="#",h.textContent=s.track_feedback,h.addEventListener("click",u=>{u.preventDefault(),n.onViewFeedback()}),a.appendChild(h)}this.el.appendChild(a),t.append(this.el),this.focusTrap=re(this.el),this.autoCloseTimer=setTimeout(r,wi)}destroy(){clearTimeout(this.autoCloseTimer),this.focusTrap.release(),this.el.remove(),this.focusTrap.restoreFocus()}}const p="[Filtered]",ki=/-----BEGIN ((?:[A-Z0-9]+ )*PRIVATE KEY)-----[\s\S]*?-----END \1-----/g,Ei=/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b/g,Si=[/\bsk-(?:proj-)?[A-Za-z0-9_-]{20,}\b/g,/\b(?:sk|rk)_(?:live|test)_[A-Za-z0-9]{20,}\b/g,/\bgh[pousr]_[A-Za-z0-9]{30,}\b/g,/\bAKIA[0-9A-Z]{16}\b/g,/\bxox[baprs]-[A-Za-z0-9-]{20,}\b/g],_i=/\b(?:\d[ -]?){12,18}\d\b/g,Ci=/\bhttps?:\/\/[^\s<>"']+/gi,Ti=new Set(["type","autocomplete","name","id","aria_label","placeholder"]),Ai=new Set(["value","content"]),Li=new Set(["password","hidden","file"]),Pi=new Set(["current_password","new_password","one_time_code","cc_number","cc_csc","cc_exp","cc_exp_month","cc_exp_year"]),Di=/(?:^|_)(?:password|passwd|passcode|card_(?:number|no)(?:_[0-9]+)?|credit_card|cc_(?:number|num|csc|cvv|cvc|exp|expiry)|cvv|cvc|csc|security_code|one_time_(?:code|password)|otp(?:_code)?|verification_code|auth(?:entication)?_token|access_token|refresh_token|id_token|token|api_key|client_secret|secret|authorization|cookie|set_cookie|credential|private_key|hidden_value|file_name|filename)(?:$|_(?:value|field|input|confirmation|confirm|header|data|pem)$)/;function T(i){let t=i.replace(ki,p).replace(Ei,p);for(const e of Si)t=t.replace(e,p);return t=t.replace(_i,e=>Mi(e)?p:e),t.replace(Ci,e=>$(e)||p)}function $(i){try{const t=new URL(i);return`${t.origin}${t.pathname}`}catch{return""}}function tt(i,t){if(t&&ne(t)&&i!=null)return p;if(typeof i=="string")return T(i);if(Array.isArray(i))return i.map(e=>tt(e));if(i&&typeof i=="object"){const e=se(i);return Object.fromEntries(Object.entries(i).map(([n,s])=>{const o=e&&Ai.has(I(n))&&s!=null?p:tt(s,n);return[T(n),o]}))}return i}function ne(i){return Di.test(I(i))}function se(i){return Object.entries(i).some(([t,e])=>{if(typeof e!="string")return!1;const r=I(t);return Ti.has(r)?r==="type"?Li.has(I(e)):r==="autocomplete"?e.split(/\s+/).some(n=>Pi.has(I(n))):ne(e):!1})}function I(i){return i.replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")}function Mi(i){const t=i.replace(/\D/g,"");if(t.length<13||t.length>19)return!1;let e=0,r=!1;for(let n=t.length-1;n>=0;n-=1){let s=Number(t[n]);r&&(s*=2,s>9&&(s-=9)),e+=s,r=!r}return e%10===0}function oe(i){return se({type:i.getAttribute("type"),autocomplete:i.getAttribute("autocomplete"),name:i.getAttribute("name"),id:i.id,"aria-label":i.getAttribute("aria-label"),placeholder:i.getAttribute("placeholder")})}function et(i,t){return i&&(oe(t)?p:T(i))}const Ri=512;function ae(){return new WeakMap}function le(i,t){let e=i.parentElement;for(;e&&e!==document.body&&e!==document.documentElement;){const r=ce(e,t);if(r==="sensitive")return!0;if(r==="contains-sensitive-child"||r==="too-large")return!1;e=e.parentElement}return!1}function ce(i,t){const e=t.get(i);if(e)return e;const r=i.textContent??"";let n="none";return r.length>Ri?n="too-large":T(r)!==r&&(n=Array.from(i.children).some(o=>{const a=ce(o,t);return a==="sensitive"||a==="contains-sensitive-child"})?"contains-sensitive-child":"sensitive"),t.set(i,n),n}function Ii(i){return new Promise(t=>{const e=new Image;e.onload=()=>t(e),e.onerror=()=>t(null),e.src=i})}function he(i){const t=[];let e=null;const r=i.match(/[ML]\s*[-\d.]+\s+[-\d.]+/g)??[];for(const n of r){const[s,o]=n.slice(1).trim().split(/\s+/).map(Number);Number.isNaN(s)||Number.isNaN(o)||(n[0]==="M"?(e=[[s,o]],t.push(e)):e&&e.push([s,o]))}return t}function Hi(i,t,e){return he(i).map(r=>r.map(([n,s],o)=>`${o===0?"M":"L"} ${n+t} ${s+e}`).join(" ")).join(" ")}let L=null;function de(){return L||(L=Promise.resolve().then(()=>require("./html-to-image.cjs")).catch(i=>{throw L=null,i}),L)}let dt,ut=null;function _t(){return dt!==void 0?Promise.resolve(dt):(ut??(ut=de().then(({getFontEmbedCSS:i})=>i(document.body)).then(i=>(dt=i,i)).catch(()=>{ut=null})),ut)}const Ni=200,Fi="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";async function Bi(i,t){try{if(t?.aborted)return null;const[{toJpeg:e},r]=await Promise.all([de(),_t()]);if(t?.aborted)return null;const n=document.body.getBoundingClientRect(),s=Xe(),o={x:window.scrollX,y:window.scrollY},a=qi(document.body),l=await e(document.body,{quality:.85,imagePlaceholder:Fi,resourceUrlResolver:i,fetchRequestInit:t?{signal:t}:void 0,width:s.width,height:s.height,pixelRatio:Vi(s),backgroundColor:"#ffffff",skipFonts:!1,skipAutoScale:!1,fontEmbedCSS:r,style:{transform:`translate(${n.left}px, ${n.top}px)`,transformOrigin:"top left"},filter:c=>{if(c instanceof HTMLElement&&c.id===v)return!1;if(!(c instanceof Element))return!0;const h=c.getBoundingClientRect();return h.width===0&&h.height===0?!0:h.top+window.scrollY-o.y<=s.height+Ni}});return t?.aborted?null:{dataUrl:l,metrics:s,redactions:a,pageScroll:o}}catch{return null}}async function zi(i,t=[],e){try{const r=t.map(n=>Oi(n,i.pageScroll));return await ji(i.dataUrl,r,i.metrics,i.redactions,e)}catch{return null}}function Oi(i,t){const e=Ui(i,t);return e.x===0&&e.y===0?i:{...i,x:i.x+e.x,y:i.y+e.y,targetRect:i.targetRect&&{...i.targetRect,top:i.targetRect.top+e.y,left:i.targetRect.left+e.x,bottom:i.targetRect.bottom+e.y},drawPath:i.drawPath&&Hi(i.drawPath,e.x,e.y)}}function Ui(i,t){return i.captureOffsetX!==void 0&&i.captureOffsetY!==void 0?Ke({x:i.captureOffsetX,y:i.captureOffsetY},t):j($i(i))}function $i(i){if(i.targetSelector)try{const t=document.querySelector(i.targetSelector);if(t)return t}catch{}return document.elementsFromPoint?.(i.x,i.y)[0]??null}async function ji(i,t,e,r,n){const s=document.createElement("canvas"),o=s.getContext("2d");if(!o)return null;const a=await Ii(i);if(!a)return null;s.width=a.naturalWidth||window.innerWidth,s.height=a.naturalHeight||window.innerHeight,o.drawImage(a,0,0);const l=Ye(e,s.width,s.height);o.fillStyle="#e5e7eb";for(const c of r){const h=Ve(l,c);o.fillRect(h.left,h.top,h.width,h.height)}for(const c of t)c.type==="draw"&&c.drawPath?Yi(o,c.drawPath,l,n?.primary):c.type==="pin"&&Xi(o,Z(l,c.x),J(l,c.y),n);return Ki(s)}function qi(i){const t=[];for(const s of Wi(i,`.${st}`))mt(t,s.getBoundingClientRect(),It(s));for(const s of i.querySelectorAll("input, textarea, select")){if(Ht(s))continue;const o=s instanceof HTMLInputElement||s instanceof HTMLTextAreaElement||s instanceof HTMLSelectElement?s.value:"",a=s.closest(`.${U}`)!==null,l=oe(s)||et(o,s)!==o;!a&&!l||mt(t,s.getBoundingClientRect(),It(s),Ft)}const e=document.createTreeWalker(i,NodeFilter.SHOW_TEXT),r=ae();let n=e.nextNode();for(;n;){const s=n.parentElement,o=n.textContent??"",a=s?.closest(`.${U}`)!==null,l=T(o)!==o||le(n,r);if(s&&!Ht(s)&&(a||l)){const c=j(s),h=document.createRange();h.selectNodeContents(n);for(const u of Array.from(h.getClientRects()))mt(t,u,c,Ft)}n=e.nextNode()}return t}function It(i){return j(Qt(i))}function Wi(i,t){const e=Array.from(i.querySelectorAll(t));return i.matches(t)?[i,...e]:e}function Ht(i){return i.closest(`#${v}`)!==null||i.closest(`.${st}`)!==null}function mt(i,t,e,r=0){if(![t.left,t.top,t.width,t.height].every(Number.isFinite))throw new Error("Invalid privacy redaction geometry");t.width<=0||t.height<=0||i.push({left:t.left+e.x-r,top:t.top+e.y-r,width:t.width+r*2,height:t.height+r*2})}function Yi(i,t,e,r=te){i.save(),i.lineCap="round",i.lineJoin="round";for(const n of he(t))if(n.length!==0){i.beginPath(),i.moveTo(Z(e,n[0][0]),J(e,n[0][1]));for(let s=1;s<n.length;s++)i.lineTo(Z(e,n[s][0]),J(e,n[s][1]));i.shadowColor="transparent",i.strokeStyle="rgba(15, 23, 42, 0.72)",i.lineWidth=7,i.stroke(),i.strokeStyle="#ffffff",i.lineWidth=5.5,i.stroke(),i.strokeStyle=r,i.lineWidth=3.5,i.stroke()}i.restore()}const Nt=16e6,Ft=2;function Vi(i){const t=i.width*i.height;return!Number.isFinite(t)||t<=Nt?1:Math.sqrt(Nt/t)}function Xi(i,t,e,r){const n=r?.primary??te;i.save(),i.shadowColor="rgba(15, 23, 42, 0.68)",i.shadowOffsetY=2,i.shadowBlur=8,i.fillStyle=n,i.beginPath(),i.arc(t,e,11,0,Math.PI*2),i.fill(),i.shadowColor="transparent",i.lineWidth=2,i.strokeStyle="#ffffff",i.stroke(),i.restore()}function Ki(i){return new Promise(t=>{try{i.toBlob(e=>t(e),"image/jpeg",.85)}catch{t(null)}})}class Gi{constructor(){this.listeners=new Set,this.originalOnError=null,this.installedOnError=null,this.rejectionHandler=null,this.hooked=!1}subscribe(t){return this.listeners.add(t),this.hook(),()=>{this.listeners.delete(t),this.listeners.size===0&&this.unhook()}}hook(){this.hooked||(this.hooked=!0,this.originalOnError=window.onerror,this.installedOnError=(t,e,r,n,s)=>(this.emit({name:Zi(s),message:String(t),source:e,line:r,col:n,error:s}),this.originalOnError?this.originalOnError.call(window,t,e,r,n,s):!1),window.onerror=this.installedOnError,this.rejectionHandler=t=>{const e=t.reason instanceof Error?t.reason.message:String(t.reason),r=t.reason instanceof Error?t.reason.name:"UnhandledRejection";this.emit({name:r,message:`Unhandled rejection: ${e}`})},window.addEventListener("unhandledrejection",this.rejectionHandler))}unhook(){this.hooked&&(this.hooked=!1,window.onerror===this.installedOnError&&(window.onerror=this.originalOnError),this.installedOnError=null,this.originalOnError=null,this.rejectionHandler&&(window.removeEventListener("unhandledrejection",this.rejectionHandler),this.rejectionHandler=null))}emit(t){for(const e of this.listeners)e(t)}}const Ct=new Gi;function Zi(i){return!i||typeof i!="object"||!("name"in i)?void 0:String(i.name)||void 0}function ue(i){const t=Ji(i.name)||Qi(i.message),e=tr(i);return e?`${t} (${e})`:t}function Ji(i){return i&&/^[A-Za-z][A-Za-z0-9]*(?:Error|Exception|Rejection)$/.test(i)?i:""}function Qi(i){return i.match(/^([A-Za-z][A-Za-z0-9]*(?:Error|Exception))\b/)?.[1]??"Error"}function tr(i){if(!i.source)return"";try{const t=new URL(i.source,window.location.href).pathname;return i.line==null?t:`${t}:${i.line}:${i.col??0}`}catch{return""}}const er=20;class ir{constructor(){this.errors=[],this.unsubscribe=null}start(){this.unsubscribe||(this.unsubscribe=Ct.subscribe(t=>this.record(t)))}record(t){this.addError(ue(t))}addError(t){this.errors.length>=er||this.errors.includes(t)||this.errors.push(t)}getErrors(){return[...this.errors]}stop(){this.unsubscribe?.(),this.unsubscribe=null}}const K=new Set;let H=null,N=null,F=null,it=null,B=null,rt=null;function me(i){K.add(i),rr();let t=!1;return()=>{t||(t=!0,K.delete(i),K.size===0&&nr())}}function bt(i,t){const e={type:i,fromUrl:t,toUrl:location.href};rt=e.toUrl;for(const r of[...K])try{r(e)}catch{}}function rr(){if(F)return;rt=location.href,B=()=>bt("pop",rt??location.href),window.addEventListener("popstate",B),H=history.pushState,N=history.replaceState;const i=H,t=N;F=function(e,r,n){const s=location.href;i.call(history,e,r,n),bt("push",s)},it=function(e,r,n){const s=location.href;t.call(history,e,r,n),bt("replace",s)},history.pushState=F,history.replaceState=it}function nr(){B&&(window.removeEventListener("popstate",B),B=null),H&&history.pushState===F&&(history.pushState=H),N&&history.replaceState===it&&(history.replaceState=N),H=null,N=null,F=null,it=null,rt=null}const sr=20;function or(i){return ot(i)?St(i):Et(i)}function ar(i){return ot(i)?ee(i):Jt(i)}class lr{constructor(){this.breadcrumbs=[],this.active=!1,this.unsubscribeErrors=null,this.unsubscribeNavigation=null,this.lastUrl="",this.boundClickHandler=t=>this.handleClick(t),this.boundChangeHandler=t=>this.handleChange(t)}start(){this.active||(this.active=!0,this.lastUrl=location.href,document.addEventListener("click",this.boundClickHandler,{capture:!0,passive:!0}),document.addEventListener("change",this.boundChangeHandler,{capture:!0,passive:!0}),this.unsubscribeErrors=Ct.subscribe(t=>this.recordError(t)),this.unsubscribeNavigation=me(()=>this.handleNavigation()))}stop(){this.active&&(this.active=!1,document.removeEventListener("click",this.boundClickHandler,!0),document.removeEventListener("change",this.boundChangeHandler,!0),this.unsubscribeErrors?.(),this.unsubscribeErrors=null,this.unsubscribeNavigation?.(),this.unsubscribeNavigation=null)}getBreadcrumbs(){return[...this.breadcrumbs]}add(t){this.breadcrumbs.push(t),this.breadcrumbs.length>sr&&this.breadcrumbs.shift()}handleClick(t){const e=t.target;if(e&&!E(e))try{this.add({type:"ui",category:"ui.click",timestamp:Date.now(),message:or(e),data:{selector:ar(e)}})}catch{}}handleChange(t){const e=t.target;if(e&&!E(e))try{const r=e,n=ot(e)?St(e):r.name||r.placeholder||e.getAttribute("aria-label")||e.tagName;this.add({type:"ui",category:"ui.input",timestamp:Date.now(),message:n,data:{field:n}})}catch{}}recordError(t){const e=ue(t);this.add({type:"console",category:"console.error",timestamp:Date.now(),message:e,data:{message:e}})}handleNavigation(){if(!this.active)return;const t=this.lastUrl,e=location.href;if(t===e)return;this.lastUrl=e;const r=$(t),n=$(e);this.add({type:"navigation",category:"navigation",timestamp:Date.now(),message:`${r} → ${n}`,data:{from:r,to:n}})}}const be="mtb_frustration_state";let wt=null;function nt(){try{const i=window.sessionStorage.getItem(be);return G(i?JSON.parse(i):wt)}catch{return G(wt)}}function pe(i){const t=G(i);wt=t;try{window.sessionStorage.setItem(be,JSON.stringify(t))}catch{}}function cr(){return nt().dismissedByUser}function hr(){pe({...nt(),dismissedByUser:!0})}function G(i){const t=i??{};return{navTimestamps:Array.isArray(t.navTimestamps)?t.navTimestamps.filter(e=>typeof e=="number"):[],cooldownUntil:typeof t.cooldownUntil=="number"?t.cooldownUntil:0,errorPageUrls:Array.isArray(t.errorPageUrls)?t.errorPageUrls.filter(e=>typeof e=="string").slice(-20):[],dismissedByUser:t.dismissedByUser===!0}}const dr=4,ur=1500,mr=3,br=5e3,pt=500,pr=2,fr=3e4,gr=2e3,vr=1e3,wr=300,yr=new Set(["A","BUTTON","INPUT","SELECT","TEXTAREA","LABEL","SUMMARY","DETAILS"]),xr=new Set(["button","link","checkbox","radio","tab","menuitem","option","switch","textbox","combobox","listbox","slider","spinbutton"]),kr=new Set(["A","BUTTON","SUMMARY"]),Er=new Set(["button","link","tab","menuitem"]),Bt=[/\bnot found\b/,/\bserver error\b/,/^\s*(?:http\s*)?[45]\d{2}\s*$/,/\b(?:error|http|status)\s*[:-]?\s*[45]\d{2}\b/,/\b[45]\d{2}\s*[:-]?\s*error\b/],O=class O{constructor(t){this.clickHistory=[],this.unsubscribeErrors=null,this.active=!1,this.lastInteraction=null,this.cooldownUntil=0,this.navTimestamps=[],this.unsubscribeNavigation=null,this.boundPageLeaveHandler=null,this.boundTurboNavigationHandler=null,this.lastNavigationAt=-1,this.boundSubmitHandler=null,this.boundInvalidHandler=null,this.recentSubmitForms=new WeakSet,this.recentFailedForms=new WeakSet,this.formFailureTimestamps=new WeakMap,this.errorPageUrls=new Set,this.domObserver=null,this.pendingDomChecks=0,this.lastMutationAt=-1,this.pendingTimers=new Set,this.onFrustration=t,this.boundClickHandler=e=>this.handleClick(e)}start(){this.active||(this.active=!0,this.restoreState(),document.addEventListener("click",this.boundClickHandler,!0),this.unsubscribeErrors=Ct.subscribe(()=>{const t=Date.now();if(!this.lastInteraction||t-this.lastInteraction.time>gr)return;const e=this.lastInteraction;this.lastInteraction=null,this.emitIfReady({signal:"dead_click",target:W(e.target),detail:"Uncaught error after interaction",timestamp:t})}),this.startNavigationTracking(),this.startFormTracking(),this.checkErrorPage())}stop(){this.active&&(this.active=!1,document.removeEventListener("click",this.boundClickHandler,!0),this.unsubscribeErrors?.(),this.unsubscribeErrors=null,this.clickHistory=[],this.lastInteraction=null,this.stopNavigationTracking(),this.stopFormTracking(),this.errorPageUrls.clear(),this.clearPendingTimers(),this.pendingDomChecks=0,this.disconnectDomObserver())}schedule(t,e){const r=setTimeout(()=>{this.pendingTimers.delete(r),t()},e);this.pendingTimers.add(r)}clearPendingTimers(){for(const t of this.pendingTimers)clearTimeout(t);this.pendingTimers.clear()}startNavigationTracking(){this.unsubscribeNavigation=me(t=>this.handleNavigation(t)),this.boundPageLeaveHandler=()=>this.noteNavigationStarted(),window.addEventListener("beforeunload",this.boundPageLeaveHandler),window.addEventListener("pagehide",this.boundPageLeaveHandler),this.boundTurboNavigationHandler=()=>this.noteNavigationStarted(),document.addEventListener("turbo:before-visit",this.boundTurboNavigationHandler),document.addEventListener("turbo:submit-start",this.boundTurboNavigationHandler),document.addEventListener("turbo:before-fetch-request",this.boundTurboNavigationHandler)}stopNavigationTracking(){this.unsubscribeNavigation?.(),this.unsubscribeNavigation=null,this.navTimestamps=[],this.boundPageLeaveHandler&&(window.removeEventListener("beforeunload",this.boundPageLeaveHandler),window.removeEventListener("pagehide",this.boundPageLeaveHandler),this.boundPageLeaveHandler=null),this.boundTurboNavigationHandler&&(document.removeEventListener("turbo:before-visit",this.boundTurboNavigationHandler),document.removeEventListener("turbo:submit-start",this.boundTurboNavigationHandler),document.removeEventListener("turbo:before-fetch-request",this.boundTurboNavigationHandler),this.boundTurboNavigationHandler=null),this.lastNavigationAt=-1}noteNavigationStarted(){this.lastNavigationAt=Date.now()}restoreState(){const t=nt();this.navTimestamps=t.navTimestamps,this.cooldownUntil=t.cooldownUntil,this.errorPageUrls=new Set(t.errorPageUrls)}persistState(){const t=nt();pe({...t,navTimestamps:this.navTimestamps,cooldownUntil:this.cooldownUntil,errorPageUrls:[...this.errorPageUrls]})}startFormTracking(){this.boundSubmitHandler=t=>this.handleFormSubmit(t),this.boundInvalidHandler=t=>this.handleFormInvalid(t),document.addEventListener("submit",this.boundSubmitHandler,!0),document.addEventListener("invalid",this.boundInvalidHandler,!0)}stopFormTracking(){this.boundSubmitHandler&&(document.removeEventListener("submit",this.boundSubmitHandler,!0),this.boundSubmitHandler=null),this.boundInvalidHandler&&(document.removeEventListener("invalid",this.boundInvalidHandler,!0),this.boundInvalidHandler=null),this.recentSubmitForms=new WeakSet,this.recentFailedForms=new WeakSet}handleClick(t){const e=t.target;if(!e||E(e))return;this.trackFormSubmitIntent(e),this.trackNativeNavigationIntent(t,e);const r=this.interactionTarget(e),n=Date.now();this.lastInteraction={target:r,time:n},this.clickHistory.push({target:r,time:n});const s=n-ur;if(this.clickHistory=this.clickHistory.filter(a=>a.time>s),this.clickHistory.filter(a=>a.target===r).length>=dr){this.clickHistory=[],this.emitHighPriority({signal:"rage_click",target:W(r),timestamp:n});return}this.checkDeadClickDom(r,n)}handleNavigation(t){const e=Date.now();if(this.noteNavigationStarted(),t.type!=="replace"&&t.fromUrl!==t.toUrl&&t.type==="pop"){this.navTimestamps.push(e);const n=e-br;this.navTimestamps=this.navTimestamps.filter(s=>s>n),this.navTimestamps.length>=mr&&(this.navTimestamps=[],this.emitIfReady({signal:"rapid_navigation",timestamp:e}))}this.persistState(),this.schedule(()=>{this.active&&this.checkErrorPage()},wr)}handleFormSubmit(t){const e=t.target;e instanceof HTMLFormElement&&(E(e)||(this.rememberSubmitAttempt(e),this.schedule(()=>{this.active&&e.querySelector('[aria-invalid="true"], .is-invalid')&&this.recordFormFailure(e)},pt)))}trackFormSubmitIntent(t){const e=t.closest("button, input");(e instanceof HTMLButtonElement||e instanceof HTMLInputElement)&&(e.type!=="submit"&&e.type!=="image"||!e.form||E(e.form)||this.rememberSubmitAttempt(e.form))}trackNativeNavigationIntent(t,e){e.closest("a[href]")&&queueMicrotask(()=>{this.active&&!t.defaultPrevented&&this.noteNavigationStarted()})}rememberSubmitAttempt(t){this.recentSubmitForms.add(t),this.schedule(()=>{this.recentSubmitForms.delete(t)},pt)}recordFormFailure(t){if(this.recentFailedForms.has(t))return;this.recentFailedForms.add(t),this.schedule(()=>this.recentFailedForms.delete(t),pt);const e=Date.now(),r=e-fr,n=(this.formFailureTimestamps.get(t)??[]).filter(s=>s>r);n.push(e),this.formFailureTimestamps.set(t,n),!(n.length<pr)&&(this.formFailureTimestamps.set(t,[]),this.emitIfReady({signal:"form_failure",target:W(t),timestamp:e}))}handleFormInvalid(t){const e=t.target;if(!e||E(e))return;const r=e.closest("form");!r||!this.recentSubmitForms.has(r)||this.recordFormFailure(r)}checkErrorPage(){const t=location.href;if(this.errorPageUrls.has(t))return;const e=document.title.toLowerCase();if(Bt.some(n=>n.test(e))){this.errorPageUrls.add(t),this.emitHighPriority({signal:"error_page",detail:document.title,timestamp:Date.now()});return}const r=document.querySelectorAll('h1, h2, [class*="error"], [class*="not-found"], [id*="error"], [id*="not-found"]');for(const n of r){const s=n.textContent??"";if(s.length<200&&Bt.some(o=>o.test(s.toLowerCase()))){this.errorPageUrls.add(t),this.emitHighPriority({signal:"error_page",detail:s.trim().slice(0,60),timestamp:Date.now()});return}}}checkDeadClickDom(t,e){this.looksInteractive(t)&&(this.pendingDomChecks++,this.ensureDomObserver(),this.schedule(()=>{this.pendingDomChecks--;const r=this.lastMutationAt>=e,n=this.lastNavigationAt>=e;this.pendingDomChecks===0&&this.disconnectDomObserver(),!r&&!n&&this.active&&this.emitIfReady({signal:"dead_click_dom",target:W(t),timestamp:e})},vr))}ensureDomObserver(){this.domObserver||(this.domObserver=new MutationObserver(()=>{this.lastMutationAt=Date.now()}),this.domObserver.observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,characterData:!0}))}disconnectDomObserver(){this.domObserver?.disconnect(),this.domObserver=null}looksInteractive(t){if(kr.has(t.tagName)||t.hasAttribute("onclick"))return!0;const e=t.getAttribute("role");if(e&&Er.has(e)||window.getComputedStyle(t).cursor==="pointer")return!0;if(t.classList)for(const n of t.classList){const s=n.toLowerCase();if(s.includes("btn")||s.includes("button"))return!0}return!1}interactionTarget(t){let e=t;for(;e&&e!==document.body;){if(this.isIntrinsicInteractive(e))return e;e=e.parentElement}let r=t;for(e=t.parentElement;e&&e!==document.body&&this.looksInteractive(e);)r=e,e=e.parentElement;return r}isIntrinsicInteractive(t){if(yr.has(t.tagName))return!0;const e=t.getAttribute("role");return e&&xr.has(e)||t.hasAttribute("onclick")||t.hasAttribute("tabindex")?!0:t.contentEditable==="true"}emitIfReady(t){const e=Date.now();e<this.cooldownUntil||(this.cooldownUntil=e+O.COOLDOWN_MS,this.persistState(),this.onFrustration(t))}emitHighPriority(t){this.cooldownUntil=Date.now()+O.COOLDOWN_MS,this.persistState(),this.onFrustration(t)}};O.COOLDOWN_MS=6e4;let yt=O;function W(i){const t=i.tagName.toLowerCase(),e=i.id?`#${i.id}`:"",r=i.className&&typeof i.className=="string"?"."+i.className.trim().split(/\s+/).slice(0,2).join("."):"",n=i.textContent?.trim().slice(0,30)??"";return`<${t}${e}${r}>${n?` "${n}"`:""}`}class Sr extends Error{constructor(t){super(`HTTP ${t}`),this.name="ApiError",this.status=t}}const _r=25e3,Cr="https://makethisbetter.dev/api/v1",Tr="sensitive-data-v1";class Ar{constructor(t){this.projectKey=t.projectKey,this.apiUrl=(t.apiUrl??Cr).replace(/\/$/,""),this.retryDelayMs=t.retryDelayMs??1e3,this.userToken=t.userToken,this.userTokenFn=t.userTokenFn}async resolveUserToken(){return this.userTokenFn?this.userTokenFn():this.userToken}async resolveScreenshotResourceUrl(t,e,r,n,s){if(!(n&&!n.startsWith("image/")))try{const o=new URL(r,window.location.href);if(!["http:","https:"].includes(o.protocol)||o.origin===window.location.origin)return;const a=await this.submissionHeaders(e,"application/json"),c=await(await this.fetchWithRetry(`${this.apiUrl}/widget/feedback_submission_sessions/${t}/image_proxy_url`,{method:"POST",headers:a,body:JSON.stringify({image_proxy_url:{source:o.href}}),signal:s})).json();return typeof c.url=="string"?c.url:void 0}catch{return}}async authHeaders(t){const e={"X-Project-Key":this.projectKey},r=await this.resolveUserToken();return r&&(e["X-User-Token"]=r),t&&(e["Content-Type"]=t),e}async submissionHeaders(t,e){const r=await this.authHeaders(e);return r["X-Submission-Token"]=t,r}async createSubmissionSession(t,e){const r=Dr(),n=new FormData;if(n.append("feedback[description]",t.description),n.append("feedback[page_url]",t.page_url),n.append("feedback[user_agent]",t.user_agent),n.append("feedback[browser]",t.browser),n.append("feedback[os]",t.os),n.append("feedback[screen_width]",String(t.screen_width)),n.append("feedback[screen_height]",String(t.screen_height)),n.append("feedback[console_errors]",JSON.stringify(t.console_errors)),n.append("feedback[annotations]",JSON.stringify(t.annotations)),t.target_element&&n.append("feedback[target_element]",JSON.stringify(t.target_element)),t.user_id&&n.append("feedback[user_id]",t.user_id),t.reporter_external_id&&n.append("feedback[reporter_external_id]",t.reporter_external_id),t.reporter_email&&n.append("feedback[reporter_email]",t.reporter_email),t.user_email&&n.append("feedback[user_email]",t.user_email),t.user_name&&n.append("feedback[user_name]",t.user_name),t.breadcrumbs&&t.breadcrumbs.length>0&&n.append("feedback[breadcrumbs]",JSON.stringify(t.breadcrumbs)),t.recording_events&&t.recording_events.length>0){const l=JSON.stringify(t.recording_events),c=new Blob([l],{type:"application/json"});n.append("feedback[recording]",c,"interaction-replay.json"),n.append("feedback[recording_duration]",String(t.recording_duration??0))}if(e){const l=e.type==="image/jpeg"?"jpg":"png";n.append("feedback[screenshot]",e,`screenshot.${l}`)}const s=await this.authHeaders();return s["X-Submission-Token"]=r,s["X-MTB-Capture-Policy"]=Tr,s["X-Idempotency-Key"]=Pr(),{...(await(await this.fetchWithRetry(`${this.apiUrl}/widget/feedback_submission_sessions`,{method:"POST",headers:s,body:n})).json()).submission_session,token:r}}async createIdentityToken(t){const e=await this.authHeaders("application/json");try{return await(await this.fetchWithRetry(`${this.apiUrl}/widget/identity_tokens`,{method:"POST",headers:e,body:JSON.stringify({reporter_external_id:t})})).json()}catch{return null}}async updateReporter(t,e,r){const n=await this.authHeaders("application/json");n["X-Identity-Token"]=r;try{return await this.fetchWithRetry(`${this.apiUrl}/widget/feedbacks/${t}/reporter`,{method:"PATCH",headers:n,body:JSON.stringify({reporter:{email:e}})}),!0}catch{return!1}}async answerClarification(t,e,r){return this.requestClarification(t,e,{message:T(r)})}async requestClarification(t,e,r){const n=await this.submissionHeaders(e,"application/json");return(await(await this.fetchWithRetry(`${this.apiUrl}/widget/feedback_submission_sessions/${t}/clarification`,{method:"POST",headers:n,body:JSON.stringify(r)})).json()).clarification}async streamClarification(t,e,r,n){const s=await this.submissionHeaders(e,"application/json");s.Accept="text/event-stream";const o=await fetch(`${this.apiUrl}/widget/feedback_submission_sessions/${t}/clarification`,{method:"POST",headers:s,body:JSON.stringify({}),signal:n}),a=o.headers.get("Content-Type")??"";if(!o.ok||!o.body||!a.includes("text/event-stream"))throw new Error("clarify stream unavailable");return Lr(o.body,r)}async finalizeSubmissionSession(t,e){const r=await this.submissionHeaders(e),n=new AbortController,s=setTimeout(()=>n.abort(),_r);try{return(await(await this.fetchWithRetry(`${this.apiUrl}/widget/feedback_submission_sessions/${t}/feedback`,{method:"POST",headers:r,signal:n.signal})).json()).feedback}finally{clearTimeout(s)}}async uploadScreenshot(t,e,r,n){const s=await this.submissionHeaders(e);delete s["Content-Type"];const o=new FormData;o.append("screenshot",r,"screenshot.jpg"),await this.fetchWithRetry(`${this.apiUrl}/widget/feedback_submission_sessions/${t}/screenshot`,{method:"PUT",headers:s,body:o,signal:n})}async abandonSubmissionSession(t,e){const r=await this.submissionHeaders(e);await this.fetchWithRetry(`${this.apiUrl}/widget/feedback_submission_sessions/${t}`,{method:"DELETE",headers:r})}async fetchWithRetry(t,e,r=1){let n;try{n=await fetch(t,e)}catch(s){if(r>0&&!e.signal?.aborted)return await zt(this.retryDelayMs),this.fetchWithRetry(t,e,r-1);throw s}if(n.ok)return n;if(n.status>=500&&r>0)return await zt(this.retryDelayMs),this.fetchWithRetry(t,e,r-1);throw new Sr(n.status)}}function zt(i){return i<=0?Promise.resolve():new Promise(t=>setTimeout(t,i))}async function Lr(i,t){const e=i.getReader(),r=new TextDecoder;let n="",s=null;const o=a=>{const l=a.split(`
65
+ `,t&&e.querySelector(".mtb-chat-finalize-retry").addEventListener("click",()=>{const r=e.querySelector(".mtb-chat-finalize-retry");r.disabled=!0,r.innerHTML='<span class="mtb-chat-finalize-spinner" aria-label="Retrying"></span>',t()}),e.querySelector(".mtb-chat-finalize-close").addEventListener("click",()=>this.opts.onCancel())}showFinalizeSuccess(){this.state="done",this.finalized=!0,this.renderSuccess()}attachHandoff(){const t=this.el.querySelector(".mtb-chat-success");if(!t)return;this.i18n.success;const e=this.opts.resolveBoardLink?.(),r=t.querySelector(".mtb-chat-success-link-pending");e&&r&&(r.classList.remove("mtb-chat-success-link-pending"),r.addEventListener("click",s=>{s.preventDefault(),e()}));const n=this.opts.resolveEmailCapture?.();n&&!t.querySelector(".mtb-chat-email-card")?(this.autoCloseTimer&&(clearTimeout(this.autoCloseTimer),this.autoCloseTimer=null),t.classList.remove("mtb-chat-success-simple"),t.appendChild(this.buildEmailCard(n))):this.finalized&&!n&&!this.autoCloseTimer&&!t.querySelector(".mtb-chat-email-card")&&(this.autoCloseTimer=setTimeout(()=>this.destroy(),Rt))}finalizeInBackground(){Promise.resolve(this.opts.onFinalize()).then(()=>this.attachHandoff()).catch(()=>{})}buildEmailCard(t){const e=this.i18n.success,r=document.createElement("div");r.className="mtb-chat-email-card";const n=document.createElement("div");n.className="mtb-chat-email-row";const s=document.createElement("div");s.className="mtb-chat-email-field";const o=document.createElement("input");o.className="mtb-chat-email-input",o.type="email",o.placeholder=e.email_cta,s.appendChild(o);const a=document.createElement("button");a.className="mtb-chat-email-submit",a.type="button",a.textContent=e.notify,a.disabled=!0;const l=async()=>{const c=o.value.trim();if(!c)return;if(a.disabled=!0,o.disabled=!0,await t.onSubmit(c)){const b=document.createElement("div");b.className="mtb-chat-email-note",b.textContent=e.email_saved,r.replaceChildren(b),this.autoCloseTimer=setTimeout(()=>this.destroy(),Rt);return}o.disabled=!1,a.disabled=!1;const u=r.querySelector(".mtb-chat-email-error")??document.createElement("div");u.className="mtb-chat-email-error",u.textContent=e.email_error,r.appendChild(u)};return o.addEventListener("input",()=>{a.disabled=!o.value.trim()}),o.addEventListener("keydown",c=>{c.key==="Enter"&&o.value.trim()&&l()}),a.addEventListener("click",()=>void l()),n.appendChild(s),n.appendChild(a),r.appendChild(n),r}appendUserBubble(t){const e=document.createElement("div");e.className="mtb-chat-bubble mtb-chat-bubble-user",e.textContent=t,this.messagesEl.appendChild(e),this.messagesEl.scrollTop=this.messagesEl.scrollHeight,this.inputEl.value="",this.sendBtn.disabled=!0}startStreamingBubble(){const t=document.createElement("div");t.className="mtb-chat-ai-row",t.innerHTML=`<div class="mtb-chat-avatar">${q}</div><div class="mtb-chat-bubble mtb-chat-bubble-ai"></div>`,this.messagesEl.appendChild(t),this.streamingBubbleEl=t.querySelector(".mtb-chat-bubble-ai")}appendStreamDelta(t){this.streamingBubbleEl&&(this.streamingBubbleEl.textContent=(this.streamingBubbleEl.textContent??"")+t,this.messagesEl.scrollTop=this.messagesEl.scrollHeight)}endStreamingBubble(){this.streamingBubbleEl=null}appendAiBubble(t){const e=document.createElement("div");e.className="mtb-chat-ai-row",e.innerHTML=`<div class="mtb-chat-avatar">${q}</div><div class="mtb-chat-bubble mtb-chat-bubble-ai"></div>`,e.querySelector(".mtb-chat-bubble-ai").textContent=t,this.messagesEl.appendChild(e),this.messagesEl.scrollTop=this.messagesEl.scrollHeight}renderSuggestions(t){if(this.clearSuggestions(),!t?.length)return;const e=document.createElement("div");e.className="mtb-chat-suggestions";for(const r of t){const n=document.createElement("button");n.className="mtb-chat-sg",n.type="button",n.textContent=r,n.addEventListener("click",()=>{this.inputEl.value=r,this.sendBtn.disabled=!1,this.inputEl.focus({preventScroll:!0})}),e.appendChild(n)}this.messagesEl.appendChild(e),this.messagesEl.scrollTop=this.messagesEl.scrollHeight}clearSuggestions(){this.messagesEl.querySelector(".mtb-chat-suggestions")?.remove()}showThinking(){if(this.messagesEl.querySelector(".mtb-chat-thinking"))return;const t=document.createElement("div");t.className="mtb-chat-ai-row mtb-chat-thinking",t.innerHTML=`<div class="mtb-chat-avatar">${q}</div><div class="mtb-chat-dots"><span></span><span></span><span></span></div>`,this.messagesEl.appendChild(t),this.messagesEl.scrollTop=this.messagesEl.scrollHeight}removeThinking(){this.messagesEl.querySelector(".mtb-chat-thinking")?.remove()}showRetryableError(t,e){this.clearError();const r=document.createElement("div");r.className="mtb-chat-error-row";const n=document.createElement("span");n.className="mtb-chat-error-text",n.textContent=t;const s=document.createElement("button");s.className="mtb-chat-error-retry",s.type="button",s.textContent=this.i18n.clarify.retry,s.addEventListener("click",e),r.appendChild(n),r.appendChild(s),this.messagesEl.appendChild(r),this.messagesEl.scrollTop=this.messagesEl.scrollHeight}clearError(){this.messagesEl.querySelectorAll(".mtb-chat-error-row").forEach(t=>t.remove())}showSkip(){if(this.actionsEl.querySelector(".mtb-chat-skip"))return;const t=document.createElement("button");t.className="mtb-chat-skip",t.type="button",t.title=this.i18n.clarify.skip,t.textContent=this.i18n.clarify.skip_short,t.addEventListener("click",()=>this.skipAndSend()),this.actionsEl.insertBefore(t,this.sendBtn)}skipAndSend(){this.hideSkip(),this.state="done",this.setComposerDisabled(!0),this.renderSuccess(),this.finalizeInBackground()}hideSkip(){this.actionsEl?.querySelector(".mtb-chat-skip")?.remove()}hideCapture(){this.actionsEl.querySelector(".mtb-chat-screenshot")?.remove(),this.actionsEl.querySelector(".mtb-chat-attachment")?.remove()}setComposerDisabled(t){this.inputEl.disabled=t,this.sendBtn.disabled=t,this.composerEl.classList.toggle("mtb-chat-composer-disabled",t)}positionCard(t,e,r,n){const s=hi(n),{vw:o,vh:a,minLeft:l,maxRight:c}=s,h=Q,u=8,b=di(mi,s),k=(this.el.offsetHeight||280)+80;let f,m;const lt=r&&r.width<o*.6&&r.height<a*.6;r&&lt?(f=r.left,m=r.bottom+u,m+k>a-h&&(m=r.top-k-u),m<h&&(m=Math.min(r.bottom+u,a-k-h))):(f=t+12,m=e+12),f+b>c&&(f=c-b),f<l&&(f=l),m<h&&(m=h),m+k>a-h&&(m=a-k-h),m<h&&(m=h),this.el.style.left=`${f}px`,this.el.style.top=`${m}px`,this.el.style.maxHeight=`${a-m-h}px`}submit(t){this.sendMessage(t)}sessionId(){return this.session?.id??null}destroy(){this.clarifyAbort?.abort(),this.autoCloseTimer&&clearTimeout(this.autoCloseTimer),window.removeEventListener("keydown",this.handleEscape),this.sheet.release(),this.focusTrap.release(),this.el.remove(),this.focusTrap.restoreFocus()}}const wi=5e3,yi='<svg width="20" height="20" viewBox="0 0 20 20" fill="currentColor"><path d="M8.1 14.6L3.8 10.3l1.5-1.5 2.8 2.8 6.6-6.6 1.5 1.5z"/></svg>';class xi{constructor(t,e,r,n){const s=e.success,o=n?.skipFollowup?s.title_no_ai:s.title;this.el=t.el("div","mtb-chat mtb-chat-receipt"),this.el.setAttribute("role","dialog"),this.el.setAttribute("aria-modal","true"),this.el.setAttribute("aria-label",o);const a=document.createElement("div");a.className="mtb-chat-success mtb-chat-success-simple";const l=document.createElement("div");l.className="mtb-chat-success-icon",l.innerHTML=yi,a.appendChild(l);const c=document.createElement("div");if(c.className="mtb-chat-success-title",c.textContent=o,a.appendChild(c),n?.onViewFeedback){const h=document.createElement("a");h.className="mtb-chat-success-link",h.href="#",h.textContent=s.track_feedback,h.addEventListener("click",u=>{u.preventDefault(),n.onViewFeedback()}),a.appendChild(h)}this.el.appendChild(a),t.append(this.el),this.focusTrap=re(this.el),this.autoCloseTimer=setTimeout(r,wi)}destroy(){clearTimeout(this.autoCloseTimer),this.focusTrap.release(),this.el.remove(),this.focusTrap.restoreFocus()}}const p="[Filtered]",ki=/-----BEGIN ((?:[A-Z0-9]+ )*PRIVATE KEY)-----[\s\S]*?-----END \1-----/g,Ei=/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b/g,Si=[/\bsk-(?:proj-)?[A-Za-z0-9_-]{20,}\b/g,/\b(?:sk|rk)_(?:live|test)_[A-Za-z0-9]{20,}\b/g,/\bgh[pousr]_[A-Za-z0-9]{30,}\b/g,/\bAKIA[0-9A-Z]{16}\b/g,/\bxox[baprs]-[A-Za-z0-9-]{20,}\b/g],_i=/\b(?:\d[ -]?){12,18}\d\b/g,Ci=/\bhttps?:\/\/[^\s<>"']+/gi,Ti=new Set(["type","autocomplete","name","id","aria_label","placeholder"]),Ai=new Set(["value","content"]),Li=new Set(["password","hidden","file"]),Pi=new Set(["current_password","new_password","one_time_code","cc_number","cc_csc","cc_exp","cc_exp_month","cc_exp_year"]),Di=/(?:^|_)(?:password|passwd|passcode|card_(?:number|no)(?:_[0-9]+)?|credit_card|cc_(?:number|num|csc|cvv|cvc|exp|expiry)|cvv|cvc|csc|security_code|one_time_(?:code|password)|otp(?:_code)?|verification_code|auth(?:entication)?_token|access_token|refresh_token|id_token|token|api_key|client_secret|secret|authorization|cookie|set_cookie|credential|private_key|hidden_value|file_name|filename)(?:$|_(?:value|field|input|confirmation|confirm|header|data|pem)$)/;function T(i){let t=i.replace(ki,p).replace(Ei,p);for(const e of Si)t=t.replace(e,p);return t=t.replace(_i,e=>Mi(e)?p:e),t.replace(Ci,e=>$(e)||p)}function $(i){try{const t=new URL(i);return`${t.origin}${t.pathname}`}catch{return""}}function tt(i,t){if(t&&ne(t)&&i!=null)return p;if(typeof i=="string")return T(i);if(Array.isArray(i))return i.map(e=>tt(e));if(i&&typeof i=="object"){const e=se(i);return Object.fromEntries(Object.entries(i).map(([n,s])=>{const o=e&&Ai.has(I(n))&&s!=null?p:tt(s,n);return[T(n),o]}))}return i}function ne(i){return Di.test(I(i))}function se(i){return Object.entries(i).some(([t,e])=>{if(typeof e!="string")return!1;const r=I(t);return Ti.has(r)?r==="type"?Li.has(I(e)):r==="autocomplete"?e.split(/\s+/).some(n=>Pi.has(I(n))):ne(e):!1})}function I(i){return i.replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")}function Mi(i){const t=i.replace(/\D/g,"");if(t.length<13||t.length>19)return!1;let e=0,r=!1;for(let n=t.length-1;n>=0;n-=1){let s=Number(t[n]);r&&(s*=2,s>9&&(s-=9)),e+=s,r=!r}return e%10===0}function oe(i){return se({type:i.getAttribute("type"),autocomplete:i.getAttribute("autocomplete"),name:i.getAttribute("name"),id:i.id,"aria-label":i.getAttribute("aria-label"),placeholder:i.getAttribute("placeholder")})}function et(i,t){return i&&(oe(t)?p:T(i))}const Ri=512;function ae(){return new WeakMap}function le(i,t){let e=i.parentElement;for(;e&&e!==document.body&&e!==document.documentElement;){const r=ce(e,t);if(r==="sensitive")return!0;if(r==="contains-sensitive-child"||r==="too-large")return!1;e=e.parentElement}return!1}function ce(i,t){const e=t.get(i);if(e)return e;const r=i.textContent??"";let n="none";return r.length>Ri?n="too-large":T(r)!==r&&(n=Array.from(i.children).some(o=>{const a=ce(o,t);return a==="sensitive"||a==="contains-sensitive-child"})?"contains-sensitive-child":"sensitive"),t.set(i,n),n}function Ii(i){return new Promise(t=>{const e=new Image;e.onload=()=>t(e),e.onerror=()=>t(null),e.src=i})}function he(i){const t=[];let e=null;const r=i.match(/[ML]\s*[-\d.]+\s+[-\d.]+/g)??[];for(const n of r){const[s,o]=n.slice(1).trim().split(/\s+/).map(Number);Number.isNaN(s)||Number.isNaN(o)||(n[0]==="M"?(e=[[s,o]],t.push(e)):e&&e.push([s,o]))}return t}function Hi(i,t,e){return he(i).map(r=>r.map(([n,s],o)=>`${o===0?"M":"L"} ${n+t} ${s+e}`).join(" ")).join(" ")}let L=null;function de(){return L||(L=Promise.resolve().then(()=>require("./html-to-image.cjs")).catch(i=>{throw L=null,i}),L)}let dt,ut=null;function _t(){return dt!==void 0?Promise.resolve(dt):(ut??(ut=de().then(({getFontEmbedCSS:i})=>i(document.body)).then(i=>(dt=i,i)).catch(()=>{ut=null})),ut)}const Ni=200,Fi="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";async function Bi(i,t){try{if(t?.aborted)return null;const[{toJpeg:e},r]=await Promise.all([de(),_t()]);if(t?.aborted)return null;const n=document.body.getBoundingClientRect(),s=Xe(),o={x:window.scrollX,y:window.scrollY},a=qi(document.body),l=await e(document.body,{quality:.85,imagePlaceholder:Fi,resourceUrlResolver:i,fetchRequestInit:t?{signal:t}:void 0,width:s.width,height:s.height,pixelRatio:Vi(s),backgroundColor:"#ffffff",skipFonts:!1,skipAutoScale:!1,fontEmbedCSS:r,style:{transform:`translate(${n.left}px, ${n.top}px)`,transformOrigin:"top left"},filter:c=>{if(c instanceof HTMLElement&&c.id===v)return!1;if(!(c instanceof Element))return!0;const h=c.getBoundingClientRect();return h.width===0&&h.height===0?!0:h.top+window.scrollY-o.y<=s.height+Ni}});return t?.aborted?null:{dataUrl:l,metrics:s,redactions:a,pageScroll:o}}catch{return null}}async function zi(i,t=[],e){try{const r=t.map(n=>Oi(n,i.pageScroll));return await ji(i.dataUrl,r,i.metrics,i.redactions,e)}catch{return null}}function Oi(i,t){const e=Ui(i,t);return e.x===0&&e.y===0?i:{...i,x:i.x+e.x,y:i.y+e.y,targetRect:i.targetRect&&{...i.targetRect,top:i.targetRect.top+e.y,left:i.targetRect.left+e.x,bottom:i.targetRect.bottom+e.y},drawPath:i.drawPath&&Hi(i.drawPath,e.x,e.y)}}function Ui(i,t){return i.captureOffsetX!==void 0&&i.captureOffsetY!==void 0?Ke({x:i.captureOffsetX,y:i.captureOffsetY},t):j($i(i))}function $i(i){if(i.targetSelector)try{const t=document.querySelector(i.targetSelector);if(t)return t}catch{}return document.elementsFromPoint?.(i.x,i.y)[0]??null}async function ji(i,t,e,r,n){const s=document.createElement("canvas"),o=s.getContext("2d");if(!o)return null;const a=await Ii(i);if(!a)return null;s.width=a.naturalWidth||window.innerWidth,s.height=a.naturalHeight||window.innerHeight,o.drawImage(a,0,0);const l=Ye(e,s.width,s.height);o.fillStyle="#e5e7eb";for(const c of r){const h=Ve(l,c);o.fillRect(h.left,h.top,h.width,h.height)}for(const c of t)c.type==="draw"&&c.drawPath?Yi(o,c.drawPath,l,n?.primary):c.type==="pin"&&Xi(o,Z(l,c.x),J(l,c.y),n);return Ki(s)}function qi(i){const t=[];for(const s of Wi(i,`.${st}`))mt(t,s.getBoundingClientRect(),It(s));for(const s of i.querySelectorAll("input, textarea, select")){if(Ht(s))continue;const o=s instanceof HTMLInputElement||s instanceof HTMLTextAreaElement||s instanceof HTMLSelectElement?s.value:"",a=s.closest(`.${U}`)!==null,l=oe(s)||et(o,s)!==o;!a&&!l||mt(t,s.getBoundingClientRect(),It(s),Ft)}const e=document.createTreeWalker(i,NodeFilter.SHOW_TEXT),r=ae();let n=e.nextNode();for(;n;){const s=n.parentElement,o=n.textContent??"",a=s?.closest(`.${U}`)!==null,l=T(o)!==o||le(n,r);if(s&&!Ht(s)&&(a||l)){const c=j(s),h=document.createRange();h.selectNodeContents(n);for(const u of Array.from(h.getClientRects()))mt(t,u,c,Ft)}n=e.nextNode()}return t}function It(i){return j(Qt(i))}function Wi(i,t){const e=Array.from(i.querySelectorAll(t));return i.matches(t)?[i,...e]:e}function Ht(i){return i.closest(`#${v}`)!==null||i.closest(`.${st}`)!==null}function mt(i,t,e,r=0){if(![t.left,t.top,t.width,t.height].every(Number.isFinite))throw new Error("Invalid privacy redaction geometry");t.width<=0||t.height<=0||i.push({left:t.left+e.x-r,top:t.top+e.y-r,width:t.width+r*2,height:t.height+r*2})}function Yi(i,t,e,r=te){i.save(),i.lineCap="round",i.lineJoin="round";for(const n of he(t))if(n.length!==0){i.beginPath(),i.moveTo(Z(e,n[0][0]),J(e,n[0][1]));for(let s=1;s<n.length;s++)i.lineTo(Z(e,n[s][0]),J(e,n[s][1]));i.shadowColor="transparent",i.strokeStyle="rgba(15, 23, 42, 0.72)",i.lineWidth=7,i.stroke(),i.strokeStyle="#ffffff",i.lineWidth=5.5,i.stroke(),i.strokeStyle=r,i.lineWidth=3.5,i.stroke()}i.restore()}const Nt=16e6,Ft=2;function Vi(i){const t=i.width*i.height;return!Number.isFinite(t)||t<=Nt?1:Math.sqrt(Nt/t)}function Xi(i,t,e,r){const n=r?.primary??te;i.save(),i.shadowColor="rgba(15, 23, 42, 0.68)",i.shadowOffsetY=2,i.shadowBlur=8,i.fillStyle=n,i.beginPath(),i.arc(t,e,11,0,Math.PI*2),i.fill(),i.shadowColor="transparent",i.lineWidth=2,i.strokeStyle="#ffffff",i.stroke(),i.restore()}function Ki(i){return new Promise(t=>{try{i.toBlob(e=>t(e),"image/jpeg",.85)}catch{t(null)}})}class Gi{constructor(){this.listeners=new Set,this.originalOnError=null,this.installedOnError=null,this.rejectionHandler=null,this.hooked=!1}subscribe(t){return this.listeners.add(t),this.hook(),()=>{this.listeners.delete(t),this.listeners.size===0&&this.unhook()}}hook(){this.hooked||(this.hooked=!0,this.originalOnError=window.onerror,this.installedOnError=(t,e,r,n,s)=>(this.emit({name:Zi(s),message:String(t),source:e,line:r,col:n,error:s}),this.originalOnError?this.originalOnError.call(window,t,e,r,n,s):!1),window.onerror=this.installedOnError,this.rejectionHandler=t=>{const e=t.reason instanceof Error?t.reason.message:String(t.reason),r=t.reason instanceof Error?t.reason.name:"UnhandledRejection";this.emit({name:r,message:`Unhandled rejection: ${e}`})},window.addEventListener("unhandledrejection",this.rejectionHandler))}unhook(){this.hooked&&(this.hooked=!1,window.onerror===this.installedOnError&&(window.onerror=this.originalOnError),this.installedOnError=null,this.originalOnError=null,this.rejectionHandler&&(window.removeEventListener("unhandledrejection",this.rejectionHandler),this.rejectionHandler=null))}emit(t){for(const e of this.listeners)e(t)}}const Ct=new Gi;function Zi(i){return!i||typeof i!="object"||!("name"in i)?void 0:String(i.name)||void 0}function ue(i){const t=Ji(i.name)||Qi(i.message),e=tr(i);return e?`${t} (${e})`:t}function Ji(i){return i&&/^[A-Za-z][A-Za-z0-9]*(?:Error|Exception|Rejection)$/.test(i)?i:""}function Qi(i){return i.match(/^([A-Za-z][A-Za-z0-9]*(?:Error|Exception))\b/)?.[1]??"Error"}function tr(i){if(!i.source)return"";try{const t=new URL(i.source,window.location.href).pathname;return i.line==null?t:`${t}:${i.line}:${i.col??0}`}catch{return""}}const er=20;class ir{constructor(){this.errors=[],this.unsubscribe=null}start(){this.unsubscribe||(this.unsubscribe=Ct.subscribe(t=>this.record(t)))}record(t){this.addError(ue(t))}addError(t){this.errors.length>=er||this.errors.includes(t)||this.errors.push(t)}getErrors(){return[...this.errors]}stop(){this.unsubscribe?.(),this.unsubscribe=null}}const K=new Set;let H=null,N=null,F=null,it=null,B=null,rt=null;function me(i){K.add(i),rr();let t=!1;return()=>{t||(t=!0,K.delete(i),K.size===0&&nr())}}function bt(i,t){const e={type:i,fromUrl:t,toUrl:location.href};rt=e.toUrl;for(const r of[...K])try{r(e)}catch{}}function rr(){if(F)return;rt=location.href,B=()=>bt("pop",rt??location.href),window.addEventListener("popstate",B),H=history.pushState,N=history.replaceState;const i=H,t=N;F=function(e,r,n){const s=location.href;i.call(history,e,r,n),bt("push",s)},it=function(e,r,n){const s=location.href;t.call(history,e,r,n),bt("replace",s)},history.pushState=F,history.replaceState=it}function nr(){B&&(window.removeEventListener("popstate",B),B=null),H&&history.pushState===F&&(history.pushState=H),N&&history.replaceState===it&&(history.replaceState=N),H=null,N=null,F=null,it=null,rt=null}const sr=20;function or(i){return ot(i)?St(i):Et(i)}function ar(i){return ot(i)?ee(i):Jt(i)}class lr{constructor(){this.breadcrumbs=[],this.active=!1,this.unsubscribeErrors=null,this.unsubscribeNavigation=null,this.lastUrl="",this.boundClickHandler=t=>this.handleClick(t),this.boundChangeHandler=t=>this.handleChange(t)}start(){this.active||(this.active=!0,this.lastUrl=location.href,document.addEventListener("click",this.boundClickHandler,{capture:!0,passive:!0}),document.addEventListener("change",this.boundChangeHandler,{capture:!0,passive:!0}),this.unsubscribeErrors=Ct.subscribe(t=>this.recordError(t)),this.unsubscribeNavigation=me(()=>this.handleNavigation()))}stop(){this.active&&(this.active=!1,document.removeEventListener("click",this.boundClickHandler,!0),document.removeEventListener("change",this.boundChangeHandler,!0),this.unsubscribeErrors?.(),this.unsubscribeErrors=null,this.unsubscribeNavigation?.(),this.unsubscribeNavigation=null)}getBreadcrumbs(){return[...this.breadcrumbs]}add(t){this.breadcrumbs.push(t),this.breadcrumbs.length>sr&&this.breadcrumbs.shift()}handleClick(t){const e=t.target;if(e&&!E(e))try{this.add({type:"ui",category:"ui.click",timestamp:Date.now(),message:or(e),data:{selector:ar(e)}})}catch{}}handleChange(t){const e=t.target;if(e&&!E(e))try{const r=e,n=ot(e)?St(e):r.name||r.placeholder||e.getAttribute("aria-label")||e.tagName;this.add({type:"ui",category:"ui.input",timestamp:Date.now(),message:n,data:{field:n}})}catch{}}recordError(t){const e=ue(t);this.add({type:"console",category:"console.error",timestamp:Date.now(),message:e,data:{message:e}})}handleNavigation(){if(!this.active)return;const t=this.lastUrl,e=location.href;if(t===e)return;this.lastUrl=e;const r=$(t),n=$(e);this.add({type:"navigation",category:"navigation",timestamp:Date.now(),message:`${r} → ${n}`,data:{from:r,to:n}})}}const be="mtb_frustration_state";let wt=null;function nt(){try{const i=window.sessionStorage.getItem(be);return G(i?JSON.parse(i):wt)}catch{return G(wt)}}function pe(i){const t=G(i);wt=t;try{window.sessionStorage.setItem(be,JSON.stringify(t))}catch{}}function cr(){return nt().dismissedByUser}function hr(){pe({...nt(),dismissedByUser:!0})}function G(i){const t=i??{};return{navTimestamps:Array.isArray(t.navTimestamps)?t.navTimestamps.filter(e=>typeof e=="number"):[],cooldownUntil:typeof t.cooldownUntil=="number"?t.cooldownUntil:0,errorPageUrls:Array.isArray(t.errorPageUrls)?t.errorPageUrls.filter(e=>typeof e=="string").slice(-20):[],dismissedByUser:t.dismissedByUser===!0}}const dr=4,ur=1500,mr=3,br=5e3,pt=500,pr=2,fr=3e4,gr=2e3,vr=1e3,wr=300,yr=new Set(["A","BUTTON","INPUT","SELECT","TEXTAREA","LABEL","SUMMARY","DETAILS"]),xr=new Set(["button","link","checkbox","radio","tab","menuitem","option","switch","textbox","combobox","listbox","slider","spinbutton"]),kr=new Set(["A","BUTTON","SUMMARY"]),Er=new Set(["button","link","tab","menuitem"]),Bt=[/\bnot found\b/,/\bserver error\b/,/^\s*(?:http\s*)?[45]\d{2}\s*$/,/\b(?:error|http|status)\s*[:-]?\s*[45]\d{2}\b/,/\b[45]\d{2}\s*[:-]?\s*error\b/],O=class O{constructor(t){this.clickHistory=[],this.unsubscribeErrors=null,this.active=!1,this.lastInteraction=null,this.cooldownUntil=0,this.navTimestamps=[],this.unsubscribeNavigation=null,this.boundPageLeaveHandler=null,this.boundTurboNavigationHandler=null,this.lastNavigationAt=-1,this.boundSubmitHandler=null,this.boundInvalidHandler=null,this.recentSubmitForms=new WeakSet,this.recentFailedForms=new WeakSet,this.formFailureTimestamps=new WeakMap,this.errorPageUrls=new Set,this.domObserver=null,this.pendingDomChecks=0,this.lastMutationAt=-1,this.pendingTimers=new Set,this.onFrustration=t,this.boundClickHandler=e=>this.handleClick(e)}start(){this.active||(this.active=!0,this.restoreState(),document.addEventListener("click",this.boundClickHandler,!0),this.unsubscribeErrors=Ct.subscribe(()=>{const t=Date.now();if(!this.lastInteraction||t-this.lastInteraction.time>gr)return;const e=this.lastInteraction;this.lastInteraction=null,this.emitIfReady({signal:"dead_click",target:W(e.target),detail:"Uncaught error after interaction",timestamp:t})}),this.startNavigationTracking(),this.startFormTracking(),this.checkErrorPage())}stop(){this.active&&(this.active=!1,document.removeEventListener("click",this.boundClickHandler,!0),this.unsubscribeErrors?.(),this.unsubscribeErrors=null,this.clickHistory=[],this.lastInteraction=null,this.stopNavigationTracking(),this.stopFormTracking(),this.errorPageUrls.clear(),this.clearPendingTimers(),this.pendingDomChecks=0,this.disconnectDomObserver())}schedule(t,e){const r=setTimeout(()=>{this.pendingTimers.delete(r),t()},e);this.pendingTimers.add(r)}clearPendingTimers(){for(const t of this.pendingTimers)clearTimeout(t);this.pendingTimers.clear()}startNavigationTracking(){this.unsubscribeNavigation=me(t=>this.handleNavigation(t)),this.boundPageLeaveHandler=()=>this.noteNavigationStarted(),window.addEventListener("beforeunload",this.boundPageLeaveHandler),window.addEventListener("pagehide",this.boundPageLeaveHandler),this.boundTurboNavigationHandler=()=>this.noteNavigationStarted(),document.addEventListener("turbo:before-visit",this.boundTurboNavigationHandler),document.addEventListener("turbo:submit-start",this.boundTurboNavigationHandler),document.addEventListener("turbo:before-fetch-request",this.boundTurboNavigationHandler)}stopNavigationTracking(){this.unsubscribeNavigation?.(),this.unsubscribeNavigation=null,this.navTimestamps=[],this.boundPageLeaveHandler&&(window.removeEventListener("beforeunload",this.boundPageLeaveHandler),window.removeEventListener("pagehide",this.boundPageLeaveHandler),this.boundPageLeaveHandler=null),this.boundTurboNavigationHandler&&(document.removeEventListener("turbo:before-visit",this.boundTurboNavigationHandler),document.removeEventListener("turbo:submit-start",this.boundTurboNavigationHandler),document.removeEventListener("turbo:before-fetch-request",this.boundTurboNavigationHandler),this.boundTurboNavigationHandler=null),this.lastNavigationAt=-1}noteNavigationStarted(){this.lastNavigationAt=Date.now()}restoreState(){const t=nt();this.navTimestamps=t.navTimestamps,this.cooldownUntil=t.cooldownUntil,this.errorPageUrls=new Set(t.errorPageUrls)}persistState(){const t=nt();pe({...t,navTimestamps:this.navTimestamps,cooldownUntil:this.cooldownUntil,errorPageUrls:[...this.errorPageUrls]})}startFormTracking(){this.boundSubmitHandler=t=>this.handleFormSubmit(t),this.boundInvalidHandler=t=>this.handleFormInvalid(t),document.addEventListener("submit",this.boundSubmitHandler,!0),document.addEventListener("invalid",this.boundInvalidHandler,!0)}stopFormTracking(){this.boundSubmitHandler&&(document.removeEventListener("submit",this.boundSubmitHandler,!0),this.boundSubmitHandler=null),this.boundInvalidHandler&&(document.removeEventListener("invalid",this.boundInvalidHandler,!0),this.boundInvalidHandler=null),this.recentSubmitForms=new WeakSet,this.recentFailedForms=new WeakSet}handleClick(t){const e=t.target;if(!e||E(e))return;this.trackFormSubmitIntent(e),this.trackNativeNavigationIntent(t,e);const r=this.interactionTarget(e),n=Date.now();this.lastInteraction={target:r,time:n},this.clickHistory.push({target:r,time:n});const s=n-ur;if(this.clickHistory=this.clickHistory.filter(a=>a.time>s),this.clickHistory.filter(a=>a.target===r).length>=dr){this.clickHistory=[],this.emitHighPriority({signal:"rage_click",target:W(r),timestamp:n});return}this.checkDeadClickDom(r,n)}handleNavigation(t){const e=Date.now();if(this.noteNavigationStarted(),t.type!=="replace"&&t.fromUrl!==t.toUrl&&t.type==="pop"){this.navTimestamps.push(e);const n=e-br;this.navTimestamps=this.navTimestamps.filter(s=>s>n),this.navTimestamps.length>=mr&&(this.navTimestamps=[],this.emitIfReady({signal:"rapid_navigation",timestamp:e}))}this.persistState(),this.schedule(()=>{this.active&&this.checkErrorPage()},wr)}handleFormSubmit(t){const e=t.target;e instanceof HTMLFormElement&&(E(e)||(this.rememberSubmitAttempt(e),this.schedule(()=>{this.active&&e.querySelector('[aria-invalid="true"], .is-invalid')&&this.recordFormFailure(e)},pt)))}trackFormSubmitIntent(t){const e=t.closest("button, input");(e instanceof HTMLButtonElement||e instanceof HTMLInputElement)&&(e.type!=="submit"&&e.type!=="image"||!e.form||E(e.form)||this.rememberSubmitAttempt(e.form))}trackNativeNavigationIntent(t,e){e.closest("a[href]")&&queueMicrotask(()=>{this.active&&!t.defaultPrevented&&this.noteNavigationStarted()})}rememberSubmitAttempt(t){this.recentSubmitForms.add(t),this.schedule(()=>{this.recentSubmitForms.delete(t)},pt)}recordFormFailure(t){if(this.recentFailedForms.has(t))return;this.recentFailedForms.add(t),this.schedule(()=>this.recentFailedForms.delete(t),pt);const e=Date.now(),r=e-fr,n=(this.formFailureTimestamps.get(t)??[]).filter(s=>s>r);n.push(e),this.formFailureTimestamps.set(t,n),!(n.length<pr)&&(this.formFailureTimestamps.set(t,[]),this.emitIfReady({signal:"form_failure",target:W(t),timestamp:e}))}handleFormInvalid(t){const e=t.target;if(!e||E(e))return;const r=e.closest("form");!r||!this.recentSubmitForms.has(r)||this.recordFormFailure(r)}checkErrorPage(){const t=location.href;if(this.errorPageUrls.has(t))return;const e=document.title.toLowerCase();if(Bt.some(n=>n.test(e))){this.errorPageUrls.add(t),this.emitHighPriority({signal:"error_page",detail:document.title,timestamp:Date.now()});return}const r=document.querySelectorAll('h1, h2, [class*="error"], [class*="not-found"], [id*="error"], [id*="not-found"]');for(const n of r){const s=n.textContent??"";if(s.length<200&&Bt.some(o=>o.test(s.toLowerCase()))){this.errorPageUrls.add(t),this.emitHighPriority({signal:"error_page",detail:s.trim().slice(0,60),timestamp:Date.now()});return}}}checkDeadClickDom(t,e){this.looksInteractive(t)&&(this.pendingDomChecks++,this.ensureDomObserver(),this.schedule(()=>{this.pendingDomChecks--;const r=this.lastMutationAt>=e,n=this.lastNavigationAt>=e;this.pendingDomChecks===0&&this.disconnectDomObserver(),!r&&!n&&this.active&&this.emitIfReady({signal:"dead_click_dom",target:W(t),timestamp:e})},vr))}ensureDomObserver(){this.domObserver||(this.domObserver=new MutationObserver(()=>{this.lastMutationAt=Date.now()}),this.domObserver.observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,characterData:!0}))}disconnectDomObserver(){this.domObserver?.disconnect(),this.domObserver=null}looksInteractive(t){if(kr.has(t.tagName)||t.hasAttribute("onclick"))return!0;const e=t.getAttribute("role");if(e&&Er.has(e)||window.getComputedStyle(t).cursor==="pointer")return!0;if(t.classList)for(const n of t.classList){const s=n.toLowerCase();if(s.includes("btn")||s.includes("button"))return!0}return!1}interactionTarget(t){let e=t;for(;e&&e!==document.body;){if(this.isIntrinsicInteractive(e))return e;e=e.parentElement}let r=t;for(e=t.parentElement;e&&e!==document.body&&this.looksInteractive(e);)r=e,e=e.parentElement;return r}isIntrinsicInteractive(t){if(yr.has(t.tagName))return!0;const e=t.getAttribute("role");return e&&xr.has(e)||t.hasAttribute("onclick")||t.hasAttribute("tabindex")?!0:t.contentEditable==="true"}emitIfReady(t){const e=Date.now();e<this.cooldownUntil||(this.cooldownUntil=e+O.COOLDOWN_MS,this.persistState(),this.onFrustration(t))}emitHighPriority(t){this.cooldownUntil=Date.now()+O.COOLDOWN_MS,this.persistState(),this.onFrustration(t)}};O.COOLDOWN_MS=6e4;let yt=O;function W(i){const t=i.tagName.toLowerCase(),e=i.id?`#${i.id}`:"",r=i.className&&typeof i.className=="string"?"."+i.className.trim().split(/\s+/).slice(0,2).join("."):"",n=i.textContent?.trim().slice(0,30)??"";return`<${t}${e}${r}>${n?` "${n}"`:""}`}class Sr extends Error{constructor(t){super(`HTTP ${t}`),this.name="ApiError",this.status=t}}const _r=25e3,Cr="https://makethisbetter.dev/api/v1",Tr="sensitive-data-v1";class Ar{constructor(t){this.projectKey=t.projectKey,this.apiUrl=(t.apiUrl??Cr).replace(/\/$/,""),this.retryDelayMs=t.retryDelayMs??1e3,this.userToken=t.userToken,this.userTokenFn=t.userTokenFn}async resolveUserToken(){return this.userTokenFn?this.userTokenFn():this.userToken}async resolveScreenshotResourceUrl(t,e,r,n,s){if(!(n&&!n.startsWith("image/")))try{const o=new URL(r,window.location.href);if(!["http:","https:"].includes(o.protocol)||o.origin===window.location.origin)return;const a=await this.submissionHeaders(e,"application/json"),c=await(await this.fetchWithRetry(`${this.apiUrl}/widget/feedback_submission_sessions/${t}/image_proxy_url`,{method:"POST",headers:a,body:JSON.stringify({image_proxy_url:{source:o.href}}),signal:s})).json();return typeof c.url=="string"?c.url:void 0}catch{return}}async authHeaders(t){const e={"X-Project-Key":this.projectKey},r=await this.resolveUserToken();return r&&(e["X-User-Token"]=r),t&&(e["Content-Type"]=t),e}async submissionHeaders(t,e){const r=await this.authHeaders(e);return r["X-Submission-Token"]=t,r}async createSubmissionSession(t,e){const r=Dr(),n=new FormData;if(n.append("feedback[description]",t.description),n.append("feedback[page_url]",t.page_url),n.append("feedback[user_agent]",t.user_agent),n.append("feedback[browser]",t.browser),n.append("feedback[os]",t.os),n.append("feedback[screen_width]",String(t.screen_width)),n.append("feedback[screen_height]",String(t.screen_height)),n.append("feedback[console_errors]",JSON.stringify(t.console_errors)),n.append("feedback[annotations]",JSON.stringify(t.annotations)),t.target_element&&n.append("feedback[target_element]",JSON.stringify(t.target_element)),t.user_id&&n.append("feedback[user_id]",t.user_id),t.reporter_external_id&&n.append("feedback[reporter_external_id]",t.reporter_external_id),t.reporter_email&&n.append("feedback[reporter_email]",t.reporter_email),t.user_email&&n.append("feedback[user_email]",t.user_email),t.user_name&&n.append("feedback[user_name]",t.user_name),t.breadcrumbs&&t.breadcrumbs.length>0&&n.append("feedback[breadcrumbs]",JSON.stringify(t.breadcrumbs)),t.recording_events&&t.recording_events.length>0){const l=JSON.stringify(t.recording_events),c=new Blob([l],{type:"application/json"});n.append("feedback[recording]",c,"interaction-replay.json"),n.append("feedback[recording_duration]",String(t.recording_duration??0))}if(e){const l=e.type==="image/jpeg"?"jpg":"png";n.append("feedback[screenshot]",e,`screenshot.${l}`)}const s=await this.authHeaders();return s["X-Submission-Token"]=r,s["X-MTB-Capture-Policy"]=Tr,s["X-Idempotency-Key"]=Pr(),{...(await(await this.fetchWithRetry(`${this.apiUrl}/widget/feedback_submission_sessions`,{method:"POST",headers:s,body:n})).json()).submission_session,token:r}}async createIdentityToken(t){const e=await this.authHeaders("application/json");try{return await(await this.fetchWithRetry(`${this.apiUrl}/widget/identity_tokens`,{method:"POST",headers:e,body:JSON.stringify({reporter_external_id:t})})).json()}catch{return null}}async updateReporter(t,e,r){const n=await this.authHeaders("application/json");n["X-Identity-Token"]=r;try{return await this.fetchWithRetry(`${this.apiUrl}/widget/feedbacks/${t}/reporter`,{method:"PATCH",headers:n,body:JSON.stringify({reporter:{email:e}})}),!0}catch{return!1}}async answerClarification(t,e,r){return this.requestClarification(t,e,{message:T(r)})}async requestClarification(t,e,r){const n=await this.submissionHeaders(e,"application/json");return(await(await this.fetchWithRetry(`${this.apiUrl}/widget/feedback_submission_sessions/${t}/clarification`,{method:"POST",headers:n,body:JSON.stringify(r)})).json()).clarification}async streamClarification(t,e,r,n){const s=await this.submissionHeaders(e,"application/json");s.Accept="text/event-stream";const o=await fetch(`${this.apiUrl}/widget/feedback_submission_sessions/${t}/clarification`,{method:"POST",headers:s,body:JSON.stringify({}),signal:n}),a=o.headers.get("Content-Type")??"";if(!o.ok||!o.body||!a.includes("text/event-stream"))throw new Error("clarify stream unavailable");return Lr(o.body,r)}async finalizeSubmissionSession(t,e){const r=await this.submissionHeaders(e),n=new AbortController,s=setTimeout(()=>n.abort(),_r);try{return(await(await this.fetchWithRetry(`${this.apiUrl}/widget/feedback_submission_sessions/${t}/feedback`,{method:"POST",headers:r,signal:n.signal})).json()).feedback}finally{clearTimeout(s)}}async uploadScreenshot(t,e,r,n){const s=await this.submissionHeaders(e);delete s["Content-Type"];const o=new FormData;o.append("screenshot",r,"screenshot.jpg"),await this.fetchWithRetry(`${this.apiUrl}/widget/feedback_submission_sessions/${t}/screenshot`,{method:"PUT",headers:s,body:o,signal:n})}async abandonSubmissionSession(t,e){const r=await this.submissionHeaders(e);await this.fetchWithRetry(`${this.apiUrl}/widget/feedback_submission_sessions/${t}`,{method:"DELETE",headers:r})}async fetchWithRetry(t,e,r=1){let n;try{n=await fetch(t,e)}catch(s){if(r>0&&!e.signal?.aborted)return await zt(this.retryDelayMs),this.fetchWithRetry(t,e,r-1);throw s}if(n.ok)return n;if(n.status>=500&&r>0)return await zt(this.retryDelayMs),this.fetchWithRetry(t,e,r-1);throw new Sr(n.status)}}function zt(i){return i<=0?Promise.resolve():new Promise(t=>setTimeout(t,i))}async function Lr(i,t){const e=i.getReader(),r=new TextDecoder;let n="",s=null;const o=a=>{const l=a.split(`
66
66
  `).find(b=>b.startsWith("event:")),c=a.split(`
67
67
  `).find(b=>b.startsWith("data:"));if(!c)return;const h=l?.slice(6).trim(),u=JSON.parse(c.slice(5).trim());h==="delta"&&typeof u.text=="string"?t(u.text):h==="done"&&(s={messages:Array.isArray(u.messages)?u.messages:[],suggestions:Array.isArray(u.suggestions)?u.suggestions.filter(b=>typeof b=="string"):[],done:u.done!==!1,failed:u.error===!0})};for(;;){const{done:a,value:l}=await e.read();if(a)break;n+=r.decode(l,{stream:!0});let c;for(;(c=n.indexOf(`
68
68
 
69
- `))!==-1;){const h=n.slice(0,c);n=n.slice(c+2);try{o(h)}catch{}}}if(n+=r.decode(),n.trim())try{o(n)}catch{}if(!s)throw new Error("clarify stream ended before done");return s}function Pr(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,12)}`}function Dr(){if(typeof crypto>"u"||typeof crypto.getRandomValues!="function")throw new Error("Secure random generation is unavailable");const i=crypto.getRandomValues(new Uint8Array(32));return Array.from(i,t=>t.toString(16).padStart(2,"0")).join("")}const Ot="mtb_anon_id",fe="mtb_reporter_email",ge="mtb_board_url";let Ut=null,ve=null,we=null;function ye(){try{const i=window.localStorage.getItem(Ot);if(i?.startsWith("anon_"))return i;const t=$t();return window.localStorage.setItem(Ot,t),t}catch{return Ut??(Ut=$t()),Ut}}function xe(){try{return window.localStorage.getItem(fe)??void 0}catch{return ve??void 0}}function Mr(i){ve=i;try{window.localStorage.setItem(fe,i)}catch{}}function Rr(){try{return window.localStorage.getItem(ge)??void 0}catch{return we??void 0}}function P(i){we=i;try{window.localStorage.setItem(ge,i)}catch{}}function $t(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`anon_${crypto.randomUUID()}`:`anon_${`${Date.now().toString(16)}-${Math.random().toString(16).slice(2,10)}`}`}const Ir={tab:"Feedback",toolbar:{markup:"Mark up",record:"Record",hint:"Click to comment, drag to draw",hintTouch:"Drag to mark what's wrong",hintRecord:"Recording your screen",exit:"Exit"},popup:{about:"About",placeholder:"Describe the issue or suggestion...",submit:"Submit",sending:"Sending...",cancel:"Cancel",close:"Close",my_feedback:"My feedback",screenshot_label:"Attach screenshot",screenshot_hint:"Passwords and other sensitive fields are covered automatically.",screenshot_short:"Screenshot",screenshot_locked_hint:"Your drawing is baked onto the screenshot, so it is always attached. Sensitive fields are covered automatically.",recording_label:"Recording",recording_locked_hint:"A replay of what the page showed and how it was used — always included with a recording. No camera or microphone. Sensitive fields are covered automatically.",quickOptions:[{emoji:"🐛",label:"Broken",value:"Something's broken"},{emoji:"💡",label:"Suggestion",value:"I have a suggestion"},{emoji:"🤔",label:"Confused",value:"I'm confused"}]},success:{title:"Thanks, your feedback is in.",title_no_ai:"Thanks! We've received your feedback.",close:"Close",email_saved:"You'll get an email when it's resolved.",email_error:"Couldn't save your email. Please try again.",track_feedback:"Track your feedback",email_cta:"Email me when it's fixed",notify:"Notify"},error:{submit:"Failed to submit. Please try again.",finalize_title:"We couldn't send this yet.",finalize_message:"Your feedback is still saved. Please try again."},pet:{bubble:"Need help?"},frustration:{prompt:"Something not working? Tell us.",action:"Annotate",dismiss:"Dismiss"},annotation:{drawing:"Drawing",element:"element"},draw:{note_placeholder:"Add a note to your drawing",undo:"Undo",redo:"Redo",cancel:"Cancel",submit:"Submit"},record:{stop:"Stop",timer_label:"Recording",max_reached:"Maximum recording time reached",replay_label:"screen-recording.json",play:"Play recording",close:"Close",preview_unavailable:"Preview unavailable"},clarify:{title:"Make This Better AI",subtitle:"Sharpening your feedback",thinking:"Thinking...",placeholder:"Add details, then submit",send:"Send",submit:"Submit",send_feedback:"Send feedback",skip:"Skip & submit",skip_short:"Skip",cancel:"Cancel — don't send feedback",retry:"Retry",error:"Couldn't load the question. Send your feedback as is.",expired:"This feedback session expired before it could be sent. Please close the widget and submit again."}},Hr={tab:"反馈",toolbar:{markup:"标注",record:"录屏",hint:"点击标注,拖动绘制",hintTouch:"用手指圈出问题",hintRecord:"正在录制屏幕",exit:"退出"},popup:{about:"关于",placeholder:"描述问题或建议...",submit:"提交",sending:"发送中...",cancel:"取消",close:"关闭",my_feedback:"我的反馈",screenshot_label:"附带页面截图",screenshot_hint:"密码等敏感字段会自动打码。",screenshot_short:"截图",screenshot_locked_hint:"圈画会画在截图上,所以必定附带。敏感字段会自动打码。",recording_label:"录制",recording_locked_hint:"页面画面与操作过程的回放,录制内容必定随反馈提交。不含摄像头和麦克风,敏感字段会自动打码。",quickOptions:[{emoji:"🐛",label:"有问题",value:"出问题了"},{emoji:"💡",label:"建议",value:"我有一个建议"},{emoji:"🤔",label:"疑问",value:"我有点疑问"}]},success:{title:"收到了,谢谢你的反馈。",title_no_ai:"感谢!我们已收到您的反馈。",close:"关闭",email_saved:"问题解决后您会收到邮件通知。",email_error:"邮箱保存失败,请重试。",track_feedback:"查看处理进度",email_cta:"解决后邮件通知我",notify:"通知我"},error:{submit:"提交失败,请重试。",finalize_title:"暂时无法发送。",finalize_message:"你的反馈仍已保存,请重试。"},pet:{bubble:"需要帮助吗?"},frustration:{prompt:"遇到问题了?告诉我们。",action:"标注",dismiss:"关闭"},annotation:{drawing:"绘制",element:"元素"},draw:{note_placeholder:"给你的绘制添加说明",undo:"撤销",redo:"重做",cancel:"取消",submit:"提交"},record:{stop:"停止",timer_label:"录制中",max_reached:"已达到最长录制时间",replay_label:"screen-recording.json",play:"播放录屏",close:"关闭",preview_unavailable:"暂无法预览"},clarify:{title:"Make This Better AI",subtitle:"正在完善你的反馈",thinking:"思考中...",placeholder:"补充说明后提交",send:"发送",submit:"提交",send_feedback:"发送反馈",skip:"跳过并提交",skip_short:"跳过",cancel:"取消并不发送",retry:"重试",error:"追问加载失败,可以直接发送反馈。",expired:"这条反馈在发送前已过期。请关闭组件后重新提交。"}},Nr={tab:"フィードバック",toolbar:{markup:"マークアップ",record:"録画",hint:"クリックでコメント、ドラッグで描画",hintTouch:"ドラッグして問題箇所を囲んでください",hintRecord:"画面を録画中",exit:"終了"},popup:{about:"概要",placeholder:"問題や提案を入力してください...",submit:"送信",sending:"送信中...",cancel:"キャンセル",close:"閉じる",my_feedback:"自分のフィードバック",screenshot_label:"スクリーンショットを添付",screenshot_hint:"パスワードなどの機密項目は自動的に隠されます。",screenshot_short:"スクリーンショット",screenshot_locked_hint:"描き込みはスクリーンショット上に焼き込まれるため、必ず添付されます。機密項目は自動的に隠されます。",recording_label:"記録",recording_locked_hint:"ページの表示と操作の再現記録で、必ず添付されます。カメラやマイクは含まれず、機密項目は自動的に隠されます。",quickOptions:[{emoji:"🐛",label:"不具合",value:"不具合があります"},{emoji:"💡",label:"提案",value:"提案があります"},{emoji:"🤔",label:"不明点",value:"わかりにくいです"}]},success:{title:"フィードバックを受け取りました。ありがとうございます。",title_no_ai:"ありがとうございます!フィードバックを受け付けました。",close:"閉じる",email_saved:"解決次第メールでお知らせします。",email_error:"メールアドレスを保存できませんでした。もう一度お試しください。",track_feedback:"対応状況を確認",email_cta:"解決したらメールで知らせる",notify:"通知"},error:{submit:"送信に失敗しました。もう一度お試しください。",finalize_title:"まだ送信できませんでした。",finalize_message:"フィードバックは保存されています。もう一度お試しください。"},pet:{bubble:"お困りですか?"},frustration:{prompt:"うまくいかないことがありますか?お知らせください。",action:"注釈",dismiss:"閉じる"},annotation:{drawing:"描画",element:"要素"},draw:{note_placeholder:"描画にメモを追加",undo:"元に戻す",redo:"やり直す",cancel:"キャンセル",submit:"送信"},record:{stop:"停止",timer_label:"録画中",max_reached:"最大記録時間に達しました",replay_label:"screen-recording.json",play:"録画を再生",close:"閉じる",preview_unavailable:"プレビューは利用できません"},clarify:{title:"Make This Better AI",subtitle:"フィードバックを整えています",thinking:"考え中...",placeholder:"詳細を追加して送信",send:"送信",submit:"送信する",send_feedback:"フィードバックを送信",skip:"スキップして送信",skip_short:"スキップ",cancel:"キャンセル — 送信しない",retry:"再試行",error:"質問を読み込めませんでした。そのままフィードバックを送信できます。",expired:"このフィードバックは送信される前に有効期限が切れました。ウィジェットを閉じて、もう一度送信してください。"}},Fr={tab:"피드백",toolbar:{markup:"마크업",record:"녹화",hint:"클릭하여 댓글, 드래그하여 그리기",hintTouch:"드래그해서 문제가 있는 곳을 표시하세요",hintRecord:"화면 녹화 중",exit:"나가기"},popup:{about:"정보",placeholder:"문제 또는 제안 사항을 설명해 주세요...",submit:"제출",sending:"전송 중...",cancel:"취소",close:"닫기",my_feedback:"내 피드백",screenshot_label:"스크린샷 첨부",screenshot_hint:"비밀번호 등 민감한 입력란은 자동으로 가려집니다.",screenshot_short:"스크린샷",screenshot_locked_hint:"그린 표시는 스크린샷 위에 합쳐지므로 항상 첨부됩니다. 민감한 입력란은 자동으로 가려집니다.",recording_label:"기록",recording_locked_hint:"페이지 화면과 조작 과정의 재현 기록으로, 항상 첨부됩니다. 카메라와 마이크는 포함되지 않으며 민감한 입력란은 자동으로 가려집니다.",quickOptions:[{emoji:"🐛",label:"오류",value:"문제가 있어요"},{emoji:"💡",label:"제안",value:"제안이 있어요"},{emoji:"🤔",label:"혼란",value:"헷갈려요"}]},success:{title:"피드백이 접수되었습니다. 감사합니다.",title_no_ai:"감사합니다! 피드백을 접수했습니다.",close:"닫기",email_saved:"해결되면 이메일로 알려드립니다.",email_error:"이메일을 저장하지 못했습니다. 다시 시도해 주세요.",track_feedback:"처리 상황 보기",email_cta:"해결되면 이메일로 알림",notify:"알림"},error:{submit:"제출에 실패했습니다. 다시 시도해 주세요.",finalize_title:"아직 전송하지 못했습니다.",finalize_message:"피드백은 저장되어 있습니다. 다시 시도해 주세요."},pet:{bubble:"도움이 필요하신가요?"},frustration:{prompt:"문제가 있으신가요? 알려 주세요.",action:"주석",dismiss:"닫기"},annotation:{drawing:"그리기",element:"요소"},draw:{note_placeholder:"그림에 메모 추가",undo:"실행 취소",redo:"다시 실행",cancel:"취소",submit:"보내기"},record:{stop:"중지",timer_label:"녹화 중",max_reached:"최대 녹화 시간에 도달했습니다",replay_label:"screen-recording.json",play:"녹화 재생",close:"닫기",preview_unavailable:"미리보기를 사용할 수 없습니다"},clarify:{title:"Make This Better AI",subtitle:"피드백을 다듬는 중",thinking:"생각 중...",placeholder:"자세히 적은 뒤 제출",send:"보내기",submit:"제출",send_feedback:"피드백 보내기",skip:"건너뛰고 보내기",skip_short:"건너뛰기",cancel:"취소 — 보내지 않기",retry:"재시도",error:"질문을 불러오지 못했습니다. 피드백을 그대로 보내세요.",expired:"이 피드백 세션은 전송되기 전에 만료되었습니다. 위젯을 닫고 다시 보내 주세요."}},Br={tab:"Comentarios",toolbar:{markup:"Anotar",record:"Grabar",hint:"Clic para comentar, arrastrar para dibujar",hintTouch:"Arrastra para marcar el problema",hintRecord:"Grabando pantalla",exit:"Salir"},popup:{about:"Acerca de",placeholder:"Describe el problema o sugerencia...",submit:"Enviar",sending:"Enviando...",cancel:"Cancelar",close:"Cerrar",my_feedback:"Mis comentarios",screenshot_label:"Adjuntar captura de pantalla",screenshot_hint:"Las contraseñas y otros campos sensibles se ocultan automáticamente.",screenshot_short:"Captura",screenshot_locked_hint:"Tu dibujo se integra en la captura, por eso siempre se adjunta. Los campos sensibles se ocultan automáticamente.",recording_label:"Grabación",recording_locked_hint:"Una reproducción de lo que mostraba la página y cómo se usó; siempre se adjunta. Sin cámara ni micrófono. Los campos sensibles se ocultan automáticamente.",quickOptions:[{emoji:"🐛",label:"Error",value:"Algo no funciona"},{emoji:"💡",label:"Sugerencia",value:"Tengo una sugerencia"},{emoji:"🤔",label:"Confuso",value:"Estoy confundido"}]},success:{title:"Gracias, hemos recibido tu comentario.",title_no_ai:"¡Gracias! Hemos recibido tu comentario.",close:"Cerrar",email_saved:"Recibirás un correo cuando se resuelva.",email_error:"No se pudo guardar tu correo. Inténtalo de nuevo.",track_feedback:"Seguir mi comentario",email_cta:"Avísame por correo cuando se arregle",notify:"Avisarme"},error:{submit:"Error al enviar. Por favor, inténtalo de nuevo.",finalize_title:"Aún no pudimos enviarlo.",finalize_message:"Tu comentario sigue guardado. Inténtalo de nuevo."},pet:{bubble:"¿Necesitas ayuda?"},frustration:{prompt:"¿Algo no funciona? Cuéntanos.",action:"Anotar",dismiss:"Cerrar"},annotation:{drawing:"Dibujo",element:"elemento"},draw:{note_placeholder:"Añade una nota a tu dibujo",undo:"Deshacer",redo:"Rehacer",cancel:"Cancelar",submit:"Enviar"},record:{stop:"Detener",timer_label:"Grabando",max_reached:"Tiempo máximo de grabación alcanzado",replay_label:"screen-recording.json",play:"Reproducir grabación",close:"Cerrar",preview_unavailable:"Vista previa no disponible"},clarify:{title:"Make This Better AI",subtitle:"Afinando tus comentarios",thinking:"Pensando...",placeholder:"Añade detalles y envía",send:"Enviar",submit:"Enviar",send_feedback:"Enviar comentario",skip:"Omitir y enviar",skip_short:"Omitir",cancel:"Cancelar — no enviar",retry:"Reintentar",error:"No se pudo cargar la pregunta. Envía tus comentarios tal cual.",expired:"Esta sesión de comentarios caducó antes de poder enviarse. Cierra el widget y envíalo de nuevo."}},zr={tab:"Avis",toolbar:{markup:"Annoter",record:"Enregistrer",hint:"Cliquer pour commenter, glisser pour dessiner",hintTouch:"Faites glisser pour marquer le problème",hintRecord:"Enregistrement de l'écran",exit:"Quitter"},popup:{about:"À propos",placeholder:"Décrivez le problème ou votre suggestion...",submit:"Envoyer",sending:"Envoi en cours...",cancel:"Annuler",close:"Fermer",my_feedback:"Mes avis",screenshot_label:"Joindre une capture d'écran",screenshot_hint:"Les mots de passe et autres champs sensibles sont masqués automatiquement.",screenshot_short:"Capture",screenshot_locked_hint:"Votre dessin est intégré à la capture, elle est donc toujours jointe. Les champs sensibles sont masqués automatiquement.",recording_label:"Enregistrement",recording_locked_hint:"Une relecture de ce que la page affichait et de son utilisation — toujours jointe. Ni caméra ni micro. Les champs sensibles sont masqués automatiquement.",quickOptions:[{emoji:"🐛",label:"Bug",value:"Quelque chose ne fonctionne pas"},{emoji:"💡",label:"Suggestion",value:"J'ai une suggestion"},{emoji:"🤔",label:"Confus",value:"Je suis perplexe"}]},success:{title:"Merci, votre retour est bien arrivé.",title_no_ai:"Merci ! Nous avons bien reçu votre avis.",close:"Fermer",email_saved:"Vous recevrez un e-mail une fois résolu.",email_error:"Impossible d'enregistrer votre e-mail. Veuillez réessayer.",track_feedback:"Suivre mon retour",email_cta:"M’avertir par e-mail une fois corrigé",notify:"Avertir"},error:{submit:"Échec de l'envoi. Veuillez réessayer.",finalize_title:"Nous n'avons pas encore pu l'envoyer.",finalize_message:"Votre retour est toujours enregistré. Veuillez réessayer."},pet:{bubble:"Besoin d'aide ?"},frustration:{prompt:"Un problème ? Dites-le-nous.",action:"Annoter",dismiss:"Fermer"},annotation:{drawing:"Dessin",element:"élément"},draw:{note_placeholder:"Ajoutez une note à votre dessin",undo:"Annuler",redo:"Rétablir",cancel:"Annuler",submit:"Envoyer"},record:{stop:"Arrêter",timer_label:"Enregistrement",max_reached:"Durée maximale d'enregistrement atteinte",replay_label:"screen-recording.json",play:"Lire l'enregistrement",close:"Fermer",preview_unavailable:"Aperçu indisponible"},clarify:{title:"Make This Better AI",subtitle:"Affinement de votre retour",thinking:"Réflexion...",placeholder:"Ajoutez des détails, puis envoyez",send:"Envoyer",submit:"Soumettre",send_feedback:"Envoyer le retour",skip:"Ignorer et envoyer",skip_short:"Ignorer",cancel:"Annuler — ne pas envoyer",retry:"Réessayer",error:"Impossible de charger la question. Envoyez votre avis tel quel.",expired:"Cette session de retour a expiré avant d'avoir pu être envoyée. Fermez le widget et renvoyez-la."}},Or={tab:"Feedback",toolbar:{markup:"Markieren",record:"Aufnehmen",hint:"Klicken zum Kommentieren, ziehen zum Zeichnen",hintTouch:"Ziehen, um das Problem zu markieren",hintRecord:"Bildschirm wird aufgenommen",exit:"Beenden"},popup:{about:"Info",placeholder:"Beschreiben Sie das Problem oder Ihren Vorschlag...",submit:"Absenden",sending:"Wird gesendet...",cancel:"Abbrechen",close:"Schließen",my_feedback:"Mein Feedback",screenshot_label:"Screenshot anhängen",screenshot_hint:"Passwörter und andere sensible Felder werden automatisch abgedeckt.",screenshot_short:"Screenshot",screenshot_locked_hint:"Deine Zeichnung wird in den Screenshot eingebrannt, daher wird er immer angehängt. Sensible Felder werden automatisch abgedeckt.",recording_label:"Aufzeichnung",recording_locked_hint:"Eine Wiedergabe dessen, was die Seite zeigte und wie sie bedient wurde — immer angehängt. Keine Kamera, kein Mikrofon. Sensible Felder werden automatisch abgedeckt.",quickOptions:[{emoji:"🐛",label:"Fehler",value:"Etwas funktioniert nicht"},{emoji:"💡",label:"Vorschlag",value:"Ich habe einen Vorschlag"},{emoji:"🤔",label:"Unklar",value:"Ich bin verwirrt"}]},success:{title:"Danke, Ihr Feedback ist angekommen.",title_no_ai:"Vielen Dank! Wir haben Ihr Feedback erhalten.",close:"Schließen",email_saved:"Sie erhalten eine E-Mail, sobald es gelöst ist.",email_error:"E-Mail konnte nicht gespeichert werden. Bitte versuchen Sie es erneut.",track_feedback:"Feedback verfolgen",email_cta:"E-Mail, sobald es behoben ist",notify:"Melden"},error:{submit:"Senden fehlgeschlagen. Bitte versuchen Sie es erneut.",finalize_title:"Wir konnten dies noch nicht senden.",finalize_message:"Ihr Feedback ist weiterhin gespeichert. Bitte versuchen Sie es erneut."},pet:{bubble:"Brauchen Sie Hilfe?"},frustration:{prompt:"Etwas funktioniert nicht? Sagen Sie es uns.",action:"Kommentieren",dismiss:"Schließen"},annotation:{drawing:"Zeichnung",element:"Element"},draw:{note_placeholder:"Fügen Sie Ihrer Zeichnung eine Notiz hinzu",undo:"Rückgängig",redo:"Wiederholen",cancel:"Abbrechen",submit:"Absenden"},record:{stop:"Stopp",timer_label:"Aufnahme",max_reached:"Maximale Aufnahmedauer erreicht",replay_label:"screen-recording.json",play:"Aufnahme abspielen",close:"Schließen",preview_unavailable:"Vorschau nicht verfügbar"},clarify:{title:"Make This Better AI",subtitle:"Wir schärfen dein Feedback",thinking:"Einen Moment...",placeholder:"Details ergänzen, dann absenden",send:"Senden",submit:"Absenden",send_feedback:"Feedback senden",skip:"Überspringen & senden",skip_short:"Überspringen",cancel:"Abbrechen — nicht senden",retry:"Erneut versuchen",error:"Die Frage konnte nicht geladen werden. Senden Sie Ihr Feedback einfach so.",expired:"Diese Feedback-Sitzung ist abgelaufen, bevor sie gesendet werden konnte. Bitte schließe das Widget und sende erneut."}},D={en:Ir,"zh-CN":Hr,ja:Nr,ko:Fr,es:Br,fr:zr,de:Or};function jt(i){if(D[i])return D[i];const t=i.split("-")[0];return D[t]?D[t]:D.en}const Ur=60,qt=["value","content"],$r=Object.fromEntries(["button","checkbox","color","date","datetime-local","email","file","hidden","image","month","number","password","radio","range","reset","search","select","submit","tel","text","textarea","time","url","week"].map(i=>[i,!0])),jr="https://cdn.jsdelivr.net/npm/@rrweb/record@2.1.0/umd/record.min.js",qr="sha384-MrD66HBNSykaP2N95+6hQCFlF5oH2tvL3TD/zyvHNkP/sAFWZx98DX9MEDy8MdVT";let M=null;function Wr(){return M||(M=Vr().catch(()=>Xr()).catch(t=>{throw M=null,t}),M)}function Yr(i,t){const e=tt(i);return xt(e,t,ae()),e}function xt(i,t,e){if(Array.isArray(i)){i.forEach(a=>xt(a,t,e));return}if(!Wt(i))return;const r=Wt(i.attributes)?i.attributes:null,n=r&&qt.some(a=>typeof r[a]=="string"),o=(typeof i.text=="string"||typeof i.textContent=="string"||typeof i.value=="string"||n)&&typeof i.id=="number"?t.mirror.getNode(i.id):null;if(o instanceof Element){if(typeof i.text=="string"&&(i.text=et(i.text,o)),r)for(const a of qt){const l=r[a];typeof l=="string"&&(r[a]=et(l,o))}}else o?.nodeType===Node.TEXT_NODE&&le(o,e)&&(typeof i.textContent=="string"&&(i.textContent=p),typeof i.value=="string"&&(i.value=p));Object.values(i).forEach(a=>xt(a,t,e))}function Wt(i){return!!i&&typeof i=="object"&&!Array.isArray(i)}async function Vr(){return(await import("@rrweb/record")).record}function Yt(){const i=globalThis;return i.rrwebRecord?.record??i.rrweb?.record}function Xr(){return new Promise((i,t)=>{const e=Yt();if(e){i(e);return}const r=document.createElement("script");r.src=jr,r.integrity=qr,r.crossOrigin="anonymous",r.onload=()=>{const n=Yt();n?i(n):t(new Error("rrweb record global not found after script load"))},r.onerror=()=>t(new Error("Failed to load rrweb from CDN")),document.head.appendChild(r)})}class Kr{constructor(t,e){this.events=[],this.stopFn=null,this.startedAt=0,this.timer=null,this.clickHandler=null,this.stopped=!1,this.destroyed=!1,this.shadow=t,this.onMaxReached=e}async start(){const t=await Wr();this.destroyed||(this.startedAt=Date.now(),this.stopped=!1,this.stopFn=t({emit:e=>{if(!this.stopped)try{this.events.push(Yr(e,t))}catch{}},maskAllInputs:!1,maskInputOptions:$r,maskInputFn:(e,r)=>r.closest(`.${U}`)?p:et(e,r),maskTextFn:()=>p,blockClass:st,maskTextClass:U}),this.clickHandler=e=>{this.showClickRipple(e.clientX,e.clientY),t.addCustomEvent?.("mtb-click",{x:e.clientX,y:e.clientY,target:e.target instanceof HTMLElement?e.target.tagName:""})},document.addEventListener("click",this.clickHandler,!0),this.timer=setTimeout(()=>{this.onMaxReached?.()},Ur*1e3))}stop(){return this.stopped=!0,this.stopFn?.(),this.stopFn=null,this.cleanupTimer(),this.cleanupClickHandler(),{events:this.events,duration:this.getDuration()}}getDuration(){return this.startedAt===0?0:Math.max(1,Math.round((Date.now()-this.startedAt)/1e3))}destroy(){this.destroyed=!0,this.stopped=!0,this.stopFn?.(),this.stopFn=null,this.cleanupTimer(),this.cleanupClickHandler(),this.events=[],this.startedAt=0}cleanupTimer(){this.timer&&(clearTimeout(this.timer),this.timer=null)}cleanupClickHandler(){this.clickHandler&&(document.removeEventListener("click",this.clickHandler,!0),this.clickHandler=null)}showClickRipple(t,e){const r=this.shadow.el("div","mtb-click-ripple");r.style.left=`${t}px`,r.style.top=`${e}px`,this.shadow.append(r),r.addEventListener("animationend",()=>r.remove())}}class Gr{constructor(t,e,r,n){this.intervalId=null,this.getDuration=r,this.el=t.el("div","mtb-record-bar"),this.el.innerHTML=`
69
+ `))!==-1;){const h=n.slice(0,c);n=n.slice(c+2);try{o(h)}catch{}}}if(n+=r.decode(),n.trim())try{o(n)}catch{}if(!s)throw new Error("clarify stream ended before done");return s}function Pr(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,12)}`}function Dr(){if(typeof crypto>"u"||typeof crypto.getRandomValues!="function")throw new Error("Secure random generation is unavailable");const i=crypto.getRandomValues(new Uint8Array(32));return Array.from(i,t=>t.toString(16).padStart(2,"0")).join("")}const Ot="mtb_anon_id",fe="mtb_reporter_email",ge="mtb_board_url";let Ut=null,ve=null,we=null;function ye(){try{const i=window.localStorage.getItem(Ot);if(i?.startsWith("anon_"))return i;const t=$t();return window.localStorage.setItem(Ot,t),t}catch{return Ut??(Ut=$t()),Ut}}function xe(){try{return window.localStorage.getItem(fe)??void 0}catch{return ve??void 0}}function Mr(i){ve=i;try{window.localStorage.setItem(fe,i)}catch{}}function Rr(){try{return window.localStorage.getItem(ge)??void 0}catch{return we??void 0}}function P(i){we=i;try{window.localStorage.setItem(ge,i)}catch{}}function $t(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`anon_${crypto.randomUUID()}`:`anon_${`${Date.now().toString(16)}-${Math.random().toString(16).slice(2,10)}`}`}const Ir={tab:"Feedback",toolbar:{markup:"Mark up",record:"Record",hint:"Click to comment, drag to draw",hintTouch:"Drag to mark what's wrong",hintRecord:"Recording your screen",exit:"Exit"},popup:{about:"About",placeholder:"Describe the issue or suggestion...",submit:"Submit",sending:"Sending...",cancel:"Cancel",close:"Close",my_feedback:"My feedback",screenshot_label:"Attach screenshot",screenshot_hint:"Passwords and other sensitive fields are covered automatically.",screenshot_short:"Screenshot",screenshot_locked_hint:"Your drawing is baked onto the screenshot, so it is always attached. Sensitive fields are covered automatically.",recording_label:"Recording",recording_locked_hint:"A replay of what the page showed and how it was used — always included with a recording. No camera or microphone. Sensitive fields are covered automatically.",quickOptions:[{emoji:"🐛",label:"Broken",value:"Something's broken"},{emoji:"💡",label:"Suggestion",value:"I have a suggestion"},{emoji:"🤔",label:"Confused",value:"I'm confused"}]},success:{title:"Thanks, your feedback is in.",title_no_ai:"Thanks! We've received your feedback.",close:"Close",email_saved:"You'll get an email when it's resolved.",email_error:"Couldn't save your email. Please try again.",track_feedback:"Track your feedback",email_cta:"Email me when it's fixed",notify:"Notify"},error:{submit:"Failed to submit. Please try again.",finalize_title:"We couldn't send this yet.",finalize_message:"Your feedback is still saved. Please try again."},pet:{bubble:"Need help?"},frustration:{prompt:"Something not working? Tell us.",action:"Annotate",dismiss:"Dismiss"},annotation:{drawing:"Drawing",element:"element"},draw:{note_placeholder:"Add a note to your drawing",undo:"Undo",redo:"Redo",cancel:"Cancel",submit:"Submit"},record:{stop:"Stop",timer_label:"Recording",max_reached:"Maximum recording time reached",replay_label:"screen-recording.json",play:"Play recording",close:"Close",preview_unavailable:"Preview unavailable"},clarify:{title:"Make This Better AI",subtitle:"Sharpening your feedback",thinking:"Thinking...",placeholder:"Add details, then submit",send:"Send",submit:"Submit",send_feedback:"Send feedback",skip:"Skip & submit",skip_short:"Skip",cancel:"Cancel — don't send feedback",retry:"Retry",error:"Couldn't load the question. Send your feedback as is.",expired:"This feedback session expired before it could be sent. Please close the widget and submit again."}},Hr={tab:"反馈",toolbar:{markup:"标注",record:"录屏",hint:"点击标注,拖动绘制",hintTouch:"用手指圈出问题",hintRecord:"正在录制屏幕",exit:"退出"},popup:{about:"关于",placeholder:"描述问题或建议...",submit:"提交",sending:"发送中...",cancel:"取消",close:"关闭",my_feedback:"我的反馈",screenshot_label:"附带页面截图",screenshot_hint:"密码等敏感字段会自动打码。",screenshot_short:"截图",screenshot_locked_hint:"圈画会画在截图上,所以必定附带。敏感字段会自动打码。",recording_label:"录制",recording_locked_hint:"页面画面与操作过程的回放,录制内容必定随反馈提交。不含摄像头和麦克风,敏感字段会自动打码。",quickOptions:[{emoji:"🐛",label:"出错",value:"出问题了"},{emoji:"💡",label:"建议",value:"我有一个建议"},{emoji:"🤔",label:"疑问",value:"我有点疑问"}]},success:{title:"收到了,谢谢你的反馈。",title_no_ai:"感谢!我们已收到您的反馈。",close:"关闭",email_saved:"问题解决后您会收到邮件通知。",email_error:"邮箱保存失败,请重试。",track_feedback:"查看处理进度",email_cta:"解决后邮件通知我",notify:"通知我"},error:{submit:"提交失败,请重试。",finalize_title:"暂时无法发送。",finalize_message:"你的反馈仍已保存,请重试。"},pet:{bubble:"需要帮助吗?"},frustration:{prompt:"遇到问题了?告诉我们。",action:"标注",dismiss:"关闭"},annotation:{drawing:"绘制",element:"元素"},draw:{note_placeholder:"给你的绘制添加说明",undo:"撤销",redo:"重做",cancel:"取消",submit:"提交"},record:{stop:"停止",timer_label:"录制中",max_reached:"已达到最长录制时间",replay_label:"screen-recording.json",play:"播放录屏",close:"关闭",preview_unavailable:"暂无法预览"},clarify:{title:"Make This Better AI",subtitle:"正在完善你的反馈",thinking:"思考中...",placeholder:"补充说明后提交",send:"发送",submit:"提交",send_feedback:"发送反馈",skip:"跳过并提交",skip_short:"跳过",cancel:"取消并不发送",retry:"重试",error:"追问加载失败,可以直接发送反馈。",expired:"这条反馈在发送前已过期。请关闭组件后重新提交。"}},Nr={tab:"フィードバック",toolbar:{markup:"マークアップ",record:"録画",hint:"クリックでコメント、ドラッグで描画",hintTouch:"ドラッグして問題箇所を囲んでください",hintRecord:"画面を録画中",exit:"終了"},popup:{about:"概要",placeholder:"問題や提案を入力してください...",submit:"送信",sending:"送信中...",cancel:"キャンセル",close:"閉じる",my_feedback:"自分のフィードバック",screenshot_label:"スクリーンショットを添付",screenshot_hint:"パスワードなどの機密項目は自動的に隠されます。",screenshot_short:"スクリーンショット",screenshot_locked_hint:"描き込みはスクリーンショット上に焼き込まれるため、必ず添付されます。機密項目は自動的に隠されます。",recording_label:"記録",recording_locked_hint:"ページの表示と操作の再現記録で、必ず添付されます。カメラやマイクは含まれず、機密項目は自動的に隠されます。",quickOptions:[{emoji:"🐛",label:"不具合",value:"不具合があります"},{emoji:"💡",label:"提案",value:"提案があります"},{emoji:"🤔",label:"不明点",value:"わかりにくいです"}]},success:{title:"フィードバックを受け取りました。ありがとうございます。",title_no_ai:"ありがとうございます!フィードバックを受け付けました。",close:"閉じる",email_saved:"解決次第メールでお知らせします。",email_error:"メールアドレスを保存できませんでした。もう一度お試しください。",track_feedback:"対応状況を確認",email_cta:"解決したらメールで知らせる",notify:"通知"},error:{submit:"送信に失敗しました。もう一度お試しください。",finalize_title:"まだ送信できませんでした。",finalize_message:"フィードバックは保存されています。もう一度お試しください。"},pet:{bubble:"お困りですか?"},frustration:{prompt:"うまくいかないことがありますか?お知らせください。",action:"注釈",dismiss:"閉じる"},annotation:{drawing:"描画",element:"要素"},draw:{note_placeholder:"描画にメモを追加",undo:"元に戻す",redo:"やり直す",cancel:"キャンセル",submit:"送信"},record:{stop:"停止",timer_label:"録画中",max_reached:"最大記録時間に達しました",replay_label:"screen-recording.json",play:"録画を再生",close:"閉じる",preview_unavailable:"プレビューは利用できません"},clarify:{title:"Make This Better AI",subtitle:"フィードバックを整えています",thinking:"考え中...",placeholder:"詳細を追加して送信",send:"送信",submit:"送信する",send_feedback:"フィードバックを送信",skip:"スキップして送信",skip_short:"スキップ",cancel:"キャンセル — 送信しない",retry:"再試行",error:"質問を読み込めませんでした。そのままフィードバックを送信できます。",expired:"このフィードバックは送信される前に有効期限が切れました。ウィジェットを閉じて、もう一度送信してください。"}},Fr={tab:"피드백",toolbar:{markup:"마크업",record:"녹화",hint:"클릭하여 댓글, 드래그하여 그리기",hintTouch:"드래그해서 문제가 있는 곳을 표시하세요",hintRecord:"화면 녹화 중",exit:"나가기"},popup:{about:"정보",placeholder:"문제 또는 제안 사항을 설명해 주세요...",submit:"제출",sending:"전송 중...",cancel:"취소",close:"닫기",my_feedback:"내 피드백",screenshot_label:"스크린샷 첨부",screenshot_hint:"비밀번호 등 민감한 입력란은 자동으로 가려집니다.",screenshot_short:"스크린샷",screenshot_locked_hint:"그린 표시는 스크린샷 위에 합쳐지므로 항상 첨부됩니다. 민감한 입력란은 자동으로 가려집니다.",recording_label:"기록",recording_locked_hint:"페이지 화면과 조작 과정의 재현 기록으로, 항상 첨부됩니다. 카메라와 마이크는 포함되지 않으며 민감한 입력란은 자동으로 가려집니다.",quickOptions:[{emoji:"🐛",label:"오류",value:"문제가 있어요"},{emoji:"💡",label:"제안",value:"제안이 있어요"},{emoji:"🤔",label:"혼란",value:"헷갈려요"}]},success:{title:"피드백이 접수되었습니다. 감사합니다.",title_no_ai:"감사합니다! 피드백을 접수했습니다.",close:"닫기",email_saved:"해결되면 이메일로 알려드립니다.",email_error:"이메일을 저장하지 못했습니다. 다시 시도해 주세요.",track_feedback:"처리 상황 보기",email_cta:"해결되면 이메일로 알림",notify:"알림"},error:{submit:"제출에 실패했습니다. 다시 시도해 주세요.",finalize_title:"아직 전송하지 못했습니다.",finalize_message:"피드백은 저장되어 있습니다. 다시 시도해 주세요."},pet:{bubble:"도움이 필요하신가요?"},frustration:{prompt:"문제가 있으신가요? 알려 주세요.",action:"주석",dismiss:"닫기"},annotation:{drawing:"그리기",element:"요소"},draw:{note_placeholder:"그림에 메모 추가",undo:"실행 취소",redo:"다시 실행",cancel:"취소",submit:"보내기"},record:{stop:"중지",timer_label:"녹화 중",max_reached:"최대 녹화 시간에 도달했습니다",replay_label:"screen-recording.json",play:"녹화 재생",close:"닫기",preview_unavailable:"미리보기를 사용할 수 없습니다"},clarify:{title:"Make This Better AI",subtitle:"피드백을 다듬는 중",thinking:"생각 중...",placeholder:"자세히 적은 뒤 제출",send:"보내기",submit:"제출",send_feedback:"피드백 보내기",skip:"건너뛰고 보내기",skip_short:"건너뛰기",cancel:"취소 — 보내지 않기",retry:"재시도",error:"질문을 불러오지 못했습니다. 피드백을 그대로 보내세요.",expired:"이 피드백 세션은 전송되기 전에 만료되었습니다. 위젯을 닫고 다시 보내 주세요."}},Br={tab:"Comentarios",toolbar:{markup:"Anotar",record:"Grabar",hint:"Clic para comentar, arrastrar para dibujar",hintTouch:"Arrastra para marcar el problema",hintRecord:"Grabando pantalla",exit:"Salir"},popup:{about:"Acerca de",placeholder:"Describe el problema o sugerencia...",submit:"Enviar",sending:"Enviando...",cancel:"Cancelar",close:"Cerrar",my_feedback:"Mis comentarios",screenshot_label:"Adjuntar captura de pantalla",screenshot_hint:"Las contraseñas y otros campos sensibles se ocultan automáticamente.",screenshot_short:"Captura",screenshot_locked_hint:"Tu dibujo se integra en la captura, por eso siempre se adjunta. Los campos sensibles se ocultan automáticamente.",recording_label:"Grabación",recording_locked_hint:"Una reproducción de lo que mostraba la página y cómo se usó; siempre se adjunta. Sin cámara ni micrófono. Los campos sensibles se ocultan automáticamente.",quickOptions:[{emoji:"🐛",label:"Error",value:"Algo no funciona"},{emoji:"💡",label:"Sugerencia",value:"Tengo una sugerencia"},{emoji:"🤔",label:"Confuso",value:"Estoy confundido"}]},success:{title:"Gracias, hemos recibido tu comentario.",title_no_ai:"¡Gracias! Hemos recibido tu comentario.",close:"Cerrar",email_saved:"Recibirás un correo cuando se resuelva.",email_error:"No se pudo guardar tu correo. Inténtalo de nuevo.",track_feedback:"Seguir mi comentario",email_cta:"Avísame por correo cuando se arregle",notify:"Avisarme"},error:{submit:"Error al enviar. Por favor, inténtalo de nuevo.",finalize_title:"Aún no pudimos enviarlo.",finalize_message:"Tu comentario sigue guardado. Inténtalo de nuevo."},pet:{bubble:"¿Necesitas ayuda?"},frustration:{prompt:"¿Algo no funciona? Cuéntanos.",action:"Anotar",dismiss:"Cerrar"},annotation:{drawing:"Dibujo",element:"elemento"},draw:{note_placeholder:"Añade una nota a tu dibujo",undo:"Deshacer",redo:"Rehacer",cancel:"Cancelar",submit:"Enviar"},record:{stop:"Detener",timer_label:"Grabando",max_reached:"Tiempo máximo de grabación alcanzado",replay_label:"screen-recording.json",play:"Reproducir grabación",close:"Cerrar",preview_unavailable:"Vista previa no disponible"},clarify:{title:"Make This Better AI",subtitle:"Afinando tus comentarios",thinking:"Pensando...",placeholder:"Añade detalles y envía",send:"Enviar",submit:"Enviar",send_feedback:"Enviar comentario",skip:"Omitir y enviar",skip_short:"Omitir",cancel:"Cancelar — no enviar",retry:"Reintentar",error:"No se pudo cargar la pregunta. Envía tus comentarios tal cual.",expired:"Esta sesión de comentarios caducó antes de poder enviarse. Cierra el widget y envíalo de nuevo."}},zr={tab:"Avis",toolbar:{markup:"Annoter",record:"Enregistrer",hint:"Cliquer pour commenter, glisser pour dessiner",hintTouch:"Faites glisser pour marquer le problème",hintRecord:"Enregistrement de l'écran",exit:"Quitter"},popup:{about:"À propos",placeholder:"Décrivez le problème ou votre suggestion...",submit:"Envoyer",sending:"Envoi en cours...",cancel:"Annuler",close:"Fermer",my_feedback:"Mes avis",screenshot_label:"Joindre une capture d'écran",screenshot_hint:"Les mots de passe et autres champs sensibles sont masqués automatiquement.",screenshot_short:"Capture",screenshot_locked_hint:"Votre dessin est intégré à la capture, elle est donc toujours jointe. Les champs sensibles sont masqués automatiquement.",recording_label:"Enregistrement",recording_locked_hint:"Une relecture de ce que la page affichait et de son utilisation — toujours jointe. Ni caméra ni micro. Les champs sensibles sont masqués automatiquement.",quickOptions:[{emoji:"🐛",label:"Bug",value:"Quelque chose ne fonctionne pas"},{emoji:"💡",label:"Suggestion",value:"J'ai une suggestion"},{emoji:"🤔",label:"Confus",value:"Je suis perplexe"}]},success:{title:"Merci, votre retour est bien arrivé.",title_no_ai:"Merci ! Nous avons bien reçu votre avis.",close:"Fermer",email_saved:"Vous recevrez un e-mail une fois résolu.",email_error:"Impossible d'enregistrer votre e-mail. Veuillez réessayer.",track_feedback:"Suivre mon retour",email_cta:"M’avertir par e-mail une fois corrigé",notify:"Avertir"},error:{submit:"Échec de l'envoi. Veuillez réessayer.",finalize_title:"Nous n'avons pas encore pu l'envoyer.",finalize_message:"Votre retour est toujours enregistré. Veuillez réessayer."},pet:{bubble:"Besoin d'aide ?"},frustration:{prompt:"Un problème ? Dites-le-nous.",action:"Annoter",dismiss:"Fermer"},annotation:{drawing:"Dessin",element:"élément"},draw:{note_placeholder:"Ajoutez une note à votre dessin",undo:"Annuler",redo:"Rétablir",cancel:"Annuler",submit:"Envoyer"},record:{stop:"Arrêter",timer_label:"Enregistrement",max_reached:"Durée maximale d'enregistrement atteinte",replay_label:"screen-recording.json",play:"Lire l'enregistrement",close:"Fermer",preview_unavailable:"Aperçu indisponible"},clarify:{title:"Make This Better AI",subtitle:"Affinement de votre retour",thinking:"Réflexion...",placeholder:"Ajoutez des détails, puis envoyez",send:"Envoyer",submit:"Soumettre",send_feedback:"Envoyer le retour",skip:"Ignorer et envoyer",skip_short:"Ignorer",cancel:"Annuler — ne pas envoyer",retry:"Réessayer",error:"Impossible de charger la question. Envoyez votre avis tel quel.",expired:"Cette session de retour a expiré avant d'avoir pu être envoyée. Fermez le widget et renvoyez-la."}},Or={tab:"Feedback",toolbar:{markup:"Markieren",record:"Aufnehmen",hint:"Klicken zum Kommentieren, ziehen zum Zeichnen",hintTouch:"Ziehen, um das Problem zu markieren",hintRecord:"Bildschirm wird aufgenommen",exit:"Beenden"},popup:{about:"Info",placeholder:"Beschreiben Sie das Problem oder Ihren Vorschlag...",submit:"Absenden",sending:"Wird gesendet...",cancel:"Abbrechen",close:"Schließen",my_feedback:"Mein Feedback",screenshot_label:"Screenshot anhängen",screenshot_hint:"Passwörter und andere sensible Felder werden automatisch abgedeckt.",screenshot_short:"Screenshot",screenshot_locked_hint:"Deine Zeichnung wird in den Screenshot eingebrannt, daher wird er immer angehängt. Sensible Felder werden automatisch abgedeckt.",recording_label:"Aufzeichnung",recording_locked_hint:"Eine Wiedergabe dessen, was die Seite zeigte und wie sie bedient wurde — immer angehängt. Keine Kamera, kein Mikrofon. Sensible Felder werden automatisch abgedeckt.",quickOptions:[{emoji:"🐛",label:"Fehler",value:"Etwas funktioniert nicht"},{emoji:"💡",label:"Vorschlag",value:"Ich habe einen Vorschlag"},{emoji:"🤔",label:"Unklar",value:"Ich bin verwirrt"}]},success:{title:"Danke, Ihr Feedback ist angekommen.",title_no_ai:"Vielen Dank! Wir haben Ihr Feedback erhalten.",close:"Schließen",email_saved:"Sie erhalten eine E-Mail, sobald es gelöst ist.",email_error:"E-Mail konnte nicht gespeichert werden. Bitte versuchen Sie es erneut.",track_feedback:"Feedback verfolgen",email_cta:"E-Mail, sobald es behoben ist",notify:"Melden"},error:{submit:"Senden fehlgeschlagen. Bitte versuchen Sie es erneut.",finalize_title:"Wir konnten dies noch nicht senden.",finalize_message:"Ihr Feedback ist weiterhin gespeichert. Bitte versuchen Sie es erneut."},pet:{bubble:"Brauchen Sie Hilfe?"},frustration:{prompt:"Etwas funktioniert nicht? Sagen Sie es uns.",action:"Kommentieren",dismiss:"Schließen"},annotation:{drawing:"Zeichnung",element:"Element"},draw:{note_placeholder:"Fügen Sie Ihrer Zeichnung eine Notiz hinzu",undo:"Rückgängig",redo:"Wiederholen",cancel:"Abbrechen",submit:"Absenden"},record:{stop:"Stopp",timer_label:"Aufnahme",max_reached:"Maximale Aufnahmedauer erreicht",replay_label:"screen-recording.json",play:"Aufnahme abspielen",close:"Schließen",preview_unavailable:"Vorschau nicht verfügbar"},clarify:{title:"Make This Better AI",subtitle:"Wir schärfen dein Feedback",thinking:"Einen Moment...",placeholder:"Details ergänzen, dann absenden",send:"Senden",submit:"Absenden",send_feedback:"Feedback senden",skip:"Überspringen & senden",skip_short:"Überspringen",cancel:"Abbrechen — nicht senden",retry:"Erneut versuchen",error:"Die Frage konnte nicht geladen werden. Senden Sie Ihr Feedback einfach so.",expired:"Diese Feedback-Sitzung ist abgelaufen, bevor sie gesendet werden konnte. Bitte schließe das Widget und sende erneut."}},D={en:Ir,"zh-CN":Hr,ja:Nr,ko:Fr,es:Br,fr:zr,de:Or};function jt(i){if(D[i])return D[i];const t=i.split("-")[0];return D[t]?D[t]:D.en}const Ur=60,qt=["value","content"],$r=Object.fromEntries(["button","checkbox","color","date","datetime-local","email","file","hidden","image","month","number","password","radio","range","reset","search","select","submit","tel","text","textarea","time","url","week"].map(i=>[i,!0])),jr="https://cdn.jsdelivr.net/npm/@rrweb/record@2.1.0/umd/record.min.js",qr="sha384-MrD66HBNSykaP2N95+6hQCFlF5oH2tvL3TD/zyvHNkP/sAFWZx98DX9MEDy8MdVT";let M=null;function Wr(){return M||(M=Vr().catch(()=>Xr()).catch(t=>{throw M=null,t}),M)}function Yr(i,t){const e=tt(i);return xt(e,t,ae()),e}function xt(i,t,e){if(Array.isArray(i)){i.forEach(a=>xt(a,t,e));return}if(!Wt(i))return;const r=Wt(i.attributes)?i.attributes:null,n=r&&qt.some(a=>typeof r[a]=="string"),o=(typeof i.text=="string"||typeof i.textContent=="string"||typeof i.value=="string"||n)&&typeof i.id=="number"?t.mirror.getNode(i.id):null;if(o instanceof Element){if(typeof i.text=="string"&&(i.text=et(i.text,o)),r)for(const a of qt){const l=r[a];typeof l=="string"&&(r[a]=et(l,o))}}else o?.nodeType===Node.TEXT_NODE&&le(o,e)&&(typeof i.textContent=="string"&&(i.textContent=p),typeof i.value=="string"&&(i.value=p));Object.values(i).forEach(a=>xt(a,t,e))}function Wt(i){return!!i&&typeof i=="object"&&!Array.isArray(i)}async function Vr(){return(await import("@rrweb/record")).record}function Yt(){const i=globalThis;return i.rrwebRecord?.record??i.rrweb?.record}function Xr(){return new Promise((i,t)=>{const e=Yt();if(e){i(e);return}const r=document.createElement("script");r.src=jr,r.integrity=qr,r.crossOrigin="anonymous",r.onload=()=>{const n=Yt();n?i(n):t(new Error("rrweb record global not found after script load"))},r.onerror=()=>t(new Error("Failed to load rrweb from CDN")),document.head.appendChild(r)})}class Kr{constructor(t,e){this.events=[],this.stopFn=null,this.startedAt=0,this.timer=null,this.clickHandler=null,this.stopped=!1,this.destroyed=!1,this.shadow=t,this.onMaxReached=e}async start(){const t=await Wr();this.destroyed||(this.startedAt=Date.now(),this.stopped=!1,this.stopFn=t({emit:e=>{if(!this.stopped)try{this.events.push(Yr(e,t))}catch{}},maskAllInputs:!1,maskInputOptions:$r,maskInputFn:(e,r)=>r.closest(`.${U}`)?p:et(e,r),maskTextFn:()=>p,blockClass:st,maskTextClass:U}),this.clickHandler=e=>{this.showClickRipple(e.clientX,e.clientY),t.addCustomEvent?.("mtb-click",{x:e.clientX,y:e.clientY,target:e.target instanceof HTMLElement?e.target.tagName:""})},document.addEventListener("click",this.clickHandler,!0),this.timer=setTimeout(()=>{this.onMaxReached?.()},Ur*1e3))}stop(){return this.stopped=!0,this.stopFn?.(),this.stopFn=null,this.cleanupTimer(),this.cleanupClickHandler(),{events:this.events,duration:this.getDuration()}}getDuration(){return this.startedAt===0?0:Math.max(1,Math.round((Date.now()-this.startedAt)/1e3))}destroy(){this.destroyed=!0,this.stopped=!0,this.stopFn?.(),this.stopFn=null,this.cleanupTimer(),this.cleanupClickHandler(),this.events=[],this.startedAt=0}cleanupTimer(){this.timer&&(clearTimeout(this.timer),this.timer=null)}cleanupClickHandler(){this.clickHandler&&(document.removeEventListener("click",this.clickHandler,!0),this.clickHandler=null)}showClickRipple(t,e){const r=this.shadow.el("div","mtb-click-ripple");r.style.left=`${t}px`,r.style.top=`${e}px`,this.shadow.append(r),r.addEventListener("animationend",()=>r.remove())}}class Gr{constructor(t,e,r,n){this.intervalId=null,this.getDuration=r,this.el=t.el("div","mtb-record-bar"),this.el.innerHTML=`
70
70
  <span class="mtb-record-dot"></span>
71
71
  <span class="mtb-record-timer">00:00</span>
72
72
  <button class="mtb-record-stop" type="button">${d(e.record.stop)}</button>