@backtrack-js/browser 0.4.0 → 0.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1799,5 +1799,5 @@
1799
1799
  </div>
1800
1800
  </div>
1801
1801
  </div>
1802
- `}updateDomValues(){var r,o;if(!this.shadow)return;const e=this.shadow.querySelector(".backtrack-panel");if(this.isOpen&&!e){this.render();return}if(!this.isOpen&&e){this.render();return}const t=((r=this.health)==null?void 0:r.state)==="recording"?"backtrack-status-recording":((o=this.health)==null?void 0:o.state)==="degraded"?"backtrack-status-degraded":"backtrack-status-idle",i=this.shadow.querySelector(".backtrack-launcher-status-dot");i&&(i.className=`backtrack-launcher-status-dot ${t}`);const n=this.shadow.getElementById("btn-launcher");if(n){let s=n.querySelector(".backtrack-incident-badge-count");this.incidents.length>0?(s||(s=document.createElement("span"),s.className="backtrack-incident-badge-count",n.appendChild(s)),s.textContent=String(this.incidents.length)):s&&s.remove()}if(this.isOpen&&e){const s=this.shadow.getElementById("backtrack-saved-count-title");if(s&&(s.textContent=String(this.incidents.length)),!this.selectedIncidentId){const a=this.shadow.getElementById("backtrack-incident-list-container");if(a){const c=Array.from(a.querySelectorAll("[data-open-detail-id]")).map(u=>u.getAttribute("data-open-detail-id")).join(","),h=this.incidents.slice(0,8).map(u=>u.id).join(",");c!==h&&(a.innerHTML=this.renderIncidentsHtml(),this.attachIncidentListeners())}}}}attachIncidentListeners(){var e;this.shadow&&(this.shadow.querySelectorAll("[data-open-detail-id]").forEach(t=>{t.addEventListener("click",i=>{const n=i.currentTarget.getAttribute("data-open-detail-id");n&&(this.selectedIncidentId=n,this.render())})}),(e=this.shadow.getElementById("btn-back-to-list"))==null||e.addEventListener("click",()=>{this.selectedIncidentId=null,this.render()}),this.shadow.querySelectorAll("[data-view-id]").forEach(t=>{t.addEventListener("click",i=>{const n=i.currentTarget.getAttribute("data-view-id");n&&this.handleViewIncident(n)})}),this.shadow.querySelectorAll("[data-share-gist-id]").forEach(t=>{t.addEventListener("click",i=>{const n=i.currentTarget.getAttribute("data-share-gist-id");n&&this.handleShareGist(n)})}),this.shadow.querySelectorAll("[data-download-id]").forEach(t=>{t.addEventListener("click",i=>{const n=i.currentTarget.getAttribute("data-download-id");n&&this.handleDownloadIncident(n)})}),this.shadow.querySelectorAll("[data-copy-id]").forEach(t=>{t.addEventListener("click",i=>{const n=i.currentTarget.getAttribute("data-copy-id");n&&this.handleCopyMarkdown(n)})}),this.shadow.querySelectorAll("[data-delete-id]").forEach(t=>{t.addEventListener("click",i=>{const n=i.currentTarget.getAttribute("data-delete-id");n&&this.handleDeleteIncident(n)})}))}attachLauncherListeners(e){if(e.dataset.hasListeners)return;e.dataset.hasListeners="true";let t=0,i=0,n=0,r=0,o=!1;e.addEventListener("touchstart",s=>{if(s.touches.length===1&&this.container){const a=s.touches[0];t=a.clientX,i=a.clientY;const c=this.container.getBoundingClientRect();n=c.left,r=c.top,o=!1}},{passive:!0}),e.addEventListener("touchmove",s=>{if(s.touches.length===1&&this.container){const a=s.touches[0],c=a.clientX-t,h=a.clientY-i;(Math.abs(c)>5||Math.abs(h)>5)&&(o=!0,this.container.style.left=`${n+c}px`,this.container.style.top=`${r+h}px`,this.container.style.bottom="auto",this.container.style.right="auto")}},{passive:!0}),e.addEventListener("touchend",()=>{o&&(this.wasDragged=!0,setTimeout(()=>{this.wasDragged=!1},150))}),e.addEventListener("click",s=>{if(this.wasDragged){s.preventDefault(),s.stopPropagation();return}this.toggleOpen()})}attachPanelListeners(){var t,i,n,r,o,s,a,c,h,u,p,g,b,k,v,f,m,w,x,S,$,M,y,A,_;if(!this.shadow)return;(t=this.shadow.getElementById("btn-close"))==null||t.addEventListener("click",()=>{this.toggleOpen()}),(i=this.shadow.getElementById("btn-dismiss-banner"))==null||i.addEventListener("click",()=>{this.dismissBanner()}),(n=this.shadow.getElementById("btn-header-menu"))==null||n.addEventListener("click",R=>{R.stopPropagation(),this.isHeaderMenuOpen=!this.isHeaderMenuOpen,this.render()}),(r=this.shadow.getElementById("btn-hide-widget"))==null||r.addEventListener("click",R=>{R.stopPropagation(),this.isHeaderMenuOpen=!1,this.showHideConfirmModal=!0,this.render()}),(o=this.shadow.getElementById("btn-duration-60"))==null||o.addEventListener("click",()=>{this.selectedDurationSeconds=60,this.isCustomDuration=!1,this.render()}),(s=this.shadow.getElementById("btn-duration-300"))==null||s.addEventListener("click",()=>{this.selectedDurationSeconds=300,this.isCustomDuration=!1,this.render()}),(a=this.shadow.getElementById("btn-duration-all"))==null||a.addEventListener("click",()=>{this.selectedDurationSeconds=0,this.isCustomDuration=!1,this.render()}),(c=this.shadow.getElementById("btn-duration-custom"))==null||c.addEventListener("click",()=>{this.isCustomDuration=!0,this.render()});const e=this.shadow.getElementById("input-custom-duration");e&&(e.addEventListener("input",R=>{const q=parseInt(R.target.value,10);isNaN(q)||(this.selectedDurationSeconds=Math.max(5,Math.min(900,q)))}),e.addEventListener("change",R=>{const q=parseInt(R.target.value,10),V=isNaN(q)?60:Math.max(5,Math.min(900,q));this.selectedDurationSeconds=V,e.value=String(V)})),(h=this.shadow.getElementById("btn-save"))==null||h.addEventListener("click",()=>{this.handleCapture()}),(u=this.shadow.getElementById("btn-annotate"))==null||u.addEventListener("click",()=>{this.handleAnnotate()}),(p=this.shadow.getElementById("btn-clear"))==null||p.addEventListener("click",()=>{this.handleClear()}),this.attachIncidentListeners(),this.exportModalIncidentId&&((g=this.shadow.getElementById("btn-close-export-modal"))==null||g.addEventListener("click",()=>{this.closeExportModal()}),(b=this.shadow.getElementById("btn-cancel-export-modal"))==null||b.addEventListener("click",()=>{this.closeExportModal()}),(k=this.shadow.getElementById("check-include-incident-link"))==null||k.addEventListener("change",R=>{this.exportModalIncludeLink=R.target.checked,this.render()}),(v=this.shadow.getElementById("btn-confirm-export-modal"))==null||v.addEventListener("click",()=>{this.confirmCopyMarkdown()})),this.downloadModalIncidentId&&((f=this.shadow.getElementById("btn-close-download-modal"))==null||f.addEventListener("click",()=>{this.closeDownloadModal()}),(m=this.shadow.getElementById("btn-cancel-download-modal"))==null||m.addEventListener("click",()=>{this.closeDownloadModal()}),(w=this.shadow.getElementById("radio-format-ai"))==null||w.addEventListener("change",()=>{this.downloadModalFormat="ai",this.downloadModalError=null,this.render()}),(x=this.shadow.getElementById("radio-format-gzip"))==null||x.addEventListener("change",()=>{this.downloadModalFormat="gzip",this.downloadModalError=null,this.render()}),(S=this.shadow.getElementById("radio-format-uncompressed"))==null||S.addEventListener("change",()=>{this.downloadModalFormat="uncompressed",this.downloadModalError=null,this.render()}),($=this.shadow.getElementById("btn-confirm-download-modal"))==null||$.addEventListener("click",()=>{this.confirmDownload()})),this.showHideConfirmModal&&((M=this.shadow.getElementById("btn-close-hide-modal"))==null||M.addEventListener("click",()=>{this.showHideConfirmModal=!1,this.render()}),(y=this.shadow.getElementById("btn-cancel-hide-modal"))==null||y.addEventListener("click",()=>{this.showHideConfirmModal=!1,this.render()}),(A=this.shadow.getElementById("btn-confirm-hide-modal"))==null||A.addEventListener("click",()=>{this.showHideConfirmModal=!1,this.hide()})),(_=this.shadow.querySelector(".backtrack-panel"))==null||_.addEventListener("click",R=>{if(this.isHeaderMenuOpen){const q=R.target;q!=null&&q.closest(".backtrack-header-menu-wrap")||(this.isHeaderMenuOpen=!1,this.render())}})}};l(F,"sessionGithubToken",null);let ee=F;const Se="0.4.0",I=class I{constructor(e,t){l(this,"options");l(this,"stateMachine");l(this,"db");l(this,"writer",null);l(this,"retention");l(this,"incidentManager",null);l(this,"widget",null);l(this,"consoleCapturer",null);l(this,"errorCapturer",null);l(this,"networkCapturer",null);l(this,"navigationCapturer",null);l(this,"rrwebCapturer",null);l(this,"performanceCapturer",null);l(this,"sequence",0);l(this,"retentionIntervalTimer",null);l(this,"retentionPromise",null);l(this,"cachedStorageBytes",0);l(this,"cachedIncidentCount",0);l(this,"pageHideHandler");l(this,"beforeUnloadHandler");l(this,"visibilityChangeHandler");l(this,"cachedProtectedBytes",0);l(this,"cachedBrowserEstimateBytes");l(this,"cachedBrowserQuotaBytes");l(this,"nextSequence",()=>(this.sequence++,this.sequence));l(this,"stoppingPromise");var i,n,r,o,s,a,c,h,u,p,g;this.options={bufferMinutes:(e==null?void 0:e.bufferMinutes)??5,afterErrorSeconds:(e==null?void 0:e.afterErrorSeconds)??15,maxStorageMb:(e==null?void 0:e.maxStorageMb)??50,captureHttpStatus:(e==null?void 0:e.captureHttpStatus)??[500,502,503,504],showWidget:(e==null?void 0:e.showWidget)??!1,widgetOptions:e==null?void 0:e.widgetOptions,metadata:e==null?void 0:e.metadata,recorderVersion:e==null?void 0:e.recorderVersion,ignoredUrls:e==null?void 0:e.ignoredUrls,network:{capturePayloads:((i=e==null?void 0:e.network)==null?void 0:i.capturePayloads)??!1,maxPayloadSize:((n=e==null?void 0:e.network)==null?void 0:n.maxPayloadSize)??64*1024},privacy:{maskAllInputs:((r=e==null?void 0:e.privacy)==null?void 0:r.maskAllInputs)??!0,maskAllText:((o=e==null?void 0:e.privacy)==null?void 0:o.maskAllText)??!1,blockMedia:((s=e==null?void 0:e.privacy)==null?void 0:s.blockMedia)??!0,blockSelector:(a=e==null?void 0:e.privacy)==null?void 0:a.blockSelector,maskTextSelector:(c=e==null?void 0:e.privacy)==null?void 0:c.maskTextSelector,sanitizeUrl:(h=e==null?void 0:e.privacy)==null?void 0:h.sanitizeUrl,sensitiveRoutes:(u=e==null?void 0:e.privacy)==null?void 0:u.sensitiveRoutes,autoMaskPII:(p=e==null?void 0:e.privacy)==null?void 0:p.autoMaskPII,recordCanvas:(g=e==null?void 0:e.privacy)==null?void 0:g.recordCanvas},storage:e==null?void 0:e.storage,sessionOptions:e==null?void 0:e.sessionOptions,batchWriterConfig:e==null?void 0:e.batchWriterConfig,transport:e==null?void 0:e.transport,beforeSend:e==null?void 0:e.beforeSend,context:e==null?void 0:e.context,getContext:e==null?void 0:e.getContext},this.stateMachine=new $e("stopped"),this.db=t||new De,this.retention=new _e(this.db,{bufferMinutes:this.options.bufferMinutes,maxStorageMb:this.options.maxStorageMb})}static async init(e,t){if(I.activeInstance)return I.activeInstance;const i=new I(e,t);if(await i.start(),I.activeInstance=i,typeof window<"u"){const n=window;n.Backtrack=I,n.flightRecorder=i,n.hideBacktrack=()=>I.hideWidget(),n.showBacktrack=()=>I.showWidget(),n.toggleBacktrack=()=>I.toggleWidget()}return i}static hideWidget(){const e=I.activeInstance;if(e!=null&&e.widget)e.widget.hide();else try{if(typeof localStorage<"u"&&localStorage.setItem("backtrack_widget_hidden","true"),typeof document<"u"){const t=document.getElementById("__backtrack_widget_host__");t&&(t.style.display="none")}}catch{}}static showWidget(){const e=I.activeInstance;if(e!=null&&e.widget)e.widget.show();else try{if(typeof localStorage<"u"&&localStorage.removeItem("backtrack_widget_hidden"),typeof document<"u"){const t=document.getElementById("__backtrack_widget_host__");t&&(t.style.display="")}}catch{}}static toggleWidget(){const e=I.activeInstance;return e!=null&&e.widget?e.widget.toggle():typeof localStorage<"u"&&localStorage.getItem("backtrack_widget_hidden")==="true"?(I.showWidget(),!0):(I.hideWidget(),!1)}static hide(){I.hideWidget()}static show(){I.showWidget()}static toggle(){return I.toggleWidget()}static async resetInstance(){I.activeInstance&&(await I.activeInstance.stop(),I.activeInstance=null)}static getInstance(){return I.activeInstance}hideWidget(){this.widget?this.widget.hide():I.hideWidget()}showWidget(){this.widget?this.widget.show():I.showWidget()}toggleWidget(){return this.widget?this.widget.toggle():I.toggleWidget()}getEnvironmentMetadata(){const e=this.options.metadata;if(typeof window>"u")return{url:"http://localhost",userAgent:"node",viewport:{width:1280,height:720},...e};const t=window;return{url:window.location.href,userAgent:window.navigator.userAgent,viewport:{width:window.innerWidth,height:window.innerHeight},appVersion:(e==null?void 0:e.appVersion)??t.__APP_VERSION__??t.__UTICKET_APP_VERSION__,gitBranch:(e==null?void 0:e.gitBranch)??t.__GIT_BRANCH__??t.__UTICKET_GIT_BRANCH__,gitCommit:(e==null?void 0:e.gitCommit)??t.__GIT_COMMIT__??t.__UTICKET_GIT_COMMIT__,...e}}async start(){var e,t,i,n;if(!this.stateMachine.isRecording())try{await this.db.open();const r=await qe({...this.options.sessionOptions,...this.options.storage?{storage:this.options.storage}:{}}),o=await this.db.getChunksBySession(r.sessionId),s=Math.max(0,...o.flatMap(c=>(c.timeline||[]).map(h=>h.sequence))),a=Math.max(0,...o.map(c=>c.sequence));this.sequence=s,this.writer=new Pe(this.db,r.sessionId,r.tabId,{...this.options.batchWriterConfig,initialChunkSequence:a},c=>{var u;c instanceof Error&&(c.name==="QuotaExceededError"||((u=c.message)==null?void 0:u.includes("QuotaExceededError")))||typeof DOMException<"u"&&c instanceof DOMException&&c.name==="QuotaExceededError"?this.handleQuotaExceeded():this.stateMachine.transition({type:"DEGRADE",reason:"Falha ao persistir um lote; a gravação pode estar incompleta."})}),this.writer.setOnChunkPersisted(()=>{this.scheduleRetention()}),this.incidentManager=new ie(this.db,r.sessionId,r.tabId,()=>this.getEnvironmentMetadata(),{afterErrorSeconds:this.options.afterErrorSeconds,recorderVersion:this.options.recorderVersion??Se,context:this.options.context,getContext:this.options.getContext,getRecordingIssues:()=>{var c;return[...this.stateMachine.getDegradedReasons(),...(((c=this.rrwebCapturer)==null?void 0:c.getDroppedEventsCount())??0)>0?["O capturador não conseguiu registrar parte do replay."]:[]]},getDroppedEventsCount:()=>{var c;return((c=this.rrwebCapturer)==null?void 0:c.getDroppedEventsCount())??0}}),this.incidentManager.setOnIncidentPending(()=>{this.stateMachine.transition({type:"TRIGGER_AUTO"})}),this.incidentManager.setOnIncidentFinalized(c=>{var h;(h=this.incidentManager)!=null&&h.getPendingIncident()||this.stateMachine.transition({type:"FINALIZE_INCIDENT"}),this.updateStatsCache(),this.sendIncident(c.id)}),this.incidentManager.setOnError(c=>{var u;c instanceof Error&&(c.name==="QuotaExceededError"||((u=c.message)==null?void 0:u.includes("QuotaExceededError")))||typeof DOMException<"u"&&c instanceof DOMException&&c.name==="QuotaExceededError"?this.handleQuotaExceeded():this.stateMachine.transition({type:"DEGRADE",reason:"Falha no gerenciamento de incidentes; o incidente pode não ter sido salvo completamente."})}),this.incidentManager.setBeforeFinalize(async()=>{this.writer&&await this.writer.flush()}),await this.incidentManager.init(),this.consoleCapturer=new Oe(this.writer,this.nextSequence),this.errorCapturer=new Ne(this.writer,this.incidentManager,this.nextSequence),this.networkCapturer=new Fe(this.writer,this.incidentManager,this.nextSequence,{captureHttpStatus:this.options.captureHttpStatus,ignoredUrls:this.options.ignoredUrls,sanitizeUrlCallback:(e=this.options.privacy)==null?void 0:e.sanitizeUrl,capturePayloads:(t=this.options.network)==null?void 0:t.capturePayloads,maxPayloadSize:(i=this.options.network)==null?void 0:i.maxPayloadSize}),this.navigationCapturer=new je(this.writer,this.nextSequence,{sanitizeUrlCallback:(n=this.options.privacy)==null?void 0:n.sanitizeUrl}),this.rrwebCapturer=new We(this.writer,{privacy:this.options.privacy}),this.performanceCapturer=new Ve(this.writer,this.nextSequence),this.consoleCapturer.start(),this.errorCapturer.start(),this.networkCapturer.start(),this.navigationCapturer.start(),this.rrwebCapturer.start(),this.performanceCapturer.start(),this.stateMachine.transition({type:"START"}),this.incidentManager.getPendingIncident()&&this.stateMachine.transition({type:"TRIGGER_AUTO"}),this.retentionIntervalTimer=setInterval(()=>{this.scheduleRetention()},3e4),this.updateStatsCache(),this.options.showWidget&&typeof window<"u"&&(this.widget=new ee(this,this.options.widgetOptions),this.widget.mount()),typeof window<"u"&&typeof window.addEventListener=="function"&&(this.pageHideHandler=()=>{var c;(c=this.incidentManager)==null||c.syncPendingIncidentDroppedEvents().catch(()=>{})},this.beforeUnloadHandler=()=>{var c;(c=this.incidentManager)==null||c.syncPendingIncidentDroppedEvents().catch(()=>{})},window.addEventListener("pagehide",this.pageHideHandler),window.addEventListener("beforeunload",this.beforeUnloadHandler)),typeof document<"u"&&typeof document.addEventListener=="function"&&(this.visibilityChangeHandler=()=>{var c;document.visibilityState==="hidden"&&((c=this.incidentManager)==null||c.syncPendingIncidentDroppedEvents().catch(()=>{}))},document.addEventListener("visibilitychange",this.visibilityChangeHandler))}catch(r){this.stateMachine.transition({type:"DEGRADE",reason:`Falha ao iniciar recorder: ${r instanceof Error?r.message:String(r)}`})}}scheduleRetention(){return this.retentionPromise?this.retentionPromise:(this.retentionPromise=(async()=>{try{this.incidentManager?await this.incidentManager.runExclusive(async()=>{var e;await((e=this.incidentManager)==null?void 0:e.protectSessionChunks()),await this.retention.prune(),await this.updateStatsCache()}):(await this.retention.prune(),await this.updateStatsCache())}catch{this.stateMachine.transition({type:"DEGRADE",reason:"Falha na manutenção do armazenamento local."})}finally{this.retentionPromise=null}})(),this.retentionPromise)}async handleQuotaExceeded(){try{this.incidentManager?await this.incidentManager.runExclusive(async()=>{var n;await((n=this.incidentManager)==null?void 0:n.protectSessionChunks()),await this.retention.emergencyPrune(),await this.updateStatsCache()}):(await this.retention.emergencyPrune(),await this.updateStatsCache())}catch{}const e=await this.retention.getStorageBreakdown().catch(()=>null),i=(e?e.bufferBytes===0&&e.protectedBytes>0:!1)||e!=null&&e.protectedExceedsLimit?"A quota do navegador foi excedida. Apenas conteúdo protegido permanece salvo; é necessário excluir incidentes ou limpar gravações para liberar espaço.":"A quota do navegador impediu a gravação de um lote. Um prune emergencial de dados não protegidos foi executado.";this.stateMachine.transition({type:"DEGRADE",reason:i})}async updateStatsCache(){try{const e=await this.retention.getStorageBreakdown();if(this.cachedStorageBytes=e.totalBytes,this.cachedProtectedBytes=e.protectedBytes,this.cachedIncidentCount=e.incidentCount,typeof navigator<"u"&&navigator.storage&&typeof navigator.storage.estimate=="function")try{const t=await navigator.storage.estimate();this.cachedBrowserEstimateBytes=t.usage,this.cachedBrowserQuotaBytes=t.quota}catch{}if(e.protectedExceedsLimit)this.stateMachine.transition({type:"DEGRADE",reason:"O armazenamento protegido por incidentes excede o limite configurado (maxStorageMb)."});else if(!e.isOverLimit&&this.stateMachine.isDegraded()){const t=this.stateMachine.getDegradedReasons();t.every(n=>n.includes("maxStorageMb")||n.includes("quota")||n.includes("Quota")||n.includes("armazenamento"))&&t.length>0&&this.stateMachine.transition({type:"RECOVER"})}}catch{}}async sendIncident(e){const t=this.options.transport;if(t)try{const i=await this.getArtifact(e),n=this.options.beforeSend?await this.options.beforeSend(i):i;n&&await t.send(n)}catch{}}stopCapturers(){var e,t,i,n,r,o;(e=this.rrwebCapturer)==null||e.stop(),(t=this.navigationCapturer)==null||t.stop(),(i=this.networkCapturer)==null||i.stop(),(n=this.errorCapturer)==null||n.stop(),(r=this.consoleCapturer)==null||r.stop(),(o=this.performanceCapturer)==null||o.stop()}clearRuntimeReferences(){this.rrwebCapturer=null,this.navigationCapturer=null,this.networkCapturer=null,this.errorCapturer=null,this.consoleCapturer=null,this.performanceCapturer=null,this.writer=null,this.incidentManager=null}async stop(){if(this.stateMachine.getState()!=="stopped"){if(this.stoppingPromise)return this.stoppingPromise;this.stoppingPromise=(async()=>{var e;if(this.stopCapturers(),this.retentionIntervalTimer&&(clearInterval(this.retentionIntervalTimer),this.retentionIntervalTimer=null),this.widget&&(this.widget.unmount(),this.widget=null),I.activeInstance===this&&(I.activeInstance=null),this.retentionPromise)try{await this.retentionPromise}catch{}typeof window<"u"&&typeof window.removeEventListener=="function"&&(this.pageHideHandler&&(window.removeEventListener("pagehide",this.pageHideHandler),this.pageHideHandler=void 0),this.beforeUnloadHandler&&(window.removeEventListener("beforeunload",this.beforeUnloadHandler),this.beforeUnloadHandler=void 0)),typeof document<"u"&&typeof document.removeEventListener=="function"&&this.visibilityChangeHandler&&(document.removeEventListener("visibilitychange",this.visibilityChangeHandler),this.visibilityChangeHandler=void 0),this.writer&&await this.writer.flush(),(e=this.writer)==null||e.destroy(),this.incidentManager&&(await this.incidentManager.syncPendingIncidentDroppedEvents().catch(()=>{}),await this.incidentManager.destroy()),te(),this.clearRuntimeReferences(),this.stateMachine.transition({type:"STOP"})})();try{await this.stoppingPromise}finally{this.stoppingPromise=void 0}}}async capture(e="manual",t,i){if(!this.incidentManager||!this.writer)throw new Error("FlightRecorder não está em execução.");const n=await this.incidentManager.runExclusive(async()=>{const r=Date.now();return this.writer.addTimelineEvent({id:`marker_manual_${r}`,timestamp:r,sequence:this.nextSequence(),type:"marker",label:`Captura manual: ${e}`}),await this.writer.flush(),this.incidentManager.executeManualTrigger({id:`trig_manual_${r}`,timestamp:r,type:"manual",signature:`manual_capture_${e}`,detail:{userReason:e,windowSeconds:t,annotationImage:i==null?void 0:i.annotationImage,notes:i==null?void 0:i.notes,annotations:i==null?void 0:i.annotations}},t)});return await this.updateStatsCache(),n}captureException(e,t){if(this.errorCapturer)try{return this.errorCapturer.captureException(e,t)}catch{}}async listIncidents(){try{return await this.db.listIncidents()}catch{return[]}}async getArtifact(e){return this.incidentManager?this.incidentManager.exportArtifact(e):new ie(this.db,"","",()=>this.getEnvironmentMetadata(),{recorderVersion:this.options.recorderVersion??Se,context:this.options.context,getContext:this.options.getContext,getRecordingIssues:()=>this.stateMachine.getDegradedReasons()}).exportArtifact(e)}async exportIncident(e,t){const i=await this.getArtifact(e),n=new Date(i.incident.triggeredAt).toISOString().replace(/:/g,"-").replace(/\..+/,""),r=(t==null?void 0:t.aiOptimized)??!1,o=!r&&((t==null?void 0:t.compress)??!1),s=r?".ai.json":o?".ffr.json.gz":".ffr.json",a=`flight-recorder-${n}-${i.incident.reason}-${e}${s}`,c=r?{...i,replay:[],_aiNote:"Replay visual removido para otimizacao de IA. Timeline, erros de console e rede preservados."}:i;if(typeof window<"u"&&typeof document<"u"){let h;if(o){const g=await ze(i);h=new Blob([g],{type:"application/gzip"})}else{const g=JSON.stringify(c,null,2);h=new Blob([g],{type:"application/json;charset=utf-8"})}const u=URL.createObjectURL(h),p=document.createElement("a");p.href=u,p.download=a,document.body.appendChild(p),p.click(),document.body.removeChild(p),URL.revokeObjectURL(u)}return c}async deleteIncident(e){this.incidentManager?(await this.incidentManager.deleteIncident(e),await this.incidentManager.runExclusive(async()=>{await this.retention.prune(),await this.updateStatsCache()})):(await this.db.deleteIncident(e),await this.retention.prune(),await this.updateStatsCache())}async clear(){if(this.writer&&await this.writer.flush(),this.retentionPromise)try{await this.retentionPromise}catch{}this.incidentManager&&await this.incidentManager.reset(),this.stateMachine.getState()==="incident_pending"&&this.stateMachine.transition({type:"FINALIZE_INCIDENT"}),await this.db.clearAll(),this.cachedStorageBytes=0,this.cachedProtectedBytes=0,this.cachedIncidentCount=0}getHealth(){var i,n;const e=((i=this.rrwebCapturer)==null?void 0:i.getDroppedEventsCount())??0,t=(this.options.maxStorageMb??50)*1024*1024;return{state:this.stateMachine.getState(),droppedEvents:e,storageBytes:this.cachedStorageBytes,protectedStorageBytes:this.cachedProtectedBytes,storageLimitBytes:t,storageLimitExceeded:this.cachedStorageBytes>t,protectedStorageExceeded:this.cachedProtectedBytes>t,browserStorageEstimateBytes:this.cachedBrowserEstimateBytes,browserStorageQuotaBytes:this.cachedBrowserQuotaBytes,pendingWrites:((n=this.writer)==null?void 0:n.getPendingWrites())??0,incidentCount:this.cachedIncidentCount,reasons:this.stateMachine.getDegradedReasons()}}getSequence(){return this.sequence}async flush(){this.writer&&await this.writer.flush()}async destroy(){await this.stop()}};l(I,"activeInstance",null);let W=I;function Je(d){return new W(d)}exports.Backtrack=W;exports.BacktrackImpl=W;exports.BacktrackWidget=ee;exports.BatchWriter=Pe;exports.ConsoleCapturer=Oe;exports.DB_NAME=Be;exports.DB_VERSION=Re;exports.ErrorCapturer=Ne;exports.FlightRecorderDB=De;exports.FlightRecorderImpl=W;exports.IncidentManager=ie;exports.MAX_ARTIFACT_BYTES=K;exports.NavigationCapturer=je;exports.NetworkCapturer=Fe;exports.PerformanceCapturer=Ve;exports.RecorderStateMachine=$e;exports.RetentionEngine=_e;exports.RrwebCapturer=We;exports.STORE_CHUNKS=B;exports.STORE_INCIDENTS=D;exports.STORE_SESSIONS=N;exports.ScreenAnnotator=Ye;exports.claimSessionContext=qe;exports.closeSessionChannel=te;exports.compressArtifact=ze;exports.compressGzip=ae;exports.createBacktrack=Je;exports.createFlightRecorder=Je;exports.decompressArtifact=rt;exports.decompressGzip=Z;exports.formatIncidentMarkdown=Xe;exports.generateIncidentId=ne;exports.getOrCreateSessionContext=He;exports.globToRegex=Ue;exports.isGzip=Le;exports.isReplayEvent=Me;exports.isValidAnnotationImage=Ce;exports.matchesSensitiveRoute=Ge;exports.readLimitedStream=oe;exports.readResponseBytes=it;exports.redactSensitiveString=L;exports.resetSessionContext=at;exports.sanitizeAndSerialize=le;exports.sanitizeHeaders=Y;exports.sanitizePayloadString=X;exports.sanitizeUrl=J;exports.sliceReplayEventsForWindow=ot;exports.sliceReplayEventsWithMetadata=se;exports.sortTimelineEvents=Te;exports.uploadArtifactToGist=re;exports.validateFlightRecorderArtifact=Ae;
1802
+ `}updateDomValues(){var r,o;if(!this.shadow)return;const e=this.shadow.querySelector(".backtrack-panel");if(this.isOpen&&!e){this.render();return}if(!this.isOpen&&e){this.render();return}const t=((r=this.health)==null?void 0:r.state)==="recording"?"backtrack-status-recording":((o=this.health)==null?void 0:o.state)==="degraded"?"backtrack-status-degraded":"backtrack-status-idle",i=this.shadow.querySelector(".backtrack-launcher-status-dot");i&&(i.className=`backtrack-launcher-status-dot ${t}`);const n=this.shadow.getElementById("btn-launcher");if(n){let s=n.querySelector(".backtrack-incident-badge-count");this.incidents.length>0?(s||(s=document.createElement("span"),s.className="backtrack-incident-badge-count",n.appendChild(s)),s.textContent=String(this.incidents.length)):s&&s.remove()}if(this.isOpen&&e){const s=this.shadow.getElementById("backtrack-saved-count-title");if(s&&(s.textContent=String(this.incidents.length)),!this.selectedIncidentId){const a=this.shadow.getElementById("backtrack-incident-list-container");if(a){const c=Array.from(a.querySelectorAll("[data-open-detail-id]")).map(u=>u.getAttribute("data-open-detail-id")).join(","),h=this.incidents.slice(0,8).map(u=>u.id).join(",");c!==h&&(a.innerHTML=this.renderIncidentsHtml(),this.attachIncidentListeners())}}}}attachIncidentListeners(){var e;this.shadow&&(this.shadow.querySelectorAll("[data-open-detail-id]").forEach(t=>{t.addEventListener("click",i=>{const n=i.currentTarget.getAttribute("data-open-detail-id");n&&(this.selectedIncidentId=n,this.render())})}),(e=this.shadow.getElementById("btn-back-to-list"))==null||e.addEventListener("click",()=>{this.selectedIncidentId=null,this.render()}),this.shadow.querySelectorAll("[data-view-id]").forEach(t=>{t.addEventListener("click",i=>{const n=i.currentTarget.getAttribute("data-view-id");n&&this.handleViewIncident(n)})}),this.shadow.querySelectorAll("[data-share-gist-id]").forEach(t=>{t.addEventListener("click",i=>{const n=i.currentTarget.getAttribute("data-share-gist-id");n&&this.handleShareGist(n)})}),this.shadow.querySelectorAll("[data-download-id]").forEach(t=>{t.addEventListener("click",i=>{const n=i.currentTarget.getAttribute("data-download-id");n&&this.handleDownloadIncident(n)})}),this.shadow.querySelectorAll("[data-copy-id]").forEach(t=>{t.addEventListener("click",i=>{const n=i.currentTarget.getAttribute("data-copy-id");n&&this.handleCopyMarkdown(n)})}),this.shadow.querySelectorAll("[data-delete-id]").forEach(t=>{t.addEventListener("click",i=>{const n=i.currentTarget.getAttribute("data-delete-id");n&&this.handleDeleteIncident(n)})}))}attachLauncherListeners(e){if(e.dataset.hasListeners)return;e.dataset.hasListeners="true";let t=0,i=0,n=0,r=0,o=!1;e.addEventListener("touchstart",s=>{if(s.touches.length===1&&this.container){const a=s.touches[0];t=a.clientX,i=a.clientY;const c=this.container.getBoundingClientRect();n=c.left,r=c.top,o=!1}},{passive:!0}),e.addEventListener("touchmove",s=>{if(s.touches.length===1&&this.container){const a=s.touches[0],c=a.clientX-t,h=a.clientY-i;(Math.abs(c)>5||Math.abs(h)>5)&&(o=!0,this.container.style.left=`${n+c}px`,this.container.style.top=`${r+h}px`,this.container.style.bottom="auto",this.container.style.right="auto")}},{passive:!0}),e.addEventListener("touchend",()=>{o&&(this.wasDragged=!0,setTimeout(()=>{this.wasDragged=!1},150))}),e.addEventListener("click",s=>{if(this.wasDragged){s.preventDefault(),s.stopPropagation();return}this.toggleOpen()})}attachPanelListeners(){var t,i,n,r,o,s,a,c,h,u,p,g,b,k,v,f,m,w,x,S,$,M,y,A,_;if(!this.shadow)return;(t=this.shadow.getElementById("btn-close"))==null||t.addEventListener("click",()=>{this.toggleOpen()}),(i=this.shadow.getElementById("btn-dismiss-banner"))==null||i.addEventListener("click",()=>{this.dismissBanner()}),(n=this.shadow.getElementById("btn-header-menu"))==null||n.addEventListener("click",R=>{R.stopPropagation(),this.isHeaderMenuOpen=!this.isHeaderMenuOpen,this.render()}),(r=this.shadow.getElementById("btn-hide-widget"))==null||r.addEventListener("click",R=>{R.stopPropagation(),this.isHeaderMenuOpen=!1,this.showHideConfirmModal=!0,this.render()}),(o=this.shadow.getElementById("btn-duration-60"))==null||o.addEventListener("click",()=>{this.selectedDurationSeconds=60,this.isCustomDuration=!1,this.render()}),(s=this.shadow.getElementById("btn-duration-300"))==null||s.addEventListener("click",()=>{this.selectedDurationSeconds=300,this.isCustomDuration=!1,this.render()}),(a=this.shadow.getElementById("btn-duration-all"))==null||a.addEventListener("click",()=>{this.selectedDurationSeconds=0,this.isCustomDuration=!1,this.render()}),(c=this.shadow.getElementById("btn-duration-custom"))==null||c.addEventListener("click",()=>{this.isCustomDuration=!0,this.render()});const e=this.shadow.getElementById("input-custom-duration");e&&(e.addEventListener("input",R=>{const q=parseInt(R.target.value,10);isNaN(q)||(this.selectedDurationSeconds=Math.max(5,Math.min(900,q)))}),e.addEventListener("change",R=>{const q=parseInt(R.target.value,10),V=isNaN(q)?60:Math.max(5,Math.min(900,q));this.selectedDurationSeconds=V,e.value=String(V)})),(h=this.shadow.getElementById("btn-save"))==null||h.addEventListener("click",()=>{this.handleCapture()}),(u=this.shadow.getElementById("btn-annotate"))==null||u.addEventListener("click",()=>{this.handleAnnotate()}),(p=this.shadow.getElementById("btn-clear"))==null||p.addEventListener("click",()=>{this.handleClear()}),this.attachIncidentListeners(),this.exportModalIncidentId&&((g=this.shadow.getElementById("btn-close-export-modal"))==null||g.addEventListener("click",()=>{this.closeExportModal()}),(b=this.shadow.getElementById("btn-cancel-export-modal"))==null||b.addEventListener("click",()=>{this.closeExportModal()}),(k=this.shadow.getElementById("check-include-incident-link"))==null||k.addEventListener("change",R=>{this.exportModalIncludeLink=R.target.checked,this.render()}),(v=this.shadow.getElementById("btn-confirm-export-modal"))==null||v.addEventListener("click",()=>{this.confirmCopyMarkdown()})),this.downloadModalIncidentId&&((f=this.shadow.getElementById("btn-close-download-modal"))==null||f.addEventListener("click",()=>{this.closeDownloadModal()}),(m=this.shadow.getElementById("btn-cancel-download-modal"))==null||m.addEventListener("click",()=>{this.closeDownloadModal()}),(w=this.shadow.getElementById("radio-format-ai"))==null||w.addEventListener("change",()=>{this.downloadModalFormat="ai",this.downloadModalError=null,this.render()}),(x=this.shadow.getElementById("radio-format-gzip"))==null||x.addEventListener("change",()=>{this.downloadModalFormat="gzip",this.downloadModalError=null,this.render()}),(S=this.shadow.getElementById("radio-format-uncompressed"))==null||S.addEventListener("change",()=>{this.downloadModalFormat="uncompressed",this.downloadModalError=null,this.render()}),($=this.shadow.getElementById("btn-confirm-download-modal"))==null||$.addEventListener("click",()=>{this.confirmDownload()})),this.showHideConfirmModal&&((M=this.shadow.getElementById("btn-close-hide-modal"))==null||M.addEventListener("click",()=>{this.showHideConfirmModal=!1,this.render()}),(y=this.shadow.getElementById("btn-cancel-hide-modal"))==null||y.addEventListener("click",()=>{this.showHideConfirmModal=!1,this.render()}),(A=this.shadow.getElementById("btn-confirm-hide-modal"))==null||A.addEventListener("click",()=>{this.showHideConfirmModal=!1,this.hide()})),(_=this.shadow.querySelector(".backtrack-panel"))==null||_.addEventListener("click",R=>{if(this.isHeaderMenuOpen){const q=R.target;q!=null&&q.closest(".backtrack-header-menu-wrap")||(this.isHeaderMenuOpen=!1,this.render())}})}};l(F,"sessionGithubToken",null);let ee=F;const Se="0.4.2",I=class I{constructor(e,t){l(this,"options");l(this,"stateMachine");l(this,"db");l(this,"writer",null);l(this,"retention");l(this,"incidentManager",null);l(this,"widget",null);l(this,"consoleCapturer",null);l(this,"errorCapturer",null);l(this,"networkCapturer",null);l(this,"navigationCapturer",null);l(this,"rrwebCapturer",null);l(this,"performanceCapturer",null);l(this,"sequence",0);l(this,"retentionIntervalTimer",null);l(this,"retentionPromise",null);l(this,"cachedStorageBytes",0);l(this,"cachedIncidentCount",0);l(this,"pageHideHandler");l(this,"beforeUnloadHandler");l(this,"visibilityChangeHandler");l(this,"cachedProtectedBytes",0);l(this,"cachedBrowserEstimateBytes");l(this,"cachedBrowserQuotaBytes");l(this,"nextSequence",()=>(this.sequence++,this.sequence));l(this,"stoppingPromise");var i,n,r,o,s,a,c,h,u,p,g;this.options={bufferMinutes:(e==null?void 0:e.bufferMinutes)??5,afterErrorSeconds:(e==null?void 0:e.afterErrorSeconds)??15,maxStorageMb:(e==null?void 0:e.maxStorageMb)??50,captureHttpStatus:(e==null?void 0:e.captureHttpStatus)??[500,502,503,504],showWidget:(e==null?void 0:e.showWidget)??!1,widgetOptions:e==null?void 0:e.widgetOptions,metadata:e==null?void 0:e.metadata,recorderVersion:e==null?void 0:e.recorderVersion,ignoredUrls:e==null?void 0:e.ignoredUrls,network:{capturePayloads:((i=e==null?void 0:e.network)==null?void 0:i.capturePayloads)??!1,maxPayloadSize:((n=e==null?void 0:e.network)==null?void 0:n.maxPayloadSize)??64*1024},privacy:{maskAllInputs:((r=e==null?void 0:e.privacy)==null?void 0:r.maskAllInputs)??!0,maskAllText:((o=e==null?void 0:e.privacy)==null?void 0:o.maskAllText)??!1,blockMedia:((s=e==null?void 0:e.privacy)==null?void 0:s.blockMedia)??!0,blockSelector:(a=e==null?void 0:e.privacy)==null?void 0:a.blockSelector,maskTextSelector:(c=e==null?void 0:e.privacy)==null?void 0:c.maskTextSelector,sanitizeUrl:(h=e==null?void 0:e.privacy)==null?void 0:h.sanitizeUrl,sensitiveRoutes:(u=e==null?void 0:e.privacy)==null?void 0:u.sensitiveRoutes,autoMaskPII:(p=e==null?void 0:e.privacy)==null?void 0:p.autoMaskPII,recordCanvas:(g=e==null?void 0:e.privacy)==null?void 0:g.recordCanvas},storage:e==null?void 0:e.storage,sessionOptions:e==null?void 0:e.sessionOptions,batchWriterConfig:e==null?void 0:e.batchWriterConfig,transport:e==null?void 0:e.transport,beforeSend:e==null?void 0:e.beforeSend,context:e==null?void 0:e.context,getContext:e==null?void 0:e.getContext},this.stateMachine=new $e("stopped"),this.db=t||new De,this.retention=new _e(this.db,{bufferMinutes:this.options.bufferMinutes,maxStorageMb:this.options.maxStorageMb})}static async init(e,t){if(I.activeInstance)return I.activeInstance;const i=new I(e,t);if(await i.start(),I.activeInstance=i,typeof window<"u"){const n=window;n.Backtrack=I,n.flightRecorder=i,n.hideBacktrack=()=>I.hideWidget(),n.showBacktrack=()=>I.showWidget(),n.toggleBacktrack=()=>I.toggleWidget()}return i}static hideWidget(){const e=I.activeInstance;if(e!=null&&e.widget)e.widget.hide();else try{if(typeof localStorage<"u"&&localStorage.setItem("backtrack_widget_hidden","true"),typeof document<"u"){const t=document.getElementById("__backtrack_widget_host__");t&&(t.style.display="none")}}catch{}}static showWidget(){const e=I.activeInstance;if(e!=null&&e.widget)e.widget.show();else try{if(typeof localStorage<"u"&&localStorage.removeItem("backtrack_widget_hidden"),typeof document<"u"){const t=document.getElementById("__backtrack_widget_host__");t&&(t.style.display="")}}catch{}}static toggleWidget(){const e=I.activeInstance;return e!=null&&e.widget?e.widget.toggle():typeof localStorage<"u"&&localStorage.getItem("backtrack_widget_hidden")==="true"?(I.showWidget(),!0):(I.hideWidget(),!1)}static hide(){I.hideWidget()}static show(){I.showWidget()}static toggle(){return I.toggleWidget()}static async resetInstance(){I.activeInstance&&(await I.activeInstance.stop(),I.activeInstance=null)}static getInstance(){return I.activeInstance}hideWidget(){this.widget?this.widget.hide():I.hideWidget()}showWidget(){this.widget?this.widget.show():I.showWidget()}toggleWidget(){return this.widget?this.widget.toggle():I.toggleWidget()}getEnvironmentMetadata(){const e=this.options.metadata;if(typeof window>"u")return{url:"http://localhost",userAgent:"node",viewport:{width:1280,height:720},...e};const t=window;return{url:window.location.href,userAgent:window.navigator.userAgent,viewport:{width:window.innerWidth,height:window.innerHeight},appVersion:(e==null?void 0:e.appVersion)??t.__APP_VERSION__??t.__UTICKET_APP_VERSION__,gitBranch:(e==null?void 0:e.gitBranch)??t.__GIT_BRANCH__??t.__UTICKET_GIT_BRANCH__,gitCommit:(e==null?void 0:e.gitCommit)??t.__GIT_COMMIT__??t.__UTICKET_GIT_COMMIT__,...e}}async start(){var e,t,i,n;if(!this.stateMachine.isRecording())try{await this.db.open();const r=await qe({...this.options.sessionOptions,...this.options.storage?{storage:this.options.storage}:{}}),o=await this.db.getChunksBySession(r.sessionId),s=Math.max(0,...o.flatMap(c=>(c.timeline||[]).map(h=>h.sequence))),a=Math.max(0,...o.map(c=>c.sequence));this.sequence=s,this.writer=new Pe(this.db,r.sessionId,r.tabId,{...this.options.batchWriterConfig,initialChunkSequence:a},c=>{var u;c instanceof Error&&(c.name==="QuotaExceededError"||((u=c.message)==null?void 0:u.includes("QuotaExceededError")))||typeof DOMException<"u"&&c instanceof DOMException&&c.name==="QuotaExceededError"?this.handleQuotaExceeded():this.stateMachine.transition({type:"DEGRADE",reason:"Falha ao persistir um lote; a gravação pode estar incompleta."})}),this.writer.setOnChunkPersisted(()=>{this.scheduleRetention()}),this.incidentManager=new ie(this.db,r.sessionId,r.tabId,()=>this.getEnvironmentMetadata(),{afterErrorSeconds:this.options.afterErrorSeconds,recorderVersion:this.options.recorderVersion??Se,context:this.options.context,getContext:this.options.getContext,getRecordingIssues:()=>{var c;return[...this.stateMachine.getDegradedReasons(),...(((c=this.rrwebCapturer)==null?void 0:c.getDroppedEventsCount())??0)>0?["O capturador não conseguiu registrar parte do replay."]:[]]},getDroppedEventsCount:()=>{var c;return((c=this.rrwebCapturer)==null?void 0:c.getDroppedEventsCount())??0}}),this.incidentManager.setOnIncidentPending(()=>{this.stateMachine.transition({type:"TRIGGER_AUTO"})}),this.incidentManager.setOnIncidentFinalized(c=>{var h;(h=this.incidentManager)!=null&&h.getPendingIncident()||this.stateMachine.transition({type:"FINALIZE_INCIDENT"}),this.updateStatsCache(),this.sendIncident(c.id)}),this.incidentManager.setOnError(c=>{var u;c instanceof Error&&(c.name==="QuotaExceededError"||((u=c.message)==null?void 0:u.includes("QuotaExceededError")))||typeof DOMException<"u"&&c instanceof DOMException&&c.name==="QuotaExceededError"?this.handleQuotaExceeded():this.stateMachine.transition({type:"DEGRADE",reason:"Falha no gerenciamento de incidentes; o incidente pode não ter sido salvo completamente."})}),this.incidentManager.setBeforeFinalize(async()=>{this.writer&&await this.writer.flush()}),await this.incidentManager.init(),this.consoleCapturer=new Oe(this.writer,this.nextSequence),this.errorCapturer=new Ne(this.writer,this.incidentManager,this.nextSequence),this.networkCapturer=new Fe(this.writer,this.incidentManager,this.nextSequence,{captureHttpStatus:this.options.captureHttpStatus,ignoredUrls:this.options.ignoredUrls,sanitizeUrlCallback:(e=this.options.privacy)==null?void 0:e.sanitizeUrl,capturePayloads:(t=this.options.network)==null?void 0:t.capturePayloads,maxPayloadSize:(i=this.options.network)==null?void 0:i.maxPayloadSize}),this.navigationCapturer=new je(this.writer,this.nextSequence,{sanitizeUrlCallback:(n=this.options.privacy)==null?void 0:n.sanitizeUrl}),this.rrwebCapturer=new We(this.writer,{privacy:this.options.privacy}),this.performanceCapturer=new Ve(this.writer,this.nextSequence),this.consoleCapturer.start(),this.errorCapturer.start(),this.networkCapturer.start(),this.navigationCapturer.start(),this.rrwebCapturer.start(),this.performanceCapturer.start(),this.stateMachine.transition({type:"START"}),this.incidentManager.getPendingIncident()&&this.stateMachine.transition({type:"TRIGGER_AUTO"}),this.retentionIntervalTimer=setInterval(()=>{this.scheduleRetention()},3e4),this.updateStatsCache(),this.options.showWidget&&typeof window<"u"&&(this.widget=new ee(this,this.options.widgetOptions),this.widget.mount()),typeof window<"u"&&typeof window.addEventListener=="function"&&(this.pageHideHandler=()=>{var c;(c=this.incidentManager)==null||c.syncPendingIncidentDroppedEvents().catch(()=>{})},this.beforeUnloadHandler=()=>{var c;(c=this.incidentManager)==null||c.syncPendingIncidentDroppedEvents().catch(()=>{})},window.addEventListener("pagehide",this.pageHideHandler),window.addEventListener("beforeunload",this.beforeUnloadHandler)),typeof document<"u"&&typeof document.addEventListener=="function"&&(this.visibilityChangeHandler=()=>{var c;document.visibilityState==="hidden"&&((c=this.incidentManager)==null||c.syncPendingIncidentDroppedEvents().catch(()=>{}))},document.addEventListener("visibilitychange",this.visibilityChangeHandler))}catch(r){this.stateMachine.transition({type:"DEGRADE",reason:`Falha ao iniciar recorder: ${r instanceof Error?r.message:String(r)}`})}}scheduleRetention(){return this.retentionPromise?this.retentionPromise:(this.retentionPromise=(async()=>{try{this.incidentManager?await this.incidentManager.runExclusive(async()=>{var e;await((e=this.incidentManager)==null?void 0:e.protectSessionChunks()),await this.retention.prune(),await this.updateStatsCache()}):(await this.retention.prune(),await this.updateStatsCache())}catch{this.stateMachine.transition({type:"DEGRADE",reason:"Falha na manutenção do armazenamento local."})}finally{this.retentionPromise=null}})(),this.retentionPromise)}async handleQuotaExceeded(){try{this.incidentManager?await this.incidentManager.runExclusive(async()=>{var n;await((n=this.incidentManager)==null?void 0:n.protectSessionChunks()),await this.retention.emergencyPrune(),await this.updateStatsCache()}):(await this.retention.emergencyPrune(),await this.updateStatsCache())}catch{}const e=await this.retention.getStorageBreakdown().catch(()=>null),i=(e?e.bufferBytes===0&&e.protectedBytes>0:!1)||e!=null&&e.protectedExceedsLimit?"A quota do navegador foi excedida. Apenas conteúdo protegido permanece salvo; é necessário excluir incidentes ou limpar gravações para liberar espaço.":"A quota do navegador impediu a gravação de um lote. Um prune emergencial de dados não protegidos foi executado.";this.stateMachine.transition({type:"DEGRADE",reason:i})}async updateStatsCache(){try{const e=await this.retention.getStorageBreakdown();if(this.cachedStorageBytes=e.totalBytes,this.cachedProtectedBytes=e.protectedBytes,this.cachedIncidentCount=e.incidentCount,typeof navigator<"u"&&navigator.storage&&typeof navigator.storage.estimate=="function")try{const t=await navigator.storage.estimate();this.cachedBrowserEstimateBytes=t.usage,this.cachedBrowserQuotaBytes=t.quota}catch{}if(e.protectedExceedsLimit)this.stateMachine.transition({type:"DEGRADE",reason:"O armazenamento protegido por incidentes excede o limite configurado (maxStorageMb)."});else if(!e.isOverLimit&&this.stateMachine.isDegraded()){const t=this.stateMachine.getDegradedReasons();t.every(n=>n.includes("maxStorageMb")||n.includes("quota")||n.includes("Quota")||n.includes("armazenamento"))&&t.length>0&&this.stateMachine.transition({type:"RECOVER"})}}catch{}}async sendIncident(e){const t=this.options.transport;if(t)try{const i=await this.getArtifact(e),n=this.options.beforeSend?await this.options.beforeSend(i):i;n&&await t.send(n)}catch{}}stopCapturers(){var e,t,i,n,r,o;(e=this.rrwebCapturer)==null||e.stop(),(t=this.navigationCapturer)==null||t.stop(),(i=this.networkCapturer)==null||i.stop(),(n=this.errorCapturer)==null||n.stop(),(r=this.consoleCapturer)==null||r.stop(),(o=this.performanceCapturer)==null||o.stop()}clearRuntimeReferences(){this.rrwebCapturer=null,this.navigationCapturer=null,this.networkCapturer=null,this.errorCapturer=null,this.consoleCapturer=null,this.performanceCapturer=null,this.writer=null,this.incidentManager=null}async stop(){if(this.stateMachine.getState()!=="stopped"){if(this.stoppingPromise)return this.stoppingPromise;this.stoppingPromise=(async()=>{var e;if(this.stopCapturers(),this.retentionIntervalTimer&&(clearInterval(this.retentionIntervalTimer),this.retentionIntervalTimer=null),this.widget&&(this.widget.unmount(),this.widget=null),I.activeInstance===this&&(I.activeInstance=null),this.retentionPromise)try{await this.retentionPromise}catch{}typeof window<"u"&&typeof window.removeEventListener=="function"&&(this.pageHideHandler&&(window.removeEventListener("pagehide",this.pageHideHandler),this.pageHideHandler=void 0),this.beforeUnloadHandler&&(window.removeEventListener("beforeunload",this.beforeUnloadHandler),this.beforeUnloadHandler=void 0)),typeof document<"u"&&typeof document.removeEventListener=="function"&&this.visibilityChangeHandler&&(document.removeEventListener("visibilitychange",this.visibilityChangeHandler),this.visibilityChangeHandler=void 0),this.writer&&await this.writer.flush(),(e=this.writer)==null||e.destroy(),this.incidentManager&&(await this.incidentManager.syncPendingIncidentDroppedEvents().catch(()=>{}),await this.incidentManager.destroy()),te(),this.clearRuntimeReferences(),this.stateMachine.transition({type:"STOP"})})();try{await this.stoppingPromise}finally{this.stoppingPromise=void 0}}}async capture(e="manual",t,i){if(!this.incidentManager||!this.writer)throw new Error("FlightRecorder não está em execução.");const n=await this.incidentManager.runExclusive(async()=>{const r=Date.now();return this.writer.addTimelineEvent({id:`marker_manual_${r}`,timestamp:r,sequence:this.nextSequence(),type:"marker",label:`Captura manual: ${e}`}),await this.writer.flush(),this.incidentManager.executeManualTrigger({id:`trig_manual_${r}`,timestamp:r,type:"manual",signature:`manual_capture_${e}`,detail:{userReason:e,windowSeconds:t,annotationImage:i==null?void 0:i.annotationImage,notes:i==null?void 0:i.notes,annotations:i==null?void 0:i.annotations}},t)});return await this.updateStatsCache(),n}captureException(e,t){if(this.errorCapturer)try{return this.errorCapturer.captureException(e,t)}catch{}}async listIncidents(){try{return await this.db.listIncidents()}catch{return[]}}async getArtifact(e){return this.incidentManager?this.incidentManager.exportArtifact(e):new ie(this.db,"","",()=>this.getEnvironmentMetadata(),{recorderVersion:this.options.recorderVersion??Se,context:this.options.context,getContext:this.options.getContext,getRecordingIssues:()=>this.stateMachine.getDegradedReasons()}).exportArtifact(e)}async exportIncident(e,t){const i=await this.getArtifact(e),n=new Date(i.incident.triggeredAt).toISOString().replace(/:/g,"-").replace(/\..+/,""),r=(t==null?void 0:t.aiOptimized)??!1,o=!r&&((t==null?void 0:t.compress)??!1),s=r?".ai.json":o?".ffr.json.gz":".ffr.json",a=`flight-recorder-${n}-${i.incident.reason}-${e}${s}`,c=r?{...i,replay:[],_aiNote:"Replay visual removido para otimizacao de IA. Timeline, erros de console e rede preservados."}:i;if(typeof window<"u"&&typeof document<"u"){let h;if(o){const g=await ze(i);h=new Blob([g],{type:"application/gzip"})}else{const g=JSON.stringify(c,null,2);h=new Blob([g],{type:"application/json;charset=utf-8"})}const u=URL.createObjectURL(h),p=document.createElement("a");p.href=u,p.download=a,document.body.appendChild(p),p.click(),document.body.removeChild(p),URL.revokeObjectURL(u)}return c}async deleteIncident(e){this.incidentManager?(await this.incidentManager.deleteIncident(e),await this.incidentManager.runExclusive(async()=>{await this.retention.prune(),await this.updateStatsCache()})):(await this.db.deleteIncident(e),await this.retention.prune(),await this.updateStatsCache())}async clear(){if(this.writer&&await this.writer.flush(),this.retentionPromise)try{await this.retentionPromise}catch{}this.incidentManager&&await this.incidentManager.reset(),this.stateMachine.getState()==="incident_pending"&&this.stateMachine.transition({type:"FINALIZE_INCIDENT"}),await this.db.clearAll(),this.cachedStorageBytes=0,this.cachedProtectedBytes=0,this.cachedIncidentCount=0}getHealth(){var i,n;const e=((i=this.rrwebCapturer)==null?void 0:i.getDroppedEventsCount())??0,t=(this.options.maxStorageMb??50)*1024*1024;return{state:this.stateMachine.getState(),droppedEvents:e,storageBytes:this.cachedStorageBytes,protectedStorageBytes:this.cachedProtectedBytes,storageLimitBytes:t,storageLimitExceeded:this.cachedStorageBytes>t,protectedStorageExceeded:this.cachedProtectedBytes>t,browserStorageEstimateBytes:this.cachedBrowserEstimateBytes,browserStorageQuotaBytes:this.cachedBrowserQuotaBytes,pendingWrites:((n=this.writer)==null?void 0:n.getPendingWrites())??0,incidentCount:this.cachedIncidentCount,reasons:this.stateMachine.getDegradedReasons()}}getSequence(){return this.sequence}async flush(){this.writer&&await this.writer.flush()}async destroy(){await this.stop()}};l(I,"activeInstance",null);let W=I;function Je(d){return new W(d)}exports.Backtrack=W;exports.BacktrackImpl=W;exports.BacktrackWidget=ee;exports.BatchWriter=Pe;exports.ConsoleCapturer=Oe;exports.DB_NAME=Be;exports.DB_VERSION=Re;exports.ErrorCapturer=Ne;exports.FlightRecorderDB=De;exports.FlightRecorderImpl=W;exports.IncidentManager=ie;exports.MAX_ARTIFACT_BYTES=K;exports.NavigationCapturer=je;exports.NetworkCapturer=Fe;exports.PerformanceCapturer=Ve;exports.RecorderStateMachine=$e;exports.RetentionEngine=_e;exports.RrwebCapturer=We;exports.STORE_CHUNKS=B;exports.STORE_INCIDENTS=D;exports.STORE_SESSIONS=N;exports.ScreenAnnotator=Ye;exports.claimSessionContext=qe;exports.closeSessionChannel=te;exports.compressArtifact=ze;exports.compressGzip=ae;exports.createBacktrack=Je;exports.createFlightRecorder=Je;exports.decompressArtifact=rt;exports.decompressGzip=Z;exports.formatIncidentMarkdown=Xe;exports.generateIncidentId=ne;exports.getOrCreateSessionContext=He;exports.globToRegex=Ue;exports.isGzip=Le;exports.isReplayEvent=Me;exports.isValidAnnotationImage=Ce;exports.matchesSensitiveRoute=Ge;exports.readLimitedStream=oe;exports.readResponseBytes=it;exports.redactSensitiveString=L;exports.resetSessionContext=at;exports.sanitizeAndSerialize=le;exports.sanitizeHeaders=Y;exports.sanitizePayloadString=X;exports.sanitizeUrl=J;exports.sliceReplayEventsForWindow=ot;exports.sliceReplayEventsWithMetadata=se;exports.sortTimelineEvents=Te;exports.uploadArtifactToGist=re;exports.validateFlightRecorderArtifact=Ae;
1803
1803
  //# sourceMappingURL=index.cjs.map
package/dist/index.js CHANGED
@@ -5234,7 +5234,7 @@ const ft = `
5234
5234
  };
5235
5235
  l(N, "sessionGithubToken", null);
5236
5236
  let Z = N;
5237
- const we = "0.4.0", I = class I {
5237
+ const we = "0.4.2", I = class I {
5238
5238
  constructor(e, t) {
5239
5239
  l(this, "options");
5240
5240
  l(this, "stateMachine");