@whoz-oss/coday-client 0.159.8 → 0.160.1
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/3rdpartylicenses.txt +26 -26
- package/browser/{chunk-TCYPGB6P.js → chunk-3WSHO4HH.js} +1 -1
- package/browser/{chunk-TWTJJETM.js → chunk-44ROPJW7.js} +1 -1
- package/browser/{chunk-J6KC3ETK.js → chunk-44U6NIYJ.js} +1 -1
- package/browser/{chunk-AEXWYSY4.js → chunk-4RMKYA7C.js} +1 -1
- package/browser/chunk-5DYITBLP.js +1 -0
- package/browser/chunk-5ETOAW5I.js +1 -0
- package/browser/{chunk-GZ5XFG52.js → chunk-73MM2OCC.js} +1 -1
- package/browser/{chunk-FXW6JMJT.js → chunk-73XLCIE3.js} +1 -1
- package/browser/chunk-7INOPTJ6.js +1 -0
- package/browser/{chunk-64KUJ72Y.js → chunk-AKNP533G.js} +1 -1
- package/browser/{chunk-EL5IQEU5.js → chunk-AUD6VMQP.js} +1 -1
- package/browser/chunk-B5UWPZYC.js +61 -0
- package/browser/{chunk-3PF557D6.js → chunk-BJL3QU5V.js} +1 -1
- package/browser/{chunk-HBPEHALV.js → chunk-C6PPTNHE.js} +1 -1
- package/browser/chunk-CFTOIYSG.js +1 -0
- package/browser/{chunk-QMQRJWM2.js → chunk-CQCFF5QA.js} +1 -1
- package/browser/{chunk-F32VEQPY.js → chunk-DWPYG4F6.js} +1 -1
- package/browser/{chunk-GKBRHSMN.js → chunk-EQGMNQH5.js} +1 -1
- package/browser/chunk-F4YDJMK7.js +1 -0
- package/browser/{chunk-4PT56FZA.js → chunk-FJTJITU2.js} +1 -1
- package/browser/{chunk-NGOS7UTY.js → chunk-GTNTE2V7.js} +1 -1
- package/browser/chunk-IJ2PFSZT.js +1 -0
- package/browser/chunk-IKNFRB6Z.js +1 -0
- package/browser/{chunk-NUN4WTCP.js → chunk-IW7LOGR6.js} +1 -1
- package/browser/{chunk-46WAGL6T.js → chunk-JK7XVLXN.js} +1 -1
- package/browser/{chunk-MKE7HI6X.js → chunk-LANL6XWU.js} +1 -1
- package/browser/{chunk-OAN35RIR.js → chunk-LEIES4AA.js} +1 -1
- package/browser/{chunk-JLVW3WZE.js → chunk-LHRGRELF.js} +1 -1
- package/browser/{chunk-6HXHF2SN.js → chunk-LLIN4HKG.js} +1 -1
- package/browser/{chunk-VU5WR5CP.js → chunk-MRYQF7JC.js} +1 -1
- package/browser/{chunk-H7MV7NCQ.js → chunk-NBZFBJ7T.js} +1 -1
- package/browser/chunk-NHYWTBYT.js +1 -0
- package/browser/{chunk-P7CSUKFY.js → chunk-OXXWNVGU.js} +1 -1
- package/browser/{chunk-MUQFZY3N.js → chunk-PGO5PZRK.js} +1 -1
- package/browser/chunk-PP5TBFXE.js +31 -0
- package/browser/chunk-Q7MOXRND.js +1 -0
- package/browser/{chunk-TGT4RBUY.js → chunk-QEUPJ2EM.js} +1 -1
- package/browser/chunk-RF7IRXXE.js +1 -0
- package/browser/{chunk-LHEQ6HXJ.js → chunk-S4QJJ7B3.js} +1 -1
- package/browser/{chunk-KRK3FNKB.js → chunk-VIFGZQZS.js} +1 -1
- package/browser/{chunk-SKABLB3F.js → chunk-WP6SVXZC.js} +1 -1
- package/browser/{chunk-ZV2GXJ7Q.js → chunk-WPGSXQ5M.js} +1 -1
- package/browser/{chunk-7YDOHTEK.js → chunk-XLNZCT7N.js} +1 -1
- package/browser/{chunk-IREZ3UJ3.js → chunk-Y2GNO2KX.js} +1 -1
- package/browser/chunk-Y2JOUXVN.js +1 -0
- package/browser/{chunk-I5HSEFR4.js → chunk-ZKUCVZCJ.js} +1 -1
- package/browser/index.html +1 -1
- package/browser/{main-3RWS5R5L.js → main-FLHOTSKQ.js} +1 -1
- package/package.json +1 -1
- package/browser/chunk-5JACHD45.js +0 -1
- package/browser/chunk-DFZI6Z7W.js +0 -1
- package/browser/chunk-EC2BCDCL.js +0 -1
- package/browser/chunk-FHERZTSZ.js +0 -1
- package/browser/chunk-FIVJTOO5.js +0 -1
- package/browser/chunk-JWRID2EL.js +0 -1
- package/browser/chunk-LMGSBI4E.js +0 -1
- package/browser/chunk-N5UH5PRX.js +0 -1
- package/browser/chunk-UVTRXG6W.js +0 -1
- package/browser/chunk-WG653S5D.js +0 -91
- package/browser/chunk-WMRLIQ4E.js +0 -1
- package/browser/chunk-XHE2FLNY.js +0 -1
|
@@ -1,91 +0,0 @@
|
|
|
1
|
-
import{a as tr}from"./chunk-XDTTR6NK.js";import{a as pn,b as mn,e as nr,g as Ye}from"./chunk-QMQRJWM2.js";import{a as vn}from"./chunk-2NBVMKPO.js";import{a as dn,b as Pe,c as jo,g as Yo,h as Go,i as Xo,m as Qo,n as Zo,p as Ko,r as xn,t as Jo,v as er,w as qe,y as _n}from"./chunk-PK3KWLLW.js";import{a as ir}from"./chunk-4HKHCNH5.js";import{d as Ro}from"./chunk-UARV2YUR.js";import{a as dr}from"./chunk-VIPJVFGJ.js";import{p as lr,r as cr}from"./chunk-F32VEQPY.js";import{b as Wo,p as or,q as rr,r as ar,v as sr}from"./chunk-7YDOHTEK.js";import{a as qo,c as bn}from"./chunk-WJFUKUVD.js";import{a as J,b as me}from"./chunk-DYANOPHQ.js";import{C as fn,c as un,g as hn,m as gn}from"./chunk-N5UH5PRX.js";import{b as Oe}from"./chunk-NMGDBGR3.js";import{E as Vo,K as Uo,O as je,Q as Bo,R as cn,S as We,i as Fo,j as Lo,p as Ho,s as No,t as zo,z as $o}from"./chunk-4YLSQZJK.js";import{$b as Oo,B as Se,Bb as O,D as en,Db as w,Fb as m,Fc as ln,G as bo,Ga as ue,Ha as Co,Hc as Do,Ic as fi,Ja as yo,Jb as ut,Ka as p,Kb as He,Kc as fe,Lb as Ne,Pa as wo,Rb as he,Sc as Me,T as K,Tb as f,Ub as F,Vb as ht,Vc as Ee,Wa as R,Wb as tn,Xa as To,Xb as nn,Ya as So,Yb as on,Z as Y,Za as ko,Zb as rn,_ as xo,_b as Eo,a as j,ac as Po,b as Te,bc as Io,ca as g,d as N,dc as It,ec as Ao,fc as gi,g as Kt,ga as T,h as xe,ha as S,i as Jt,jb as Be,kc as an,la as _o,lb as x,m as mi,mb as _,n as go,oa as H,pa as vo,pb as de,qb as pe,rb as M,sb as c,t as Ve,ta as Ue,tb as d,u as fo,ub as I,uc as sn,va as ke,vb as ui,wb as hi,xb as Mo,ya as mt}from"./chunk-QPN22TF2.js";var Cn=class i{sanitizer=g(Ee);transform(e,t){if(!t||!e)return e;let n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=new RegExp(`(${n})`,"gi"),r=e.replace(o,"<strong>$1</strong>");return this.sanitizer.bypassSecurityTrustHtml(r)}static \u0275fac=function(t){return new(t||i)};static \u0275pipe=ko({name:"highlight",type:i,pure:!0})};var gt=class i{http=g(Me);projectState=g(Oe);threadState=g(Pe);transcribeAudio(e,t,n){let o=this.projectState.getSelectedProjectIdOrThrow();return this.http.post(`/api/projects/${o}/transcribe`,j({audio:e,mimeType:t},n?{language:n}:{}))}sendVoiceMessage(e,t,n){let o=this.projectState.getSelectedProjectIdOrThrow(),r=this.threadState.getSelectedThreadIdOrThrow();return this.http.post(`/api/projects/${o}/threads/${r}/voice-message`,j({audio:e,mimeType:t},n?{language:n}:{}))}static \u0275fac=function(t){return new(t||i)};static \u0275prov=Y({token:i,factory:i.\u0275fac,providedIn:"root"})};var za=["messageInput"],$a=["fileInput"],Va=(i,e)=>e.name;function Ua(i,e){i&1&&(c(0,"div",3),I(1,"span",8),f(2," Recording... Click mic to stop "),d())}function Ba(i,e){i&1&&(c(0,"div",3),I(1,"span",9),f(2," Transcribing... "),d())}function ja(i,e){if(i&1&&(c(0,"span",14),f(1),d()),i&2){let t=m().$implicit,n=m(2);p(),F(" "+(n.getParameterFormat(t)||""))}}function Wa(i,e){if(i&1){let t=O();c(0,"div",11),w("click",function(){let o=T(t).$index,r=m(2);return S(r.selectAutocompleteItemByClick(o))})("keydown.enter",function(){let o=T(t).$index,r=m(2);return S(r.selectAutocompleteItemByClick(o))})("keydown.space",function(){let o=T(t).$index,r=m(2);return S(r.selectAutocompleteItemByClick(o))})("mouseenter",function(){let o=T(t).$index,r=m(2);return S(r.selectedAutocompleteIndex=o)}),c(1,"div",12),I(2,"span",13),It(3,"highlight"),x(4,ja,2,1,"span",14),d(),I(5,"div",15),It(6,"highlight"),d()}if(i&2){let t=e.$implicit,n=e.$index,o=m(2);he("selected",n===o.selectedAutocompleteIndex),Be("aria-selected",n===o.selectedAutocompleteIndex),p(2),M("innerHTML",gi(3,6,o.autocompleteTrigger+t.name,o.getAutocompleteQuery()),ue),p(2),_(o.hasParameterFormat(t)?4:-1),p(),M("innerHTML",gi(6,9,t.description,o.getAutocompleteQuery()),ue)}}function qa(i,e){if(i&1&&(c(0,"div",4),de(1,Wa,7,12,"div",10,Va),d()),i&2){let t=m();p(),pe(t.autocompleteItems)}}function Ya(i,e){if(i&1){let t=O();c(0,"ds-icon-button",18),w("action",function(){T(t);let o=m(2);return S(o.onStopClick())}),d()}}function Ga(i,e){if(i&1){let t=O();c(0,"ds-icon-button",19),w("action",function(){T(t);let o=m(2);return S(o.sendMessage())}),d()}if(i&2){let t=m(2);he("hidden",t.isDisabled||!t.message.trim())("active",!!t.message.trim()&&!t.isDisabled),M("title",t.getSendButtonTooltip())("disabled",t.isDisabled||!t.message.trim())}}function Xa(i,e){if(i&1){let t=O();c(0,"ds-icon-button",21),w("action",function(){T(t);let o=m(3);return S(o.triggerFileUpload())}),d(),c(1,"input",22,1),w("change",function(o){T(t);let r=m(3);return S(r.onFileInputChange(o))}),d()}if(i&2){let t=m(3);M("disabled",t.isDisabled)}}function Qa(i,e){if(i&1){let t=O();x(0,Xa,3,1),c(1,"ds-icon-button",20),w("action",function(){T(t);let o=m(2);return S(o.toggleRecording())}),d()}if(i&2){let t=m(2);_(!t.showWelcome&&!(t.isVoiceMessageMode&&(t.isRecording||t.isTranscribing))?0:-1),p(),he("hidden",t.message.trim()&&!t.isRecording&&!t.isTranscribing),M("variant",t.isVoiceMessageMode&&(t.isRecording||t.isTranscribing)?"danger":"default")("disabled",t.isVoiceMessageMode&&t.isTranscribing)("title",t.isRecording?"Click to stop recording":t.isTranscribing?"Uploading...":"Click to start recording")}}function Za(i,e){if(i&1&&(c(0,"div",7),x(1,Ya,1,0,"ds-icon-button",16),x(2,Ga,1,6,"ds-icon-button",17),x(3,Qa,2,6),d()),i&2){let t=m();p(),_(t.isThinking?1:-1),p(),_((!t.isThinking||t.message.trim())&&!(t.isVoiceMessageMode&&(t.isRecording||t.isTranscribing))?2:-1),p(),_(t.isThinking?-1:3)}}var yn=class i{isDisabled=!1;showWelcome=!1;isThinking=!1;isStarting=!1;isSessionInitializing=!1;isStopping=!1;filesPasted=new H;messageSubmitted=new H;voiceMessageReady=new H;voiceRecordingToggled=new H;heightChanged=new H;stopRequested=new H;textareaFocused=new H;messageInput;fileInput;message="";isRecording=!1;isTranscribing=!1;isFocused=!1;recognition=null;mediaRecorder=null;audioChunks=[];voiceInputMode="browser";get isVoiceMessageMode(){return this.voiceInputMode==="voice-message"}sessionHadTranscript=!1;pendingLineBreaksTimeout=null;lastProcessedResultIndex=0;useEnterToSend=!1;currentInvite="";subscriptions=[];thinkingPhrases=["Processing request...","Thinking...","Working on it..."];currentThinkingPhrase="Processing request...";thinkingPhraseIndex=0;thinkingInterval=null;autocompleteVisible=!1;autocompleteTrigger=null;autocompleteItems=[];selectedAutocompleteIndex=0;preferencesService=g(qe);codayService=g(Ye);agentApiService=g(tr);promptApiService=g(dr);projectStateService=g(Oe);audioApiService=g(gt);threadStateService=g(Pe);ngOnInit(){this.initializeVoiceInput(),this.useEnterToSend=this.preferencesService.getEnterToSend(),this.subscriptions.push(this.preferencesService.voiceLanguage$.subscribe(()=>this.updateRecognitionLanguage())),this.subscriptions.push(this.preferencesService.voiceInputMode$.subscribe(e=>{this.voiceInputMode=e})),this.subscriptions.push(this.preferencesService.enterToSend$.subscribe(e=>{this.useEnterToSend=e})),this.subscribeToInviteEvents(),this.subscribeToMessageRestore()}ngAfterViewInit(){this.adjustTextareaHeight(),requestAnimationFrame(()=>{setTimeout(()=>this.focusTextarea(),200)})}ngOnChanges(e){e.isThinking&&(e.isThinking.currentValue?this.startThinkingAnimation():(this.stopThinkingAnimation(),this.isStopping=!1,e.isThinking.previousValue&&(console.log("[CHAT-TEXTAREA] Thinking ended, scheduling focus"),requestAnimationFrame(()=>{setTimeout(()=>this.focusTextarea(),100)})))),e.isSessionInitializing&&!e.isSessionInitializing.currentValue&&e.isSessionInitializing.previousValue&&(console.log("[CHAT-TEXTAREA] Session initialization completed, scheduling focus"),requestAnimationFrame(()=>{setTimeout(()=>this.focusTextarea(),100)})),e.isStarting&&!e.isStarting.currentValue&&e.isStarting.previousValue&&this.isThinking&&(this.thinkingPhraseIndex===0?(console.log("[CHAT-TEXTAREA] Transitioning from Starting to Thinking at index 0 - restarting animation"),this.stopThinkingAnimation(),this.startThinkingAnimation()):console.log("[CHAT-TEXTAREA] Transitioning from Starting to Thinking at index",this.thinkingPhraseIndex,"- continuing without restart"))}ngOnDestroy(){this.subscriptions.forEach(e=>e.unsubscribe()),this.subscriptions=[],this.clearPendingLineBreaks(),this.stopThinkingAnimation()}onKeyDown(e){if(this.autocompleteVisible)switch(e.key){case"ArrowDown":e.preventDefault(),this.selectedAutocompleteIndex=Math.min(this.selectedAutocompleteIndex+1,this.autocompleteItems.length-1),this.scrollSelectedItemIntoView();return;case"ArrowUp":e.preventDefault(),this.selectedAutocompleteIndex=Math.max(this.selectedAutocompleteIndex-1,0),this.scrollSelectedItemIntoView();return;case"Tab":case"Enter":if(!this.message.includes(" ")){e.preventDefault(),this.selectAutocompleteItem();return}break;case"Escape":e.preventDefault(),this.hideAutocomplete();return}e.key==="Enter"&&(this.useEnterToSend?!e.shiftKey&&!e.metaKey&&!e.ctrlKey&&(e.preventDefault(),this.sendMessage(!0)):(navigator.platform.toLowerCase().includes("mac")?e.metaKey:e.ctrlKey)&&!e.shiftKey&&(e.preventDefault(),this.sendMessage(!0)))}onInput(){this.adjustTextareaHeight(),this.checkForAutocomplete()}onPaste(e){let t=e.clipboardData?.items;if(!t)return;let n=Array.from(t).filter(r=>r.kind==="file");if(!n.length)return;e.preventDefault();let o=n.reduce((r,a)=>{let l=a.getAsFile();return l?[...r,l]:r},[]);o.length&&this.filesPasted.emit(o)}triggerFileUpload(){console.log("[CHAT-TEXTAREA] Triggering file upload"),this.fileInput?.nativeElement?.click()}onFileInputChange(e){let t=e.target,n=t.files;if(!n||n.length===0){console.log("[CHAT-TEXTAREA] No files selected");return}console.log("[CHAT-TEXTAREA] Files selected:",n.length);let o=Array.from(n);this.filesPasted.emit(o),t.value=""}onDocumentClick(e){if(!this.autocompleteVisible)return;let t=e.target,n=document.querySelector(".autocomplete-popup"),o=this.messageInput?.nativeElement;n&&!n.contains(t)&&o&&!o.contains(t)&&this.hideAutocomplete()}sendMessage(e=!1){let t=this.message.trim();!this.isDisabled&&(e||t)&&(this.isRecording&&this.recognition&&(this.clearPendingLineBreaks(),this.recognition.stop()),this.messageSubmitted.emit(t),this.message="",setTimeout(()=>this.adjustTextareaHeight(),0))}onStopClick(){this.isStopping=!0,this.stopRequested.emit()}toggleRecording(){this.isRecording?this.voiceInputMode==="whisper"||this.voiceInputMode==="voice-message"?this.stopWhisperRecording():this.stopRecording():this.voiceInputMode==="whisper"||this.voiceInputMode==="voice-message"?this.startWhisperRecording():this.startRecording()}startWhisperRecording(){return N(this,null,function*(){if(!this.isRecording)try{let e=yield navigator.mediaDevices.getUserMedia({audio:!0});this.audioChunks=[],this.mediaRecorder=new MediaRecorder(e),this.mediaRecorder.ondataavailable=t=>{t.data.size>0&&this.audioChunks.push(t.data)},this.mediaRecorder.onstop=()=>{e.getTracks().forEach(t=>t.stop()),this.processWhisperAudio()},this.mediaRecorder.onerror=t=>{console.error("[WHISPER] MediaRecorder error:",t),e.getTracks().forEach(n=>n.stop()),this.isRecording=!1,this.voiceRecordingToggled.emit(!1)},this.mediaRecorder.start(),this.isRecording=!0,this.voiceRecordingToggled.emit(!0),console.log("[WHISPER] Started recording")}catch(e){console.error("[WHISPER] Failed to start recording:",e),this.isRecording=!1,this.voiceRecordingToggled.emit(!1)}})}stopWhisperRecording(){if(!(!this.mediaRecorder||!this.isRecording))try{this.mediaRecorder.stop(),this.isRecording=!1,this.voiceRecordingToggled.emit(!1),console.log("[WHISPER] Stopped recording")}catch(e){console.error("[WHISPER] Failed to stop recording:",e),this.isRecording=!1,this.voiceRecordingToggled.emit(!1)}}processWhisperAudio(){if(this.audioChunks.length===0)return;let e=new Blob(this.audioChunks,{type:this.mediaRecorder?.mimeType||"audio/webm"}),t=e.type.split(";")[0]||"audio/webm";this.audioChunks=[],this.isTranscribing=!0;let n=new FileReader;n.onloadend=()=>{let o=n.result.split(",")[1];if(!o){console.error("[WHISPER] Failed to read audio as base64"),this.isTranscribing=!1;return}let a=this.preferencesService.getVoiceLanguage().split("-")[0];if(this.voiceInputMode==="voice-message"){if(!this.threadStateService.getSelectedThreadId()){console.log("[WHISPER] No thread selected \u2014 emitting voiceMessageReady for thread creation"),this.isTranscribing=!1,this.voiceMessageReady.emit({base64:o,mimeType:t,language:a});return}this.audioApiService.sendVoiceMessage(o,t,a).subscribe({next:l=>{this.isTranscribing=!1,console.log("[WHISPER] Voice message sent, transcription:",l.transcription?.substring(0,50))},error:l=>{console.error("[WHISPER] Voice message error:",l),this.isTranscribing=!1,this.fallbackToTranscription(o,t,a)}})}else this.audioApiService.transcribeAudio(o,t,a).subscribe({next:l=>{this.isTranscribing=!1,l.text&&this.appendToTextarea(l.text+" ")},error:l=>{console.error("[WHISPER] Transcription error:",l),this.isTranscribing=!1}})},n.readAsDataURL(e)}fallbackToTranscription(e,t,n){this.audioApiService.transcribeAudio(e,t,n).subscribe({next:o=>{this.isTranscribing=!1,o.text&&this.appendToTextarea(o.text+" ")},error:o=>{console.error("[WHISPER] Fallback transcription also failed:",o),this.isTranscribing=!1}})}initializeVoiceInput(){let e=window.SpeechRecognition??window.webkitSpeechRecognition;if(console.log("[SPEECH] speechRecognition",e),!e){console.warn("[SPEECH] Speech Recognition API not available");return}this.recognition=new e,this.recognition.continuous=!0,this.recognition.interimResults=!0,this.recognition.maxAlternatives=1,this.recognition.lang=this.getSelectedLanguage();try{"grammars"in this.recognition&&(this.recognition.serviceURI=void 0)}catch(t){console.log("[SPEECH] Advanced speech recognition parameters not supported")}this.recognition.onresult=t=>{let n="",o=Math.max(t.resultIndex,this.lastProcessedResultIndex);for(let r=o;r<t.results.length;r++)t.results[r].isFinal&&(n+=t.results[r][0].transcript,this.lastProcessedResultIndex=r+1);if(n){let r=this.improveTranscriptPunctuation(n.trim());this.sessionHadTranscript=!0,console.log("[SPEECH] onresult ending, appending to textarea",this.isRecording),this.appendToTextarea(r)}},this.recognition.onend=()=>{console.log("[SPEECH] Recognition ended. Was recording:",this.isRecording),this.isRecording=!1,this.lastProcessedResultIndex=0,this.voiceRecordingToggled.emit(this.isRecording)},this.recognition.onerror=t=>{console.error("[SPEECH] Speech recognition error:",t.error),console.log("[SPEECH] Error details:",{error:t.error,message:t.message,timeStamp:t.timeStamp}),this.isRecording=!1,this.lastProcessedResultIndex=0,this.clearPendingLineBreaks(),this.voiceRecordingToggled.emit(this.isRecording)},this.recognition.onstart=()=>{console.log("[SPEECH] Recognition started successfully")},this.recognition.onspeechstart=()=>{console.log("[SPEECH] Speech detected")},this.recognition.onspeechend=()=>{console.log("[SPEECH] Speech ended")}}startRecording(){return N(this,null,function*(){if(!(!this.recognition||this.isRecording))try{this.isRecording=!0,this.sessionHadTranscript=!1,this.lastProcessedResultIndex=0,this.clearPendingLineBreaks(),this.voiceRecordingToggled.emit(this.isRecording),this.recognition.start(),console.log("[SPEECH] Started recording")}catch(e){console.error("[SPEECH] Failed to start recording:",e),this.isRecording=!1,this.voiceRecordingToggled.emit(this.isRecording)}})}stopRecording(){if(!this.recognition||!this.isRecording){console.log("[SPEECH] stopRecording not recording");return}try{console.log("[SPEECH] stopRecording recognition stop"),this.recognition.stop(),this.schedulePendingLineBreaks()}catch(e){console.error("[SPEECH] Failed to stop recording:",e)}}getSelectedLanguage(){return this.preferencesService.getVoiceLanguage()}updateRecognitionLanguage(){if(this.recognition){let e=this.getSelectedLanguage();this.recognition.lang=e,console.log("[SPEECH] Language changed to:",e)}}improveTranscriptPunctuation(e){let t=e;return/[.!?]$/.test(t.trim())||(t=t.trim()+"."),t=t.charAt(0).toUpperCase()+t.slice(1),t=t.replace(/\s+/g," "),t=t+" ",t}appendToTextarea(e){let t=this.message;if(this.message=t?`${t}${e}`:e,this.messageInput?.nativeElement){this.messageInput.nativeElement.focus();let n=this.message.length;this.messageInput.nativeElement.setSelectionRange(n,n)}setTimeout(()=>this.adjustTextareaHeight(),0)}schedulePendingLineBreaks(){this.clearPendingLineBreaks(),this.pendingLineBreaksTimeout=window.setTimeout(()=>{this.sessionHadTranscript&&(console.log("[SPEECH] Adding line breaks after transcript session"),this.appendToTextarea(`
|
|
2
|
-
|
|
3
|
-
`),this.sessionHadTranscript=!1),this.pendingLineBreaksTimeout=null},500)}clearPendingLineBreaks(){this.pendingLineBreaksTimeout&&(clearTimeout(this.pendingLineBreaksTimeout),this.pendingLineBreaksTimeout=null)}adjustTextareaHeight(){let e=this.messageInput?.nativeElement;if(!e)return;let t=e.parentElement?.offsetHeight??e.offsetHeight+32;this.heightChanged.emit(t)}getSendButtonShortcut(){return this.useEnterToSend?"Enter":navigator.platform.toLowerCase().includes("mac")?"\u2318+Enter":"Ctrl+Enter"}getSendButtonTooltip(){return this.useEnterToSend?"Send message (Enter) - Shift+Enter for new line":`Send message (${navigator.platform.toLowerCase().includes("mac")?"Cmd+Enter":"Ctrl+Enter"}) - Enter for new line`}getPlaceholder(){return this.isSessionInitializing?"Initializing session...":this.isThinking?this.isStopping?"Stopping...":this.isStarting?"Processing request...":this.currentThinkingPhrase:this.isVoiceMessageMode&&this.isTranscribing?"Uploading...":this.isVoiceMessageMode&&this.isRecording?"Listening...":this.showWelcome?"How can I help you today?":"Type '@' for agents, '/' for commands, or just your message..."}startThinkingAnimation(){this.thinkingPhraseIndex=0,this.currentThinkingPhrase=this.thinkingPhrases[0]??"Thinking...",this.thinkingInterval=window.setInterval(()=>{this.thinkingPhraseIndex<this.thinkingPhrases.length-1&&(this.thinkingPhraseIndex++,this.currentThinkingPhrase=this.thinkingPhrases[this.thinkingPhraseIndex]??"Thinking...")},2e3)}stopThinkingAnimation(){this.thinkingInterval&&(clearInterval(this.thinkingInterval),this.thinkingInterval=null),this.thinkingPhraseIndex=0,this.currentThinkingPhrase="Thinking..."}subscribeToInviteEvents(){this.subscriptions.push(this.codayService.currentInviteEvent$.subscribe(e=>{e?this.handleInviteEvent(e.invite,e.defaultValue):this.currentInvite=""}))}handleInviteEvent(e,t){this.currentInvite=e,t&&(this.message=t,setTimeout(()=>this.adjustTextareaHeight(),0)),setTimeout(()=>{this.messageInput?.nativeElement&&this.messageInput.nativeElement.focus()},50)}subscribeToMessageRestore(){this.subscriptions.push(this.codayService.messageToRestore$.subscribe(e=>{e.trim()&&(console.log("[CHAT-TEXTAREA] Restoring message content:",e.substring(0,50)+"..."),this.restoreMessageContent(e))}))}restoreMessageContent(e){this.message=e,this.messageInput?.nativeElement&&(this.messageInput.nativeElement.focus(),setTimeout(()=>{let t=this.messageInput.nativeElement,n=this.message.length;t.setSelectionRange(n,n)},0)),setTimeout(()=>this.adjustTextareaHeight(),10)}focusTextarea(){let e=this.messageInput?.nativeElement;console.log("[CHAT-TEXTAREA] focusTextarea called",{hasElement:!!e,isDisabled:this.isDisabled,isThinking:this.isThinking,elementDisabled:e?.disabled,isSessionInitializing:this.isSessionInitializing}),e&&!e.disabled?(e.focus(),console.log("[CHAT-TEXTAREA] Textarea focused successfully")):console.log("[CHAT-TEXTAREA] Focus blocked - element disabled or not available")}checkForAutocomplete(){let e=this.message;if(e.startsWith("@")){let t=e.substring(1);if(t.includes(" ")){this.hideAutocomplete();return}this.showAgentAutocomplete(t);return}if(e.startsWith("/")){let t=e.substring(1);if(t.includes(" ")){this.hideAutocomplete();return}this.showPromptAutocomplete(t);return}this.hideAutocomplete()}showAgentAutocomplete(e){this.autocompleteTrigger="@";try{let t=this.projectStateService.getSelectedProjectIdOrThrow();this.agentApiService.getAgentsAutocomplete(t,e).subscribe({next:n=>{this.autocompleteItems=n,this.autocompleteVisible=n.length>0,this.selectedAutocompleteIndex=0},error:n=>{console.error("[AUTOCOMPLETE] Error loading agents:",n),this.hideAutocomplete()}})}catch(t){console.warn("[AUTOCOMPLETE] No project selected, cannot load agents"),this.hideAutocomplete()}}showPromptAutocomplete(e){this.autocompleteTrigger="/";try{let t=this.projectStateService.getSelectedProjectIdOrThrow();this.promptApiService.getPromptsAutocomplete(t,e).subscribe({next:n=>{this.autocompleteItems=n,this.autocompleteVisible=n.length>0,this.selectedAutocompleteIndex=0},error:n=>{console.error("[AUTOCOMPLETE] Error loading prompts:",n),this.hideAutocomplete()}})}catch(t){console.warn("[AUTOCOMPLETE] No project selected, cannot load prompts"),this.hideAutocomplete()}}hideAutocomplete(){this.autocompleteVisible=!1,this.autocompleteItems=[],this.selectedAutocompleteIndex=0}selectAutocompleteItem(){let e=this.autocompleteItems[this.selectedAutocompleteIndex];if(!e)return;let t=null;if(this.autocompleteTrigger==="/"){let n=e,o=n.parameterFormat;if(console.log(n),o===void 0)this.message=`/${e.name}`;else if(o==="")this.message=`/${e.name} `;else{this.message=`/${e.name} ${o}`;let r=this.message.indexOf('=""');r!==-1&&(t=r+2)}}else this.message=`@${e.name} `;this.hideAutocomplete(),setTimeout(()=>{if(this.messageInput?.nativeElement)if(this.messageInput.nativeElement.focus(),t!==null)this.messageInput.nativeElement.setSelectionRange(t,t);else{let n=this.message.length;this.messageInput.nativeElement.setSelectionRange(n,n)}},0)}selectAutocompleteItemByClick(e){this.selectedAutocompleteIndex=e,this.selectAutocompleteItem()}getAutocompleteQuery(){return this.message.substring(1).split(" ")[0]??""}getParameterFormat(e){return e.parameterFormat}hasParameterFormat(e){return this.autocompleteTrigger==="/"&&e.parameterFormat!==void 0}scrollSelectedItemIntoView(){setTimeout(()=>{let e=document.querySelector(".autocomplete-popup");if(!e)return;let t=e.querySelector(".autocomplete-item.selected");t&&t.scrollIntoView({behavior:"smooth",block:"nearest",inline:"nearest"})},0)}static \u0275fac=function(t){return new(t||i)};static \u0275cmp=R({type:i,selectors:[["app-chat-textarea"]],viewQuery:function(t,n){if(t&1&&ut(za,7)($a,5),t&2){let o;He(o=Ne())&&(n.messageInput=o.first),He(o=Ne())&&(n.fileInput=o.first)}},hostBindings:function(t,n){t&1&&w("paste",function(r){return n.onPaste(r)})("click",function(r){return n.onDocumentClick(r)},yo)},inputs:{isDisabled:"isDisabled",showWelcome:"showWelcome",isThinking:"isThinking",isStarting:"isStarting",isSessionInitializing:"isSessionInitializing"},outputs:{filesPasted:"filesPasted",messageSubmitted:"messageSubmitted",voiceMessageReady:"voiceMessageReady",voiceRecordingToggled:"voiceRecordingToggled",heightChanged:"heightChanged",stopRequested:"stopRequested",textareaFocused:"textareaFocused"},features:[ke],decls:8,vars:15,consts:[["messageInput",""],["fileInput",""],[1,"chat-input-container"],[1,"recording-indicator"],[1,"autocomplete-popup"],[1,"input-row","grouped-input"],[1,"message-input",3,"ngModelChange","keydown","input","focus","blur","ngModel","placeholder","disabled"],[1,"actions"],[1,"recording-dot"],[1,"transcribing-dot"],["role","option","tabindex","0",1,"autocomplete-item",3,"selected"],["role","option","tabindex","0",1,"autocomplete-item",3,"click","keydown.enter","keydown.space","mouseenter"],[1,"item-name"],[3,"innerHTML"],[1,"parameter-format"],[1,"item-description",3,"innerHTML"],["icon","stop","variant","danger","title","Stop generation",1,"action-btn"],["icon","send","variant","primary",1,"send-btn",3,"title","disabled","hidden","active"],["icon","stop","variant","danger","title","Stop generation",1,"action-btn",3,"action"],["icon","send","variant","primary",1,"send-btn",3,"action","title","disabled"],["icon","mic",1,"voice-btn",3,"action","variant","disabled","title"],["icon","attach_file","variant","default","title","Upload files (images or documents)",1,"upload-btn",3,"action","disabled"],["type","file","multiple","","accept","image/*,application/pdf,.pdf,.doc,.docx,.txt,.md,.json,.yaml,.yml,.csv,.xml,.html",2,"display","none",3,"change"]],template:function(t,n){if(t&1){let o=O();c(0,"div",2),x(1,Ua,3,0,"div",3),x(2,Ba,3,0,"div",3),x(3,qa,3,0,"div",4),c(4,"div",5)(5,"textarea",6,0),rn("ngModelChange",function(a){return T(o),on(n.message,a)||(n.message=a),S(a)}),w("keydown",function(a){return n.onKeyDown(a)})("input",function(){return n.onInput()})("focus",function(){return T(o),n.isFocused=!0,S(n.textareaFocused.emit())})("blur",function(){return n.isFocused=!1}),d(),x(7,Za,4,3,"div",7),d()()}t&2&&(p(),_(!n.isVoiceMessageMode&&n.isRecording?1:-1),p(),_(!n.isVoiceMessageMode&&n.isTranscribing?2:-1),p(),_(n.autocompleteVisible?3:-1),p(),he("focused",n.isFocused)("welcome-mode",n.showWelcome)("is-thinking",n.isThinking)("is-listening",n.isVoiceMessageMode&&(n.isRecording||n.isTranscribing)),p(),nn("ngModel",n.message),M("placeholder",n.getPlaceholder())("disabled",n.isDisabled||n.isVoiceMessageMode&&(n.isRecording||n.isTranscribing)),p(2),_(n.isSessionInitializing?-1:7))},dependencies:[fn,un,hn,gn,lr,Cn],styles:['@keyframes _ngcontent-%COMP%_gradientBorderShift{0%{background-position:0 0}50%{background-position:100% 0}to{background-position:0 0}}.chat-input-container[_ngcontent-%COMP%]{flex-shrink:0;width:100%;position:relative}.thinking-progress[_ngcontent-%COMP%]{position:absolute;top:0;left:0;right:0;height:3px;z-index:1}.thinking-progress[_ngcontent-%COMP%] .mdc-linear-progress__bar-inner{border-top-width:3px}.input-row.grouped-input[_ngcontent-%COMP%]{display:flex;align-items:stretch;background:var(--glass-bg);border-radius:16px;padding:0 .15rem 0 1.25rem;position:relative;transition:border-color .2s,box-shadow .2s,background .3s}.input-row[_ngcontent-%COMP%]{position:relative;background:var(--glass-bg, #1e1e1e)!important;background-clip:padding-box}.input-row[_ngcontent-%COMP%]:before{content:"";position:absolute;inset:-2px;border-radius:inherit;background-size:200% 100%;background:linear-gradient(90deg,var(--color-primary, #3b82f6) 0%,var(--color-accent, #8b5cf6) 50%,var(--color-primary, #3b82f6) 100%);-webkit-mask:linear-gradient(#fff 0 0) content-box,linear-gradient(#fff 0 0);mask:linear-gradient(#fff 0 0) content-box,linear-gradient(#fff 0 0);-webkit-mask-composite:xor;mask-composite:exclude;padding:1px;pointer-events:none;z-index:-1;animation:_ngcontent-%COMP%_gradientBorderShift 3s ease-in-out infinite}.input-row.is-listening[_ngcontent-%COMP%]:before{inset:0;-webkit-mask:none;mask:none;padding:0;opacity:.15;z-index:0;background:linear-gradient(90deg,var(--color-error, #ef4444) 0%,var(--color-accent, #8b5cf6) 50%,var(--color-error, #ef4444) 100%);background-size:200% 100%;animation:_ngcontent-%COMP%_gradientBorderShift 2s ease-in-out infinite}.input-row.is-listening[_ngcontent-%COMP%] .message-input[_ngcontent-%COMP%], .input-row.is-listening[_ngcontent-%COMP%] .action-btn[_ngcontent-%COMP%]{position:relative;z-index:1}.input-row.is-thinking[_ngcontent-%COMP%]:before{inset:0;-webkit-mask:none;mask:none;padding:0;opacity:.15;z-index:0;background:linear-gradient(90deg,var(--color-primary, #3b82f6) 0%,var(--color-accent, #8b5cf6) 50%,var(--color-primary, #3b82f6) 100%);background-size:200% 100%;animation:_ngcontent-%COMP%_gradientBorderShift 3s ease-in-out infinite}.input-row.is-thinking[_ngcontent-%COMP%] .message-input[_ngcontent-%COMP%], .input-row.is-thinking[_ngcontent-%COMP%] .action-btn[_ngcontent-%COMP%]{position:relative;z-index:1}.input-row.grouped-input.focused[_ngcontent-%COMP%]:not(.is-thinking):before{background:var(--color-primary);animation:none}.input-row.grouped-input.focused[_ngcontent-%COMP%]:not(.is-thinking){box-shadow:0 0 0 4px #007aff1a}.message-input[_ngcontent-%COMP%]{flex:1;border:none;outline:none;background:transparent!important;box-shadow:none;font-size:1rem;padding:1rem 0;color:var(--color-text);resize:none;field-sizing:content;min-height:36px;max-height:70vh;overflow-y:auto;font-family:-apple-system,BlinkMacSystemFont,SF Pro Display,system-ui,sans-serif;line-height:1.5}.message-input[_ngcontent-%COMP%]::-webkit-scrollbar{width:8px}.message-input[_ngcontent-%COMP%]::-webkit-scrollbar-track{background:transparent}.message-input[_ngcontent-%COMP%]::-webkit-scrollbar-thumb{background:var(--color-border);border-radius:4px}.message-input[_ngcontent-%COMP%]::-webkit-scrollbar-thumb:hover{background:var(--color-text-secondary)}.message-input[_ngcontent-%COMP%]:focus{outline:none;border:none;box-shadow:none}.message-input[_ngcontent-%COMP%]:disabled{background-color:var(--color-bg-secondary);color:var(--color-text-secondary);cursor:not-allowed;opacity:.6}.message-input[_ngcontent-%COMP%]::placeholder{color:var(--color-text-secondary);transition:opacity .3s ease-in-out}.message-input[_ngcontent-%COMP%]:disabled::placeholder{animation:_ngcontent-%COMP%_thinkingPulsate 2s ease-in-out infinite}@keyframes _ngcontent-%COMP%_thinkingPulsate{0%,to{opacity:.6}50%{opacity:1}}.voice-btn[_ngcontent-%COMP%], .send-btn[_ngcontent-%COMP%], .action-btn[_ngcontent-%COMP%], .upload-btn[_ngcontent-%COMP%]{margin:0}.actions[_ngcontent-%COMP%]{display:flex;flex-direction:column;flex-wrap:wrap;justify-content:center}.send-btn[_ngcontent-%COMP%]{transition:opacity .4s,margin-left .4s}.send-btn.active[_ngcontent-%COMP%] button[_ngcontent-%COMP%]{opacity:1}.send-btn[_ngcontent-%COMP%]:not(.active) button[_ngcontent-%COMP%]{opacity:0;margin-left:calc(-.5rem - 36px)}.send-btn[_ngcontent-%COMP%] button[_ngcontent-%COMP%]:hover:not(:disabled){color:#fff;background:linear-gradient(90deg,var(--color-primary, #3b82f6) 0%,var(--color-primary, #3b82f6) 20%,var(--color-accent, #8b5cf6) 50%,var(--color-primary, #3b82f6) 80%,var(--color-primary, #3b82f6) 100%);background-size:300% auto;animation:sendButtonGradientShift 6s ease-in-out infinite;box-shadow:0 4px 14px #007aff30;transform:scale(1.2)}.send-btn[_ngcontent-%COMP%] button[_ngcontent-%COMP%]:active:not(:disabled){transform:scale(1.3);box-shadow:0 4px 24px #007aff30}.recording-indicator[_ngcontent-%COMP%]{display:flex;align-items:center;gap:.5rem;margin-top:.2rem;margin-bottom:.2rem;color:var(--color-error, #ff5555);font-size:.9rem;position:absolute;top:-1.5rem}@keyframes _ngcontent-%COMP%_pulse{0%,to{opacity:1}50%{opacity:.5}}.autocomplete-popup[_ngcontent-%COMP%]{position:absolute;bottom:100%;left:0;right:0;margin-bottom:.5rem;background:var(--glass-bg);-webkit-backdrop-filter:var(--glass-backdrop-blur);backdrop-filter:var(--glass-backdrop-blur);border-radius:12px;box-shadow:0 8px 32px #00000026;border:1px solid var(--color-border);max-height:400px;max-width:500px;overflow-y:auto;z-index:100}.autocomplete-popup[_ngcontent-%COMP%]::-webkit-scrollbar{width:8px}.autocomplete-popup[_ngcontent-%COMP%]::-webkit-scrollbar-track{background:transparent}.autocomplete-popup[_ngcontent-%COMP%]::-webkit-scrollbar-thumb{background:var(--color-border);border-radius:4px}.autocomplete-popup[_ngcontent-%COMP%]::-webkit-scrollbar-thumb:hover{background:var(--color-text-secondary)}.autocomplete-popup[_ngcontent-%COMP%] .autocomplete-item[_ngcontent-%COMP%]{padding:.75rem 1rem;cursor:pointer;transition:background .2s;border-left:3px solid transparent}.autocomplete-popup[_ngcontent-%COMP%] .autocomplete-item[_ngcontent-%COMP%]:hover, .autocomplete-popup[_ngcontent-%COMP%] .autocomplete-item.selected[_ngcontent-%COMP%]{background:var(--color-bg-hover)}.autocomplete-popup[_ngcontent-%COMP%] .autocomplete-item.selected[_ngcontent-%COMP%]{border-left-color:var(--color-primary)}.autocomplete-popup[_ngcontent-%COMP%] .autocomplete-item[_ngcontent-%COMP%] .item-name[_ngcontent-%COMP%]{font-weight:600;color:var(--color-text);margin-bottom:.25rem;font-family:SF Mono,Monaco,Menlo,Cascadia Code,Consolas,monospace;font-size:.95rem}.autocomplete-popup[_ngcontent-%COMP%] .autocomplete-item[_ngcontent-%COMP%] .item-name[_ngcontent-%COMP%] strong{font-weight:700;color:var(--color-primary);background:var(--color-primary-light, rgba(99, 102, 241, .1));padding:0 2px;border-radius:2px}.autocomplete-popup[_ngcontent-%COMP%] .autocomplete-item[_ngcontent-%COMP%] .item-name[_ngcontent-%COMP%] .parameter-format[_ngcontent-%COMP%]{color:var(--color-text-secondary);font-weight:400;opacity:.7}.autocomplete-popup[_ngcontent-%COMP%] .autocomplete-item[_ngcontent-%COMP%] .item-description[_ngcontent-%COMP%]{font-size:.85rem;color:var(--color-text-secondary);line-height:1.3}.autocomplete-popup[_ngcontent-%COMP%] .autocomplete-item[_ngcontent-%COMP%] .item-description[_ngcontent-%COMP%] strong{font-weight:700;color:var(--color-primary);background:var(--color-primary-light, rgba(99, 102, 241, .1))}@media print{.thinking-progress[_ngcontent-%COMP%], .action-btn[_ngcontent-%COMP%], .voice-btn[_ngcontent-%COMP%], .send-btn[_ngcontent-%COMP%], .upload-btn[_ngcontent-%COMP%], .recording-indicator[_ngcontent-%COMP%], .autocomplete-popup[_ngcontent-%COMP%]{display:none!important}}']})};var ft=class i{unreadCountSubject=new Jt(0);unreadCount$=this.unreadCountSubject.asObservable();constructor(){console.log("[UNREAD] Service initialized")}addUnread(){let t=this.unreadCountSubject.value+1;this.unreadCountSubject.next(t),console.log("[UNREAD] Added unread message, total:",t)}markAllAsRead(){this.unreadCountSubject.value>0&&(this.unreadCountSubject.next(0),console.log("[UNREAD] Marked all messages as read"))}getCurrentCount(){return this.unreadCountSubject.value}reset(){this.unreadCountSubject.next(0),console.log("[UNREAD] Counter reset")}static \u0275fac=function(t){return new(t||i)};static \u0275prov=Y({token:i,factory:i.\u0275fac,providedIn:"root"})};var wn=class i{ATTENTION_EMOJI="\u{1F534}";isSystemActive=!1;systemActiveTimer=null;SYSTEM_ACTIVE_TIMEOUT=4e3;unreadService=g(ft);project=g(Oe);constructor(){this.initializeTitleUpdates()}initializeTitleUpdates(){fo([this.project.selectedProject$,this.unreadService.unreadCount$]).subscribe(([e,t])=>{this.updateTitle(e?.name??"...",t)})}updateTitle(e,t){let n;this.isSystemActive?n=`\u23F3${t>0?` (${t}) `:" "}${e}`:t>0?n=`${this.ATTENTION_EMOJI} (${t}) ${e}`:n=e,document.title=n,console.log("[TAB-TITLE] Updated to:",n)}setSystemActive(){console.log("[TAB-TITLE] System active - showing hourglass"),this.isSystemActive=!0,this.systemActiveTimer&&clearTimeout(this.systemActiveTimer),this.systemActiveTimer=setTimeout(()=>{console.log("[TAB-TITLE] System active timeout - hiding hourglass"),this.isSystemActive=!1,this.forceUpdateTitle()},this.SYSTEM_ACTIVE_TIMEOUT),this.forceUpdateTitle()}setSystemInactive(){console.log("[TAB-TITLE] System inactive - hiding hourglass"),this.isSystemActive=!1,this.systemActiveTimer&&(clearTimeout(this.systemActiveTimer),this.systemActiveTimer=null),this.forceUpdateTitle()}forceUpdateTitle(){let e=this.project.getSelectedProjectId()??"...",t=this.unreadService.getCurrentCount();this.updateTitle(e,t)}static \u0275fac=function(t){return new(t||i)};static \u0275prov=Y({token:i,factory:i.\u0275fac,providedIn:"root"})};var Tn=class i{pendingFirstMessage=null;pendingVoiceMessage=null;setPendingFirstMessage(e){console.log("[FIRST-MESSAGE-STATE] Storing pending first message:",e.substring(0,50)+"..."),this.pendingFirstMessage=e}consumePendingFirstMessage(){let e=this.pendingFirstMessage;return e?(console.log("[FIRST-MESSAGE-STATE] Consuming pending first message:",e.substring(0,50)+"..."),this.pendingFirstMessage=null):console.log("[FIRST-MESSAGE-STATE] No pending first message to consume"),e}setPendingVoiceMessage(e){console.log("[FIRST-MESSAGE-STATE] Storing pending voice message"),this.pendingVoiceMessage=e}consumePendingVoiceMessage(){let e=this.pendingVoiceMessage;return e&&(console.log("[FIRST-MESSAGE-STATE] Consuming pending voice message"),this.pendingVoiceMessage=null),e}hasPendingFirstMessage(){return this.pendingFirstMessage!==null||this.pendingVoiceMessage!==null}clear(){this.pendingFirstMessage&&(console.log("[FIRST-MESSAGE-STATE] Clearing pending first message"),this.pendingFirstMessage=null),this.pendingVoiceMessage=null}static \u0275fac=function(t){return new(t||i)};static \u0275prov=Y({token:i,factory:i.\u0275fac,providedIn:"root"})};var Ka=(i,e)=>e.label;function Ja(i,e){if(i&1){let t=O();c(0,"button",2),w("click",function(o){let r=T(t).$implicit,a=m();return S(a.executeAction(r,o))}),c(1,"mat-icon"),f(2),d()()}if(i&2){let t=e.$implicit;Be("title",t.tooltip||t.label),p(),Be("aria-label",t.label),p(),F(t.icon)}}var Sn=class i{actions=[];executeAction(e,t){t.stopPropagation(),e.action()}static \u0275fac=function(t){return new(t||i)};static \u0275cmp=R({type:i,selectors:[["app-message-context-menu"]],inputs:{actions:"actions"},decls:3,vars:0,consts:[[1,"context-menu-wrapper"],["mat-icon-button",""],["mat-icon-button","",3,"click"]],template:function(t,n){t&1&&(c(0,"div",0),de(1,Ja,3,3,"button",1,Ka),d()),t&2&&(p(),pe(n.actions))},dependencies:[fe,je,J],styles:[".context-menu-wrapper[_ngcontent-%COMP%]{position:relative;display:flex;align-items:center}.context-menu-wrapper[_ngcontent-%COMP%] button[_ngcontent-%COMP%]{transform:scale(.75)}"]})};function vi(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var nt=vi();function br(i){nt=i}var Ft={exec:()=>null};function A(i,e=""){let t=typeof i=="string"?i:i.source,n={replace:(o,r)=>{let a=typeof r=="string"?r:r.source;return a=a.replace(oe.caret,"$1"),t=t.replace(o,a),n},getRegex:()=>new RegExp(t,e)};return n}var oe={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceTabs:/^\t+/,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] /,listReplaceTask:/^\[[ xX]\] +/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,unescapeTest:/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:i=>new RegExp(`^( {0,3}${i})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:i=>new RegExp(`^ {0,${Math.min(3,i-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),hrRegex:i=>new RegExp(`^ {0,${Math.min(3,i-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),fencesBeginRegex:i=>new RegExp(`^ {0,${Math.min(3,i-1)}}(?:\`\`\`|~~~)`),headingBeginRegex:i=>new RegExp(`^ {0,${Math.min(3,i-1)}}#`),htmlBeginRegex:i=>new RegExp(`^ {0,${Math.min(3,i-1)}}<(?:[a-z].*>|!--)`,"i")},es=/^(?:[ \t]*(?:\n|$))+/,ts=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,ns=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,Lt=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,is=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,Ci=/(?:[*+-]|\d{1,9}[.)])/,xr=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,_r=A(xr).replace(/bull/g,Ci).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),os=A(xr).replace(/bull/g,Ci).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),yi=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,rs=/^[^\n]+/,wi=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,as=A(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",wi).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),ss=A(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,Ci).getRegex(),On="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",Ti=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,ls=A("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",Ti).replace("tag",On).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),vr=A(yi).replace("hr",Lt).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",On).getRegex(),cs=A(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",vr).getRegex(),Si={blockquote:cs,code:ts,def:as,fences:ns,heading:is,hr:Lt,html:ls,lheading:_r,list:ss,newline:es,paragraph:vr,table:Ft,text:rs},pr=A("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",Lt).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",On).getRegex(),ds=Te(j({},Si),{lheading:os,table:pr,paragraph:A(yi).replace("hr",Lt).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",pr).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",On).getRegex()}),ps=Te(j({},Si),{html:A(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",Ti).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:Ft,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:A(yi).replace("hr",Lt).replace("heading",` *#{1,6} *[^
|
|
4
|
-
]`).replace("lheading",_r).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()}),ms=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,us=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,Cr=/^( {2,}|\\)\n(?!\s*$)/,hs=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,Pn=/[\p{P}\p{S}]/u,ki=/[\s\p{P}\p{S}]/u,yr=/[^\s\p{P}\p{S}]/u,gs=A(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,ki).getRegex(),wr=/(?!~)[\p{P}\p{S}]/u,fs=/(?!~)[\s\p{P}\p{S}]/u,bs=/(?:[^\s\p{P}\p{S}]|~)/u,xs=/\[(?:[^\[\]`]|`[^`]*?`)*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)|`[^`]*?`|<(?! )[^<>]*?>/g,Tr=/^(?:\*+(?:((?!\*)punct)|[^\s*]))|^_+(?:((?!_)punct)|([^\s_]))/,_s=A(Tr,"u").replace(/punct/g,Pn).getRegex(),vs=A(Tr,"u").replace(/punct/g,wr).getRegex(),Sr="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",Cs=A(Sr,"gu").replace(/notPunctSpace/g,yr).replace(/punctSpace/g,ki).replace(/punct/g,Pn).getRegex(),ys=A(Sr,"gu").replace(/notPunctSpace/g,bs).replace(/punctSpace/g,fs).replace(/punct/g,wr).getRegex(),ws=A("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,yr).replace(/punctSpace/g,ki).replace(/punct/g,Pn).getRegex(),Ts=A(/\\(punct)/,"gu").replace(/punct/g,Pn).getRegex(),Ss=A(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),ks=A(Ti).replace("(?:-->|$)","-->").getRegex(),Ms=A("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",ks).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),Mn=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+[^`]*?`+(?!`)|[^\[\]\\`])*?/,Es=A(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]*(?:\n[ \t]*)?)(title))?\s*\)/).replace("label",Mn).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),kr=A(/^!?\[(label)\]\[(ref)\]/).replace("label",Mn).replace("ref",wi).getRegex(),Mr=A(/^!?\[(ref)\](?:\[\])?/).replace("ref",wi).getRegex(),Os=A("reflink|nolink(?!\\()","g").replace("reflink",kr).replace("nolink",Mr).getRegex(),mr=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,Mi={_backpedal:Ft,anyPunctuation:Ts,autolink:Ss,blockSkip:xs,br:Cr,code:us,del:Ft,emStrongLDelim:_s,emStrongRDelimAst:Cs,emStrongRDelimUnd:ws,escape:ms,link:Es,nolink:Mr,punctuation:gs,reflink:kr,reflinkSearch:Os,tag:Ms,text:hs,url:Ft},Ps=Te(j({},Mi),{link:A(/^!?\[(label)\]\((.*?)\)/).replace("label",Mn).getRegex(),reflink:A(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",Mn).getRegex()}),bi=Te(j({},Mi),{emStrongRDelimAst:ys,emStrongLDelim:vs,url:A(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",mr).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:A(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",mr).getRegex()}),Is=Te(j({},bi),{br:A(Cr).replace("{2,}","*").getRegex(),text:A(bi.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()}),kn={normal:Si,gfm:ds,pedantic:ps},At={normal:Mi,gfm:bi,breaks:Is,pedantic:Ps},As={"&":"&","<":"<",">":">",'"':""","'":"'"},ur=i=>As[i];function Ie(i,e){if(e){if(oe.escapeTest.test(i))return i.replace(oe.escapeReplace,ur)}else if(oe.escapeTestNoEncode.test(i))return i.replace(oe.escapeReplaceNoEncode,ur);return i}function hr(i){try{i=encodeURI(i).replace(oe.percentDecode,"%")}catch(e){return null}return i}function gr(i,e){let t=i.replace(oe.findPipe,(r,a,l)=>{let u=!1,b=a;for(;--b>=0&&l[b]==="\\";)u=!u;return u?"|":" |"}),n=t.split(oe.splitPipe),o=0;if(n[0].trim()||n.shift(),n.length>0&&!n.at(-1)?.trim()&&n.pop(),e)if(n.length>e)n.splice(e);else for(;n.length<e;)n.push("");for(;o<n.length;o++)n[o]=n[o].trim().replace(oe.slashPipe,"|");return n}function Dt(i,e,t){let n=i.length;if(n===0)return"";let o=0;for(;o<n;){let r=i.charAt(n-o-1);if(r===e&&!t)o++;else if(r!==e&&t)o++;else break}return i.slice(0,n-o)}function Ds(i,e){if(i.indexOf(e[1])===-1)return-1;let t=0;for(let n=0;n<i.length;n++)if(i[n]==="\\")n++;else if(i[n]===e[0])t++;else if(i[n]===e[1]&&(t--,t<0))return n;return t>0?-2:-1}function fr(i,e,t,n,o){let r=e.href,a=e.title||null,l=i[1].replace(o.other.outputLinkReplace,"$1");n.state.inLink=!0;let u={type:i[0].charAt(0)==="!"?"image":"link",raw:t,href:r,title:a,text:l,tokens:n.inlineTokens(l)};return n.state.inLink=!1,u}function Rs(i,e,t){let n=i.match(t.other.indentCodeCompensation);if(n===null)return e;let o=n[1];return e.split(`
|
|
5
|
-
`).map(r=>{let a=r.match(t.other.beginningSpace);if(a===null)return r;let[l]=a;return l.length>=o.length?r.slice(o.length):r}).join(`
|
|
6
|
-
`)}var En=class{options;rules;lexer;constructor(i){this.options=i||nt}space(i){let e=this.rules.block.newline.exec(i);if(e&&e[0].length>0)return{type:"space",raw:e[0]}}code(i){let e=this.rules.block.code.exec(i);if(e){let t=e[0].replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:e[0],codeBlockStyle:"indented",text:this.options.pedantic?t:Dt(t,`
|
|
7
|
-
`)}}}fences(i){let e=this.rules.block.fences.exec(i);if(e){let t=e[0],n=Rs(t,e[3]||"",this.rules);return{type:"code",raw:t,lang:e[2]?e[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):e[2],text:n}}}heading(i){let e=this.rules.block.heading.exec(i);if(e){let t=e[2].trim();if(this.rules.other.endingHash.test(t)){let n=Dt(t,"#");(this.options.pedantic||!n||this.rules.other.endingSpaceChar.test(n))&&(t=n.trim())}return{type:"heading",raw:e[0],depth:e[1].length,text:t,tokens:this.lexer.inline(t)}}}hr(i){let e=this.rules.block.hr.exec(i);if(e)return{type:"hr",raw:Dt(e[0],`
|
|
8
|
-
`)}}blockquote(i){let e=this.rules.block.blockquote.exec(i);if(e){let t=Dt(e[0],`
|
|
9
|
-
`).split(`
|
|
10
|
-
`),n="",o="",r=[];for(;t.length>0;){let a=!1,l=[],u;for(u=0;u<t.length;u++)if(this.rules.other.blockquoteStart.test(t[u]))l.push(t[u]),a=!0;else if(!a)l.push(t[u]);else break;t=t.slice(u);let b=l.join(`
|
|
11
|
-
`),y=b.replace(this.rules.other.blockquoteSetextReplace,`
|
|
12
|
-
$1`).replace(this.rules.other.blockquoteSetextReplace2,"");n=n?`${n}
|
|
13
|
-
${b}`:b,o=o?`${o}
|
|
14
|
-
${y}`:y;let k=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(y,r,!0),this.lexer.state.top=k,t.length===0)break;let P=r.at(-1);if(P?.type==="code")break;if(P?.type==="blockquote"){let W=P,z=W.raw+`
|
|
15
|
-
`+t.join(`
|
|
16
|
-
`),le=this.blockquote(z);r[r.length-1]=le,n=n.substring(0,n.length-W.raw.length)+le.raw,o=o.substring(0,o.length-W.text.length)+le.text;break}else if(P?.type==="list"){let W=P,z=W.raw+`
|
|
17
|
-
`+t.join(`
|
|
18
|
-
`),le=this.list(z);r[r.length-1]=le,n=n.substring(0,n.length-P.raw.length)+le.raw,o=o.substring(0,o.length-W.raw.length)+le.raw,t=z.substring(r.at(-1).raw.length).split(`
|
|
19
|
-
`);continue}}return{type:"blockquote",raw:n,tokens:r,text:o}}}list(i){let e=this.rules.block.list.exec(i);if(e){let t=e[1].trim(),n=t.length>1,o={type:"list",raw:"",ordered:n,start:n?+t.slice(0,-1):"",loose:!1,items:[]};t=n?`\\d{1,9}\\${t.slice(-1)}`:`\\${t}`,this.options.pedantic&&(t=n?t:"[*+-]");let r=this.rules.other.listItemRegex(t),a=!1;for(;i;){let u=!1,b="",y="";if(!(e=r.exec(i))||this.rules.block.hr.test(i))break;b=e[0],i=i.substring(b.length);let k=e[2].split(`
|
|
20
|
-
`,1)[0].replace(this.rules.other.listReplaceTabs,Mt=>" ".repeat(3*Mt.length)),P=i.split(`
|
|
21
|
-
`,1)[0],W=!k.trim(),z=0;if(this.options.pedantic?(z=2,y=k.trimStart()):W?z=e[1].length+1:(z=e[2].search(this.rules.other.nonSpaceChar),z=z>4?1:z,y=k.slice(z),z+=e[1].length),W&&this.rules.other.blankLine.test(P)&&(b+=P+`
|
|
22
|
-
`,i=i.substring(P.length+1),u=!0),!u){let Mt=this.rules.other.nextBulletRegex(z),jt=this.rules.other.hrRegex(z),Xe=this.rules.other.fencesBeginRegex(z),Q=this.rules.other.headingBeginRegex(z),Qe=this.rules.other.htmlBeginRegex(z);for(;i;){let Ze=i.split(`
|
|
23
|
-
`,1)[0],Ke;if(P=Ze,this.options.pedantic?(P=P.replace(this.rules.other.listReplaceNesting," "),Ke=P):Ke=P.replace(this.rules.other.tabCharGlobal," "),Xe.test(P)||Q.test(P)||Qe.test(P)||Mt.test(P)||jt.test(P))break;if(Ke.search(this.rules.other.nonSpaceChar)>=z||!P.trim())y+=`
|
|
24
|
-
`+Ke.slice(z);else{if(W||k.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||Xe.test(k)||Q.test(k)||jt.test(k))break;y+=`
|
|
25
|
-
`+P}!W&&!P.trim()&&(W=!0),b+=Ze+`
|
|
26
|
-
`,i=i.substring(Ze.length+1),k=Ke.slice(z)}}o.loose||(a?o.loose=!0:this.rules.other.doubleBlankLine.test(b)&&(a=!0));let le=null,Bt;this.options.gfm&&(le=this.rules.other.listIsTask.exec(y),le&&(Bt=le[0]!=="[ ] ",y=y.replace(this.rules.other.listReplaceTask,""))),o.items.push({type:"list_item",raw:b,task:!!le,checked:Bt,loose:!1,text:y,tokens:[]}),o.raw+=b}let l=o.items.at(-1);if(l)l.raw=l.raw.trimEnd(),l.text=l.text.trimEnd();else return;o.raw=o.raw.trimEnd();for(let u=0;u<o.items.length;u++)if(this.lexer.state.top=!1,o.items[u].tokens=this.lexer.blockTokens(o.items[u].text,[]),!o.loose){let b=o.items[u].tokens.filter(k=>k.type==="space"),y=b.length>0&&b.some(k=>this.rules.other.anyLine.test(k.raw));o.loose=y}if(o.loose)for(let u=0;u<o.items.length;u++)o.items[u].loose=!0;return o}}html(i){let e=this.rules.block.html.exec(i);if(e)return{type:"html",block:!0,raw:e[0],pre:e[1]==="pre"||e[1]==="script"||e[1]==="style",text:e[0]}}def(i){let e=this.rules.block.def.exec(i);if(e){let t=e[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),n=e[2]?e[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",o=e[3]?e[3].substring(1,e[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):e[3];return{type:"def",tag:t,raw:e[0],href:n,title:o}}}table(i){let e=this.rules.block.table.exec(i);if(!e||!this.rules.other.tableDelimiter.test(e[2]))return;let t=gr(e[1]),n=e[2].replace(this.rules.other.tableAlignChars,"").split("|"),o=e[3]?.trim()?e[3].replace(this.rules.other.tableRowBlankLine,"").split(`
|
|
27
|
-
`):[],r={type:"table",raw:e[0],header:[],align:[],rows:[]};if(t.length===n.length){for(let a of n)this.rules.other.tableAlignRight.test(a)?r.align.push("right"):this.rules.other.tableAlignCenter.test(a)?r.align.push("center"):this.rules.other.tableAlignLeft.test(a)?r.align.push("left"):r.align.push(null);for(let a=0;a<t.length;a++)r.header.push({text:t[a],tokens:this.lexer.inline(t[a]),header:!0,align:r.align[a]});for(let a of o)r.rows.push(gr(a,r.header.length).map((l,u)=>({text:l,tokens:this.lexer.inline(l),header:!1,align:r.align[u]})));return r}}lheading(i){let e=this.rules.block.lheading.exec(i);if(e)return{type:"heading",raw:e[0],depth:e[2].charAt(0)==="="?1:2,text:e[1],tokens:this.lexer.inline(e[1])}}paragraph(i){let e=this.rules.block.paragraph.exec(i);if(e){let t=e[1].charAt(e[1].length-1)===`
|
|
28
|
-
`?e[1].slice(0,-1):e[1];return{type:"paragraph",raw:e[0],text:t,tokens:this.lexer.inline(t)}}}text(i){let e=this.rules.block.text.exec(i);if(e)return{type:"text",raw:e[0],text:e[0],tokens:this.lexer.inline(e[0])}}escape(i){let e=this.rules.inline.escape.exec(i);if(e)return{type:"escape",raw:e[0],text:e[1]}}tag(i){let e=this.rules.inline.tag.exec(i);if(e)return!this.lexer.state.inLink&&this.rules.other.startATag.test(e[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(e[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(e[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(e[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:e[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:e[0]}}link(i){let e=this.rules.inline.link.exec(i);if(e){let t=e[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(t)){if(!this.rules.other.endAngleBracket.test(t))return;let r=Dt(t.slice(0,-1),"\\");if((t.length-r.length)%2===0)return}else{let r=Ds(e[2],"()");if(r===-2)return;if(r>-1){let a=(e[0].indexOf("!")===0?5:4)+e[1].length+r;e[2]=e[2].substring(0,r),e[0]=e[0].substring(0,a).trim(),e[3]=""}}let n=e[2],o="";if(this.options.pedantic){let r=this.rules.other.pedanticHrefTitle.exec(n);r&&(n=r[1],o=r[3])}else o=e[3]?e[3].slice(1,-1):"";return n=n.trim(),this.rules.other.startAngleBracket.test(n)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(t)?n=n.slice(1):n=n.slice(1,-1)),fr(e,{href:n&&n.replace(this.rules.inline.anyPunctuation,"$1"),title:o&&o.replace(this.rules.inline.anyPunctuation,"$1")},e[0],this.lexer,this.rules)}}reflink(i,e){let t;if((t=this.rules.inline.reflink.exec(i))||(t=this.rules.inline.nolink.exec(i))){let n=(t[2]||t[1]).replace(this.rules.other.multipleSpaceGlobal," "),o=e[n.toLowerCase()];if(!o){let r=t[0].charAt(0);return{type:"text",raw:r,text:r}}return fr(t,o,t[0],this.lexer,this.rules)}}emStrong(i,e,t=""){let n=this.rules.inline.emStrongLDelim.exec(i);if(!(!n||n[3]&&t.match(this.rules.other.unicodeAlphaNumeric))&&(!(n[1]||n[2])||!t||this.rules.inline.punctuation.exec(t))){let o=[...n[0]].length-1,r,a,l=o,u=0,b=n[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(b.lastIndex=0,e=e.slice(-1*i.length+o);(n=b.exec(e))!=null;){if(r=n[1]||n[2]||n[3]||n[4]||n[5]||n[6],!r)continue;if(a=[...r].length,n[3]||n[4]){l+=a;continue}else if((n[5]||n[6])&&o%3&&!((o+a)%3)){u+=a;continue}if(l-=a,l>0)continue;a=Math.min(a,a+l+u);let y=[...n[0]][0].length,k=i.slice(0,o+n.index+y+a);if(Math.min(o,a)%2){let W=k.slice(1,-1);return{type:"em",raw:k,text:W,tokens:this.lexer.inlineTokens(W)}}let P=k.slice(2,-2);return{type:"strong",raw:k,text:P,tokens:this.lexer.inlineTokens(P)}}}}codespan(i){let e=this.rules.inline.code.exec(i);if(e){let t=e[2].replace(this.rules.other.newLineCharGlobal," "),n=this.rules.other.nonSpaceChar.test(t),o=this.rules.other.startingSpaceChar.test(t)&&this.rules.other.endingSpaceChar.test(t);return n&&o&&(t=t.substring(1,t.length-1)),{type:"codespan",raw:e[0],text:t}}}br(i){let e=this.rules.inline.br.exec(i);if(e)return{type:"br",raw:e[0]}}del(i){let e=this.rules.inline.del.exec(i);if(e)return{type:"del",raw:e[0],text:e[2],tokens:this.lexer.inlineTokens(e[2])}}autolink(i){let e=this.rules.inline.autolink.exec(i);if(e){let t,n;return e[2]==="@"?(t=e[1],n="mailto:"+t):(t=e[1],n=t),{type:"link",raw:e[0],text:t,href:n,tokens:[{type:"text",raw:t,text:t}]}}}url(i){let e;if(e=this.rules.inline.url.exec(i)){let t,n;if(e[2]==="@")t=e[0],n="mailto:"+t;else{let o;do o=e[0],e[0]=this.rules.inline._backpedal.exec(e[0])?.[0]??"";while(o!==e[0]);t=e[0],e[1]==="www."?n="http://"+e[0]:n=e[0]}return{type:"link",raw:e[0],text:t,href:n,tokens:[{type:"text",raw:t,text:t}]}}}inlineText(i){let e=this.rules.inline.text.exec(i);if(e){let t=this.lexer.state.inRawBlock;return{type:"text",raw:e[0],text:e[0],escaped:t}}}},_e=class xi{tokens;options;state;tokenizer;inlineQueue;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||nt,this.options.tokenizer=this.options.tokenizer||new En,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let t={other:oe,block:kn.normal,inline:At.normal};this.options.pedantic?(t.block=kn.pedantic,t.inline=At.pedantic):this.options.gfm&&(t.block=kn.gfm,this.options.breaks?t.inline=At.breaks:t.inline=At.gfm),this.tokenizer.rules=t}static get rules(){return{block:kn,inline:At}}static lex(e,t){return new xi(t).lex(e)}static lexInline(e,t){return new xi(t).inlineTokens(e)}lex(e){e=e.replace(oe.carriageReturn,`
|
|
29
|
-
`),this.blockTokens(e,this.tokens);for(let t=0;t<this.inlineQueue.length;t++){let n=this.inlineQueue[t];this.inlineTokens(n.src,n.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(e,t=[],n=!1){for(this.options.pedantic&&(e=e.replace(oe.tabCharGlobal," ").replace(oe.spaceLine,""));e;){let o;if(this.options.extensions?.block?.some(a=>(o=a.call({lexer:this},e,t))?(e=e.substring(o.raw.length),t.push(o),!0):!1))continue;if(o=this.tokenizer.space(e)){e=e.substring(o.raw.length);let a=t.at(-1);o.raw.length===1&&a!==void 0?a.raw+=`
|
|
30
|
-
`:t.push(o);continue}if(o=this.tokenizer.code(e)){e=e.substring(o.raw.length);let a=t.at(-1);a?.type==="paragraph"||a?.type==="text"?(a.raw+=(a.raw.endsWith(`
|
|
31
|
-
`)?"":`
|
|
32
|
-
`)+o.raw,a.text+=`
|
|
33
|
-
`+o.text,this.inlineQueue.at(-1).src=a.text):t.push(o);continue}if(o=this.tokenizer.fences(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.heading(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.hr(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.blockquote(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.list(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.html(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.def(e)){e=e.substring(o.raw.length);let a=t.at(-1);a?.type==="paragraph"||a?.type==="text"?(a.raw+=(a.raw.endsWith(`
|
|
34
|
-
`)?"":`
|
|
35
|
-
`)+o.raw,a.text+=`
|
|
36
|
-
`+o.raw,this.inlineQueue.at(-1).src=a.text):this.tokens.links[o.tag]||(this.tokens.links[o.tag]={href:o.href,title:o.title},t.push(o));continue}if(o=this.tokenizer.table(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.lheading(e)){e=e.substring(o.raw.length),t.push(o);continue}let r=e;if(this.options.extensions?.startBlock){let a=1/0,l=e.slice(1),u;this.options.extensions.startBlock.forEach(b=>{u=b.call({lexer:this},l),typeof u=="number"&&u>=0&&(a=Math.min(a,u))}),a<1/0&&a>=0&&(r=e.substring(0,a+1))}if(this.state.top&&(o=this.tokenizer.paragraph(r))){let a=t.at(-1);n&&a?.type==="paragraph"?(a.raw+=(a.raw.endsWith(`
|
|
37
|
-
`)?"":`
|
|
38
|
-
`)+o.raw,a.text+=`
|
|
39
|
-
`+o.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=a.text):t.push(o),n=r.length!==e.length,e=e.substring(o.raw.length);continue}if(o=this.tokenizer.text(e)){e=e.substring(o.raw.length);let a=t.at(-1);a?.type==="text"?(a.raw+=(a.raw.endsWith(`
|
|
40
|
-
`)?"":`
|
|
41
|
-
`)+o.raw,a.text+=`
|
|
42
|
-
`+o.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=a.text):t.push(o);continue}if(e){let a="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(a);break}else throw new Error(a)}}return this.state.top=!0,t}inline(e,t=[]){return this.inlineQueue.push({src:e,tokens:t}),t}inlineTokens(e,t=[]){let n=e,o=null;if(this.tokens.links){let l=Object.keys(this.tokens.links);if(l.length>0)for(;(o=this.tokenizer.rules.inline.reflinkSearch.exec(n))!=null;)l.includes(o[0].slice(o[0].lastIndexOf("[")+1,-1))&&(n=n.slice(0,o.index)+"["+"a".repeat(o[0].length-2)+"]"+n.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(o=this.tokenizer.rules.inline.anyPunctuation.exec(n))!=null;)n=n.slice(0,o.index)+"++"+n.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);for(;(o=this.tokenizer.rules.inline.blockSkip.exec(n))!=null;)n=n.slice(0,o.index)+"["+"a".repeat(o[0].length-2)+"]"+n.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);n=this.options.hooks?.emStrongMask?.call({lexer:this},n)??n;let r=!1,a="";for(;e;){r||(a=""),r=!1;let l;if(this.options.extensions?.inline?.some(b=>(l=b.call({lexer:this},e,t))?(e=e.substring(l.raw.length),t.push(l),!0):!1))continue;if(l=this.tokenizer.escape(e)){e=e.substring(l.raw.length),t.push(l);continue}if(l=this.tokenizer.tag(e)){e=e.substring(l.raw.length),t.push(l);continue}if(l=this.tokenizer.link(e)){e=e.substring(l.raw.length),t.push(l);continue}if(l=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(l.raw.length);let b=t.at(-1);l.type==="text"&&b?.type==="text"?(b.raw+=l.raw,b.text+=l.text):t.push(l);continue}if(l=this.tokenizer.emStrong(e,n,a)){e=e.substring(l.raw.length),t.push(l);continue}if(l=this.tokenizer.codespan(e)){e=e.substring(l.raw.length),t.push(l);continue}if(l=this.tokenizer.br(e)){e=e.substring(l.raw.length),t.push(l);continue}if(l=this.tokenizer.del(e)){e=e.substring(l.raw.length),t.push(l);continue}if(l=this.tokenizer.autolink(e)){e=e.substring(l.raw.length),t.push(l);continue}if(!this.state.inLink&&(l=this.tokenizer.url(e))){e=e.substring(l.raw.length),t.push(l);continue}let u=e;if(this.options.extensions?.startInline){let b=1/0,y=e.slice(1),k;this.options.extensions.startInline.forEach(P=>{k=P.call({lexer:this},y),typeof k=="number"&&k>=0&&(b=Math.min(b,k))}),b<1/0&&b>=0&&(u=e.substring(0,b+1))}if(l=this.tokenizer.inlineText(u)){e=e.substring(l.raw.length),l.raw.slice(-1)!=="_"&&(a=l.raw.slice(-1)),r=!0;let b=t.at(-1);b?.type==="text"?(b.raw+=l.raw,b.text+=l.text):t.push(l);continue}if(e){let b="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(b);break}else throw new Error(b)}}return t}},bt=class{options;parser;constructor(i){this.options=i||nt}space(i){return""}code({text:i,lang:e,escaped:t}){let n=(e||"").match(oe.notSpaceStart)?.[0],o=i.replace(oe.endingNewline,"")+`
|
|
43
|
-
`;return n?'<pre><code class="language-'+Ie(n)+'">'+(t?o:Ie(o,!0))+`</code></pre>
|
|
44
|
-
`:"<pre><code>"+(t?o:Ie(o,!0))+`</code></pre>
|
|
45
|
-
`}blockquote({tokens:i}){return`<blockquote>
|
|
46
|
-
${this.parser.parse(i)}</blockquote>
|
|
47
|
-
`}html({text:i}){return i}def(i){return""}heading({tokens:i,depth:e}){return`<h${e}>${this.parser.parseInline(i)}</h${e}>
|
|
48
|
-
`}hr(i){return`<hr>
|
|
49
|
-
`}list(i){let e=i.ordered,t=i.start,n="";for(let a=0;a<i.items.length;a++){let l=i.items[a];n+=this.listitem(l)}let o=e?"ol":"ul",r=e&&t!==1?' start="'+t+'"':"";return"<"+o+r+`>
|
|
50
|
-
`+n+"</"+o+`>
|
|
51
|
-
`}listitem(i){let e="";if(i.task){let t=this.checkbox({checked:!!i.checked});i.loose?i.tokens[0]?.type==="paragraph"?(i.tokens[0].text=t+" "+i.tokens[0].text,i.tokens[0].tokens&&i.tokens[0].tokens.length>0&&i.tokens[0].tokens[0].type==="text"&&(i.tokens[0].tokens[0].text=t+" "+Ie(i.tokens[0].tokens[0].text),i.tokens[0].tokens[0].escaped=!0)):i.tokens.unshift({type:"text",raw:t+" ",text:t+" ",escaped:!0}):e+=t+" "}return e+=this.parser.parse(i.tokens,!!i.loose),`<li>${e}</li>
|
|
52
|
-
`}checkbox({checked:i}){return"<input "+(i?'checked="" ':"")+'disabled="" type="checkbox">'}paragraph({tokens:i}){return`<p>${this.parser.parseInline(i)}</p>
|
|
53
|
-
`}table(i){let e="",t="";for(let o=0;o<i.header.length;o++)t+=this.tablecell(i.header[o]);e+=this.tablerow({text:t});let n="";for(let o=0;o<i.rows.length;o++){let r=i.rows[o];t="";for(let a=0;a<r.length;a++)t+=this.tablecell(r[a]);n+=this.tablerow({text:t})}return n&&(n=`<tbody>${n}</tbody>`),`<table>
|
|
54
|
-
<thead>
|
|
55
|
-
`+e+`</thead>
|
|
56
|
-
`+n+`</table>
|
|
57
|
-
`}tablerow({text:i}){return`<tr>
|
|
58
|
-
${i}</tr>
|
|
59
|
-
`}tablecell(i){let e=this.parser.parseInline(i.tokens),t=i.header?"th":"td";return(i.align?`<${t} align="${i.align}">`:`<${t}>`)+e+`</${t}>
|
|
60
|
-
`}strong({tokens:i}){return`<strong>${this.parser.parseInline(i)}</strong>`}em({tokens:i}){return`<em>${this.parser.parseInline(i)}</em>`}codespan({text:i}){return`<code>${Ie(i,!0)}</code>`}br(i){return"<br>"}del({tokens:i}){return`<del>${this.parser.parseInline(i)}</del>`}link({href:i,title:e,tokens:t}){let n=this.parser.parseInline(t),o=hr(i);if(o===null)return n;i=o;let r='<a href="'+i+'"';return e&&(r+=' title="'+Ie(e)+'"'),r+=">"+n+"</a>",r}image({href:i,title:e,text:t,tokens:n}){n&&(t=this.parser.parseInline(n,this.parser.textRenderer));let o=hr(i);if(o===null)return Ie(t);i=o;let r=`<img src="${i}" alt="${t}"`;return e&&(r+=` title="${Ie(e)}"`),r+=">",r}text(i){return"tokens"in i&&i.tokens?this.parser.parseInline(i.tokens):"escaped"in i&&i.escaped?i.text:Ie(i.text)}},Ei=class{strong({text:i}){return i}em({text:i}){return i}codespan({text:i}){return i}del({text:i}){return i}html({text:i}){return i}text({text:i}){return i}link({text:i}){return""+i}image({text:i}){return""+i}br(){return""}},ve=class _i{options;renderer;textRenderer;constructor(e){this.options=e||nt,this.options.renderer=this.options.renderer||new bt,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new Ei}static parse(e,t){return new _i(t).parse(e)}static parseInline(e,t){return new _i(t).parseInline(e)}parse(e,t=!0){let n="";for(let o=0;o<e.length;o++){let r=e[o];if(this.options.extensions?.renderers?.[r.type]){let l=r,u=this.options.extensions.renderers[l.type].call({parser:this},l);if(u!==!1||!["space","hr","heading","code","table","blockquote","list","html","def","paragraph","text"].includes(l.type)){n+=u||"";continue}}let a=r;switch(a.type){case"space":{n+=this.renderer.space(a);continue}case"hr":{n+=this.renderer.hr(a);continue}case"heading":{n+=this.renderer.heading(a);continue}case"code":{n+=this.renderer.code(a);continue}case"table":{n+=this.renderer.table(a);continue}case"blockquote":{n+=this.renderer.blockquote(a);continue}case"list":{n+=this.renderer.list(a);continue}case"html":{n+=this.renderer.html(a);continue}case"def":{n+=this.renderer.def(a);continue}case"paragraph":{n+=this.renderer.paragraph(a);continue}case"text":{let l=a,u=this.renderer.text(l);for(;o+1<e.length&&e[o+1].type==="text";)l=e[++o],u+=`
|
|
61
|
-
`+this.renderer.text(l);t?n+=this.renderer.paragraph({type:"paragraph",raw:u,text:u,tokens:[{type:"text",raw:u,text:u,escaped:!0}]}):n+=u;continue}default:{let l='Token with "'+a.type+'" type was not found.';if(this.options.silent)return console.error(l),"";throw new Error(l)}}}return n}parseInline(e,t=this.renderer){let n="";for(let o=0;o<e.length;o++){let r=e[o];if(this.options.extensions?.renderers?.[r.type]){let l=this.options.extensions.renderers[r.type].call({parser:this},r);if(l!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(r.type)){n+=l||"";continue}}let a=r;switch(a.type){case"escape":{n+=t.text(a);break}case"html":{n+=t.html(a);break}case"link":{n+=t.link(a);break}case"image":{n+=t.image(a);break}case"strong":{n+=t.strong(a);break}case"em":{n+=t.em(a);break}case"codespan":{n+=t.codespan(a);break}case"br":{n+=t.br(a);break}case"del":{n+=t.del(a);break}case"text":{n+=t.text(a);break}default:{let l='Token with "'+a.type+'" type was not found.';if(this.options.silent)return console.error(l),"";throw new Error(l)}}}return n}},Rt=class{options;block;constructor(i){this.options=i||nt}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens","emStrongMask"]);static passThroughHooksRespectAsync=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(i){return i}postprocess(i){return i}processAllTokens(i){return i}emStrongMask(i){return i}provideLexer(){return this.block?_e.lex:_e.lexInline}provideParser(){return this.block?ve.parse:ve.parseInline}},Fs=class{defaults=vi();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=ve;Renderer=bt;TextRenderer=Ei;Lexer=_e;Tokenizer=En;Hooks=Rt;constructor(...i){this.use(...i)}walkTokens(i,e){let t=[];for(let n of i)switch(t=t.concat(e.call(this,n)),n.type){case"table":{let o=n;for(let r of o.header)t=t.concat(this.walkTokens(r.tokens,e));for(let r of o.rows)for(let a of r)t=t.concat(this.walkTokens(a.tokens,e));break}case"list":{let o=n;t=t.concat(this.walkTokens(o.items,e));break}default:{let o=n;this.defaults.extensions?.childTokens?.[o.type]?this.defaults.extensions.childTokens[o.type].forEach(r=>{let a=o[r].flat(1/0);t=t.concat(this.walkTokens(a,e))}):o.tokens&&(t=t.concat(this.walkTokens(o.tokens,e)))}}return t}use(...i){let e=this.defaults.extensions||{renderers:{},childTokens:{}};return i.forEach(t=>{let n=j({},t);if(n.async=this.defaults.async||n.async||!1,t.extensions&&(t.extensions.forEach(o=>{if(!o.name)throw new Error("extension name required");if("renderer"in o){let r=e.renderers[o.name];r?e.renderers[o.name]=function(...a){let l=o.renderer.apply(this,a);return l===!1&&(l=r.apply(this,a)),l}:e.renderers[o.name]=o.renderer}if("tokenizer"in o){if(!o.level||o.level!=="block"&&o.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let r=e[o.level];r?r.unshift(o.tokenizer):e[o.level]=[o.tokenizer],o.start&&(o.level==="block"?e.startBlock?e.startBlock.push(o.start):e.startBlock=[o.start]:o.level==="inline"&&(e.startInline?e.startInline.push(o.start):e.startInline=[o.start]))}"childTokens"in o&&o.childTokens&&(e.childTokens[o.name]=o.childTokens)}),n.extensions=e),t.renderer){let o=this.defaults.renderer||new bt(this.defaults);for(let r in t.renderer){if(!(r in o))throw new Error(`renderer '${r}' does not exist`);if(["options","parser"].includes(r))continue;let a=r,l=t.renderer[a],u=o[a];o[a]=(...b)=>{let y=l.apply(o,b);return y===!1&&(y=u.apply(o,b)),y||""}}n.renderer=o}if(t.tokenizer){let o=this.defaults.tokenizer||new En(this.defaults);for(let r in t.tokenizer){if(!(r in o))throw new Error(`tokenizer '${r}' does not exist`);if(["options","rules","lexer"].includes(r))continue;let a=r,l=t.tokenizer[a],u=o[a];o[a]=(...b)=>{let y=l.apply(o,b);return y===!1&&(y=u.apply(o,b)),y}}n.tokenizer=o}if(t.hooks){let o=this.defaults.hooks||new Rt;for(let r in t.hooks){if(!(r in o))throw new Error(`hook '${r}' does not exist`);if(["options","block"].includes(r))continue;let a=r,l=t.hooks[a],u=o[a];Rt.passThroughHooks.has(r)?o[a]=b=>{if(this.defaults.async&&Rt.passThroughHooksRespectAsync.has(r))return N(this,null,function*(){let k=yield l.call(o,b);return u.call(o,k)});let y=l.call(o,b);return u.call(o,y)}:o[a]=(...b)=>{if(this.defaults.async)return N(this,null,function*(){let k=yield l.apply(o,b);return k===!1&&(k=yield u.apply(o,b)),k});let y=l.apply(o,b);return y===!1&&(y=u.apply(o,b)),y}}n.hooks=o}if(t.walkTokens){let o=this.defaults.walkTokens,r=t.walkTokens;n.walkTokens=function(a){let l=[];return l.push(r.call(this,a)),o&&(l=l.concat(o.call(this,a))),l}}this.defaults=j(j({},this.defaults),n)}),this}setOptions(i){return this.defaults=j(j({},this.defaults),i),this}lexer(i,e){return _e.lex(i,e??this.defaults)}parser(i,e){return ve.parse(i,e??this.defaults)}parseMarkdown(i){return(e,t)=>{let n=j({},t),o=j(j({},this.defaults),n),r=this.onError(!!o.silent,!!o.async);if(this.defaults.async===!0&&n.async===!1)return r(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof e>"u"||e===null)return r(new Error("marked(): input parameter is undefined or null"));if(typeof e!="string")return r(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(e)+", string expected"));if(o.hooks&&(o.hooks.options=o,o.hooks.block=i),o.async)return N(this,null,function*(){let a=o.hooks?yield o.hooks.preprocess(e):e,l=yield(o.hooks?yield o.hooks.provideLexer():i?_e.lex:_e.lexInline)(a,o),u=o.hooks?yield o.hooks.processAllTokens(l):l;o.walkTokens&&(yield Promise.all(this.walkTokens(u,o.walkTokens)));let b=yield(o.hooks?yield o.hooks.provideParser():i?ve.parse:ve.parseInline)(u,o);return o.hooks?yield o.hooks.postprocess(b):b}).catch(r);try{o.hooks&&(e=o.hooks.preprocess(e));let a=(o.hooks?o.hooks.provideLexer():i?_e.lex:_e.lexInline)(e,o);o.hooks&&(a=o.hooks.processAllTokens(a)),o.walkTokens&&this.walkTokens(a,o.walkTokens);let l=(o.hooks?o.hooks.provideParser():i?ve.parse:ve.parseInline)(a,o);return o.hooks&&(l=o.hooks.postprocess(l)),l}catch(a){return r(a)}}}onError(i,e){return t=>{if(t.message+=`
|
|
62
|
-
Please report this to https://github.com/markedjs/marked.`,i){let n="<p>An error occurred:</p><pre>"+Ie(t.message+"",!0)+"</pre>";return e?Promise.resolve(n):n}if(e)return Promise.reject(t);throw t}}},tt=new Fs;function L(i,e){return tt.parse(i,e)}L.options=L.setOptions=function(i){return tt.setOptions(i),L.defaults=tt.defaults,br(L.defaults),L};L.getDefaults=vi;L.defaults=nt;L.use=function(...i){return tt.use(...i),L.defaults=tt.defaults,br(L.defaults),L};L.walkTokens=function(i,e){return tt.walkTokens(i,e)};L.parseInline=tt.parseInline;L.Parser=ve;L.parser=ve.parse;L.Renderer=bt;L.TextRenderer=Ei;L.Lexer=_e;L.lexer=_e.lex;L.Tokenizer=En;L.Hooks=Rt;L.parse=L;var op=L.options,rp=L.setOptions,ap=L.use,sp=L.walkTokens,lp=L.parseInline;var cp=ve.parse,dp=_e.lex;var{entries:Lr,setPrototypeOf:Er,isFrozen:Ls,getPrototypeOf:Hs,getOwnPropertyDescriptor:Ns}=Object,{freeze:ae,seal:be,create:Fi}=Object,{apply:Li,construct:Hi}=typeof Reflect<"u"&&Reflect;ae||(ae=function(e){return e});be||(be=function(e){return e});Li||(Li=function(e,t){for(var n=arguments.length,o=new Array(n>2?n-2:0),r=2;r<n;r++)o[r-2]=arguments[r];return e.apply(t,o)});Hi||(Hi=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),o=1;o<t;o++)n[o-1]=arguments[o];return new e(...n)});var In=se(Array.prototype.forEach),zs=se(Array.prototype.lastIndexOf),Or=se(Array.prototype.pop),Ht=se(Array.prototype.push),$s=se(Array.prototype.splice),Dn=se(String.prototype.toLowerCase),Oi=se(String.prototype.toString),Pi=se(String.prototype.match),Nt=se(String.prototype.replace),Vs=se(String.prototype.indexOf),Us=se(String.prototype.trim),Ce=se(Object.prototype.hasOwnProperty),re=se(RegExp.prototype.test),zt=Bs(TypeError);function se(i){return function(e){e instanceof RegExp&&(e.lastIndex=0);for(var t=arguments.length,n=new Array(t>1?t-1:0),o=1;o<t;o++)n[o-1]=arguments[o];return Li(i,e,n)}}function Bs(i){return function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return Hi(i,t)}}function E(i,e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Dn;Er&&Er(i,null);let n=e.length;for(;n--;){let o=e[n];if(typeof o=="string"){let r=t(o);r!==o&&(Ls(e)||(e[n]=r),o=r)}i[o]=!0}return i}function js(i){for(let e=0;e<i.length;e++)Ce(i,e)||(i[e]=null);return i}function Ae(i){let e=Fi(null);for(let[t,n]of Lr(i))Ce(i,t)&&(Array.isArray(n)?e[t]=js(n):n&&typeof n=="object"&&n.constructor===Object?e[t]=Ae(n):e[t]=n);return e}function $t(i,e){for(;i!==null;){let n=Ns(i,e);if(n){if(n.get)return se(n.get);if(typeof n.value=="function")return se(n.value)}i=Hs(i)}function t(){return null}return t}var Pr=ae(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","search","section","select","shadow","slot","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),Ii=ae(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","enterkeyhint","exportparts","filter","font","g","glyph","glyphref","hkern","image","inputmode","line","lineargradient","marker","mask","metadata","mpath","part","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),Ai=ae(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),Ws=ae(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),Di=ae(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),qs=ae(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),Ir=ae(["#text"]),Ar=ae(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","exportparts","face","for","headers","height","hidden","high","href","hreflang","id","inert","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","part","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","slot","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns","slot"]),Ri=ae(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","mask-type","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),Dr=ae(["accent","accentunder","align","bevelled","close","columnsalign","columnlines","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lspace","lquote","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),An=ae(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),Ys=be(/\{\{[\w\W]*|[\w\W]*\}\}/gm),Gs=be(/<%[\w\W]*|[\w\W]*%>/gm),Xs=be(/\$\{[\w\W]*/gm),Qs=be(/^data-[\-\w.\u00B7-\uFFFF]+$/),Zs=be(/^aria-[\-\w]+$/),Hr=be(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),Ks=be(/^(?:\w+script|data):/i),Js=be(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),Nr=be(/^html$/i),el=be(/^[a-z][.\w]*(-[.\w]+)+$/i),Rr=Object.freeze({__proto__:null,ARIA_ATTR:Zs,ATTR_WHITESPACE:Js,CUSTOM_ELEMENT:el,DATA_ATTR:Qs,DOCTYPE_NAME:Nr,ERB_EXPR:Gs,IS_ALLOWED_URI:Hr,IS_SCRIPT_OR_DATA:Ks,MUSTACHE_EXPR:Ys,TMPLIT_EXPR:Xs}),Vt={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,progressingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},tl=function(){return typeof window>"u"?null:window},nl=function(e,t){if(typeof e!="object"||typeof e.createPolicy!="function")return null;let n=null,o="data-tt-policy-suffix";t&&t.hasAttribute(o)&&(n=t.getAttribute(o));let r="dompurify"+(n?"#"+n:"");try{return e.createPolicy(r,{createHTML(a){return a},createScriptURL(a){return a}})}catch(a){return console.warn("TrustedTypes policy "+r+" could not be created."),null}},Fr=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function zr(){let i=arguments.length>0&&arguments[0]!==void 0?arguments[0]:tl(),e=C=>zr(C);if(e.version="3.3.1",e.removed=[],!i||!i.document||i.document.nodeType!==Vt.document||!i.Element)return e.isSupported=!1,e;let{document:t}=i,n=t,o=n.currentScript,{DocumentFragment:r,HTMLTemplateElement:a,Node:l,Element:u,NodeFilter:b,NamedNodeMap:y=i.NamedNodeMap||i.MozNamedAttrMap,HTMLFormElement:k,DOMParser:P,trustedTypes:W}=i,z=u.prototype,le=$t(z,"cloneNode"),Bt=$t(z,"remove"),Mt=$t(z,"nextSibling"),jt=$t(z,"childNodes"),Xe=$t(z,"parentNode");if(typeof a=="function"){let C=t.createElement("template");C.content&&C.content.ownerDocument&&(t=C.content.ownerDocument)}let Q,Qe="",{implementation:Ze,createNodeIterator:Ke,createDocumentFragment:wa,getElementsByTagName:Ta}=t,{importNode:Sa}=n,ie=Fr();e.isSupported=typeof Lr=="function"&&typeof Xe=="function"&&Ze&&Ze.createHTMLDocument!==void 0;let{MUSTACHE_EXPR:Zn,ERB_EXPR:Kn,TMPLIT_EXPR:Jn,DATA_ATTR:ka,ARIA_ATTR:Ma,IS_SCRIPT_OR_DATA:Ea,ATTR_WHITESPACE:ji,CUSTOM_ELEMENT:Oa}=Rr,{IS_ALLOWED_URI:Wi}=Rr,Z=null,qi=E({},[...Pr,...Ii,...Ai,...Di,...Ir]),ee=null,Yi=E({},[...Ar,...Ri,...Dr,...An]),B=Object.seal(Fi(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),Et=null,ei=null,rt=Object.seal(Fi(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}})),Gi=!0,ti=!0,Xi=!1,Qi=!0,at=!1,Wt=!0,Je=!1,ni=!1,ii=!1,st=!1,qt=!1,Yt=!1,Zi=!0,Ki=!1,Pa="user-content-",oi=!0,Ot=!1,lt={},ye=null,ri=E({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]),Ji=null,eo=E({},["audio","video","img","source","image","track"]),ai=null,to=E({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Gt="http://www.w3.org/1998/Math/MathML",Xt="http://www.w3.org/2000/svg",Re="http://www.w3.org/1999/xhtml",ct=Re,si=!1,li=null,Ia=E({},[Gt,Xt,Re],Oi),Qt=E({},["mi","mo","mn","ms","mtext"]),Zt=E({},["annotation-xml"]),Aa=E({},["title","style","font","a","script"]),Pt=null,Da=["application/xhtml+xml","text/html"],Ra="text/html",X=null,dt=null,Fa=t.createElement("form"),no=function(s){return s instanceof RegExp||s instanceof Function},ci=function(){let s=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(dt&&dt===s)){if((!s||typeof s!="object")&&(s={}),s=Ae(s),Pt=Da.indexOf(s.PARSER_MEDIA_TYPE)===-1?Ra:s.PARSER_MEDIA_TYPE,X=Pt==="application/xhtml+xml"?Oi:Dn,Z=Ce(s,"ALLOWED_TAGS")?E({},s.ALLOWED_TAGS,X):qi,ee=Ce(s,"ALLOWED_ATTR")?E({},s.ALLOWED_ATTR,X):Yi,li=Ce(s,"ALLOWED_NAMESPACES")?E({},s.ALLOWED_NAMESPACES,Oi):Ia,ai=Ce(s,"ADD_URI_SAFE_ATTR")?E(Ae(to),s.ADD_URI_SAFE_ATTR,X):to,Ji=Ce(s,"ADD_DATA_URI_TAGS")?E(Ae(eo),s.ADD_DATA_URI_TAGS,X):eo,ye=Ce(s,"FORBID_CONTENTS")?E({},s.FORBID_CONTENTS,X):ri,Et=Ce(s,"FORBID_TAGS")?E({},s.FORBID_TAGS,X):Ae({}),ei=Ce(s,"FORBID_ATTR")?E({},s.FORBID_ATTR,X):Ae({}),lt=Ce(s,"USE_PROFILES")?s.USE_PROFILES:!1,Gi=s.ALLOW_ARIA_ATTR!==!1,ti=s.ALLOW_DATA_ATTR!==!1,Xi=s.ALLOW_UNKNOWN_PROTOCOLS||!1,Qi=s.ALLOW_SELF_CLOSE_IN_ATTR!==!1,at=s.SAFE_FOR_TEMPLATES||!1,Wt=s.SAFE_FOR_XML!==!1,Je=s.WHOLE_DOCUMENT||!1,st=s.RETURN_DOM||!1,qt=s.RETURN_DOM_FRAGMENT||!1,Yt=s.RETURN_TRUSTED_TYPE||!1,ii=s.FORCE_BODY||!1,Zi=s.SANITIZE_DOM!==!1,Ki=s.SANITIZE_NAMED_PROPS||!1,oi=s.KEEP_CONTENT!==!1,Ot=s.IN_PLACE||!1,Wi=s.ALLOWED_URI_REGEXP||Hr,ct=s.NAMESPACE||Re,Qt=s.MATHML_TEXT_INTEGRATION_POINTS||Qt,Zt=s.HTML_INTEGRATION_POINTS||Zt,B=s.CUSTOM_ELEMENT_HANDLING||{},s.CUSTOM_ELEMENT_HANDLING&&no(s.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(B.tagNameCheck=s.CUSTOM_ELEMENT_HANDLING.tagNameCheck),s.CUSTOM_ELEMENT_HANDLING&&no(s.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(B.attributeNameCheck=s.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),s.CUSTOM_ELEMENT_HANDLING&&typeof s.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(B.allowCustomizedBuiltInElements=s.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),at&&(ti=!1),qt&&(st=!0),lt&&(Z=E({},Ir),ee=[],lt.html===!0&&(E(Z,Pr),E(ee,Ar)),lt.svg===!0&&(E(Z,Ii),E(ee,Ri),E(ee,An)),lt.svgFilters===!0&&(E(Z,Ai),E(ee,Ri),E(ee,An)),lt.mathMl===!0&&(E(Z,Di),E(ee,Dr),E(ee,An))),s.ADD_TAGS&&(typeof s.ADD_TAGS=="function"?rt.tagCheck=s.ADD_TAGS:(Z===qi&&(Z=Ae(Z)),E(Z,s.ADD_TAGS,X))),s.ADD_ATTR&&(typeof s.ADD_ATTR=="function"?rt.attributeCheck=s.ADD_ATTR:(ee===Yi&&(ee=Ae(ee)),E(ee,s.ADD_ATTR,X))),s.ADD_URI_SAFE_ATTR&&E(ai,s.ADD_URI_SAFE_ATTR,X),s.FORBID_CONTENTS&&(ye===ri&&(ye=Ae(ye)),E(ye,s.FORBID_CONTENTS,X)),s.ADD_FORBID_CONTENTS&&(ye===ri&&(ye=Ae(ye)),E(ye,s.ADD_FORBID_CONTENTS,X)),oi&&(Z["#text"]=!0),Je&&E(Z,["html","head","body"]),Z.table&&(E(Z,["tbody"]),delete Et.tbody),s.TRUSTED_TYPES_POLICY){if(typeof s.TRUSTED_TYPES_POLICY.createHTML!="function")throw zt('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof s.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw zt('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');Q=s.TRUSTED_TYPES_POLICY,Qe=Q.createHTML("")}else Q===void 0&&(Q=nl(W,o)),Q!==null&&typeof Qe=="string"&&(Qe=Q.createHTML(""));ae&&ae(s),dt=s}},io=E({},[...Ii,...Ai,...Ws]),oo=E({},[...Di,...qs]),La=function(s){let h=Xe(s);(!h||!h.tagName)&&(h={namespaceURI:ct,tagName:"template"});let v=Dn(s.tagName),V=Dn(h.tagName);return li[s.namespaceURI]?s.namespaceURI===Xt?h.namespaceURI===Re?v==="svg":h.namespaceURI===Gt?v==="svg"&&(V==="annotation-xml"||Qt[V]):!!io[v]:s.namespaceURI===Gt?h.namespaceURI===Re?v==="math":h.namespaceURI===Xt?v==="math"&&Zt[V]:!!oo[v]:s.namespaceURI===Re?h.namespaceURI===Xt&&!Zt[V]||h.namespaceURI===Gt&&!Qt[V]?!1:!oo[v]&&(Aa[v]||!io[v]):!!(Pt==="application/xhtml+xml"&&li[s.namespaceURI]):!1},we=function(s){Ht(e.removed,{element:s});try{Xe(s).removeChild(s)}catch(h){Bt(s)}},et=function(s,h){try{Ht(e.removed,{attribute:h.getAttributeNode(s),from:h})}catch(v){Ht(e.removed,{attribute:null,from:h})}if(h.removeAttribute(s),s==="is")if(st||qt)try{we(h)}catch(v){}else try{h.setAttribute(s,"")}catch(v){}},ro=function(s){let h=null,v=null;if(ii)s="<remove></remove>"+s;else{let q=Pi(s,/^[\r\n\t ]+/);v=q&&q[0]}Pt==="application/xhtml+xml"&&ct===Re&&(s='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+s+"</body></html>");let V=Q?Q.createHTML(s):s;if(ct===Re)try{h=new P().parseFromString(V,Pt)}catch(q){}if(!h||!h.documentElement){h=Ze.createDocument(ct,"template",null);try{h.documentElement.innerHTML=si?Qe:V}catch(q){}}let ne=h.body||h.documentElement;return s&&v&&ne.insertBefore(t.createTextNode(v),ne.childNodes[0]||null),ct===Re?Ta.call(h,Je?"html":"body")[0]:Je?h.documentElement:ne},ao=function(s){return Ke.call(s.ownerDocument||s,s,b.SHOW_ELEMENT|b.SHOW_COMMENT|b.SHOW_TEXT|b.SHOW_PROCESSING_INSTRUCTION|b.SHOW_CDATA_SECTION,null)},di=function(s){return s instanceof k&&(typeof s.nodeName!="string"||typeof s.textContent!="string"||typeof s.removeChild!="function"||!(s.attributes instanceof y)||typeof s.removeAttribute!="function"||typeof s.setAttribute!="function"||typeof s.namespaceURI!="string"||typeof s.insertBefore!="function"||typeof s.hasChildNodes!="function")},so=function(s){return typeof l=="function"&&s instanceof l};function Fe(C,s,h){In(C,v=>{v.call(e,s,h,dt)})}let lo=function(s){let h=null;if(Fe(ie.beforeSanitizeElements,s,null),di(s))return we(s),!0;let v=X(s.nodeName);if(Fe(ie.uponSanitizeElement,s,{tagName:v,allowedTags:Z}),Wt&&s.hasChildNodes()&&!so(s.firstElementChild)&&re(/<[/\w!]/g,s.innerHTML)&&re(/<[/\w!]/g,s.textContent)||s.nodeType===Vt.progressingInstruction||Wt&&s.nodeType===Vt.comment&&re(/<[/\w]/g,s.data))return we(s),!0;if(!(rt.tagCheck instanceof Function&&rt.tagCheck(v))&&(!Z[v]||Et[v])){if(!Et[v]&&po(v)&&(B.tagNameCheck instanceof RegExp&&re(B.tagNameCheck,v)||B.tagNameCheck instanceof Function&&B.tagNameCheck(v)))return!1;if(oi&&!ye[v]){let V=Xe(s)||s.parentNode,ne=jt(s)||s.childNodes;if(ne&&V){let q=ne.length;for(let ce=q-1;ce>=0;--ce){let Le=le(ne[ce],!0);Le.__removalCount=(s.__removalCount||0)+1,V.insertBefore(Le,Mt(s))}}}return we(s),!0}return s instanceof u&&!La(s)||(v==="noscript"||v==="noembed"||v==="noframes")&&re(/<\/no(script|embed|frames)/i,s.innerHTML)?(we(s),!0):(at&&s.nodeType===Vt.text&&(h=s.textContent,In([Zn,Kn,Jn],V=>{h=Nt(h,V," ")}),s.textContent!==h&&(Ht(e.removed,{element:s.cloneNode()}),s.textContent=h)),Fe(ie.afterSanitizeElements,s,null),!1)},co=function(s,h,v){if(Zi&&(h==="id"||h==="name")&&(v in t||v in Fa))return!1;if(!(ti&&!ei[h]&&re(ka,h))){if(!(Gi&&re(Ma,h))){if(!(rt.attributeCheck instanceof Function&&rt.attributeCheck(h,s))){if(!ee[h]||ei[h]){if(!(po(s)&&(B.tagNameCheck instanceof RegExp&&re(B.tagNameCheck,s)||B.tagNameCheck instanceof Function&&B.tagNameCheck(s))&&(B.attributeNameCheck instanceof RegExp&&re(B.attributeNameCheck,h)||B.attributeNameCheck instanceof Function&&B.attributeNameCheck(h,s))||h==="is"&&B.allowCustomizedBuiltInElements&&(B.tagNameCheck instanceof RegExp&&re(B.tagNameCheck,v)||B.tagNameCheck instanceof Function&&B.tagNameCheck(v))))return!1}else if(!ai[h]){if(!re(Wi,Nt(v,ji,""))){if(!((h==="src"||h==="xlink:href"||h==="href")&&s!=="script"&&Vs(v,"data:")===0&&Ji[s])){if(!(Xi&&!re(Ea,Nt(v,ji,"")))){if(v)return!1}}}}}}}return!0},po=function(s){return s!=="annotation-xml"&&Pi(s,Oa)},mo=function(s){Fe(ie.beforeSanitizeAttributes,s,null);let{attributes:h}=s;if(!h||di(s))return;let v={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:ee,forceKeepAttr:void 0},V=h.length;for(;V--;){let ne=h[V],{name:q,namespaceURI:ce,value:Le}=ne,pt=X(q),pi=Le,te=q==="value"?pi:Us(pi);if(v.attrName=pt,v.attrValue=te,v.keepAttr=!0,v.forceKeepAttr=void 0,Fe(ie.uponSanitizeAttribute,s,v),te=v.attrValue,Ki&&(pt==="id"||pt==="name")&&(et(q,s),te=Pa+te),Wt&&re(/((--!?|])>)|<\/(style|title|textarea)/i,te)){et(q,s);continue}if(pt==="attributename"&&Pi(te,"href")){et(q,s);continue}if(v.forceKeepAttr)continue;if(!v.keepAttr){et(q,s);continue}if(!Qi&&re(/\/>/i,te)){et(q,s);continue}at&&In([Zn,Kn,Jn],ho=>{te=Nt(te,ho," ")});let uo=X(s.nodeName);if(!co(uo,pt,te)){et(q,s);continue}if(Q&&typeof W=="object"&&typeof W.getAttributeType=="function"&&!ce)switch(W.getAttributeType(uo,pt)){case"TrustedHTML":{te=Q.createHTML(te);break}case"TrustedScriptURL":{te=Q.createScriptURL(te);break}}if(te!==pi)try{ce?s.setAttributeNS(ce,q,te):s.setAttribute(q,te),di(s)?we(s):Or(e.removed)}catch(ho){et(q,s)}}Fe(ie.afterSanitizeAttributes,s,null)},Ha=function C(s){let h=null,v=ao(s);for(Fe(ie.beforeSanitizeShadowDOM,s,null);h=v.nextNode();)Fe(ie.uponSanitizeShadowNode,h,null),lo(h),mo(h),h.content instanceof r&&C(h.content);Fe(ie.afterSanitizeShadowDOM,s,null)};return e.sanitize=function(C){let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},h=null,v=null,V=null,ne=null;if(si=!C,si&&(C="<!-->"),typeof C!="string"&&!so(C))if(typeof C.toString=="function"){if(C=C.toString(),typeof C!="string")throw zt("dirty is not a string, aborting")}else throw zt("toString is not a function");if(!e.isSupported)return C;if(ni||ci(s),e.removed=[],typeof C=="string"&&(Ot=!1),Ot){if(C.nodeName){let Le=X(C.nodeName);if(!Z[Le]||Et[Le])throw zt("root node is forbidden and cannot be sanitized in-place")}}else if(C instanceof l)h=ro("<!---->"),v=h.ownerDocument.importNode(C,!0),v.nodeType===Vt.element&&v.nodeName==="BODY"||v.nodeName==="HTML"?h=v:h.appendChild(v);else{if(!st&&!at&&!Je&&C.indexOf("<")===-1)return Q&&Yt?Q.createHTML(C):C;if(h=ro(C),!h)return st?null:Yt?Qe:""}h&&ii&&we(h.firstChild);let q=ao(Ot?C:h);for(;V=q.nextNode();)lo(V),mo(V),V.content instanceof r&&Ha(V.content);if(Ot)return C;if(st){if(qt)for(ne=wa.call(h.ownerDocument);h.firstChild;)ne.appendChild(h.firstChild);else ne=h;return(ee.shadowroot||ee.shadowrootmode)&&(ne=Sa.call(n,ne,!0)),ne}let ce=Je?h.outerHTML:h.innerHTML;return Je&&Z["!doctype"]&&h.ownerDocument&&h.ownerDocument.doctype&&h.ownerDocument.doctype.name&&re(Nr,h.ownerDocument.doctype.name)&&(ce="<!DOCTYPE "+h.ownerDocument.doctype.name+`>
|
|
63
|
-
`+ce),at&&In([Zn,Kn,Jn],Le=>{ce=Nt(ce,Le," ")}),Q&&Yt?Q.createHTML(ce):ce},e.setConfig=function(){let C=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};ci(C),ni=!0},e.clearConfig=function(){dt=null,ni=!1},e.isValidAttribute=function(C,s,h){dt||ci({});let v=X(C),V=X(s);return co(v,V,h)},e.addHook=function(C,s){typeof s=="function"&&Ht(ie[C],s)},e.removeHook=function(C,s){if(s!==void 0){let h=zs(ie[C],s);return h===-1?void 0:$s(ie[C],h,1)[0]}return Or(ie[C])},e.removeHooks=function(C){ie[C]=[]},e.removeAllHooks=function(){ie=Fr()},e}var $r=zr();var De=class i{renderer;constructor(){this.renderer=new bt,this.configureRenderer()}configureRenderer(){let e=this.renderer.link.bind(this.renderer);this.renderer.link=t=>{let n=this.isExternalLink(t.href),o=e(t);if(n){o=o.replace("<a ",'<a target="_blank" rel="noopener noreferrer" ');let r=t.title?`${t.text} - ${t.title} (opens in new tab)`:`${t.text} (opens in new tab)`;o=o.replace("<a ",`<a aria-label="${this.escapeHtml(r)}" `),o=o.replace("</a>",'<span class="external-link-icon" aria-hidden="true">\u2197</span></a>')}return o}}isExternalLink(e){if(!e||e.startsWith("/")||e.startsWith("#")||e.startsWith("?"))return!1;if(e.startsWith("//"))return!0;try{return new URL(e,window.location.href).hostname!==window.location.hostname}catch(t){return!1}}escapeHtml(e){let t={"&":"&","<":"<",">":">",'"':""","'":"'"};return e.replace(/[&<>"']/g,n=>t[n]||n)}parse(e){return N(this,null,function*(){let t=yield L.parse(e,{renderer:this.renderer,breaks:!0,gfm:!0});return $r.sanitize(t,{ADD_TAGS:["span"],ADD_ATTR:["aria-hidden","aria-label","target","rel"],ALLOWED_URI_REGEXP:/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp):|[^a-z]|[a-z+.-]+(?:[^a-z+.-:]|$))/i})})}static \u0275fac=function(t){return new(t||i)};static \u0275prov=Y({token:i,factory:i.\u0275fac,providedIn:"root"})};var il=i=>({"user-message-wrapper":i});function ol(i,e){if(i&1&&(c(0,"div",5)(1,"div",9),f(2),d()()),i&2){let t=m(2);p(2),ht(" ",t.message.speaker," ")}}function rl(i,e){if(i&1&&(c(0,"time",7),f(1),d()),i&2){let t=m(2);p(),F(t.formattedTimestamp)}}function al(i,e){if(i&1&&(c(0,"div",8),I(1,"app-message-context-menu",10),d()),i&2){let t=m(2);p(),M("actions",t.actions)}}function sl(i,e){if(i&1&&(x(0,ol,3,1,"div",5),I(1,"div",6),x(2,rl,2,1,"time",7),x(3,al,2,1,"div",8)),i&2){let t=m();_(t.shouldShowSpeaker?0:-1),p(),M("innerHTML",t.renderedContent,ue),p(),_(t.formattedTimestamp?2:-1),p(),_(t.isLongMessage&&t.shouldShowActions&&t.message.role==="assistant"?3:-1)}}function ll(i,e){if(i&1&&(c(0,"a",12),f(1,"view"),d()),i&2){let t=m(2);M("href",t.eventLink,Co)}}function cl(i,e){if(i&1&&(c(0,"div",2),I(1,"span",11),x(2,ll,2,1,"a",12),d()),i&2){let t=m();p(),M("innerHTML",t.renderedContent,ue),p(),_(t.eventLink?2:-1)}}function dl(i,e){if(i&1&&(c(0,"div",3),I(1,"app-message-context-menu",10),d()),i&2){let t=m();p(),M("actions",t.actions)}}function pl(i,e){if(i&1&&(c(0,"div",4),I(1,"app-message-context-menu",10),d()),i&2){let t=m();p(),M("actions",t.actions)}}var xt=class i{destroy$=new xe;message;canDelete=!0;isOtherUser=!1;copyRequested=new H;deleteRequested=new H;renderedContent="";shouldHideTechnical=!1;shouldHideWarning=!1;sanitizer=g(Ee);notificationService=g(ir);preferencesService=g(qe);projectState=g(Oe);threadState=g(Pe);markdownService=g(De);get messageClasses(){return{[this.message.role]:!0,[this.message.type]:!0,"hidden-technical":this.shouldHideTechnical&&this.message.type==="technical","hidden-warning":this.shouldHideWarning&&this.message.type==="warning","other-user":this.isOtherUser}}ngOnInit(){return N(this,null,function*(){yield this.renderMarkdown(),this.preferencesService.hideTechnicalMessages$.pipe(K(this.destroy$)).subscribe(e=>{this.shouldHideTechnical=e}),this.preferencesService.hideWarningMessages$.pipe(K(this.destroy$)).subscribe(e=>{this.shouldHideWarning=e}),this.shouldHideTechnical=this.preferencesService.getHideTechnicalMessages(),this.shouldHideWarning=this.preferencesService.getHideWarningMessages()})}ngOnDestroy(){this.destroy$.next(),this.destroy$.complete()}get shouldShowSpeaker(){return this.message.role==="user"?this.isOtherUser||this.message.speaker.startsWith("@"):this.message.role==="assistant"}get shouldShowActions(){return this.message.role==="user"||this.message.role==="assistant"}get isSimplified(){return this.message.role!=="user"&&this.message.role!=="assistant"}datePipe=g(fi);get formattedTimestamp(){if(this.message.role!=="user"||!this.message.timestamp)return null;let e=new Date().toDateString()===this.message.timestamp.toDateString();return this.datePipe.transform(this.message.timestamp,e?"HH:mm":"dd/MM HH:mm")}get isLongMessage(){let e=this.extractTextContent();return e.length>1e3||e.split(`
|
|
64
|
-
`).length>20}get actions(){let e=[];return this.message.role==="user"&&this.canDelete&&e.push({icon:"delete",label:"Delete from here",tooltip:"Delete this message and all following messages",action:()=>this.onDelete(),destructive:!0}),e.push({icon:"content_copy",label:"Copy message",tooltip:"Copy message content to clipboard",action:()=>this.onCopy()}),e}get eventLink(){if(!this.message.eventId)return null;let e=this.projectState.getSelectedProjectId(),t=this.threadState.getSelectedThreadId();return!e||!t?null:`/api/projects/${e}/threads/${t}/messages/${encodeURIComponent(this.message.eventId)}/formatted`}renderMarkdown(){return N(this,null,function*(){try{let e=yield this.renderRichContent(this.message.content);this.renderedContent=this.sanitizer.bypassSecurityTrustHtml(e)}catch(e){console.error("Error parsing rich content:",e);let t=this.extractTextContent();this.renderedContent=this.sanitizer.bypassSecurityTrustHtml(t)}})}renderRichContent(e){return N(this,null,function*(){let t=[];for(let n of e)if(n.type==="text"){let o=yield this.markdownService.parse(n.content);t.push(`<div class="text-part">${o}</div>`)}else if(n.type==="image"){let o=`data:${n.mimeType};base64,${n.content}`,r=n.source||"Image",a=`
|
|
65
|
-
<div class="image-content">
|
|
66
|
-
<img src="${o}"
|
|
67
|
-
alt="${r}"
|
|
68
|
-
class="message-image"
|
|
69
|
-
style="max-width: 100%; height: auto; margin: 8px 0; border-radius: 8px; cursor: pointer; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1); transition: transform 0.2s ease, box-shadow 0.2s ease;"
|
|
70
|
-
onclick="window.open(this.src, '_blank')" />
|
|
71
|
-
</div>
|
|
72
|
-
`;t.push(a)}else if(n.type==="audio"){let o=`data:${n.mimeType};base64,${n.content}`,r=n.transcription?`<div class="audio-transcription" style="margin-top: 4px; font-style: italic; color: var(--text-secondary, #666); font-size: 0.9em;">\u201C${n.transcription}\u201D</div>`:"",a=`
|
|
73
|
-
<div class="audio-content" style="margin: 8px 0;">
|
|
74
|
-
<audio controls preload="metadata" style="width: 100%; max-width: 400px; display: block;">
|
|
75
|
-
<source src="${o}" type="${n.mimeType}">
|
|
76
|
-
Your browser does not support the audio element.
|
|
77
|
-
</audio>
|
|
78
|
-
${r}
|
|
79
|
-
</div>
|
|
80
|
-
`;t.push(a)}return t.join("")})}onCopy(){let e=this.extractTextContent();e.trim()&&navigator.clipboard.writeText(e).then(()=>{console.log("[CHAT-MESSAGE] Message copied to clipboard"),this.notificationService.success("Message copied to clipboard")}).catch(t=>{console.error("[CHAT-MESSAGE] Failed to copy message:",t),this.notificationService.error("Failed to copy message")}),this.copyRequested.emit(this.message)}onDelete(){console.log("[CHAT-MESSAGE] Delete requested for message:",this.message.id),this.deleteRequested.emit(this.message)}extractTextContent(){return this.message.content.filter(e=>e.type==="text"||e.type==="audio"&&e.transcription).map(e=>e.type==="text"?e.content:`[Voice message]: ${e.transcription}`).join(`
|
|
81
|
-
|
|
82
|
-
`)}static \u0275fac=function(t){return new(t||i)};static \u0275cmp=R({type:i,selectors:[["app-chat-message"]],inputs:{message:"message",canDelete:"canDelete",isOtherUser:"isOtherUser"},outputs:{copyRequested:"copyRequested",deleteRequested:"deleteRequested"},features:[Oo([fi])],decls:6,vars:8,consts:[[1,"message-wrapper",3,"ngClass"],[1,"message",3,"ngClass"],[1,"simple-content","markdown-content"],[1,"actions","assistant-top-actions"],[1,"actions","user-top-actions"],[1,"message-header"],[1,"content","markdown-content",3,"innerHTML"],[1,"message-timestamp"],[1,"actions","bottom-actions"],[1,"speaker"],[3,"actions"],[3,"innerHTML"],["target","_blank",1,"event-link",3,"href"]],template:function(t,n){t&1&&(c(0,"div",0)(1,"div",1),x(2,sl,4,4),x(3,cl,3,2,"div",2),d(),x(4,dl,2,1,"div",3),x(5,pl,2,1,"div",4),d()),t&2&&(M("ngClass",Io(6,il,n.message.role==="user")),p(),M("ngClass",n.messageClasses),p(),_(n.isSimplified?-1:2),p(),_(n.isSimplified?3:-1),p(),_(!n.isLongMessage&&n.shouldShowActions&&n.message.role==="assistant"?4:-1),p(),_(n.shouldShowActions&&n.message.role==="user"?5:-1))},dependencies:[Sn,ln],styles:[".message-wrapper[_ngcontent-%COMP%]{margin:0;display:flex;align-items:flex-start;gap:.5rem}.message-wrapper.user-message-wrapper[_ngcontent-%COMP%]{margin:.75rem 0;flex-direction:row-reverse;align-items:flex-start}.message-wrapper.user-message-wrapper[_ngcontent-%COMP%]:has(.other-user){flex-direction:row}.message[_ngcontent-%COMP%]{position:relative}.message.user[_ngcontent-%COMP%]{padding:1rem 1.25rem .5rem}.message.user[_ngcontent-%COMP%] .message-timestamp[_ngcontent-%COMP%]{display:block;text-align:right;font-size:.7rem;color:var(--color-text-secondary, #6272a4);white-space:nowrap;margin-top:.4rem;opacity:.7}.message.user[_ngcontent-%COMP%]{background:var(--color-message-user);border-radius:18px 18px 6px;border:1px solid var(--glass-border);box-shadow:none;backdrop-filter:var(--glass-backdrop-blur);-webkit-backdrop-filter:var(--glass-backdrop-blur);width:fit-content;max-width:75%;min-width:120px;word-wrap:break-word;transition:transform .2s ease,box-shadow .2s ease}.message.user[_ngcontent-%COMP%]:hover{transform:translateY(-1px);box-shadow:0 12px 40px #1f268733}.message.user.other-user[_ngcontent-%COMP%]{border-bottom-right-radius:18px;border-bottom-left-radius:6px}.message.assistant[_ngcontent-%COMP%]{background:transparent;border:none;box-shadow:none;border-radius:0;margin-left:0;margin-right:auto;padding:.5rem 0;width:100%;max-width:none;min-width:0}.message.system[_ngcontent-%COMP%], .message.technical[_ngcontent-%COMP%]{padding:.5rem .75rem;background:transparent;border:none;box-shadow:none;backdrop-filter:none;-webkit-backdrop-filter:none;margin:0;font-family:SF Mono,Monaco,Menlo,monospace;font-size:.85rem;color:var(--color-text-secondary);max-width:none;width:auto;min-width:auto}.message.system[_ngcontent-%COMP%]:hover, .message.technical[_ngcontent-%COMP%]:hover{transform:none;box-shadow:none}.message.hidden-technical[_ngcontent-%COMP%], .message.hidden-warning[_ngcontent-%COMP%]{display:none!important}.message.error[_ngcontent-%COMP%]{padding:1rem 1.25rem;background:#ff3b301f;border-left:3px solid var(--color-error);color:var(--color-error)}.message.warning[_ngcontent-%COMP%]{padding:1rem 1.25rem;background:#ff95001f;border-left:3px solid var(--color-warning);color:var(--color-warning)}.message-header[_ngcontent-%COMP%]{margin-bottom:.5rem}.speaker[_ngcontent-%COMP%]{font-weight:600;font-size:.85rem;color:var(--color-text-secondary, #6272a4)}.content[_ngcontent-%COMP%]{line-height:1.5}.context-menu-top[_ngcontent-%COMP%]{top:.5rem;right:.5rem;z-index:10}.context-menu-bottom[_ngcontent-%COMP%]{bottom:.5rem;right:.5rem;z-index:10}.user-top-actions[_ngcontent-%COMP%]{display:flex;align-items:flex-start;padding-top:.5rem;opacity:0;transition:opacity .2s ease}.user-message-wrapper[_ngcontent-%COMP%]:hover .user-top-actions[_ngcontent-%COMP%]{opacity:1}.assistant-top-actions[_ngcontent-%COMP%]{display:flex;align-items:flex-start;padding-top:.5rem;opacity:0;transition:opacity .2s ease}.message-wrapper[_ngcontent-%COMP%]:hover .assistant-top-actions[_ngcontent-%COMP%]{opacity:1}.simple-content[_ngcontent-%COMP%]{display:flex}.simple-content[_ngcontent-%COMP%] .event-link[_ngcontent-%COMP%]{margin-left:5px;font-size:.9em;color:var(--color-link, #3498db);text-decoration:none}.simple-content[_ngcontent-%COMP%] .event-link[_ngcontent-%COMP%]:hover{text-decoration:underline}.text-part[_ngcontent-%COMP%]{margin:4px 0}.image-content[_ngcontent-%COMP%]{display:flex;flex-direction:column;align-items:center;margin:1em 0}.message-image[_ngcontent-%COMP%]{display:block;max-width:100%;height:auto;margin:8px 0;border-radius:12px;cursor:pointer;box-shadow:var(--glass-shadow);transition:transform .3s ease,box-shadow .3s ease;border:1px solid var(--glass-border)}.message-image[_ngcontent-%COMP%]:hover{transform:scale(1.02) translateY(-2px);box-shadow:0 16px 48px #00000026}@media(max-width:768px){.message-image[_ngcontent-%COMP%]{border-radius:4px;margin:6px 0}}@media(max-width:480px){.message-image[_ngcontent-%COMP%]{margin:4px 0}}"]})};var ul=(i,e)=>e.id;function hl(i,e){if(i&1&&(c(0,"span",4),f(1),d()),i&2){let t=m();p(),F(t.taskSummary)}}function gl(i,e){i&1&&(c(0,"div",6),I(1,"mat-spinner",8),c(2,"span"),f(3,"Loading..."),d()()),i&2&&(p(),M("diameter",16))}function fl(i,e){if(i&1&&I(0,"app-delegation-inline",9),i&2){let t=m().$implicit;M("subThreadId",t.subThreadId)("agentName",t.delegationAgentName)}}function bl(i,e){if(i&1&&I(0,"app-chat-message",10),i&2){let t=m().$implicit;M("message",t)("canDelete",!1)}}function xl(i,e){if(i&1&&x(0,fl,1,2,"app-delegation-inline",9)(1,bl,1,2,"app-chat-message",10),i&2){let t=e.$implicit;_(t.type==="delegation"?0:1)}}function _l(i,e){if(i&1&&(c(0,"div",7)(1,"div",11),f(2),d()()),i&2){let t=m(2);p(2),F(t.streamingText)}}function vl(i,e){if(i&1&&(c(0,"div",5),x(1,gl,4,1,"div",6),de(2,xl,2,1,null,null,ul),x(4,_l,3,1,"div",7),d()),i&2){let t=m();p(),_(t.isLoading&&t.subMessages.length===0?1:-1),p(),pe(t.subMessages),p(2),_(t.streamingText?4:-1)}}var Rn=class i{subThreadId;agentName;isExpanded=!1;isLoading=!1;subMessages=[];streamingText="";restLoaded=!1;messageIds=new Set;eventSubscription;codayService=g(Ye);threadApi=g(dn);get taskSummary(){let e=this.subMessages.find(t=>t.role==="user");if(e){let t=e.content.filter(n=>n.type==="text").map(n=>n.content).join(" ");return t.length>120?t.substring(0,120)+"...":t}return""}ngOnInit(){for(let e of this.codayService.getBufferedSubThreadEvents(this.subThreadId))this.handleSubThreadEvent(e);this.eventSubscription=this.codayService.subThreadEvents$.pipe(Se(e=>e.threadId===this.subThreadId)).subscribe(e=>this.handleSubThreadEvent(e))}ngOnDestroy(){this.eventSubscription?.unsubscribe()}toggle(){this.isExpanded=!this.isExpanded,this.isExpanded&&!this.restLoaded&&this.loadSubThreadMessages()}loadSubThreadMessages(){this.isLoading=!0,this.threadApi.getThreadMessages(this.subThreadId).subscribe({next:e=>{if(e.messages){for(let t of e.messages){let n=er(t);n&&this.handleSubThreadEvent(n)}this.subMessages=[...this.subMessages].sort((t,n)=>t.id.localeCompare(n.id))}this.restLoaded=!0,this.isLoading=!1},error:e=>{console.error("[DELEGATION-INLINE] Failed to load sub-thread messages:",e),this.restLoaded=!0,this.isLoading=!1}})}handleSubThreadEvent(e){e instanceof Yo?this.addMessage({id:e.timestamp,role:"user",speaker:"User",content:[{type:"text",content:e.answer}],timestamp:new Date,type:"text"}):e instanceof Xo?this.streamingText+=e.chunk:e instanceof Ko?(e.role==="assistant"&&(this.streamingText=""),this.addMessage({id:e.timestamp,role:e.role,speaker:e.name,content:e.content,timestamp:new Date,type:"text"})):e instanceof Qo?this.addMessage({id:e.timestamp,role:"system",speaker:"System",content:[{type:"text",content:e.toSingleLineString()}],timestamp:new Date,type:"technical",eventId:e.timestamp}):e instanceof Zo?this.addMessage({id:e.timestamp,role:"system",speaker:"System",content:[{type:"text",content:e.toSingleLineString()}],timestamp:new Date,type:"technical",eventId:e.timestamp}):e instanceof Jo?this.addMessage({id:e.timestamp,role:"system",speaker:e.agentName,content:[{type:"text",content:""}],timestamp:new Date,type:"delegation",subThreadId:e.subThreadId,delegationAgentName:e.agentName}):e instanceof Go&&this.addMessage({id:e.timestamp,role:"system",speaker:e.speaker??"System",content:[{type:"text",content:e.text}],timestamp:new Date,type:"technical"})}addMessage(e){this.messageIds.has(e.id)||(this.messageIds.add(e.id),this.subMessages=[...this.subMessages,e])}static \u0275fac=function(t){return new(t||i)};static \u0275cmp=R({type:i,selectors:[["app-delegation-inline"]],inputs:{subThreadId:"subThreadId",agentName:"agentName"},decls:8,vars:4,consts:[[1,"delegation-inline"],["role","button","tabindex","0",1,"delegation-header",3,"click","keydown.enter","keydown.space"],[1,"expand-icon"],[1,"agent-name"],[1,"task-summary"],[1,"delegation-body"],[1,"loading"],[1,"streaming-message"],[3,"diameter"],[3,"subThreadId","agentName"],[3,"message","canDelete"],[1,"content"]],template:function(t,n){t&1&&(c(0,"div",0)(1,"div",1),w("click",function(){return n.toggle()})("keydown.enter",function(){return n.toggle()})("keydown.space",function(){return n.toggle()}),c(2,"mat-icon",2),f(3),d(),c(4,"span",3),f(5),d(),x(6,hl,2,1,"span",4),d(),x(7,vl,5,2,"div",5),d()),t&2&&(p(3),F(n.isExpanded?"expand_more":"chevron_right"),p(2),F(n.agentName),p(),_(n.taskSummary?6:-1),p(),_(n.isExpanded?7:-1))},dependencies:[i,fe,me,J,mn,pn,xt],styles:[".delegation-inline[_ngcontent-%COMP%]{margin:.5rem 0;border-left:3px solid var(--color-primary, #6366f1);border-radius:4px;background:var(--color-bg-secondary);overflow:hidden}.delegation-header[_ngcontent-%COMP%]{display:flex;align-items:center;gap:.5rem;padding:.5rem .75rem;cursor:pointer;-webkit-user-select:none;user-select:none}.delegation-header[_ngcontent-%COMP%]:hover{background:var(--color-bg-hover)}.delegation-header[_ngcontent-%COMP%] .expand-icon[_ngcontent-%COMP%]{font-size:18px;width:18px;height:18px;color:var(--color-text-secondary, #94a3b8)}.delegation-header[_ngcontent-%COMP%] .agent-name[_ngcontent-%COMP%]{font-weight:600;color:var(--color-primary, #6366f1);white-space:nowrap}.delegation-header[_ngcontent-%COMP%] .task-summary[_ngcontent-%COMP%]{flex:1;color:var(--color-text-secondary, #94a3b8);font-size:.85rem;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.delegation-body[_ngcontent-%COMP%]{padding:0 .75rem .75rem 1.5rem;border-top:1px solid var(--color-border-light)}.delegation-body[_ngcontent-%COMP%] .loading[_ngcontent-%COMP%]{display:flex;align-items:center;gap:.5rem;padding:.75rem 0;color:var(--color-text-secondary, #94a3b8);font-size:.85rem}.delegation-body[_ngcontent-%COMP%] .sub-messages[_ngcontent-%COMP%]{padding:.5rem 0}"]})};var Fn=class i{thinkingPhrases=["Processing request...","Thinking...","Working on it..."];currentThinkingPhrase="Processing request...";thinkingPhraseIndex=0;thinkingInterval=null;ngOnInit(){this.startThinkingAnimation()}ngOnDestroy(){this.stopThinkingAnimation()}startThinkingAnimation(){this.thinkingPhraseIndex=0,this.currentThinkingPhrase=this.thinkingPhrases[0]||"Thinking...",this.thinkingInterval=window.setInterval(()=>{this.thinkingPhraseIndex<this.thinkingPhrases.length-1&&(this.thinkingPhraseIndex++,this.currentThinkingPhrase=this.thinkingPhrases[this.thinkingPhraseIndex]||"Thinking...")},2e3)}stopThinkingAnimation(){this.thinkingInterval&&(clearInterval(this.thinkingInterval),this.thinkingInterval=null),this.thinkingPhraseIndex=0,this.currentThinkingPhrase="Thinking..."}static \u0275fac=function(t){return new(t||i)};static \u0275cmp=R({type:i,selectors:[["app-thinking-loader"]],decls:8,vars:1,consts:[[1,"message-wrapper"],[1,"message","assistant","thinking-message"],[1,"content"],[1,"thinking-loader"],[1,"logo-container"],["src","CODAY-Logo.png","alt","Coday Logo",1,"coday-logo"],[1,"thinking-text"]],template:function(t,n){t&1&&(ui(0,"div",0)(1,"div",1)(2,"div",2)(3,"div",3)(4,"div",4),Mo(5,"img",5),hi(),ui(6,"p",6),f(7),hi()()()()()),t&2&&(p(7),F(n.currentThinkingPhrase))},dependencies:[fe],styles:[".message-wrapper[_ngcontent-%COMP%]{margin:0;display:flex;align-items:flex-start;gap:.5rem}.message.assistant[_ngcontent-%COMP%]{background:transparent;border:none;box-shadow:none;border-radius:0;margin-left:0;margin-right:auto;padding:.5rem 0;width:100%;max-width:none;min-width:0}.message.thinking-message[_ngcontent-%COMP%] .content[_ngcontent-%COMP%]{line-height:1.5}.thinking-loader[_ngcontent-%COMP%]{display:flex;align-items:center;gap:1rem;padding:.75rem 0}.logo-container[_ngcontent-%COMP%]{position:relative;width:32px;height:32px;display:flex;align-items:center;justify-content:center;flex-shrink:0}.coday-logo[_ngcontent-%COMP%]{width:100%;height:100%;object-fit:contain;animation:_ngcontent-%COMP%_pulse 2s ease-in-out infinite;filter:drop-shadow(0 1px 4px rgba(0,0,0,.1))}.thinking-text[_ngcontent-%COMP%]{font-size:.95rem;font-weight:400;color:var(--color-text-secondary);margin:0;animation:_ngcontent-%COMP%_fadeInOut 2s ease-in-out infinite;letter-spacing:.01em;font-style:italic}@keyframes _ngcontent-%COMP%_pulse{0%,to{transform:scale(1);opacity:1}50%{transform:scale(1.1);opacity:.7}}@keyframes _ngcontent-%COMP%_fadeInOut{0%,to{opacity:.6}50%{opacity:1}}@media(max-width:768px){.logo-container[_ngcontent-%COMP%]{width:28px;height:28px}.thinking-text[_ngcontent-%COMP%]{font-size:.875rem}.thinking-loader[_ngcontent-%COMP%]{gap:.75rem}}@media print{.thinking-loader[_ngcontent-%COMP%]{display:none!important}}"]})};var Cl=(i,e)=>e.id;function yl(i,e){if(i&1&&I(0,"app-delegation-inline",3),i&2){let t=m().$implicit;M("subThreadId",t.subThreadId)("agentName",t.delegationAgentName)}}function wl(i,e){if(i&1){let t=O();c(0,"app-chat-message",5),w("copyRequested",function(o){T(t);let r=m(2);return S(r.onCopyMessage(o))})("deleteRequested",function(o){T(t);let r=m(2);return S(r.onDeleteMessage(o))}),d()}if(i&2){let t=m(),n=t.$implicit,o=t.$index,r=m();M("message",n)("canDelete",r.canDeleteMessage(o))("isOtherUser",n.role==="user"&&!!r.currentUsername&&n.speaker!==r.currentUsername)}}function Tl(i,e){if(i&1&&x(0,yl,1,2,"app-delegation-inline",3)(1,wl,1,3,"app-chat-message",4),i&2){let t=e.$implicit;_(t.type==="delegation"?0:1)}}function Sl(i,e){if(i&1&&(c(0,"div",1),I(1,"div",6),d()),i&2){let t=m();p(),M("innerHTML",t.renderedStreamingText,ue)}}function kl(i,e){i&1&&I(0,"app-thinking-loader")}function Ml(i,e){if(i&1){let t=O();c(0,"button",7),w("click",function(){T(t);let o=m();return S(o.goToBottom())}),c(1,"mat-icon",8),f(2,"arrow_downward"),d()()}}var Ln=class i{messages=[];streamingText="";isThinking=!1;currentUsername="";copyRequested=new H;stopRequested=new H;lastMessageCount=0;destroy$=new xe;renderedStreamingText="";isTracking=!0;showGoToBottom=!1;scrollContainer=null;lastScrollTop=0;NEAR_BOTTOM_THRESHOLD=100;scrollCheckTimeout;isProgrammaticScroll=!1;MESSAGE_FRESHNESS_THRESHOLD=300*1e3;elementRef=g(mt);unreadService=g(ft);voiceSynthesisService=g(nr);preferencesService=g(qe);codayService=g(Ye);markdownService=g(De);sanitizer=g(Ee);ngOnInit(){this.findScrollContainer(),this.setupFocusListeners()}ngOnDestroy(){this.destroy$.next(),this.destroy$.complete(),this.scrollCheckTimeout&&clearTimeout(this.scrollCheckTimeout),window.removeEventListener("focus",this.handleWindowFocus),window.removeEventListener("blur",this.handleWindowBlur)}ngOnChanges(e){e.streamingText&&(this.renderStreamingText(),this.streamingText&&this.isTracking&&setTimeout(()=>this.scrollToBottom(),0))}ngAfterViewChecked(){if(this.messages.length!==this.lastMessageCount){console.log("[CHAT-HISTORY] Message count changed:",this.lastMessageCount,"->",this.messages.length);let e=this.messages.length-this.lastMessageCount;e>0&&(this.handleNewMessages(e),this.handleVoiceAnnouncement(e)),this.lastMessageCount=this.messages.length,this.isTracking&&this.scrollToBottom()}this.scrollContainer||this.findScrollContainer()}scrollToBottom(){try{this.scrollContainer||this.findScrollContainer(),this.scrollContainer&&(this.isProgrammaticScroll=!0,setTimeout(()=>{this.scrollContainer&&this.scrollContainer.scrollTo({top:this.scrollContainer.scrollHeight,behavior:"smooth"}),setTimeout(()=>{this.isProgrammaticScroll=!1},600)},50))}catch(e){console.error("Error scrolling to bottom:",e)}}trackByMessageId(e,t){return t.id}onCopyMessage(e){let t=e.content.filter(n=>n.type==="text").map(n=>n.content).join(`
|
|
83
|
-
|
|
84
|
-
`);navigator.clipboard.writeText(t).then(()=>console.log("Message copied")).catch(n=>console.error("Failed to copy:",n)),this.copyRequested.emit(e)}onStop(){this.stopRequested.emit()}canDeleteMessage(e){return e===0?!1:!this.isThinking}onDeleteMessage(e){if(console.log("[CHAT-HISTORY] Delete requested for message:",e.id),this.messages.findIndex(o=>o.id===e.id)===0){console.warn("[CHAT-HISTORY] Cannot delete first message");return}if(this.isThinking){console.warn("[CHAT-HISTORY] Cannot delete message while agent is thinking");return}if(e.role!=="user"){console.warn("[CHAT-HISTORY] Can only delete user messages");return}confirm(`Delete this message and all following messages?
|
|
85
|
-
|
|
86
|
-
This action cannot be undone once you post another message.`)&&(console.log("[CHAT-HISTORY] Proceeding with message deletion"),this.codayService.deleteMessage(e.id).subscribe({next:o=>{o.success?console.log("[CHAT-HISTORY] Message deleted successfully"):(console.error("[CHAT-HISTORY] Failed to delete message:",o.error),alert(`Failed to delete message: ${o.error}`))},error:o=>{console.error("[CHAT-HISTORY] Error deleting message:",o),alert(`Error deleting message: ${o.message||"Unknown error"}`)}}))}onScroll(){}findScrollContainer(){let e=this.elementRef.nativeElement;this.scrollContainer=e.closest(".chat-wrapper"),this.scrollContainer?(console.log("[CHAT-HISTORY] Scroll container found"),this.scrollContainer.addEventListener("scroll",this.handleScroll.bind(this)),this.lastScrollTop=this.scrollContainer.scrollTop,this.checkScrollPosition()):(console.warn("[CHAT-HISTORY] Scroll container not found"),setTimeout(()=>this.findScrollContainer(),100))}handleScroll=()=>{if(!this.scrollContainer)return;let e=this.scrollContainer.scrollTop;if(Math.abs(e-this.lastScrollTop)<1){this.lastScrollTop=e;return}if(this.isProgrammaticScroll){this.lastScrollTop=e;return}console.log("[CHAT-HISTORY] User scroll detected - disabling auto-scroll"),this.isTracking&&(this.isTracking=!1,this.showGoToBottom=!0),clearTimeout(this.scrollCheckTimeout),this.scrollCheckTimeout=setTimeout(()=>{this.checkScrollPosition()},500),this.lastScrollTop=e};checkScrollPosition(){if(!this.scrollContainer)return;let{scrollTop:e,scrollHeight:t,clientHeight:n}=this.scrollContainer,r=t-e-n<=this.NEAR_BOTTOM_THRESHOLD;r&&!this.isTracking&&(console.log("[CHAT-HISTORY] Near bottom - re-enabling auto-scroll"),this.isTracking=!0,this.showGoToBottom=!1,this.unreadService.markAllAsRead()),!this.isTracking&&!r&&(this.showGoToBottom=!0)}goToBottom(){console.log("[CHAT-HISTORY] Go to bottom clicked - re-enabling auto-scroll"),this.scrollToBottom(),this.isTracking=!0,this.showGoToBottom=!1,this.unreadService.markAllAsRead()}handleNewMessages(e){let n=this.messages.slice(-e).filter(r=>r.role==="assistant");if(n.length===0){console.log("[CHAT-HISTORY] No new assistant messages to count");return}if(this.shouldMarkNewMessagesAsUnread()){console.log("[CHAT-HISTORY] Marking",n.length,"new assistant messages as unread");for(let r=0;r<n.length;r++)this.unreadService.addUnread()}else console.log("[CHAT-HISTORY] New assistant messages are considered read (user is focused and tracking)")}shouldMarkNewMessagesAsUnread(){return document.hasFocus()?this.isTracking?!1:(console.log("[CHAT-HISTORY] User is not tracking (scrolled up) -> unread"),!0):(console.log("[CHAT-HISTORY] Tab does not have focus -> unread"),!0)}setupFocusListeners(){window.addEventListener("focus",this.handleWindowFocus),window.addEventListener("blur",this.handleWindowBlur)}handleWindowFocus=()=>{console.log("[CHAT-HISTORY] Window gained focus"),this.isTracking&&(console.log("[CHAT-HISTORY] User is tracking and focused -> marking messages as read"),this.unreadService.markAllAsRead())};handleWindowBlur=()=>{console.log("[CHAT-HISTORY] Window lost focus")};handleVoiceAnnouncement(e){if(!this.preferencesService.getVoiceAnnounceEnabled())return;let o=this.messages.slice(-e).filter(l=>l.role==="assistant");if(o.length===0){console.log("[CHAT-HISTORY] No new assistant messages to announce");return}let r=o[o.length-1];if(!r){console.warn("[CHAT-HISTORY] No last assistant message found");return}if(!this.isMessageRecentEnoughForAnnouncement(r)){console.log("[CHAT-HISTORY] Message too old for voice announcement");return}if(this.preferencesService.getVoiceMode()==="notification")console.log("[CHAT-HISTORY] Playing notification sound for new assistant message"),this.voiceSynthesisService.ding();else{let l=this.extractTextContentFromMessage(r);if(l.trim()){console.log("[CHAT-HISTORY] Announcing new assistant message via speech");let b=this.preferencesService.getVoiceReadFullText()?l:this.extractPartialText(l);this.voiceSynthesisService.speak(b).then(y=>{y||console.warn("[CHAT-HISTORY] Failed to announce message via speech")}).catch(y=>{console.error("[CHAT-HISTORY] Error during voice announcement:",y)})}}}isMessageRecentEnoughForAnnouncement(e){try{let t=e.timestamp.getTime();return Date.now()-t<=this.MESSAGE_FRESHNESS_THRESHOLD}catch(t){return console.warn("[CHAT-HISTORY] Error checking message freshness:",t),!0}}extractTextContentFromMessage(e){return e.content.filter(t=>t.type==="text").map(t=>t.content).join(`
|
|
87
|
-
|
|
88
|
-
`)}extractPartialText(e){return e.split(`
|
|
89
|
-
`).filter(a=>a.trim().length>0).reduce((a,l)=>{if(a.paragraphs>=3)return a;let u=l.length>80?1:0;return{paragraphs:a.paragraphs+u,text:a.text+(a.text?`
|
|
90
|
-
`:"")+l}},{paragraphs:0,text:""}).text||e}renderStreamingText(){return N(this,null,function*(){if(!this.streamingText){this.renderedStreamingText="";return}try{let e=yield this.markdownService.parse(this.streamingText);this.renderedStreamingText=this.sanitizer.bypassSecurityTrustHtml(e)}catch(e){console.error("[CHAT-HISTORY] Error rendering streaming text markdown:",e),this.renderedStreamingText=this.sanitizer.bypassSecurityTrustHtml(this.streamingText)}})}static \u0275fac=function(t){return new(t||i)};static \u0275cmp=R({type:i,selectors:[["app-chat-history"]],hostBindings:function(t,n){t&1&&w("scroll",function(){return n.onScroll()})},inputs:{messages:"messages",streamingText:"streamingText",isThinking:"isThinking",currentUsername:"currentUsername"},outputs:{copyRequested:"copyRequested",stopRequested:"stopRequested"},features:[ke],decls:6,vars:3,consts:[[1,"chat-history"],[1,"streaming-message","message","assistant"],["mat-fab","","color","primary","title","Go to bottom",1,"go-to-bottom-btn"],[3,"subThreadId","agentName"],[3,"message","canDelete","isOtherUser"],[3,"copyRequested","deleteRequested","message","canDelete","isOtherUser"],[1,"content","markdown-content",3,"innerHTML"],["mat-fab","","color","primary","title","Go to bottom",1,"go-to-bottom-btn",3,"click"],["fontSet","material-icons-outlined"]],template:function(t,n){t&1&&(c(0,"div",0),de(1,Tl,2,1,null,null,Cl),x(3,Sl,2,1,"div",1),x(4,kl,1,0,"app-thinking-loader"),x(5,Ml,3,0,"button",2),d()),t&2&&(p(),pe(n.messages),p(2),_(n.streamingText?3:-1),p(),_(n.isThinking?4:-1),p(),_(n.showGoToBottom?5:-1))},dependencies:[xt,J,Fn,cn,Rn],styles:[".streaming-message.assistant[_ngcontent-%COMP%]{background:transparent;border:none;box-shadow:none;border-radius:0;margin-left:0;margin-right:auto;padding:.5rem 0;width:100%;max-width:none;min-width:0}.streaming-message[_ngcontent-%COMP%] .content[_ngcontent-%COMP%]{color:var(--color-text);line-height:1.5}.go-to-bottom-btn[_ngcontent-%COMP%]{position:fixed!important;bottom:30%!important;right:1rem!important;z-index:1000!important}@media(max-width:768px){.go-to-bottom-btn[_ngcontent-%COMP%]{width:40px!important;height:40px!important;right:.75rem!important}.go-to-bottom-btn[_ngcontent-%COMP%] mat-icon[_ngcontent-%COMP%]{font-size:20px;width:20px;height:20px}}@media print{[_nghost-%COMP%]{display:block!important;height:auto!important;max-height:none!important;overflow:visible!important;position:static!important}.chat-history[_ngcontent-%COMP%]{display:block!important;height:auto!important;max-height:none!important;overflow:visible!important;position:static!important}.go-to-bottom-btn[_ngcontent-%COMP%]{display:none!important}}"]})};var El=["buttonContainer"],Ol=["freeTextInput"],Pl=(i,e)=>e.value;function Il(i,e){i&1&&(c(0,"mat-icon",10),f(1,"keyboard_return"),d())}function Al(i,e){if(i&1){let t=O();c(0,"button",8),w("click",function(){let o=T(t).$implicit,r=m(2);return S(r.onOptionClick(o.value))}),c(1,"span",9),f(2),d(),x(3,Il,2,0,"mat-icon",10),d()}if(i&2){let t=e.$implicit,n=e.$index,o=m(2);he("highlighted",n===o.highlightedIndex),M("disabled",t.disabled)("id","choice-option-"+n),Be("aria-selected",n===o.highlightedIndex),p(2),F(t.label),p(),_(n===o.highlightedIndex?3:-1)}}function Dl(i,e){if(i&1){let t=O();c(0,"div",6)(1,"span",11),f(2,"Or type your own answer:"),d(),c(3,"div",12)(4,"input",13,1),rn("ngModelChange",function(o){T(t);let r=m(2);return on(r.freeTextValue,o)||(r.freeTextValue=o),S(o)}),w("keydown",function(o){T(t);let r=m(2);return S(r.onFreeTextKeyDown(o))}),d(),c(6,"button",14),w("click",function(){T(t);let o=m(2);return S(o.onFreeTextSubmit())}),c(7,"mat-icon"),f(8,"send"),d()()()()}if(i&2){let t=m(2);p(4),nn("ngModel",t.freeTextValue),p(2),M("disabled",!t.freeTextValue.trim())}}function Rl(i,e){if(i&1&&(c(0,"div",7)(1,"mat-icon"),f(2,"search"),d(),c(3,"span"),f(4),d()()),i&2){let t=m(2);p(4),F(t.searchText)}}function Fl(i,e){if(i&1){let t=O();c(0,"div",2),I(1,"div",3),It(2,"async"),c(3,"div",4,0),w("keydown",function(o){T(t);let r=m();return S(r.onKeyDown(o))}),de(5,Al,4,7,"button",5,Pl),d(),x(7,Dl,9,2,"div",6),x(8,Rl,5,1,"div",7),d()}if(i&2){let t=m();p(),M("innerHTML",Ao(2,4,t.renderedLabel$),ue),p(2),Be("aria-activedescendant","choice-option-"+t.highlightedIndex),p(2),pe(t.options),p(2),_(t.allowFreeText?7:-1),p(),_(t.searchText?8:-1)}}var Hn=class i{options=[];allowFreeText=!1;set labelHtml(e){typeof e=="object"?this.renderedLabelSubject.next(e):this.renderLabelMarkdown(e)}isVisible=!1;choiceSelected=new H;buttonContainer;freeTextInput;highlightedIndex=0;searchText="";freeTextValue="";searchTimeout;destroy$=new xe;renderedLabelSubject=new Jt("");renderedLabel$=this.renderedLabelSubject.asObservable();sanitizer=g(Ee);markdownService=g(De);ngOnDestroy(){this.renderedLabelSubject.complete(),this.destroy$.next(),this.destroy$.complete(),this.searchTimeout&&clearTimeout(this.searchTimeout)}ngAfterViewInit(){this.isVisible&&this.buttonContainer&&setTimeout(()=>this.focusContainer(),100)}ngOnChanges(e){e.isVisible&&e.isVisible.currentValue&&!e.isVisible.previousValue&&(this.highlightedIndex=0,setTimeout(()=>this.focusContainer(),150)),e.options&&!e.options.firstChange&&(this.highlightedIndex=0,this.searchText="",this.freeTextValue="")}focusContainer(){this.buttonContainer?.nativeElement&&this.buttonContainer.nativeElement.focus()}onKeyDown(e){if(this.options.filter(n=>!n.disabled).length!==0)switch(e.key){case"ArrowDown":e.preventDefault(),this.moveHighlight(1);break;case"ArrowUp":e.preventDefault(),this.moveHighlight(-1);break;case"Enter":case" ":e.preventDefault(),this.selectHighlighted();break;case"Home":e.preventDefault(),this.highlightFirst();break;case"End":e.preventDefault(),this.highlightLast();break;case"Escape":e.preventDefault();break;default:e.key.length===1&&!e.ctrlKey&&!e.metaKey&&!e.altKey&&this.handleTypeAhead(e.key);break}}moveHighlight(e){let t=this.options.map((r,a)=>({opt:r,idx:a})).filter(({opt:r})=>!r.disabled).map(({idx:r})=>r);if(t.length===0)return;let o=t.findIndex(r=>r===this.highlightedIndex)+e;if(o>=0&&o<t.length){let r=t[o];r!==void 0&&(this.highlightedIndex=r,this.scrollToHighlighted())}else if(e===1&&o>=t.length){let r=t[0];r!==void 0&&(this.highlightedIndex=r,this.scrollToHighlighted())}else if(e===-1&&o<0){let r=t[t.length-1];r!==void 0&&(this.highlightedIndex=r,this.scrollToHighlighted())}}highlightFirst(){let e=this.options.findIndex(t=>!t.disabled);e>=0&&(this.highlightedIndex=e,this.scrollToHighlighted())}highlightLast(){let e=this.options.map((t,n)=>({opt:t,idx:n})).filter(({opt:t})=>!t.disabled).map(({idx:t})=>t);if(e.length>0){let t=e[e.length-1];t!==void 0&&(this.highlightedIndex=t,this.scrollToHighlighted())}}scrollToHighlighted(){setTimeout(()=>{let e=document.getElementById("choice-option-"+this.highlightedIndex);e&&e.scrollIntoView({block:"nearest",behavior:"smooth"})},0)}selectHighlighted(){let e=this.options[this.highlightedIndex];e&&!e.disabled&&this.onOptionClick(e.value)}handleTypeAhead(e){this.searchText+=e.toLowerCase();let t=this.options.findIndex(n=>!n.disabled&&n.label.toLowerCase().startsWith(this.searchText));t>=0&&(this.highlightedIndex=t,this.scrollToHighlighted()),this.searchTimeout&&clearTimeout(this.searchTimeout),this.searchTimeout=setTimeout(()=>{this.searchText=""},1e3)}onOptionClick(e){this.choiceSelected.emit(e)}onFreeTextSubmit(){let e=this.freeTextValue.trim();e&&(this.freeTextValue="",this.choiceSelected.emit(e))}onFreeTextKeyDown(e){e.key==="Enter"&&!e.shiftKey&&(e.preventDefault(),this.onFreeTextSubmit())}renderLabelMarkdown(e){return N(this,null,function*(){if(!e){this.renderedLabelSubject.next(this.sanitizer.bypassSecurityTrustHtml(""));return}try{let t=yield this.markdownService.parse(e);this.renderedLabelSubject.next(this.sanitizer.bypassSecurityTrustHtml(t))}catch(t){console.error("[CHOICE-SELECT] Error parsing label markdown:",t),this.renderedLabelSubject.next(this.sanitizer.bypassSecurityTrustHtml(e))}})}static \u0275fac=function(t){return new(t||i)};static \u0275cmp=R({type:i,selectors:[["app-choice-select"]],viewQuery:function(t,n){if(t&1&&ut(El,5)(Ol,5),t&2){let o;He(o=Ne())&&(n.buttonContainer=o.first),He(o=Ne())&&(n.freeTextInput=o.first)}},inputs:{options:"options",allowFreeText:"allowFreeText",labelHtml:"labelHtml",isVisible:"isVisible"},outputs:{choiceSelected:"choiceSelected"},features:[ke],decls:1,vars:1,consts:[["buttonContainer",""],["freeTextInput",""],[1,"choice-container"],[1,"choice-label",3,"innerHTML"],["role","listbox","tabindex","0",1,"choice-buttons",3,"keydown"],["type","button","role","option",1,"choice-button",3,"highlighted","disabled","id"],[1,"free-text-section"],[1,"search-indicator"],["type","button","role","option",1,"choice-button",3,"click","disabled","id"],[1,"choice-button-label"],[1,"choice-button-icon"],[1,"free-text-hint"],[1,"free-text-input-row"],["type","text","placeholder","Type a custom answer\u2026","aria-label","Custom answer",1,"free-text-input",3,"ngModelChange","keydown","ngModel"],["type","button","aria-label","Send custom answer",1,"free-text-send-btn",3,"click","disabled"]],template:function(t,n){t&1&&x(0,Fl,9,6,"div",2),t&2&&_(n.isVisible?0:-1)},dependencies:[me,J,fn,un,hn,gn,Do],styles:[".choice-container[_ngcontent-%COMP%]{width:100%;display:flex;flex-direction:column;gap:1rem}.choice-label[_ngcontent-%COMP%]{display:block;font-weight:500;color:var(--color-text);font-size:1rem;line-height:1.5}.choice-label[_ngcontent-%COMP%] p{margin:0 0 .5rem}.choice-label[_ngcontent-%COMP%] p:last-child{margin-bottom:0}.choice-label[_ngcontent-%COMP%] code{background:var(--color-code-bg);padding:.2em .4em;border-radius:4px;font-family:monospace;font-size:.9em}.choice-label[_ngcontent-%COMP%] strong{font-weight:600}.choice-buttons[_ngcontent-%COMP%]{display:flex;flex-direction:column;gap:.5rem;max-height:400px;overflow-y:auto;padding:.5rem;background:var(--color-background);border:2px solid var(--color-border);border-radius:12px;outline:none}.choice-buttons[_ngcontent-%COMP%]:focus-within{border-color:var(--color-primary);box-shadow:0 0 0 3px #007aff1a}.choice-buttons[_ngcontent-%COMP%]::-webkit-scrollbar{width:8px}.choice-buttons[_ngcontent-%COMP%]::-webkit-scrollbar-track{background:var(--color-background);border-radius:4px}.choice-buttons[_ngcontent-%COMP%]::-webkit-scrollbar-thumb{background:var(--color-border);border-radius:4px}.choice-buttons[_ngcontent-%COMP%]::-webkit-scrollbar-thumb:hover{background:var(--color-text-secondary)}.choice-button[_ngcontent-%COMP%]{display:flex;align-items:center;justify-content:space-between;width:100%;padding:.75rem 1rem;border:1px solid var(--color-border);border-radius:8px;background:var(--color-background);color:var(--color-text);font-family:-apple-system,BlinkMacSystemFont,SF Pro Display,system-ui,sans-serif;font-size:1rem;text-align:left;cursor:pointer;transition:all .2s ease}.choice-button[_ngcontent-%COMP%]:hover:not(:disabled):not(.highlighted){background:var(--color-bg-hover);border-color:var(--color-primary);transform:translate(2px)}.choice-button.highlighted[_ngcontent-%COMP%]{background:var(--color-primary);color:#fff;border-color:var(--color-primary);box-shadow:0 2px 8px #007aff4d}.choice-button.highlighted[_ngcontent-%COMP%] .choice-button-icon[_ngcontent-%COMP%]{color:#fff}.choice-button[_ngcontent-%COMP%]:disabled{opacity:.5;cursor:not-allowed}.choice-button[_ngcontent-%COMP%]:focus{outline:none}.choice-button-label[_ngcontent-%COMP%]{flex:1;line-height:1.5}.choice-button-icon[_ngcontent-%COMP%]{flex-shrink:0;margin-left:.5rem;font-size:1.2rem;width:1.2rem;height:1.2rem}.free-text-section[_ngcontent-%COMP%]{display:flex;flex-direction:column;gap:.5rem}.free-text-hint[_ngcontent-%COMP%]{font-size:.85rem;color:var(--color-text-secondary);font-style:italic}.free-text-input-row[_ngcontent-%COMP%]{display:flex;gap:.5rem;align-items:center}.free-text-input[_ngcontent-%COMP%]{flex:1;padding:.625rem .875rem;border:1px solid var(--color-border);border-radius:8px;background:var(--color-background);color:var(--color-text);font-family:-apple-system,BlinkMacSystemFont,SF Pro Display,system-ui,sans-serif;font-size:1rem;outline:none;transition:border-color .2s ease,box-shadow .2s ease}.free-text-input[_ngcontent-%COMP%]:focus{border-color:var(--color-primary);box-shadow:0 0 0 3px #007aff1a}.free-text-input[_ngcontent-%COMP%]::placeholder{color:var(--color-text-secondary);opacity:.7}.free-text-send-btn[_ngcontent-%COMP%]{display:flex;align-items:center;justify-content:center;width:2.5rem;height:2.5rem;flex-shrink:0;border:none;border-radius:8px;background:var(--color-primary);color:#fff;cursor:pointer;transition:background .2s ease,opacity .2s ease}.free-text-send-btn[_ngcontent-%COMP%]:hover:not(:disabled){opacity:.9}.free-text-send-btn[_ngcontent-%COMP%]:disabled{opacity:.4;cursor:not-allowed}.free-text-send-btn[_ngcontent-%COMP%] mat-icon[_ngcontent-%COMP%]{font-size:1.2rem;width:1.2rem;height:1.2rem}.search-indicator[_ngcontent-%COMP%]{display:flex;align-items:center;gap:.5rem;padding:.5rem 1rem;background:var(--color-primary);color:#fff;border-radius:8px;font-size:.9rem;font-weight:500;animation:_ngcontent-%COMP%_fadeIn .2s ease}.search-indicator[_ngcontent-%COMP%] mat-icon[_ngcontent-%COMP%]{font-size:1rem;width:1rem;height:1rem;color:#fff}@keyframes _ngcontent-%COMP%_fadeIn{0%{opacity:0;transform:translateY(-4px)}to{opacity:1;transform:translateY(0)}}@media(max-width:480px){.choice-container[_ngcontent-%COMP%]{gap:.75rem}.choice-label[_ngcontent-%COMP%]{font-size:.95rem}.choice-buttons[_ngcontent-%COMP%]{max-height:300px;gap:.375rem}.choice-button[_ngcontent-%COMP%]{font-size:.95rem;padding:.625rem .875rem}}@media print{.choice-buttons[_ngcontent-%COMP%]{max-height:none;overflow:visible}.search-indicator[_ngcontent-%COMP%]{display:none!important}}"]})};function Ll(i,e){if(i&1){let t=O();c(0,"div",0)(1,"div",1)(2,"mat-icon"),f(3,"lock_open"),d()(),c(4,"div",2)(5,"p",3),f(6,"Authorization required"),d(),c(7,"p",4)(8,"strong"),f(9),d(),f(10," needs your permission to continue. "),d()(),c(11,"div",5)(12,"button",6),w("click",function(){let o=T(t),r=m();return S(r.onCancel(o))}),f(13,"Cancel"),d(),c(14,"button",7),w("click",function(){let o=T(t),r=m();return S(r.onAuthorize(o))}),c(15,"mat-icon"),f(16,"open_in_new"),d(),f(17," Authorize "),d()()()}i&2&&(p(9),F(e.integrationName))}var Nn=class i{oauthService=g(vn);pendingRequest=bn(this.oauthService.pendingRequest$,{initialValue:null});onAuthorize(e){this.oauthService.openPopup(e)}onCancel(e){this.oauthService.cancelRequest(e)}static \u0275fac=function(t){return new(t||i)};static \u0275cmp=R({type:i,selectors:[["app-oauth-request-panel"]],decls:1,vars:1,consts:[[1,"oauth-panel"],[1,"oauth-icon"],[1,"oauth-content"],[1,"oauth-title"],[1,"oauth-description"],[1,"oauth-actions"],["type","button",1,"oauth-btn","oauth-btn--cancel",3,"click"],["type","button",1,"oauth-btn","oauth-btn--authorize",3,"click"]],template:function(t,n){if(t&1&&x(0,Ll,18,1,"div",0),t&2){let o;_((o=n.pendingRequest())?0:-1,o)}},dependencies:[me,J],styles:[".oauth-panel[_ngcontent-%COMP%]{display:flex;align-items:center;gap:1rem;padding:1rem;border:1px solid var(--color-border);border-radius:12px;background:var(--color-background);width:100%}@media(max-width:480px){.oauth-panel[_ngcontent-%COMP%]{flex-direction:column;align-items:flex-start}}.oauth-icon[_ngcontent-%COMP%]{flex-shrink:0;display:flex;align-items:center;justify-content:center;width:2.5rem;height:2.5rem;border-radius:50%;background:var(--color-primary);color:#fff}.oauth-icon[_ngcontent-%COMP%] mat-icon[_ngcontent-%COMP%]{font-size:1.25rem;width:1.25rem;height:1.25rem}.oauth-content[_ngcontent-%COMP%]{flex:1;min-width:0}.oauth-title[_ngcontent-%COMP%]{margin:0 0 .25rem;font-weight:600;font-size:.95rem;color:var(--color-text)}.oauth-description[_ngcontent-%COMP%]{margin:0;font-size:.875rem;color:var(--color-text-secondary)}.oauth-actions[_ngcontent-%COMP%]{display:flex;gap:.5rem;flex-shrink:0}.oauth-btn[_ngcontent-%COMP%]{display:inline-flex;align-items:center;gap:.375rem;padding:.5rem 1rem;border-radius:8px;border:1px solid var(--color-border);font-size:.9rem;font-family:inherit;cursor:pointer;transition:all .2s ease}.oauth-btn[_ngcontent-%COMP%] mat-icon[_ngcontent-%COMP%]{font-size:1rem;width:1rem;height:1rem}.oauth-btn--cancel[_ngcontent-%COMP%]{background:var(--color-background);color:var(--color-text-secondary)}.oauth-btn--cancel[_ngcontent-%COMP%]:hover{background:var(--color-bg-hover);color:var(--color-text)}.oauth-btn--authorize[_ngcontent-%COMP%]{background:var(--color-primary);color:#fff;border-color:var(--color-primary)}.oauth-btn--authorize[_ngcontent-%COMP%]:hover{opacity:.9}"],changeDetection:0})};var zn=class i{http=g(Me);projectState=g(Oe);threadState=g(Pe);getBaseUrl(){return`/api/projects/${this.projectState.getSelectedProjectIdOrThrow()}/threads/${this.threadState.getSelectedThreadIdOrThrow()}/files`}uploadFile(e){let t=this.projectState.getSelectedProjectIdOrThrow(),n=this.threadState.getSelectedThreadIdOrThrow();return new Kt(o=>{let r=new FileReader;r.onload=()=>{let l=r.result.split(",")[1];this.http.post(`/api/projects/${t}/threads/${n}/upload`,{content:l,mimeType:e.type||"application/octet-stream",filename:e.name}).subscribe({next:u=>{o.next({success:u.success,filename:u.filename}),o.complete()},error:u=>o.error(u)})},r.onerror=()=>o.error(new Error("Failed to read file")),r.readAsDataURL(e)})}listFiles(){return this.http.get(this.getBaseUrl()).pipe(Ve(e=>e.files))}downloadFile(e){let t=encodeURIComponent(e);return this.http.get(`${this.getBaseUrl()}/${t}`,{responseType:"blob"})}deleteFile(e){let t=encodeURIComponent(e);return this.http.delete(`${this.getBaseUrl()}/${t}`)}static \u0275fac=function(t){return new(t||i)};static \u0275prov=Y({token:i,factory:i.\u0275fac,providedIn:"root"})};var vt=class i{fileApi=g(zn);eventStream=g(_n);filesSignal=Ue([]);isLoadingSignal=Ue(!1);currentProjectSignal=Ue(null);currentThreadSignal=Ue(null);files=an(()=>this.filesSignal());isLoading=an(()=>this.isLoadingSignal());fileCount=an(()=>this.filesSignal().length);constructor(){this.subscribeToFileEvents()}initializeForThread(e,t){this.currentProjectSignal.set(e),this.currentThreadSignal.set(t),this.refreshFileList()}clear(){this.filesSignal.set([]),this.currentProjectSignal.set(null),this.currentThreadSignal.set(null)}refreshFileList(){this.isLoadingSignal.set(!0),this.fileApi.listFiles().subscribe({next:e=>{let t=e.map(n=>Te(j({},n),{lastModified:new Date(n.lastModified)})).sort((n,o)=>o.lastModified.getTime()-n.lastModified.getTime());this.filesSignal.set(t),this.isLoadingSignal.set(!1)},error:e=>{console.error("[FILE_EXCHANGE_STATE] Error loading files:",e),this.isLoadingSignal.set(!1)}})}uploadFile(e){return N(this,null,function*(){return new Promise(t=>{this.fileApi.uploadFile(e).subscribe({next:()=>{this.refreshFileList(),t({success:!0})},error:n=>{console.error("[FILE_EXCHANGE_STATE] Upload error:",n),t({success:!1,error:n.message||"Upload failed"})}})})})}downloadAllFiles(){let e=this.filesSignal();if(e.length===0){console.warn("[FILE_EXCHANGE_STATE] No files to download");return}e.forEach((t,n)=>{setTimeout(()=>{this.downloadFile(t.filename)},n*300)})}downloadFile(e){this.fileApi.downloadFile(e).subscribe({next:t=>{let n=window.URL.createObjectURL(t),o=document.createElement("a");o.href=n,o.download=e,o.click(),window.URL.revokeObjectURL(n)},error:t=>{console.error("[FILE_EXCHANGE_STATE] Download error:",t)}})}deleteFile(e){return N(this,null,function*(){return new Promise(t=>{this.fileApi.deleteFile(e).subscribe({next:()=>{this.refreshFileList(),t({success:!0})},error:n=>{console.error("[FILE_EXCHANGE_STATE] Delete error:",n),t({success:!1,error:n.message||"Delete failed"})}})})})}subscribeToFileEvents(){this.eventStream.events$.pipe(Se(e=>e instanceof xn),qo()).subscribe(e=>{this.handleFileEvent(e)})}handleFileEvent(e){let t=this.filesSignal();switch(e.operation){case"created":{let n=e.timestamp,o=e.timestamp.lastIndexOf("-");if(o>0){let a=e.timestamp.substring(o+1);a.length===5&&/^[a-z0-9]+$/.test(a)&&(n=e.timestamp.substring(0,o))}let r={filename:e.filename,size:e.size||0,lastModified:new Date(n)};this.filesSignal.set([r,...t]);break}case"updated":{let n=t.filter(u=>u.filename!==e.filename),o=t.find(u=>u.filename===e.filename),r=e.timestamp,a=e.timestamp.lastIndexOf("-");if(a>0){let u=e.timestamp.substring(a+1);u.length===5&&/^[a-z0-9]+$/.test(u)&&(r=e.timestamp.substring(0,a))}let l={filename:e.filename,size:e.size||o?.size||0,lastModified:new Date(r)};this.filesSignal.set([l,...n]);break}case"deleted":{let n=t.filter(o=>o.filename!==e.filename);this.filesSignal.set(n);break}}}static \u0275fac=function(t){return new(t||i)};static \u0275prov=Y({token:i,factory:i.\u0275fac,providedIn:"root"})};function Hl(i,e){if(i&1&&I(0,"div",1),i&2){let t=m();M("innerHTML",t.renderedContent,ue)}}function Nl(i,e){if(i&1&&I(0,"iframe",2),i&2){let t=m();M("srcdoc",t.content,ue)}}function zl(i,e){if(i&1&&(c(0,"pre",3),f(1),d()),i&2){let t=m();p(),F(t.content)}}var $n=class i{content="";format="text";renderedContent="";sanitizer=g(Ee);markdownService=g(De);ngOnChanges(e){(e.content||e.format)&&this.renderContent()}renderContent(){this.format==="markdown"?this.renderMarkdown():this.format==="json"&&this.formatJson()}renderMarkdown(){return N(this,null,function*(){try{let e=yield this.markdownService.parse(this.content);this.renderedContent=this.sanitizer.bypassSecurityTrustHtml(e)}catch(e){console.error("[CONTENT_RENDERER] Error rendering markdown:",e),this.content=this.content}})}formatJson(){try{let e=JSON.parse(this.content);this.content=JSON.stringify(e,null,2)}catch(e){console.error("[CONTENT_RENDERER] Error formatting JSON:",e)}}static \u0275fac=function(t){return new(t||i)};static \u0275cmp=R({type:i,selectors:[["app-content-renderer"]],inputs:{content:"content",format:"format"},features:[ke],decls:4,vars:2,consts:[[1,"content-renderer",3,"ngClass"],[1,"markdown-content",3,"innerHTML"],["sandbox","allow-same-origin",1,"html-viewer",3,"srcdoc"],[1,"code-content"]],template:function(t,n){t&1&&(c(0,"div",0),x(1,Hl,1,1,"div",1)(2,Nl,1,1,"iframe",2)(3,zl,2,1,"pre",3),d()),t&2&&(M("ngClass","format-"+n.format),p(),_(n.format==="markdown"?1:n.format==="html"?2:3))},dependencies:[fe,ln],styles:[".content-renderer[_ngcontent-%COMP%]{width:100%;height:100%;overflow:auto;padding:1rem}.markdown-content[_ngcontent-%COMP%]{line-height:1.6;color:var(--color-text)}.code-content[_ngcontent-%COMP%]{font-family:Monaco,Menlo,Ubuntu Mono,monospace;font-size:.9rem;line-height:1.5;margin:0;white-space:pre-wrap;word-wrap:break-word;color:var(--color-text)}.format-json[_ngcontent-%COMP%] .code-content[_ngcontent-%COMP%]{color:var(--color-code-text, #d63384)}.format-yaml[_ngcontent-%COMP%] .code-content[_ngcontent-%COMP%], .format-text[_ngcontent-%COMP%] .code-content[_ngcontent-%COMP%]{color:var(--color-text)}.html-viewer[_ngcontent-%COMP%]{width:100%;height:100%;min-height:400px;border:1px solid var(--color-border);border-radius:8px;background:#fff}"]})};var Ct=class i{http=g(Me);MAX_FILE_SIZE=20*1024*1024;isViewable(e){return e<=this.MAX_FILE_SIZE}isFormatViewable(e){let t=e.split(".").pop()?.toLowerCase();return!(t&&["pdf","png","jpg","jpeg","gif","webp","zip","tar","gz","exe","bin","doc","docx","xls","xlsx","ppt","pptx"].includes(t))}detectFormat(e){switch(e.split(".").pop()?.toLowerCase()){case"md":return"markdown";case"json":return"json";case"yaml":case"yml":return"yaml";case"html":case"htm":return"html";default:return"text"}}loadFileContent(e,t,n){let o=`/api/projects/${e}/threads/${t}/files/${encodeURIComponent(n)}`,r=this.detectFormat(n);return this.http.get(o,{responseType:"text",observe:"response"}).pipe(Ve(a=>{let l=a.body||"",u=new Blob([l]).size;return{content:l,format:r,filename:n,size:u}}),en(a=>(console.error("[CONTENT_VIEWER] Error loading file:",n,a),go(()=>new Error(`Failed to load file: ${a.message||"Unknown error"}`)))))}formatSize(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}static \u0275fac=function(t){return new(t||i)};static \u0275prov=Y({token:i,factory:i.\u0275fac,providedIn:"root"})};function $l(i,e){if(i&1){let t=O();c(0,"button",12),w("click",function(){T(t);let o=m();return S(o.download())}),c(1,"mat-icon"),f(2,"download"),d()()}}function Vl(i,e){i&1&&(c(0,"div",9),I(1,"mat-spinner",13),c(2,"p"),f(3,"Loading file content..."),d()())}function Ul(i,e){if(i&1){let t=O();c(0,"div",10)(1,"mat-icon",14),f(2,"error_outline"),d(),c(3,"p",15),f(4),d(),c(5,"button",16),w("click",function(){T(t);let o=m();return S(o.download())}),c(6,"mat-icon"),f(7,"download"),d(),f(8," Download instead "),d()()}if(i&2){let t=m();p(4),F(t.error)}}function Bl(i,e){if(i&1&&I(0,"app-content-renderer",11),i&2){let t=m();M("content",t.fileContent.content)("format",t.fileContent.format)}}var Vn=class i{destroy$=new xe;file;projectName;threadId;closeViewer=new H;contentService=g(Ct);eventStream=g(_n);fileContent=null;isLoading=!1;error="";ngOnInit(){this.loadContent(),this.subscribeToFileEvents()}ngOnDestroy(){this.destroy$.next(),this.destroy$.complete()}loadContent(){if(!this.contentService.isViewable(this.file.size)){this.error=`File too large to view (${this.contentService.formatSize(this.file.size)}). Maximum size: 20 MB.`;return}this.isLoading=!0,this.error="",this.contentService.loadFileContent(this.projectName,this.threadId,this.file.filename).subscribe({next:e=>{console.log("[CONTENT_VIEWER] Content loaded:",e.filename),this.fileContent=e,this.isLoading=!1},error:e=>{console.error("[CONTENT_VIEWER] Error loading content:",e),this.error=e.message||"Failed to load file content",this.isLoading=!1}})}onClose(){this.closeViewer.emit()}download(){let e=new Blob([this.fileContent?.content||""],{type:"text/plain"}),t=window.URL.createObjectURL(e),n=document.createElement("a");n.href=t,n.download=this.file.filename,n.click(),window.URL.revokeObjectURL(t)}formatSize(e){return this.contentService.formatSize(e)}subscribeToFileEvents(){this.eventStream.events$.pipe(Se(e=>e instanceof xn),Se(e=>e.filename===this.file.filename),Se(e=>e.operation==="updated"),K(this.destroy$)).subscribe(e=>{console.log("[CONTENT_VIEWER] File updated event received, reloading:",e.filename),e.size&&(this.file.size=e.size),this.loadContent()})}static \u0275fac=function(t){return new(t||i)};static \u0275cmp=R({type:i,selectors:[["app-content-viewer"]],inputs:{file:"file",projectName:"projectName",threadId:"threadId"},outputs:{closeViewer:"closeViewer"},decls:16,vars:6,consts:[[1,"viewer-container"],[1,"viewer-header"],[1,"header-info"],[1,"filename"],[1,"file-size"],[1,"header-actions"],["mat-icon-button","","title","Download","type","button"],["mat-icon-button","","title","Close","type","button",3,"click"],[1,"viewer-content"],[1,"loading-state"],[1,"error-state"],[3,"content","format"],["mat-icon-button","","title","Download","type","button",3,"click"],["diameter","48"],[1,"error-icon"],[1,"error-message"],["mat-raised-button","","color","primary","type","button",3,"click"]],template:function(t,n){t&1&&(c(0,"div",0)(1,"div",1)(2,"div",2)(3,"span",3),f(4),d(),c(5,"span",4),f(6),d()(),c(7,"div",5),x(8,$l,3,0,"button",6),c(9,"button",7),w("click",function(){return n.onClose()}),c(10,"mat-icon"),f(11,"chevron_right"),d()()()(),c(12,"div",8),x(13,Vl,4,0,"div",9),x(14,Ul,9,1,"div",10),x(15,Bl,1,2,"app-content-renderer",11),d()()),t&2&&(p(4),F(n.file.filename),p(2),F(n.formatSize(n.file.size)),p(2),_(n.fileContent&&!n.isLoading&&!n.error?8:-1),p(5),_(n.isLoading?13:-1),p(),_(n.error?14:-1),p(),_(n.fileContent&&!n.isLoading&&!n.error?15:-1))},dependencies:[fe,me,J,We,Bo,je,mn,pn,$n],styles:["[_nghost-%COMP%]{display:flex;flex-direction:column;flex:1;min-height:0;height:100%}.viewer-container[_ngcontent-%COMP%]{display:flex;flex-direction:column;flex:1;min-height:0;height:100%;background:var(--color-bg)}.viewer-header[_ngcontent-%COMP%]{display:flex;align-items:center;gap:.5rem;padding:1rem;border-bottom:1px solid var(--color-border);background:var(--color-bg);flex-shrink:0}.header-info[_ngcontent-%COMP%]{flex:1;min-width:0;display:flex;flex-direction:column;gap:.25rem}.filename[_ngcontent-%COMP%]{font-weight:500;color:var(--color-text);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.file-size[_ngcontent-%COMP%]{font-size:.75rem;color:var(--color-text-secondary)}.header-actions[_ngcontent-%COMP%]{display:flex;gap:.25rem;flex-shrink:0}.viewer-content[_ngcontent-%COMP%]{flex:1;overflow:auto;background:var(--color-bg)}.loading-state[_ngcontent-%COMP%]{display:flex;flex-direction:column;align-items:center;justify-content:center;height:100%;gap:1rem;color:var(--color-text-secondary)}.error-state[_ngcontent-%COMP%]{display:flex;flex-direction:column;align-items:center;justify-content:center;height:100%;gap:1rem;padding:2rem;text-align:center}.error-icon[_ngcontent-%COMP%]{font-size:3rem;width:3rem;height:3rem;color:var(--color-error)}.error-message[_ngcontent-%COMP%]{color:var(--color-text);margin:0;max-width:400px}"]})};var jl=Math.pow(10,8)*24*60*60*1e3,ah=-jl,Un=6048e5,Vr=864e5;var Wl=3600;var Ur=Wl*24,sh=Ur*7,ql=Ur*365.2425,Yl=ql/12,lh=Yl*3,zi=Symbol.for("constructDateFrom");function G(i,e){return typeof i=="function"?i(e):i&&typeof i=="object"&&zi in i?i[zi](e):i instanceof Date?new i.constructor(e):new Date(e)}function U(i,e){return G(e||i,i)}function Br(i,e,t){let n=U(i,t?.in);return isNaN(e)?G(t?.in||i,NaN):(e&&n.setDate(n.getDate()+e),n)}var Gl={};function Ge(){return Gl}function ze(i,e){let t=Ge(),n=e?.weekStartsOn??e?.locale?.options?.weekStartsOn??t.weekStartsOn??t.locale?.options?.weekStartsOn??0,o=U(i,e?.in),r=o.getDay(),a=(r<n?7:0)+r-n;return o.setDate(o.getDate()-a),o.setHours(0,0,0,0),o}function it(i,e){return ze(i,Te(j({},e),{weekStartsOn:1}))}function Bn(i,e){let t=U(i,e?.in),n=t.getFullYear(),o=G(t,0);o.setFullYear(n+1,0,4),o.setHours(0,0,0,0);let r=it(o),a=G(t,0);a.setFullYear(n,0,4),a.setHours(0,0,0,0);let l=it(a);return t.getTime()>=r.getTime()?n+1:t.getTime()>=l.getTime()?n:n-1}function $i(i){let e=U(i),t=new Date(Date.UTC(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds()));return t.setUTCFullYear(e.getFullYear()),+i-+t}function yt(i,...e){let t=G.bind(null,i||e.find(n=>typeof n=="object"));return e.map(t)}function wt(i,e){let t=U(i,e?.in);return t.setHours(0,0,0,0),t}function jn(i,e,t){let[n,o]=yt(t?.in,i,e),r=wt(n),a=wt(o),l=+r-$i(r),u=+a-$i(a);return Math.round((l-u)/Vr)}function jr(i,e){let t=Bn(i,e),n=G(e?.in||i,0);return n.setFullYear(t,0,4),n.setHours(0,0,0,0),it(n)}function Wr(i){return G(i,Date.now())}function qr(i,e,t){let[n,o]=yt(t?.in,i,e);return+wt(n)==+wt(o)}function Yr(i){return i instanceof Date||typeof i=="object"&&Object.prototype.toString.call(i)==="[object Date]"}function Gr(i){return!(!Yr(i)&&typeof i!="number"||isNaN(+U(i)))}function Qr(i,e,t){let[n,o]=yt(t?.in,i,e),r=Xr(n,o),a=Math.abs(jn(n,o));n.setDate(n.getDate()-r*a);let l=+(Xr(n,o)===-r),u=r*(a-l);return u===0?0:u}function Xr(i,e){let t=i.getFullYear()-e.getFullYear()||i.getMonth()-e.getMonth()||i.getDate()-e.getDate()||i.getHours()-e.getHours()||i.getMinutes()-e.getMinutes()||i.getSeconds()-e.getSeconds()||i.getMilliseconds()-e.getMilliseconds();return t<0?-1:t>0?1:t}function Zr(i,e){let t=U(i,e?.in);return t.setFullYear(t.getFullYear(),0,1),t.setHours(0,0,0,0),t}var Xl={lessThanXSeconds:{one:"less than a second",other:"less than {{count}} seconds"},xSeconds:{one:"1 second",other:"{{count}} seconds"},halfAMinute:"half a minute",lessThanXMinutes:{one:"less than a minute",other:"less than {{count}} minutes"},xMinutes:{one:"1 minute",other:"{{count}} minutes"},aboutXHours:{one:"about 1 hour",other:"about {{count}} hours"},xHours:{one:"1 hour",other:"{{count}} hours"},xDays:{one:"1 day",other:"{{count}} days"},aboutXWeeks:{one:"about 1 week",other:"about {{count}} weeks"},xWeeks:{one:"1 week",other:"{{count}} weeks"},aboutXMonths:{one:"about 1 month",other:"about {{count}} months"},xMonths:{one:"1 month",other:"{{count}} months"},aboutXYears:{one:"about 1 year",other:"about {{count}} years"},xYears:{one:"1 year",other:"{{count}} years"},overXYears:{one:"over 1 year",other:"over {{count}} years"},almostXYears:{one:"almost 1 year",other:"almost {{count}} years"}},Kr=(i,e,t)=>{let n,o=Xl[i];return typeof o=="string"?n=o:e===1?n=o.one:n=o.other.replace("{{count}}",e.toString()),t?.addSuffix?t.comparison&&t.comparison>0?"in "+n:n+" ago":n};function Wn(i){return(e={})=>{let t=e.width?String(e.width):i.defaultWidth;return i.formats[t]||i.formats[i.defaultWidth]}}var Ql={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},Zl={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},Kl={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},Jr={date:Wn({formats:Ql,defaultWidth:"full"}),time:Wn({formats:Zl,defaultWidth:"full"}),dateTime:Wn({formats:Kl,defaultWidth:"full"})};var Jl={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},ea=(i,e,t,n)=>Jl[i];function Tt(i){return(e,t)=>{let n=t?.context?String(t.context):"standalone",o;if(n==="formatting"&&i.formattingValues){let a=i.defaultFormattingWidth||i.defaultWidth,l=t?.width?String(t.width):a;o=i.formattingValues[l]||i.formattingValues[a]}else{let a=i.defaultWidth,l=t?.width?String(t.width):i.defaultWidth;o=i.values[l]||i.values[a]}let r=i.argumentCallback?i.argumentCallback(e):e;return o[r]}}var ec={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},tc={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},nc={narrow:["J","F","M","A","M","J","J","A","S","O","N","D"],abbreviated:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],wide:["January","February","March","April","May","June","July","August","September","October","November","December"]},ic={narrow:["S","M","T","W","T","F","S"],short:["Su","Mo","Tu","We","Th","Fr","Sa"],abbreviated:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],wide:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]},oc={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"}},rc={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"}},ac=(i,e)=>{let t=Number(i),n=t%100;if(n>20||n<10)switch(n%10){case 1:return t+"st";case 2:return t+"nd";case 3:return t+"rd"}return t+"th"},ta={ordinalNumber:ac,era:Tt({values:ec,defaultWidth:"wide"}),quarter:Tt({values:tc,defaultWidth:"wide",argumentCallback:i=>i-1}),month:Tt({values:nc,defaultWidth:"wide"}),day:Tt({values:ic,defaultWidth:"wide"}),dayPeriod:Tt({values:oc,defaultWidth:"wide",formattingValues:rc,defaultFormattingWidth:"wide"})};function St(i){return(e,t={})=>{let n=t.width,o=n&&i.matchPatterns[n]||i.matchPatterns[i.defaultMatchWidth],r=e.match(o);if(!r)return null;let a=r[0],l=n&&i.parsePatterns[n]||i.parsePatterns[i.defaultParseWidth],u=Array.isArray(l)?lc(l,k=>k.test(a)):sc(l,k=>k.test(a)),b;b=i.valueCallback?i.valueCallback(u):u,b=t.valueCallback?t.valueCallback(b):b;let y=e.slice(a.length);return{value:b,rest:y}}}function sc(i,e){for(let t in i)if(Object.prototype.hasOwnProperty.call(i,t)&&e(i[t]))return t}function lc(i,e){for(let t=0;t<i.length;t++)if(e(i[t]))return t}function na(i){return(e,t={})=>{let n=e.match(i.matchPattern);if(!n)return null;let o=n[0],r=e.match(i.parsePattern);if(!r)return null;let a=i.valueCallback?i.valueCallback(r[0]):r[0];a=t.valueCallback?t.valueCallback(a):a;let l=e.slice(o.length);return{value:a,rest:l}}}var cc=/^(\d+)(th|st|nd|rd)?/i,dc=/\d+/i,pc={narrow:/^(b|a)/i,abbreviated:/^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i,wide:/^(before christ|before common era|anno domini|common era)/i},mc={any:[/^b/i,/^(a|c)/i]},uc={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},hc={any:[/1/i,/2/i,/3/i,/4/i]},gc={narrow:/^[jfmasond]/i,abbreviated:/^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,wide:/^(january|february|march|april|may|june|july|august|september|october|november|december)/i},fc={narrow:[/^j/i,/^f/i,/^m/i,/^a/i,/^m/i,/^j/i,/^j/i,/^a/i,/^s/i,/^o/i,/^n/i,/^d/i],any:[/^ja/i,/^f/i,/^mar/i,/^ap/i,/^may/i,/^jun/i,/^jul/i,/^au/i,/^s/i,/^o/i,/^n/i,/^d/i]},bc={narrow:/^[smtwf]/i,short:/^(su|mo|tu|we|th|fr|sa)/i,abbreviated:/^(sun|mon|tue|wed|thu|fri|sat)/i,wide:/^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i},xc={narrow:[/^s/i,/^m/i,/^t/i,/^w/i,/^t/i,/^f/i,/^s/i],any:[/^su/i,/^m/i,/^tu/i,/^w/i,/^th/i,/^f/i,/^sa/i]},_c={narrow:/^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,any:/^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i},vc={any:{am:/^a/i,pm:/^p/i,midnight:/^mi/i,noon:/^no/i,morning:/morning/i,afternoon:/afternoon/i,evening:/evening/i,night:/night/i}},ia={ordinalNumber:na({matchPattern:cc,parsePattern:dc,valueCallback:i=>parseInt(i,10)}),era:St({matchPatterns:pc,defaultMatchWidth:"wide",parsePatterns:mc,defaultParseWidth:"any"}),quarter:St({matchPatterns:uc,defaultMatchWidth:"wide",parsePatterns:hc,defaultParseWidth:"any",valueCallback:i=>i+1}),month:St({matchPatterns:gc,defaultMatchWidth:"wide",parsePatterns:fc,defaultParseWidth:"any"}),day:St({matchPatterns:bc,defaultMatchWidth:"wide",parsePatterns:xc,defaultParseWidth:"any"}),dayPeriod:St({matchPatterns:_c,defaultMatchWidth:"any",parsePatterns:vc,defaultParseWidth:"any"})};var Vi={code:"en-US",formatDistance:Kr,formatLong:Jr,formatRelative:ea,localize:ta,match:ia,options:{weekStartsOn:0,firstWeekContainsDate:1}};function oa(i,e){let t=U(i,e?.in);return jn(t,Zr(t))+1}function ra(i,e){let t=U(i,e?.in),n=+it(t)-+jr(t);return Math.round(n/Un)+1}function qn(i,e){let t=U(i,e?.in),n=t.getFullYear(),o=Ge(),r=e?.firstWeekContainsDate??e?.locale?.options?.firstWeekContainsDate??o.firstWeekContainsDate??o.locale?.options?.firstWeekContainsDate??1,a=G(e?.in||i,0);a.setFullYear(n+1,0,r),a.setHours(0,0,0,0);let l=ze(a,e),u=G(e?.in||i,0);u.setFullYear(n,0,r),u.setHours(0,0,0,0);let b=ze(u,e);return+t>=+l?n+1:+t>=+b?n:n-1}function aa(i,e){let t=Ge(),n=e?.firstWeekContainsDate??e?.locale?.options?.firstWeekContainsDate??t.firstWeekContainsDate??t.locale?.options?.firstWeekContainsDate??1,o=qn(i,e),r=G(e?.in||i,0);return r.setFullYear(o,0,n),r.setHours(0,0,0,0),ze(r,e)}function sa(i,e){let t=U(i,e?.in),n=+ze(t,e)-+aa(t,e);return Math.round(n/Un)+1}function D(i,e){let t=i<0?"-":"",n=Math.abs(i).toString().padStart(e,"0");return t+n}var $e={y(i,e){let t=i.getFullYear(),n=t>0?t:1-t;return D(e==="yy"?n%100:n,e.length)},M(i,e){let t=i.getMonth();return e==="M"?String(t+1):D(t+1,2)},d(i,e){return D(i.getDate(),e.length)},a(i,e){let t=i.getHours()/12>=1?"pm":"am";switch(e){case"a":case"aa":return t.toUpperCase();case"aaa":return t;case"aaaaa":return t[0];default:return t==="am"?"a.m.":"p.m."}},h(i,e){return D(i.getHours()%12||12,e.length)},H(i,e){return D(i.getHours(),e.length)},m(i,e){return D(i.getMinutes(),e.length)},s(i,e){return D(i.getSeconds(),e.length)},S(i,e){let t=e.length,n=i.getMilliseconds(),o=Math.trunc(n*Math.pow(10,t-3));return D(o,e.length)}};var kt={am:"am",pm:"pm",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},Ui={G:function(i,e,t){let n=i.getFullYear()>0?1:0;switch(e){case"G":case"GG":case"GGG":return t.era(n,{width:"abbreviated"});case"GGGGG":return t.era(n,{width:"narrow"});default:return t.era(n,{width:"wide"})}},y:function(i,e,t){if(e==="yo"){let n=i.getFullYear(),o=n>0?n:1-n;return t.ordinalNumber(o,{unit:"year"})}return $e.y(i,e)},Y:function(i,e,t,n){let o=qn(i,n),r=o>0?o:1-o;if(e==="YY"){let a=r%100;return D(a,2)}return e==="Yo"?t.ordinalNumber(r,{unit:"year"}):D(r,e.length)},R:function(i,e){let t=Bn(i);return D(t,e.length)},u:function(i,e){let t=i.getFullYear();return D(t,e.length)},Q:function(i,e,t){let n=Math.ceil((i.getMonth()+1)/3);switch(e){case"Q":return String(n);case"QQ":return D(n,2);case"Qo":return t.ordinalNumber(n,{unit:"quarter"});case"QQQ":return t.quarter(n,{width:"abbreviated",context:"formatting"});case"QQQQQ":return t.quarter(n,{width:"narrow",context:"formatting"});default:return t.quarter(n,{width:"wide",context:"formatting"})}},q:function(i,e,t){let n=Math.ceil((i.getMonth()+1)/3);switch(e){case"q":return String(n);case"qq":return D(n,2);case"qo":return t.ordinalNumber(n,{unit:"quarter"});case"qqq":return t.quarter(n,{width:"abbreviated",context:"standalone"});case"qqqqq":return t.quarter(n,{width:"narrow",context:"standalone"});default:return t.quarter(n,{width:"wide",context:"standalone"})}},M:function(i,e,t){let n=i.getMonth();switch(e){case"M":case"MM":return $e.M(i,e);case"Mo":return t.ordinalNumber(n+1,{unit:"month"});case"MMM":return t.month(n,{width:"abbreviated",context:"formatting"});case"MMMMM":return t.month(n,{width:"narrow",context:"formatting"});default:return t.month(n,{width:"wide",context:"formatting"})}},L:function(i,e,t){let n=i.getMonth();switch(e){case"L":return String(n+1);case"LL":return D(n+1,2);case"Lo":return t.ordinalNumber(n+1,{unit:"month"});case"LLL":return t.month(n,{width:"abbreviated",context:"standalone"});case"LLLLL":return t.month(n,{width:"narrow",context:"standalone"});default:return t.month(n,{width:"wide",context:"standalone"})}},w:function(i,e,t,n){let o=sa(i,n);return e==="wo"?t.ordinalNumber(o,{unit:"week"}):D(o,e.length)},I:function(i,e,t){let n=ra(i);return e==="Io"?t.ordinalNumber(n,{unit:"week"}):D(n,e.length)},d:function(i,e,t){return e==="do"?t.ordinalNumber(i.getDate(),{unit:"date"}):$e.d(i,e)},D:function(i,e,t){let n=oa(i);return e==="Do"?t.ordinalNumber(n,{unit:"dayOfYear"}):D(n,e.length)},E:function(i,e,t){let n=i.getDay();switch(e){case"E":case"EE":case"EEE":return t.day(n,{width:"abbreviated",context:"formatting"});case"EEEEE":return t.day(n,{width:"narrow",context:"formatting"});case"EEEEEE":return t.day(n,{width:"short",context:"formatting"});default:return t.day(n,{width:"wide",context:"formatting"})}},e:function(i,e,t,n){let o=i.getDay(),r=(o-n.weekStartsOn+8)%7||7;switch(e){case"e":return String(r);case"ee":return D(r,2);case"eo":return t.ordinalNumber(r,{unit:"day"});case"eee":return t.day(o,{width:"abbreviated",context:"formatting"});case"eeeee":return t.day(o,{width:"narrow",context:"formatting"});case"eeeeee":return t.day(o,{width:"short",context:"formatting"});default:return t.day(o,{width:"wide",context:"formatting"})}},c:function(i,e,t,n){let o=i.getDay(),r=(o-n.weekStartsOn+8)%7||7;switch(e){case"c":return String(r);case"cc":return D(r,e.length);case"co":return t.ordinalNumber(r,{unit:"day"});case"ccc":return t.day(o,{width:"abbreviated",context:"standalone"});case"ccccc":return t.day(o,{width:"narrow",context:"standalone"});case"cccccc":return t.day(o,{width:"short",context:"standalone"});default:return t.day(o,{width:"wide",context:"standalone"})}},i:function(i,e,t){let n=i.getDay(),o=n===0?7:n;switch(e){case"i":return String(o);case"ii":return D(o,e.length);case"io":return t.ordinalNumber(o,{unit:"day"});case"iii":return t.day(n,{width:"abbreviated",context:"formatting"});case"iiiii":return t.day(n,{width:"narrow",context:"formatting"});case"iiiiii":return t.day(n,{width:"short",context:"formatting"});default:return t.day(n,{width:"wide",context:"formatting"})}},a:function(i,e,t){let o=i.getHours()/12>=1?"pm":"am";switch(e){case"a":case"aa":return t.dayPeriod(o,{width:"abbreviated",context:"formatting"});case"aaa":return t.dayPeriod(o,{width:"abbreviated",context:"formatting"}).toLowerCase();case"aaaaa":return t.dayPeriod(o,{width:"narrow",context:"formatting"});default:return t.dayPeriod(o,{width:"wide",context:"formatting"})}},b:function(i,e,t){let n=i.getHours(),o;switch(n===12?o=kt.noon:n===0?o=kt.midnight:o=n/12>=1?"pm":"am",e){case"b":case"bb":return t.dayPeriod(o,{width:"abbreviated",context:"formatting"});case"bbb":return t.dayPeriod(o,{width:"abbreviated",context:"formatting"}).toLowerCase();case"bbbbb":return t.dayPeriod(o,{width:"narrow",context:"formatting"});default:return t.dayPeriod(o,{width:"wide",context:"formatting"})}},B:function(i,e,t){let n=i.getHours(),o;switch(n>=17?o=kt.evening:n>=12?o=kt.afternoon:n>=4?o=kt.morning:o=kt.night,e){case"B":case"BB":case"BBB":return t.dayPeriod(o,{width:"abbreviated",context:"formatting"});case"BBBBB":return t.dayPeriod(o,{width:"narrow",context:"formatting"});default:return t.dayPeriod(o,{width:"wide",context:"formatting"})}},h:function(i,e,t){if(e==="ho"){let n=i.getHours()%12;return n===0&&(n=12),t.ordinalNumber(n,{unit:"hour"})}return $e.h(i,e)},H:function(i,e,t){return e==="Ho"?t.ordinalNumber(i.getHours(),{unit:"hour"}):$e.H(i,e)},K:function(i,e,t){let n=i.getHours()%12;return e==="Ko"?t.ordinalNumber(n,{unit:"hour"}):D(n,e.length)},k:function(i,e,t){let n=i.getHours();return n===0&&(n=24),e==="ko"?t.ordinalNumber(n,{unit:"hour"}):D(n,e.length)},m:function(i,e,t){return e==="mo"?t.ordinalNumber(i.getMinutes(),{unit:"minute"}):$e.m(i,e)},s:function(i,e,t){return e==="so"?t.ordinalNumber(i.getSeconds(),{unit:"second"}):$e.s(i,e)},S:function(i,e){return $e.S(i,e)},X:function(i,e,t){let n=i.getTimezoneOffset();if(n===0)return"Z";switch(e){case"X":return ca(n);case"XXXX":case"XX":return ot(n);default:return ot(n,":")}},x:function(i,e,t){let n=i.getTimezoneOffset();switch(e){case"x":return ca(n);case"xxxx":case"xx":return ot(n);default:return ot(n,":")}},O:function(i,e,t){let n=i.getTimezoneOffset();switch(e){case"O":case"OO":case"OOO":return"GMT"+la(n,":");default:return"GMT"+ot(n,":")}},z:function(i,e,t){let n=i.getTimezoneOffset();switch(e){case"z":case"zz":case"zzz":return"GMT"+la(n,":");default:return"GMT"+ot(n,":")}},t:function(i,e,t){let n=Math.trunc(+i/1e3);return D(n,e.length)},T:function(i,e,t){return D(+i,e.length)}};function la(i,e=""){let t=i>0?"-":"+",n=Math.abs(i),o=Math.trunc(n/60),r=n%60;return r===0?t+String(o):t+String(o)+e+D(r,2)}function ca(i,e){return i%60===0?(i>0?"-":"+")+D(Math.abs(i)/60,2):ot(i,e)}function ot(i,e=""){let t=i>0?"-":"+",n=Math.abs(i),o=D(Math.trunc(n/60),2),r=D(n%60,2);return t+o+e+r}var da=(i,e)=>{switch(i){case"P":return e.date({width:"short"});case"PP":return e.date({width:"medium"});case"PPP":return e.date({width:"long"});default:return e.date({width:"full"})}},pa=(i,e)=>{switch(i){case"p":return e.time({width:"short"});case"pp":return e.time({width:"medium"});case"ppp":return e.time({width:"long"});default:return e.time({width:"full"})}},Cc=(i,e)=>{let t=i.match(/(P+)(p+)?/)||[],n=t[1],o=t[2];if(!o)return da(i,e);let r;switch(n){case"P":r=e.dateTime({width:"short"});break;case"PP":r=e.dateTime({width:"medium"});break;case"PPP":r=e.dateTime({width:"long"});break;default:r=e.dateTime({width:"full"});break}return r.replace("{{date}}",da(n,e)).replace("{{time}}",pa(o,e))},ma={p:pa,P:Cc};var yc=/^D+$/,wc=/^Y+$/,Tc=["D","DD","YY","YYYY"];function ua(i){return yc.test(i)}function ha(i){return wc.test(i)}function ga(i,e,t){let n=Sc(i,e,t);if(console.warn(n),Tc.includes(i))throw new RangeError(n)}function Sc(i,e,t){let n=i[0]==="Y"?"years":"days of the month";return`Use \`${i.toLowerCase()}\` instead of \`${i}\` (in \`${e}\`) for formatting ${n} to the input \`${t}\`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md`}var kc=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,Mc=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,Ec=/^'([^]*?)'?$/,Oc=/''/g,Pc=/[a-zA-Z]/;function Bi(i,e,t){let n=Ge(),o=t?.locale??n.locale??Vi,r=t?.firstWeekContainsDate??t?.locale?.options?.firstWeekContainsDate??n.firstWeekContainsDate??n.locale?.options?.firstWeekContainsDate??1,a=t?.weekStartsOn??t?.locale?.options?.weekStartsOn??n.weekStartsOn??n.locale?.options?.weekStartsOn??0,l=U(i,t?.in);if(!Gr(l))throw new RangeError("Invalid time value");let u=e.match(Mc).map(y=>{let k=y[0];if(k==="p"||k==="P"){let P=ma[k];return P(y,o.formatLong)}return y}).join("").match(kc).map(y=>{if(y==="''")return{isToken:!1,value:"'"};let k=y[0];if(k==="'")return{isToken:!1,value:Ic(y)};if(Ui[k])return{isToken:!0,value:y};if(k.match(Pc))throw new RangeError("Format string contains an unescaped latin alphabet character `"+k+"`");return{isToken:!1,value:y}});o.localize.preprocessor&&(u=o.localize.preprocessor(l,u));let b={firstWeekContainsDate:r,weekStartsOn:a,locale:o};return u.map(y=>{if(!y.isToken)return y.value;let k=y.value;(!t?.useAdditionalWeekYearTokens&&ha(k)||!t?.useAdditionalDayOfYearTokens&&ua(k))&&ga(k,e,String(i));let P=Ui[k[0]];return P(l,k,o.localize,b)}).join("")}function Ic(i){let e=i.match(Ec);return e?e[1].replace(Oc,"'"):i}function fa(i,e,t){return Br(i,-e,t)}function ba(i,e){return qr(G(e?.in||i,i),fa(Wr(e?.in||i),1))}function xa(i){if(!i||isNaN(i.getTime()))return"unknown";let e=new Date,t=Bi(i,"HH:mm:ss"),n=e.getTime()-i.getTime(),o=Math.floor(n/(1e3*60));if(o<1)return`just now (${t})`;if(o<60)return`${o} min ago (${t})`;let r=Math.floor(n/(1e3*60*60));if(r<24)return`${r}h ago (${t})`;if(ba(i))return`yesterday ${t}`;let a=Qr(e,i);return a<7?`${a}d ago ${t}`:`${Bi(i,"dd/MM/yyyy")} ${t}`}var Ac=(i,e)=>e.filename;function Dc(i,e){if(i&1){let t=O();c(0,"button",11),w("click",function(){T(t);let o=m(2);return S(o.downloadAll())}),c(1,"mat-icon"),f(2,"download_for_offline"),d()()}}function Rc(i,e){i&1&&(c(0,"div",10),I(1,"span",12),c(2,"span",13),f(3,"Loading files..."),d()())}function Fc(i,e){i&1&&(c(0,"div",14)(1,"mat-icon",15),f(2,"folder_open"),d(),c(3,"p",16),f(4,"No files in exchange space"),d(),c(5,"p",17),f(6,"Upload files to share with the agent"),d()())}function Lc(i,e){if(i&1){let t=O();c(0,"button",28),w("click",function(){T(t);let o=m().$implicit,r=m(4);return S(r.viewFile(o))}),c(1,"mat-icon"),f(2,"visibility"),d()()}}function Hc(i,e){if(i&1){let t=O();c(0,"div",18)(1,"div",19)(2,"mat-icon",20),f(3),d(),c(4,"div",21)(5,"span",22),f(6),d(),c(7,"span",23),f(8),d()()(),c(9,"div",24),x(10,Lc,3,0,"button",25),c(11,"button",26),w("click",function(){let o=T(t).$implicit,r=m(4);return S(r.download(o))}),c(12,"mat-icon"),f(13,"download"),d()(),c(14,"button",27),w("click",function(){let o=T(t).$implicit,r=m(4);return S(r.delete(o))}),c(15,"mat-icon"),f(16,"delete"),d()()()()}if(i&2){let t=e.$implicit,n=m(4);p(3),F(n.getFileIcon(t.filename)),p(2),M("title",t.filename),p(),F(t.filename),p(2),tn("",n.formatSize(t.size)," \u2022 ",n.formatDate(t.lastModified)),p(2),_(n.canViewFile(t)?10:-1)}}function Nc(i,e){if(i&1&&de(0,Hc,17,6,"div",18,Ac),i&2){let t=m(3);pe(t.files())}}function zc(i,e){if(i&1&&x(0,Fc,7,0,"div",14)(1,Nc,2,0),i&2){let t=m(2);_(t.files().length===0?0:1)}}function $c(i,e){if(i&1){let t=O();c(0,"div",0)(1,"div",2)(2,"div",3)(3,"h3",4),f(4,"Exchange"),d(),c(5,"span",5),f(6),d()(),c(7,"div",6),x(8,Dc,3,0,"button",7),c(9,"button",8),w("click",function(){T(t);let o=m();return S(o.close())}),c(10,"mat-icon"),f(11,"chevron_right"),d()()()(),c(12,"div",9),x(13,Rc,4,0,"div",10)(14,zc,2,1),d()()}if(i&2){let t=m();p(6),ht("(",t.files().length,")"),p(2),_(t.files().length>0?8:-1),p(5),_(t.isLoading()?13:14)}}function Vc(i,e){if(i&1){let t=O();c(0,"app-content-viewer",29),w("closeViewer",function(){T(t);let o=m();return S(o.backToList())}),d()}if(i&2){let t=m();M("file",t.currentFile)("projectName",t.projectName)("threadId",t.threadId)}}var Yn=class i{projectName;threadId;closeDrawer=new H;fileExchangeState=g(vt);contentViewerService=g(Ct);files=this.fileExchangeState.files;isLoading=this.fileExchangeState.isLoading;viewerState="list";currentFile=null;close(){this.viewerState==="content"?this.backToList():this.closeDrawer.emit()}viewFile(e){this.currentFile=e,this.viewerState="content"}backToList(){this.viewerState="list",this.currentFile=null}downloadAll(){this.fileExchangeState.downloadAllFiles()}download(e){this.fileExchangeState.downloadFile(e.filename)}delete(e){return N(this,null,function*(){if(!confirm(`Delete file "${e.filename}"?`))return;let n=yield this.fileExchangeState.deleteFile(e.filename);n.success||alert(`Failed to delete file: ${n.error}`)})}getFileIcon(e){switch(e.split(".").pop()?.toLowerCase()){case"pdf":return"picture_as_pdf";case"csv":case"xlsx":case"xls":return"table_chart";case"txt":case"md":return"description";case"jpg":case"jpeg":case"png":case"gif":case"webp":return"image";case"zip":case"tar":case"gz":return"folder_zip";default:return"insert_drive_file"}}formatSize(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}formatDate(e){return xa(e)}canViewFile(e){return this.contentViewerService.isFormatViewable(e.filename)&&this.contentViewerService.isViewable(e.size)}static \u0275fac=function(t){return new(t||i)};static \u0275cmp=R({type:i,selectors:[["app-file-exchange-drawer"]],inputs:{projectName:"projectName",threadId:"threadId"},outputs:{closeDrawer:"closeDrawer"},decls:2,vars:2,consts:[[1,"file-drawer-container"],[3,"file","projectName","threadId"],[1,"drawer-header"],[1,"header-left"],[1,"drawer-title"],[1,"file-count"],[1,"header-actions"],["mat-icon-button","","title","Download all files","type","button",1,"download-all-btn"],["mat-icon-button","","title","Close","type","button",1,"close-btn",3,"click"],[1,"file-list"],[1,"file-loading"],["mat-icon-button","","title","Download all files","type","button",1,"download-all-btn",3,"click"],[1,"loading-spinner"],[1,"loading-text"],[1,"file-empty"],[1,"empty-icon"],[1,"empty-text"],[1,"empty-hint"],[1,"file-item"],[1,"file-info"],[1,"file-icon"],[1,"file-details"],[1,"file-name",3,"title"],[1,"file-meta"],[1,"file-actions"],["mat-icon-button","","title","View","type","button",1,"action-btn","view-btn"],["mat-icon-button","","title","Download","type","button",1,"action-btn","download-btn",3,"click"],["mat-icon-button","","title","Delete","type","button",1,"action-btn","delete-btn",3,"click"],["mat-icon-button","","title","View","type","button",1,"action-btn","view-btn",3,"click"],[3,"closeViewer","file","projectName","threadId"]],template:function(t,n){t&1&&(x(0,$c,15,3,"div",0),x(1,Vc,1,3,"app-content-viewer",1)),t&2&&(_(n.viewerState==="list"?0:-1),p(),_(n.viewerState==="content"&&n.currentFile?1:-1))},dependencies:[fe,me,J,We,je,Vn],styles:["[_nghost-%COMP%]{display:flex;flex-direction:column;flex:1;min-height:0;height:100%}.file-drawer-container[_ngcontent-%COMP%]{display:flex;flex-direction:column;flex:1;min-height:0;height:100%;background:var(--glass-bg);backdrop-filter:var(--glass-backdrop-blur);-webkit-backdrop-filter:var(--glass-backdrop-blur);color:var(--color-text)}.drawer-header[_ngcontent-%COMP%]{display:flex;align-items:center;justify-content:space-between;padding:1rem;border-bottom:1px solid var(--color-border);flex-shrink:0}.header-left[_ngcontent-%COMP%]{display:flex;align-items:baseline;gap:.5rem}.header-actions[_ngcontent-%COMP%]{display:flex;align-items:center;gap:.25rem}.drawer-title[_ngcontent-%COMP%]{margin:0;font-size:1.25rem;font-weight:600;color:var(--color-text)}.file-count[_ngcontent-%COMP%]{font-size:.9rem;color:var(--color-text-secondary)}.download-all-btn[_ngcontent-%COMP%]{color:var(--color-primary)}.download-all-btn[_ngcontent-%COMP%]:hover{background:var(--color-bg-hover)}.close-btn[_ngcontent-%COMP%]{color:var(--color-text-secondary)}.close-btn[_ngcontent-%COMP%]:hover{color:var(--color-text);background:var(--color-bg-hover)}.file-list[_ngcontent-%COMP%]{flex:1;overflow-y:auto;padding:.5rem}.file-loading[_ngcontent-%COMP%]{display:flex;flex-direction:column;align-items:center;justify-content:center;padding:3rem 1rem;gap:1rem;color:var(--color-text-secondary)}.loading-spinner[_ngcontent-%COMP%]{display:inline-block;width:32px;height:32px;border:3px solid var(--color-border);border-top-color:var(--color-primary);border-radius:50%;animation:_ngcontent-%COMP%_spin .8s linear infinite}@keyframes _ngcontent-%COMP%_spin{to{transform:rotate(360deg)}}.loading-text[_ngcontent-%COMP%]{font-size:.9rem}.file-empty[_ngcontent-%COMP%]{display:flex;flex-direction:column;align-items:center;justify-content:center;padding:3rem 1rem;text-align:center;color:var(--color-text-secondary)}.empty-icon[_ngcontent-%COMP%]{font-size:64px;width:64px;height:64px;margin-bottom:1rem;opacity:.5}.empty-text[_ngcontent-%COMP%]{margin:0 0 .5rem;font-size:1rem;font-weight:500}.empty-hint[_ngcontent-%COMP%]{margin:0;font-size:.85rem;opacity:.7}.file-item[_ngcontent-%COMP%]{display:flex;align-items:center;justify-content:space-between;padding:.75rem;border-radius:8px;transition:background .2s;gap:1rem}.file-item[_ngcontent-%COMP%]:hover{background:var(--color-bg-hover)}.file-item[_ngcontent-%COMP%]:hover .file-actions[_ngcontent-%COMP%]{opacity:1}.file-info[_ngcontent-%COMP%]{display:flex;align-items:center;gap:.75rem;flex:1;min-width:0}.file-icon[_ngcontent-%COMP%]{flex-shrink:0;color:var(--color-primary);font-size:28px;width:28px;height:28px}.file-details[_ngcontent-%COMP%]{display:flex;flex-direction:column;gap:.25rem;min-width:0}.file-name[_ngcontent-%COMP%]{font-weight:500;color:var(--color-text);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.file-meta[_ngcontent-%COMP%]{font-size:.8rem;color:var(--color-text-secondary)}.file-actions[_ngcontent-%COMP%]{display:flex;gap:.25rem;flex-shrink:0;opacity:0;transition:opacity .2s}.action-btn[_ngcontent-%COMP%]{color:var(--color-text-secondary)}.action-btn[_ngcontent-%COMP%]:hover{background:var(--color-bg-hover)}.action-btn.view-btn[_ngcontent-%COMP%]:hover, .action-btn.download-btn[_ngcontent-%COMP%]:hover{color:var(--color-primary)}.action-btn.delete-btn[_ngcontent-%COMP%]:hover{color:var(--color-error)}@media(max-width:768px){.file-actions[_ngcontent-%COMP%]{opacity:1}.file-item[_ngcontent-%COMP%]{padding:1rem .75rem}.drawer-header[_ngcontent-%COMP%]{padding:.75rem;padding-top:calc(.75rem + env(safe-area-inset-top,0px))}}"]})};var Gn=class i{http=g(Me);listUsers(){return this.http.get("/api/users")}static \u0275fac=function(t){return new(t||i)};static \u0275prov=Y({token:i,factory:i.\u0275fac,providedIn:"root"})};var Xn=class i{excludedUserIds=[];placeholder="Search username";disabled=!1;userSelected=new H;userApi=g(Gn);search(e){let t=e.toLowerCase();return this.userApi.listUsers().pipe(Ve(n=>n.filter(o=>!this.excludedUserIds.includes(o.username)).filter(o=>o.username.toLowerCase().includes(t)).map(o=>({id:o.username,name:o.username}))))}onItemSelected(e){this.userSelected.emit(e.id)}static \u0275fac=function(t){return new(t||i)};static \u0275cmp=R({type:i,selectors:[["app-user-autocomplete"]],inputs:{excludedUserIds:"excludedUserIds",placeholder:"placeholder",disabled:"disabled"},outputs:{userSelected:"userSelected"},decls:1,vars:3,consts:[[3,"itemSelected","dataSource","placeholder","disabled"]],template:function(t,n){t&1&&(c(0,"ds-autocomplete-input",0),w("itemSelected",function(r){return n.onItemSelected(r)}),d()),t&2&&M("dataSource",n)("placeholder",n.placeholder)("disabled",n.disabled)},dependencies:[cr],styles:["[_nghost-%COMP%]{display:block}"]})};var Uc=(i,e)=>e.userId;function Bc(i,e){if(i&1&&(c(0,"div",7),f(1),d()),i&2){let t=m();p(),F(t.errorMessage())}}function jc(i,e){if(i&1){let t=O();c(0,"button",13),w("click",function(){T(t);let o=m().$implicit,r=m();return S(r.removeUser(o.userId))}),c(1,"mat-icon"),f(2,"close"),d()()}}function Wc(i,e){if(i&1&&(c(0,"div",9)(1,"mat-icon",10),f(2,"person"),d(),c(3,"span",11),f(4),d(),x(5,jc,3,0,"button",12),d()),i&2){let t=e.$implicit,n=m();p(4),F(t.userId),p(),_(n.users.length>1?5:-1)}}var Ut=class i{threadId;users=[];currentUsername;userAdded=new H;userRemoved=new H;closed=new H;isAdding=Ue(!1);errorMessage=Ue("");get excludedUserIds(){return[this.currentUsername,...this.users.map(e=>e.userId)]}setAdding(e){this.isAdding.set(e)}setError(e){this.errorMessage.set(e),this.isAdding.set(!1)}onUserSelected(e){this.errorMessage.set(""),this.userAdded.emit(e)}removeUser(e){this.userRemoved.emit(e)}close(){this.closed.emit()}static \u0275fac=function(t){return new(t||i)};static \u0275cmp=R({type:i,selectors:[["app-thread-share"]],inputs:{threadId:"threadId",users:"users",currentUsername:"currentUsername"},outputs:{userAdded:"userAdded",userRemoved:"userRemoved",closed:"closed"},decls:19,vars:3,consts:[[1,"thread-share"],[1,"share-header"],[1,"header-left"],["mat-icon-button","","title","Close","type","button",1,"close-btn",3,"click"],[1,"share-subheader"],[1,"add-user-section"],[3,"userSelected","excludedUserIds","disabled"],[1,"error-message"],[1,"users-list"],[1,"user-item"],[1,"user-icon"],[1,"user-name"],["mat-icon-button","","title","Remove user",1,"remove-button"],["mat-icon-button","","title","Remove user",1,"remove-button",3,"click"]],template:function(t,n){t&1&&(c(0,"div",0)(1,"div",1)(2,"div",2)(3,"mat-icon"),f(4,"group"),d(),c(5,"span"),f(6,"Share"),d()(),c(7,"button",3),w("click",function(){return n.close()}),c(8,"mat-icon"),f(9,"chevron_right"),d()()(),c(10,"div",4)(11,"span"),f(12,"Participants"),d()(),c(13,"div",5)(14,"app-user-autocomplete",6),w("userSelected",function(r){return n.onUserSelected(r)}),d()(),x(15,Bc,2,1,"div",7),c(16,"div",8),de(17,Wc,6,2,"div",9,Uc),d()()),t&2&&(p(14),M("excludedUserIds",n.excludedUserIds)("disabled",n.isAdding()),p(),_(n.errorMessage()?15:-1),p(2),pe(n.users))},dependencies:[me,J,We,je,Wo,Xn],styles:["[_nghost-%COMP%]{display:flex;flex-direction:column;height:100%}.thread-share[_ngcontent-%COMP%]{display:flex;flex-direction:column;flex:1;min-height:0;background:var(--glass-bg);backdrop-filter:var(--glass-backdrop-blur);-webkit-backdrop-filter:var(--glass-backdrop-blur);color:var(--color-text)}.share-header[_ngcontent-%COMP%]{display:flex;align-items:center;justify-content:space-between;padding:1rem;padding-top:calc(1rem + env(safe-area-inset-top,0px));border-bottom:1px solid var(--color-border);flex-shrink:0}.share-header[_ngcontent-%COMP%] .header-left[_ngcontent-%COMP%]{display:flex;align-items:center;gap:.5rem;font-weight:600;font-size:1.1rem;color:var(--color-text)}.share-header[_ngcontent-%COMP%] .header-left[_ngcontent-%COMP%] mat-icon[_ngcontent-%COMP%]{font-size:20px;width:20px;height:20px;color:var(--color-text-secondary)}.share-header[_ngcontent-%COMP%] .close-btn[_ngcontent-%COMP%]{color:var(--color-text-secondary)}.share-header[_ngcontent-%COMP%] .close-btn[_ngcontent-%COMP%]:hover{color:var(--color-text);background:var(--color-bg-hover)}.share-subheader[_ngcontent-%COMP%]{padding:.75rem 1rem .25rem;font-size:.75rem;font-weight:600;text-transform:uppercase;letter-spacing:.05em;color:var(--color-text-secondary)}.add-user-section[_ngcontent-%COMP%]{display:flex;align-items:center;padding:0 1rem .75rem;width:50%}.error-message[_ngcontent-%COMP%]{color:var(--color-error);font-size:.75rem;margin-top:-.5rem;padding:0 1rem}.users-list[_ngcontent-%COMP%]{display:flex;flex-direction:column;gap:.25rem;padding:.25rem}.user-item[_ngcontent-%COMP%]{display:flex;align-items:center;gap:.5rem;padding:.5rem .75rem;border-radius:6px;transition:background .15s ease}.user-item[_ngcontent-%COMP%]:hover{background:var(--color-bg-hover)}.user-icon[_ngcontent-%COMP%]{font-size:18px;width:18px;height:18px;color:var(--color-text-secondary);flex-shrink:0}.user-name[_ngcontent-%COMP%]{flex:1;font-size:.875rem;color:var(--color-text);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.remove-button[_ngcontent-%COMP%]{flex-shrink:0;width:28px!important;height:28px!important;padding:0!important}.remove-button[_ngcontent-%COMP%] mat-icon[_ngcontent-%COMP%]{font-size:16px;width:16px;height:16px;color:var(--color-text-secondary)}.remove-button[_ngcontent-%COMP%]:hover mat-icon[_ngcontent-%COMP%]{color:var(--color-error, #ef4444)}"]})};var _a="mat-badge-content",qc=(()=>{class i{static \u0275fac=function(n){return new(n||i)};static \u0275cmp=R({type:i,selectors:[["ng-component"]],decls:0,vars:0,template:function(n,o){},styles:[`.mat-badge{position:relative}.mat-badge.mat-badge{overflow:visible}.mat-badge-content{position:absolute;text-align:center;display:inline-block;transition:transform 200ms ease-in-out;transform:scale(0.6);overflow:hidden;white-space:nowrap;text-overflow:ellipsis;box-sizing:border-box;pointer-events:none;background-color:var(--mat-badge-background-color, var(--mat-sys-error));color:var(--mat-badge-text-color, var(--mat-sys-on-error));font-family:var(--mat-badge-text-font, var(--mat-sys-label-small-font));font-weight:var(--mat-badge-text-weight, var(--mat-sys-label-small-weight));border-radius:var(--mat-badge-container-shape, var(--mat-sys-corner-full))}.mat-badge-above .mat-badge-content{bottom:100%}.mat-badge-below .mat-badge-content{top:100%}.mat-badge-before .mat-badge-content{right:100%}[dir=rtl] .mat-badge-before .mat-badge-content{right:auto;left:100%}.mat-badge-after .mat-badge-content{left:100%}[dir=rtl] .mat-badge-after .mat-badge-content{left:auto;right:100%}@media(forced-colors: active){.mat-badge-content{outline:solid 1px;border-radius:0}}.mat-badge-disabled .mat-badge-content{background-color:var(--mat-badge-disabled-state-background-color, color-mix(in srgb, var(--mat-sys-error) 38%, transparent));color:var(--mat-badge-disabled-state-text-color, var(--mat-sys-on-error))}.mat-badge-hidden .mat-badge-content{display:none}.ng-animate-disabled .mat-badge-content,.mat-badge-content._mat-animation-noopable{transition:none}.mat-badge-content.mat-badge-active{transform:none}.mat-badge-small .mat-badge-content{width:var(--mat-badge-legacy-small-size-container-size, unset);height:var(--mat-badge-legacy-small-size-container-size, unset);min-width:var(--mat-badge-small-size-container-size, 6px);min-height:var(--mat-badge-small-size-container-size, 6px);line-height:var(--mat-badge-small-size-line-height, 6px);padding:var(--mat-badge-small-size-container-padding, 0);font-size:var(--mat-badge-small-size-text-size, 0);margin:var(--mat-badge-small-size-container-offset, -6px 0)}.mat-badge-small.mat-badge-overlap .mat-badge-content{margin:var(--mat-badge-small-size-container-overlap-offset, -6px)}.mat-badge-medium .mat-badge-content{width:var(--mat-badge-legacy-container-size, unset);height:var(--mat-badge-legacy-container-size, unset);min-width:var(--mat-badge-container-size, 16px);min-height:var(--mat-badge-container-size, 16px);line-height:var(--mat-badge-line-height, 16px);padding:var(--mat-badge-container-padding, 0 4px);font-size:var(--mat-badge-text-size, var(--mat-sys-label-small-size));margin:var(--mat-badge-container-offset, -12px 0)}.mat-badge-medium.mat-badge-overlap .mat-badge-content{margin:var(--mat-badge-container-overlap-offset, -12px)}.mat-badge-large .mat-badge-content{width:var(--mat-badge-legacy-large-size-container-size, unset);height:var(--mat-badge-legacy-large-size-container-size, unset);min-width:var(--mat-badge-large-size-container-size, 16px);min-height:var(--mat-badge-large-size-container-size, 16px);line-height:var(--mat-badge-large-size-line-height, 16px);padding:var(--mat-badge-large-size-container-padding, 0 4px);font-size:var(--mat-badge-large-size-text-size, var(--mat-sys-label-small-size));margin:var(--mat-badge-large-size-container-offset, -12px 0)}.mat-badge-large.mat-badge-overlap .mat-badge-content{margin:var(--mat-badge-large-size-container-overlap-offset, -12px)}
|
|
91
|
-
`],encapsulation:2,changeDetection:0})}return i})(),va=(()=>{class i{_ngZone=g(vo);_elementRef=g(mt);_ariaDescriber=g($o);_renderer=g(wo);_animationsDisabled=Uo();_idGenerator=g(zo);get color(){return this._color}set color(t){this._setColor(t),this._color=t}_color="primary";overlap=!0;disabled=!1;position="above after";get content(){return this._content}set content(t){this._updateRenderedContent(t)}_content;get description(){return this._description}set description(t){this._updateDescription(t)}_description;size="medium";hidden=!1;_badgeElement;_inlineBadgeDescription;_isInitialized=!1;_interactivityChecker=g(Ho);_document=g(_o);constructor(){let t=g(Fo);t.load(qc),t.load(Lo)}isAbove(){return this.position.indexOf("below")===-1}isAfter(){return this.position.indexOf("before")===-1}getBadgeElement(){return this._badgeElement}ngOnInit(){this._clearExistingBadges(),this.content&&!this._badgeElement&&(this._badgeElement=this._createBadgeElement(),this._updateRenderedContent(this.content)),this._isInitialized=!0}ngAfterViewInit(){}ngOnDestroy(){this._renderer.destroyNode&&(this._renderer.destroyNode(this._badgeElement),this._inlineBadgeDescription?.remove()),this._ariaDescriber.removeDescription(this._elementRef.nativeElement,this.description)}_isHostInteractive(){return this._interactivityChecker.isFocusable(this._elementRef.nativeElement,{ignoreVisibility:!0})}_createBadgeElement(){let t=this._renderer.createElement("span"),n="mat-badge-active";return t.setAttribute("id",this._idGenerator.getId("mat-badge-content-")),t.setAttribute("aria-hidden","true"),t.classList.add(_a),this._animationsDisabled&&t.classList.add("_mat-animation-noopable"),this._elementRef.nativeElement.appendChild(t),typeof requestAnimationFrame=="function"&&!this._animationsDisabled?this._ngZone.runOutsideAngular(()=>{requestAnimationFrame(()=>{t.classList.add(n)})}):t.classList.add(n),t}_updateRenderedContent(t){let n=`${t??""}`.trim();this._isInitialized&&n&&!this._badgeElement&&(this._badgeElement=this._createBadgeElement()),this._badgeElement&&(this._badgeElement.textContent=n),this._content=n}_updateDescription(t){this._ariaDescriber.removeDescription(this._elementRef.nativeElement,this.description),(!t||this._isHostInteractive())&&this._removeInlineDescription(),this._description=t,this._isHostInteractive()?this._ariaDescriber.describe(this._elementRef.nativeElement,t):this._updateInlineDescription()}_updateInlineDescription(){this._inlineBadgeDescription||(this._inlineBadgeDescription=this._document.createElement("span"),this._inlineBadgeDescription.classList.add("cdk-visually-hidden")),this._inlineBadgeDescription.textContent=this.description,this._badgeElement?.appendChild(this._inlineBadgeDescription)}_removeInlineDescription(){this._inlineBadgeDescription?.remove(),this._inlineBadgeDescription=void 0}_setColor(t){let n=this._elementRef.nativeElement.classList;n.remove(`mat-badge-${this._color}`),t&&n.add(`mat-badge-${t}`)}_clearExistingBadges(){let t=this._elementRef.nativeElement.querySelectorAll(`:scope > .${_a}`);for(let n of Array.from(t))n!==this._badgeElement&&n.remove()}static \u0275fac=function(n){return new(n||i)};static \u0275dir=So({type:i,selectors:[["","matBadge",""]],hostAttrs:[1,"mat-badge"],hostVars:20,hostBindings:function(n,o){n&2&&he("mat-badge-overlap",o.overlap)("mat-badge-above",o.isAbove())("mat-badge-below",!o.isAbove())("mat-badge-before",!o.isAfter())("mat-badge-after",o.isAfter())("mat-badge-small",o.size==="small")("mat-badge-medium",o.size==="medium")("mat-badge-large",o.size==="large")("mat-badge-hidden",o.hidden||!o.content)("mat-badge-disabled",o.disabled)},inputs:{color:[0,"matBadgeColor","color"],overlap:[2,"matBadgeOverlap","overlap",sn],disabled:[2,"matBadgeDisabled","disabled",sn],position:[0,"matBadgePosition","position"],content:[0,"matBadge","content"],description:[0,"matBadgeDescription","description"],size:[0,"matBadgeSize","size"],hidden:[2,"matBadgeHidden","hidden",sn]}})}return i})(),Ca=(()=>{class i{static \u0275fac=function(n){return new(n||i)};static \u0275mod=To({type:i});static \u0275inj=xo({imports:[No,Vo]})}return i})();var Qn=class i{http=g(Me);maxFileSize=5*1024*1024;supportedTypes=["image/png","image/jpeg","image/gif","image/webp"];validateFile(e){if(!this.supportedTypes.includes(e.type))throw new Error(`Unsupported file type: ${e.type}`);if(e.size>this.maxFileSize)throw new Error(`File too large: ${(e.size/1024/1024).toFixed(1)}MB exceeds 5MB limit`)}fileToBase64(e){return N(this,null,function*(){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;if(!r){n(new Error("Failed to read file"));return}let a=r.split(",")[1];if(!a){n(new Error("Invalid file format"));return}t(a)},o.onerror=n,o.readAsDataURL(e)})})}getUploadUrl(e,t){return`/api/projects/${e}/threads/${t}/upload`}uploadImage(e,t,n){console.log("[IMAGE-UPLOAD] uploadImage - file:",e.name,e.type,e.size),console.log("[IMAGE-UPLOAD] uploadImage - project:",t,"thread:",n);try{console.log("[IMAGE-UPLOAD] Validating file..."),this.validateFile(e)}catch(o){return console.log("[IMAGE-UPLOAD] Validation failed:",o),mi({success:!1,error:o instanceof Error?o.message:"Validation failed"})}return new Kt(o=>{console.log("[IMAGE-UPLOAD] Converting to base64..."),this.fileToBase64(e).then(r=>{console.log("[IMAGE-UPLOAD] Base64 length:",r.length),console.log("[IMAGE-UPLOAD] Sending upload request..."),this.http.post(this.getUploadUrl(t,n),{content:r,mimeType:e.type,filename:e.name}).pipe(Ve(a=>(console.log("[IMAGE-UPLOAD] Upload success result:",a),{success:!0,processedSize:a.processedSize,dimensions:a.dimensions})),en(a=>{console.log("[IMAGE-UPLOAD] Upload failed:",a);let l=a.error?.error||a.message||"Upload failed";return mi({success:!1,error:l})})).subscribe({next:a=>{o.next(a),o.complete()},error:a=>o.error(a)})}).catch(r=>{console.log("[IMAGE-UPLOAD] Base64 conversion failed:",r),o.next({success:!1,error:r instanceof Error?r.message:"Failed to read file"}),o.complete()})})}hasImageFiles(e){if(console.log("[IMAGE-UPLOAD] hasImageFiles - dataTransfer:",e),!e)return console.log("[IMAGE-UPLOAD] hasImageFiles - no dataTransfer"),!1;if(console.log("[IMAGE-UPLOAD] hasImageFiles - types:",Array.from(e.types)),!Array.from(e.types).includes("Files"))return console.log("[IMAGE-UPLOAD] hasImageFiles - no Files type"),!1;let t=Array.from(e.files||[]);console.log("[IMAGE-UPLOAD] hasImageFiles - files:",t.map(o=>({name:o.name,type:o.type})));let n=t.some(o=>this.supportedTypes.includes(o.type));return console.log("[IMAGE-UPLOAD] hasImageFiles - result:",n),n}filterImageFiles(e){return Array.from(e).filter(n=>this.supportedTypes.includes(n.type))}static \u0275fac=function(t){return new(t||i)};static \u0275prov=Y({token:i,factory:i.\u0275fac,providedIn:"root"})};var Gc=["inputSection"],Xc=()=>[];function Qc(i,e){if(i&1){let t=O();c(0,"button",20),w("click",function(){T(t);let o=m();return S(o.toggleFileDrawer())}),c(1,"mat-icon"),f(2,"folder_open"),d()()}if(i&2){let t=m();he("has-files",t.fileCount>0),M("title",Eo("Files Exchange",t.fileCount>0?" ("+t.fileCount+" file"+(t.fileCount>1?"s":"")+")":""))("matBadge",t.fileCount>0?t.fileCount:null)}}function Zc(i,e){if(i&1){let t=O();c(0,"button",21),w("click",function(){T(t);let o=m();return S(o.toggleSharePanel())}),c(1,"mat-icon"),f(2,"group"),d()()}if(i&2){let t=m();he("has-shared-users",((t.threadDetails==null||t.threadDetails.users==null?null:t.threadDetails.users.length)??0)>1)}}function Kc(i,e){if(i&1&&(c(0,"div",6),f(1),d()),i&2){let t=m();p(),tn(" \u26A0\uFE0F Connection lost. Reconnecting... (",t.connectionStatus.reconnectAttempts,"/",t.connectionStatus.maxAttempts,") ")}}function Jc(i,e){if(i&1&&(c(0,"div",22),f(1),d()),i&2){let t=m();he("error",t.uploadStatus.isError),p(),ht(" ",t.uploadStatus.message," ")}}function ed(i,e){if(i&1){let t=O();c(0,"app-chat-textarea",23),w("messageSubmitted",function(o){T(t);let r=m();return S(r.onMessageSubmitted(o))})("voiceRecordingToggled",function(o){T(t);let r=m();return S(r.onVoiceToggled(o))})("heightChanged",function(o){T(t);let r=m();return S(r.onInputHeightChanged(o))})("stopRequested",function(){T(t);let o=m();return S(o.onStopRequested())})("filesPasted",function(o){T(t);let r=m();return S(r.onFilesPasted(o))}),d()}if(i&2){let t=m();M("isDisabled",!t.isConnected)("isSessionInitializing",!1)("showWelcome",!1)("isThinking",t.isThinking)("isStarting",!1)}}function td(i,e){if(i&1){let t=O();c(0,"app-choice-select",24),w("choiceSelected",function(o){T(t);let r=m();return S(r.onChoiceSelected(o))}),d()}if(i&2){let t=m();M("options",t.currentChoice.options)("labelHtml",t.currentChoice.label)("isVisible",!!t.currentChoice)("allowFreeText",t.currentChoice.allowFreeText)}}function nd(i,e){i&1&&I(0,"app-oauth-request-panel")}function id(i,e){if(i&1){let t=O();c(0,"app-file-exchange-drawer",25),w("closeDrawer",function(){T(t);let o=m();return S(o.closeDrawer())}),d()}if(i&2){let t=m();M("projectName",t.projectName)("threadId",t.threadId)}}function od(i,e){if(i&1){let t=O();c(0,"app-thread-share",26),w("userAdded",function(o){T(t);let r=m();return S(r.onUserAdded(o))})("userRemoved",function(o){T(t);let r=m();return S(r.onUserRemoved(o))})("closed",function(){T(t);let o=m();return S(o.closeDrawer())}),d()}if(i&2){let t=m();M("threadId",t.threadId)("users",t.threadDetails.users||Po(3,Xc))("currentUsername",t.currentUsername)}}function rd(i,e){i&1&&(c(0,"div",19)(1,"div",27)(2,"div",28),f(3,"\u{1F4CE}"),d(),c(4,"div",29),f(5,"Drop files here to upload"),d(),c(6,"div",30),f(7,"Images will be added to conversation, other files to exchange space"),d()()())}var ya=class i{projectName;threadId;chatFocused=new H;drawerStateChange=new H;destroy$=new xe;connectionDestroy$=new xe;inputSection;messages=[];streamingText="";isThinking=!1;currentChoice=null;connectionStatus=null;isConnected=!1;showConnectionStatus=!1;hasEverConnected=!1;inputSectionHeight=80;uploadStatus={message:"",isError:!1};isDragOver=!1;drawerMode="none";get isDrawerOpen(){return this.drawerMode!=="none"}threadDetails=null;threadShareRef;get fileCount(){return this.fileExchangeState.fileCount()}currentUsername="";authEnabled=!1;pendingFirstMessage=null;subscriptions=[];codayService=g(Ye);oauthService=g(vn);pendingOAuthRequest=bn(this.oauthService.pendingRequest$,{initialValue:null});preferencesService=g(qe);titleService=g(wn);elementRef=g(mt);threadState=g(Pe);threadApiService=g(dn);userService=g(jo);router=g(Ro);imageUploadService=g(Qn);fileExchangeState=g(vt);firstMessageState=g(Tn);audioApiService=g(gt);ngOnInit(){if(console.log("[THREAD] Initializing with project:",this.projectName,"thread:",this.threadId),!this.projectName||!this.threadId){console.error("[THREAD] Missing required inputs: projectName or threadId");return}this.setupPrintHandlers(),this.userService.authEnabled$.pipe(K(this.destroy$)).subscribe(e=>{this.authEnabled=e}),this.userService.username$.pipe(K(this.destroy$)).subscribe(e=>{this.currentUsername=e??"",this.messages.length>0&&(this.messages=[...this.messages])}),this.initializeThreadConnection()}ngOnChanges(e){console.log("[THREAD] ngOnChanges called",e),e.threadId&&(console.log("[THREAD] threadId changed:",{firstChange:e.threadId.firstChange,previousValue:e.threadId.previousValue,currentValue:e.threadId.currentValue}),e.threadId.firstChange||(console.log("[THREAD] Reconnecting to new thread"),this.initializeThreadConnection()))}initializeThreadConnection(){console.log("[THREAD] Initializing connection for thread:",this.threadId),this.fileExchangeState.initializeForThread(this.projectName,this.threadId),this.connectionDestroy$.next(),this.codayService.messages$.pipe(K(this.connectionDestroy$)).subscribe(n=>{console.log("[THREAD] Messages updated:",n.length),this.messages=n}),this.codayService.streamingText$.pipe(K(this.connectionDestroy$)).subscribe(n=>{this.streamingText=n}),this.codayService.isThinking$.pipe(K(this.connectionDestroy$)).subscribe(n=>{this.isThinking=n}),this.codayService.currentChoice$.pipe(K(this.connectionDestroy$)).subscribe(n=>{this.currentChoice=n}),this.codayService.connectionStatus$.pipe(K(this.connectionDestroy$)).subscribe(n=>{this.connectionStatus=n,this.isConnected=n.connected,n.connected&&!this.hasEverConnected&&(this.hasEverConnected=!0,this.showConnectionStatus=!0),!n.connected&&!this.hasEverConnected?setTimeout(()=>{!this.isConnected&&!this.hasEverConnected&&(this.showConnectionStatus=!0)},2e3):!n.connected&&this.hasEverConnected?this.showConnectionStatus=!0:n.connected&&(this.showConnectionStatus=!0)}),this.codayService.threadUpdateEvent$.pipe(K(this.connectionDestroy$)).subscribe(n=>{n&&(console.log("[THREAD] Thread update event received:",n),this.threadState.refreshThreadList())}),this.threadState.selectedThread$.pipe(K(this.connectionDestroy$)).subscribe(n=>{this.threadDetails=n}),this.codayService.resetMessages(),this.codayService.setTabTitleService(this.titleService),console.log("[THREAD] Connecting to thread event stream"),this.codayService.connectToThread(this.projectName,this.threadId),this.threadApiService.getThreadMessages(this.threadId).pipe(K(this.connectionDestroy$)).subscribe({next:({messages:n})=>{console.log("[THREAD] Loaded",n.length,"messages from REST history"),this.codayService.loadHistoryFromRest(n)},error:n=>console.warn("[THREAD] Could not load REST history:",n)});let e=this.firstMessageState.consumePendingVoiceMessage();if(e){console.log("[THREAD] Pending voice message found, waiting for InviteEvent before sending"),this.codayService.setThinkingForPendingMessage(),this.subscriptions.push(this.codayService.currentInviteEvent$.pipe(Se(n=>!!n),bo(1)).subscribe(()=>{console.log("[THREAD] InviteEvent received, sending pending voice message"),this.audioApiService.sendVoiceMessage(e.base64,e.mimeType,e.language).subscribe({next:n=>{console.log("[THREAD] First voice message sent, transcription:",n.transcription?.substring(0,50))},error:n=>{console.error("[THREAD] Failed to send first voice message:",n)}})}));return}let t=this.firstMessageState.consumePendingFirstMessage();t?(console.log("[THREAD] First message pending:",t.substring(0,50)+"..."),this.pendingFirstMessage=t,this.codayService.setThinkingForPendingMessage(),this.subscribeToFirstInvite()):console.log("[THREAD] No first message found in state service")}ngAfterViewChecked(){if(this.inputSection?.nativeElement){let e=this.inputSection.nativeElement.offsetHeight;e!==this.inputSectionHeight&&e>0&&(this.inputSectionHeight=e)}}ngOnDestroy(){console.log("[THREAD] Destroying component"),this.connectionDestroy$.next(),this.connectionDestroy$.complete(),this.destroy$.next(),this.destroy$.complete(),this.fileExchangeState.clear(),this.subscriptions.forEach(e=>e.unsubscribe()),this.subscriptions=[],window.removeEventListener("beforeprint",this.handleBeforePrint),window.removeEventListener("afterprint",this.handleAfterPrint)}onMessageSubmitted(e){console.log("[THREAD] Sending message:",e),this.codayService.sendMessage(e)}onVoiceToggled(e){console.log("[VOICE] Recording:",e)}onChoiceSelected(e){console.log("[THREAD] Choice selected:",e),this.codayService.sendChoice(e)}onCopyMessage(e){console.log("[COPY] Message copied:",e.id)}onStopRequested(){this.threadState.stop()}onInputHeightChanged(e){console.log("[THREAD] Input height changed:",e),this.inputSectionHeight=e}onFilesPasted(e){console.log("[THREAD] File(s) pasted:",e.length);let t=this.imageUploadService.filterImageFiles(e),n=e.filter(o=>!o.type.startsWith("image/"));t.length&&this.uploadFilesSequentially(t,0),n.length&&this.uploadFilesToExchangeSpace(n),!t.length&&!n.length&&this.showUploadError("No supported files found")}emitDrawerState(){this.drawerStateChange.emit(this.isDrawerOpen)}toggleFileDrawer(){this.drawerMode=this.drawerMode==="files"?"none":"files",this.emitDrawerState()}toggleSharePanel(){this.drawerMode=this.drawerMode==="share"?"none":"share",this.emitDrawerState()}closeDrawer(){this.drawerMode="none",this.emitDrawerState()}onUserAdded(e){if(console.log("[THREAD] Adding user to thread:",e),!this.threadDetails)return;let t=this.threadDetails.users||[];if(t.some(o=>o.userId===e)){this.threadShareRef?.setError("User already has access to this thread");return}this.threadShareRef?.setAdding(!0);let n=[...t,{userId:e}];this.threadState.updateThreadUsers(this.threadId,n).pipe(K(this.destroy$)).subscribe({next:()=>{console.log("[THREAD] User added successfully"),this.threadShareRef?.setAdding(!1),this.threadState.refreshSelectedThread()},error:o=>{console.error("[THREAD] Error adding user:",o),this.threadShareRef?.setError(o?.error?.error||"Failed to add user")}})}onUserRemoved(e){if(console.log("[THREAD] Removing user from thread:",e),!this.threadDetails)return;let t=e===this.currentUsername,n=(this.threadDetails.users||[]).filter(o=>o.userId!==e);this.threadState.updateThreadUsers(this.threadId,n).pipe(K(this.destroy$)).subscribe({next:()=>{console.log("[THREAD] User removed successfully"),t?(this.threadState.clearSelection(),this.threadState.refreshThreadList(),this.router.navigate(["project",this.projectName])):this.threadState.refreshSelectedThread()},error:o=>{console.error("[THREAD] Error removing user:",o)}})}onDragEnter(e){e.preventDefault(),e.dataTransfer?.types.includes("Files")&&(console.log("[THREAD] Image files detected - showing drag overlay"),this.isDragOver=!0)}onDragOver(e){e.preventDefault(),e.dataTransfer&&(e.dataTransfer.dropEffect="copy")}onDragLeave(e){this.elementRef.nativeElement.contains(e.relatedTarget)||(console.log("[THREAD] Leaving component area - hiding drag overlay"),this.isDragOver=!1)}onDrop(e){e.preventDefault(),this.isDragOver=!1,console.log("[THREAD] Files dropped:",e.dataTransfer?.files?.length||0);let t=e.dataTransfer?.files;if(!t||t.length===0){console.log("[THREAD] No files in drop event");return}let n=this.imageUploadService.filterImageFiles(t),o=Array.from(t).filter(r=>!r.type.startsWith("image/"));console.log("[THREAD] Image files:",n.length,"Other files:",o.length),n.length>0&&this.uploadFilesSequentially(n,0),o.length>0&&this.uploadFilesToExchangeSpace(o),n.length===0&&o.length===0&&this.showUploadError("No supported files found")}uploadFilesSequentially(e,t){if(t>=e.length)return;let n=e[t];if(!n){console.error("[THREAD] File at index",t,"is undefined");return}console.log("[THREAD] Uploading file:",n.name),this.uploadStatus={message:`Uploading ${n.name}...`,isError:!1},this.imageUploadService.uploadImage(n,this.projectName,this.threadId).subscribe({next:o=>{o.success?(console.log("[THREAD] Upload successful:",n.name),this.uploadStatus={message:`\u2713 ${n.name} uploaded (${(o.processedSize/1024).toFixed(1)} KB)`,isError:!1},setTimeout(()=>{this.uploadStatus.isError||(this.uploadStatus={message:"",isError:!1})},3e3),this.uploadFilesSequentially(e,t+1)):(console.error("[THREAD] Upload failed:",n.name,o.error),this.showUploadError(`Failed to upload ${n.name}: ${o.error}`))},error:o=>{console.error("[THREAD] Upload error:",n.name,o),this.showUploadError(`Failed to upload ${n.name}: ${o.message||"Unknown error"}`)}})}showUploadError(e){this.uploadStatus={message:e,isError:!0},setTimeout(()=>{this.uploadStatus={message:"",isError:!1}},5e3)}uploadFilesToExchangeSpace(e){return N(this,null,function*(){for(let t of e){console.log("[THREAD] Uploading to exchange space:",t.name),this.uploadStatus={message:`Uploading ${t.name}...`,isError:!1};let n=yield this.fileExchangeState.uploadFile(t);if(n.success)console.log("[THREAD] Upload to exchange space successful:",t.name),this.uploadStatus={message:`\u2713 ${t.name} uploaded to exchange space`,isError:!1},setTimeout(()=>{this.uploadStatus.isError||(this.uploadStatus={message:"",isError:!1})},3e3);else{console.error("[THREAD] Upload to exchange space failed:",t.name,n.error),this.showUploadError(`Failed to upload ${t.name}: ${n.error}`);break}}})}subscribeToFirstInvite(){console.log("[THREAD] Subscribing to wait for InviteEvent"),this.subscriptions.push(this.codayService.currentInviteEvent$.subscribe(e=>{if(e&&this.pendingFirstMessage){console.log("[THREAD] Received InviteEvent, sending pending message");let t=this.pendingFirstMessage;this.pendingFirstMessage=null,this.codayService.sendMessage(t)}}))}setupPrintHandlers(){window.addEventListener("beforeprint",this.handleBeforePrint),window.addEventListener("afterprint",this.handleAfterPrint)}handleBeforePrint=()=>{console.log("[PRINT] Before print event triggered");let e=this.preferencesService.getPrintTechnicalMessages();console.log("[PRINT] Print technical messages:",e),e?document.body.classList.add("print-include-technical"):document.body.classList.remove("print-include-technical")};handleAfterPrint=()=>{console.log("[PRINT] After print event triggered"),document.body.classList.remove("print-include-technical")};static \u0275fac=function(t){return new(t||i)};static \u0275cmp=R({type:i,selectors:[["app-thread"]],viewQuery:function(t,n){if(t&1&&ut(Gc,5)(Ut,5),t&2){let o;He(o=Ne())&&(n.inputSection=o.first),He(o=Ne())&&(n.threadShareRef=o.first)}},inputs:{projectName:"projectName",threadId:"threadId"},outputs:{chatFocused:"chatFocused",drawerStateChange:"drawerStateChange"},features:[ke],decls:22,vars:16,consts:[["inputSection",""],[1,"drag-drop-wrapper",3,"dragenter","dragover","dragleave","drop"],[1,"file-drawer-container",3,"hasBackdrop"],[1,"thread-container"],["matFab","","type","button",1,"file-drawer-toggle-btn",3,"has-files","matBadge","title"],["matFab","","title","Share thread","type","button",1,"share-toggle-btn",3,"has-shared-users"],[1,"connection-status"],[1,"chat-wrapper",3,"mousedown","touchstart"],[1,"chat-center"],[3,"copyRequested","stopRequested","messages","streamingText","isThinking","currentUsername"],[1,"upload-status",3,"error"],[1,"input-section"],[1,"input-center"],[1,"input-glass"],[3,"isDisabled","isSessionInitializing","showWelcome","isThinking","isStarting"],[1,"choice-overlay",3,"options","labelHtml","isVisible","allowFreeText"],["mode","side","position","end",3,"closed","opened"],[3,"projectName","threadId"],[3,"threadId","users","currentUsername"],[1,"drag-overlay"],["matFab","","type","button",1,"file-drawer-toggle-btn",3,"click","matBadge","title"],["matFab","","title","Share thread","type","button",1,"share-toggle-btn",3,"click"],[1,"upload-status"],[3,"messageSubmitted","voiceRecordingToggled","heightChanged","stopRequested","filesPasted","isDisabled","isSessionInitializing","showWelcome","isThinking","isStarting"],[1,"choice-overlay",3,"choiceSelected","options","labelHtml","isVisible","allowFreeText"],[3,"closeDrawer","projectName","threadId"],[3,"userAdded","userRemoved","closed","threadId","users","currentUsername"],[1,"drag-overlay-content"],[1,"drag-icon"],[1,"drag-text"],[1,"drag-hint"]],template:function(t,n){t&1&&(c(0,"div",1),w("dragenter",function(r){return n.onDragEnter(r)})("dragover",function(r){return n.onDragOver(r)})("dragleave",function(r){return n.onDragLeave(r)})("drop",function(r){return n.onDrop(r)}),c(1,"mat-drawer-container",2)(2,"mat-drawer-content")(3,"div",3),x(4,Qc,3,5,"button",4),x(5,Zc,3,2,"button",5),x(6,Kc,2,2,"div",6),c(7,"div",7),w("mousedown",function(){return n.chatFocused.emit()})("touchstart",function(){return n.chatFocused.emit()}),c(8,"div",8)(9,"app-chat-history",9),w("copyRequested",function(r){return n.onCopyMessage(r)})("stopRequested",function(){return n.onStopRequested()}),d(),x(10,Jc,2,3,"div",10),d()(),c(11,"div",11,0)(13,"div",12)(14,"div",13),x(15,ed,1,5,"app-chat-textarea",14),x(16,td,1,4,"app-choice-select",15),x(17,nd,1,0,"app-oauth-request-panel"),d()()()()(),c(18,"mat-drawer",16),w("closed",function(){return n.closeDrawer()}),x(19,id,1,2,"app-file-exchange-drawer",17),x(20,od,1,4,"app-thread-share",18),d()(),x(21,rd,8,0,"div",19),d()),t&2&&(p(),M("hasBackdrop",!1),p(3),_(n.drawerMode!=="files"?4:-1),p(),_(n.authEnabled&&n.drawerMode!=="share"?5:-1),p(),_(n.showConnectionStatus&&n.connectionStatus&&!n.connectionStatus.connected?6:-1),p(3),M("messages",n.messages)("streamingText",n.streamingText)("isThinking",n.isThinking)("currentUsername",n.currentUsername),p(),_(n.uploadStatus.message?10:-1),p(5),_(!n.currentChoice&&!n.pendingOAuthRequest()?15:-1),p(),_(n.currentChoice?16:-1),p(),_(n.pendingOAuthRequest()?17:-1),p(),M("opened",n.isDrawerOpen),p(),_(n.drawerMode==="files"?19:-1),p(),_(n.drawerMode==="share"&&n.threadDetails?20:-1),p(),_(n.isDragOver?21:-1))},dependencies:[Ln,yn,Hn,Nn,Yn,Ut,sr,rr,ar,or,me,J,We,cn,Ca,va],styles:[".drag-drop-wrapper[_ngcontent-%COMP%]{height:100vh;height:100dvh;width:100%;position:relative}.thread-container[_ngcontent-%COMP%]{display:flex;flex-direction:column;height:100%;width:100%;position:relative;background:transparent}.file-drawer-toggle-btn[_ngcontent-%COMP%]{position:fixed!important;top:1rem!important;right:1rem!important;z-index:100!important}.file-drawer-toggle-btn.has-files[_ngcontent-%COMP%]{animation:_ngcontent-%COMP%_pulse-subtle 3s infinite}@media(max-width:768px){.file-drawer-toggle-btn[_ngcontent-%COMP%]{width:40px!important;height:40px!important;top:.75rem!important;right:.75rem!important}.file-drawer-toggle-btn[_ngcontent-%COMP%] mat-icon[_ngcontent-%COMP%]{font-size:20px;width:20px;height:20px}}.share-toggle-btn[_ngcontent-%COMP%]{position:fixed!important;top:5rem!important;right:1rem!important;z-index:100!important}.share-toggle-btn.has-shared-users[_ngcontent-%COMP%]{color:var(--color-primary)!important}@media(max-width:768px){.share-toggle-btn[_ngcontent-%COMP%]{width:40px!important;height:40px!important;top:calc(1.25rem + 40px)!important;right:.75rem!important}.share-toggle-btn[_ngcontent-%COMP%] mat-icon[_ngcontent-%COMP%]{font-size:20px;width:20px;height:20px}}@keyframes _ngcontent-%COMP%_pulse-subtle{0%,to{box-shadow:0 2px 8px #00000026}50%{box-shadow:0 4px 16px rgba(var(--color-primary-rgb, 25, 118, 210),.3)}}.file-drawer-container[_ngcontent-%COMP%]{height:100dvh;width:100%;background:var(--color-bg)}.file-drawer-container[_ngcontent-%COMP%] .mat-drawer-content{display:flex;flex-direction:column;height:100%;overflow:hidden;background:transparent}.file-drawer-container[_ngcontent-%COMP%] .mat-drawer{width:35%;min-width:280px;max-width:480px;box-shadow:-2px 0 8px #0000001a}@media(max-width:768px){.file-drawer-container[_ngcontent-%COMP%] .mat-drawer{width:100%;max-width:100%;padding-bottom:env(safe-area-inset-bottom,0px)}}.file-drawer-container[_ngcontent-%COMP%] .mat-drawer-backdrop{display:none}.connection-status[_ngcontent-%COMP%]{position:fixed;top:0;left:0;right:0;z-index:1000;background:var(--color-warning);color:var(--color-text);padding:.5rem 1rem;text-align:center;font-size:.9rem;box-shadow:0 2px 4px #0000001a}.chat-wrapper[_ngcontent-%COMP%]{flex:1;overflow-y:auto;overflow-x:hidden;display:flex;flex-direction:column;width:100%;padding:1rem 0}.chat-center[_ngcontent-%COMP%]{max-width:800px;width:100%;margin:0 auto;padding:0 2rem;display:flex;flex-direction:column;gap:1rem}@media(max-width:768px){.chat-center[_ngcontent-%COMP%]{padding:0 1rem}}.input-section[_ngcontent-%COMP%]{width:100%;padding:1rem 0;padding-bottom:calc(1rem + env(safe-area-inset-bottom,0px));background:transparent;position:relative}.input-center[_ngcontent-%COMP%]{max-width:800px;width:100%;margin:0 auto;padding:0 2rem}@media(max-width:768px){.input-center[_ngcontent-%COMP%]{padding:0 1rem}}.choice-overlay[_ngcontent-%COMP%]{display:block;width:100%}.upload-status[_ngcontent-%COMP%]{padding:.75rem 1rem;border-radius:8px;background:var(--color-success-light);color:var(--color-text);font-size:.9rem;text-align:center}.upload-status.error[_ngcontent-%COMP%]{background:var(--color-error-light)}@media print{.file-drawer-toggle-btn[_ngcontent-%COMP%], .share-toggle-btn[_ngcontent-%COMP%], .connection-status[_ngcontent-%COMP%]{display:none}.thread-container[_ngcontent-%COMP%]{background:#fff}.input-section[_ngcontent-%COMP%]{display:none}}"]})};export{yn as a,wn as b,Tn as c,ya as d};
|