@backtrack-js/browser 0.5.1 → 0.5.3

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.
Files changed (89) hide show
  1. package/README.md +30 -483
  2. package/dist/capturers/console.d.ts +0 -1
  3. package/dist/capturers/errors.d.ts +0 -1
  4. package/dist/capturers/index.d.ts +0 -1
  5. package/dist/capturers/navigation.d.ts +0 -1
  6. package/dist/capturers/network.d.ts +0 -1
  7. package/dist/capturers/performance.d.ts +0 -1
  8. package/dist/capturers/route-matcher.d.ts +0 -1
  9. package/dist/capturers/rrweb.d.ts +0 -1
  10. package/dist/capturers/sanitizer.d.ts +0 -1
  11. package/dist/core/flight-recorder.d.ts +0 -1
  12. package/dist/core/state-machine.d.ts +0 -1
  13. package/dist/dev-server/index.d.ts +0 -1
  14. package/dist/dev-server/middleware.d.ts +0 -1
  15. package/dist/dev-server.cjs +0 -1
  16. package/dist/dev-server.js +0 -1
  17. package/dist/index.cjs +6 -7
  18. package/dist/index.d.ts +0 -1
  19. package/dist/index.js +628 -608
  20. package/dist/markdown-Ao5Ah9MF.cjs +0 -1
  21. package/dist/markdown-D3C94OlY.js +0 -1
  22. package/dist/storage/batch-writer.d.ts +0 -1
  23. package/dist/storage/db.d.ts +0 -1
  24. package/dist/storage/incident-manager.d.ts +0 -1
  25. package/dist/storage/index.d.ts +0 -1
  26. package/dist/storage/retention.d.ts +0 -1
  27. package/dist/storage/session.d.ts +0 -1
  28. package/dist/types/artifact.d.ts +0 -1
  29. package/dist/types/chunk.d.ts +0 -1
  30. package/dist/types/health.d.ts +0 -1
  31. package/dist/types/incident.d.ts +1 -1
  32. package/dist/types/index.d.ts +0 -1
  33. package/dist/types/options.d.ts +0 -1
  34. package/dist/types/timeline.d.ts +0 -1
  35. package/dist/types/transport.d.ts +0 -1
  36. package/dist/utils/compression.d.ts +0 -1
  37. package/dist/utils/gist-uploader.d.ts +0 -1
  38. package/dist/utils/markdown.d.ts +0 -1
  39. package/dist/validation/validate.d.ts +0 -1
  40. package/dist/viewer/assets/index-092olPra.css +1 -0
  41. package/dist/viewer/assets/index-BkV3C4kX.js +197 -0
  42. package/dist/viewer/index.html +2 -2
  43. package/dist/widget/annotator.d.ts +0 -1
  44. package/dist/widget/styles.d.ts +0 -1
  45. package/dist/widget/widget.d.ts +0 -1
  46. package/package.json +15 -4
  47. package/dist/capturers/console.d.ts.map +0 -1
  48. package/dist/capturers/errors.d.ts.map +0 -1
  49. package/dist/capturers/index.d.ts.map +0 -1
  50. package/dist/capturers/navigation.d.ts.map +0 -1
  51. package/dist/capturers/network.d.ts.map +0 -1
  52. package/dist/capturers/performance.d.ts.map +0 -1
  53. package/dist/capturers/route-matcher.d.ts.map +0 -1
  54. package/dist/capturers/rrweb.d.ts.map +0 -1
  55. package/dist/capturers/sanitizer.d.ts.map +0 -1
  56. package/dist/core/flight-recorder.d.ts.map +0 -1
  57. package/dist/core/state-machine.d.ts.map +0 -1
  58. package/dist/dev-server/index.d.ts.map +0 -1
  59. package/dist/dev-server/middleware.d.ts.map +0 -1
  60. package/dist/dev-server.cjs.map +0 -1
  61. package/dist/dev-server.js.map +0 -1
  62. package/dist/index.cjs.map +0 -1
  63. package/dist/index.d.ts.map +0 -1
  64. package/dist/index.js.map +0 -1
  65. package/dist/markdown-Ao5Ah9MF.cjs.map +0 -1
  66. package/dist/markdown-D3C94OlY.js.map +0 -1
  67. package/dist/storage/batch-writer.d.ts.map +0 -1
  68. package/dist/storage/db.d.ts.map +0 -1
  69. package/dist/storage/incident-manager.d.ts.map +0 -1
  70. package/dist/storage/index.d.ts.map +0 -1
  71. package/dist/storage/retention.d.ts.map +0 -1
  72. package/dist/storage/session.d.ts.map +0 -1
  73. package/dist/types/artifact.d.ts.map +0 -1
  74. package/dist/types/chunk.d.ts.map +0 -1
  75. package/dist/types/health.d.ts.map +0 -1
  76. package/dist/types/incident.d.ts.map +0 -1
  77. package/dist/types/index.d.ts.map +0 -1
  78. package/dist/types/options.d.ts.map +0 -1
  79. package/dist/types/timeline.d.ts.map +0 -1
  80. package/dist/types/transport.d.ts.map +0 -1
  81. package/dist/utils/compression.d.ts.map +0 -1
  82. package/dist/utils/gist-uploader.d.ts.map +0 -1
  83. package/dist/utils/markdown.d.ts.map +0 -1
  84. package/dist/validation/validate.d.ts.map +0 -1
  85. package/dist/viewer/assets/index-C3SZvpLL.js +0 -197
  86. package/dist/viewer/assets/index-CKVr0pQ5.css +0 -1
  87. package/dist/widget/annotator.d.ts.map +0 -1
  88. package/dist/widget/styles.d.ts.map +0 -1
  89. package/dist/widget/widget.d.ts.map +0 -1
package/dist/index.cjs CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var Ft=Object.defineProperty;var jt=(d,t,e)=>t in d?Ft(d,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):d[t]=e;var l=(d,t,e)=>jt(d,typeof t!="symbol"?t+"":t,e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const q=require("./markdown-Ao5Ah9MF.cjs"),Ut=require("@rrweb/record");class xt{constructor(t="stopped"){l(this,"currentState","stopped");l(this,"degradedReasons",new Set);l(this,"previousOperationalState","stopped");this.currentState=t}getState(){return this.currentState}getDegradedReasons(){return Array.from(this.degradedReasons)}isDegraded(){return this.currentState==="degraded"}isRecording(){return this.currentState==="recording"||this.currentState==="incident_pending"||this.currentState==="degraded"&&(this.previousOperationalState==="recording"||this.previousOperationalState==="incident_pending")}transition(t){switch(t.type){case"START":this.currentState==="stopped"&&(this.currentState="recording");break;case"STOP":this.currentState="stopped",this.degradedReasons.clear(),this.previousOperationalState="stopped";break;case"TRIGGER_AUTO":this.currentState==="recording"?this.currentState="incident_pending":this.currentState==="degraded"&&(this.previousOperationalState="incident_pending");break;case"TRIGGER_MANUAL":break;case"FINALIZE_INCIDENT":this.currentState==="incident_pending"?this.currentState="recording":this.currentState==="degraded"&&(this.previousOperationalState="recording");break;case"DEGRADE":this.degradedReasons.add(t.reason),this.currentState!=="degraded"&&(this.previousOperationalState=this.currentState,this.currentState="degraded");break;case"RECOVER":this.degradedReasons.clear(),this.currentState==="degraded"&&(this.currentState=this.previousOperationalState==="stopped"?"stopped":this.previousOperationalState);break}return this.currentState}}const It="backtrack_db",Et=1,$="sessions",S="chunks",R="incidents";class St{constructor(t,e){l(this,"db",null);l(this,"idbFactory");l(this,"dbName");this.idbFactory=t||(typeof indexedDB<"u"?indexedDB:void 0),this.dbName=e||It}async open(){if(this.db)return this.db;if(!this.idbFactory)throw new Error("IndexedDB não está disponível neste ambiente.");return new Promise((t,e)=>{const r=this.idbFactory.open(this.dbName,Et);r.onupgradeneeded=n=>{const i=n.target.result;if(i.objectStoreNames.contains($)||i.createObjectStore($,{keyPath:"id"}).createIndex("startedAt","startedAt",{unique:!1}),!i.objectStoreNames.contains(S)){const a=i.createObjectStore(S,{keyPath:"id"});a.createIndex("sessionId","sessionId",{unique:!1}),a.createIndex("tabId","tabId",{unique:!1}),a.createIndex("sequence","sequence",{unique:!1}),a.createIndex("startedAt","startedAt",{unique:!1}),a.createIndex("endedAt","endedAt",{unique:!1})}if(!i.objectStoreNames.contains(R)){const a=i.createObjectStore(R,{keyPath:"id"});a.createIndex("sessionId","sessionId",{unique:!1}),a.createIndex("state","state",{unique:!1}),a.createIndex("triggeredAt","triggeredAt",{unique:!1})}},r.onsuccess=n=>{this.db=n.target.result,t(this.db)},r.onerror=n=>{e(n.target.error)}})}close(){this.db&&(this.db.close(),this.db=null)}async putSession(t){const e=await this.open();return new Promise((r,n)=>{const i=e.transaction($,"readwrite");i.objectStore($).put(t),i.oncomplete=()=>r(),i.onerror=()=>n(i.error)})}async getSession(t){const e=await this.open();return new Promise((r,n)=>{const a=e.transaction($,"readonly").objectStore($).get(t);a.onsuccess=()=>r(a.result||null),a.onerror=()=>n(a.error)})}async putChunk(t){const e=await this.open();return new Promise((r,n)=>{const i=e.transaction(S,"readwrite");i.objectStore(S).put(t),i.oncomplete=()=>r(),i.onerror=()=>n(i.error)})}async putChunks(t){if(t.length===0)return;const e=await this.open();return new Promise((r,n)=>{const i=e.transaction(S,"readwrite"),a=i.objectStore(S);for(const s of t)a.put(s);i.oncomplete=()=>r(),i.onerror=()=>n(i.error)})}async getChunk(t){const e=await this.open();return new Promise((r,n)=>{const a=e.transaction(S,"readonly").objectStore(S).get(t);a.onsuccess=()=>r(a.result||null),a.onerror=()=>n(a.error)})}async getChunksByIds(t){if(t.length===0)return[];const e=await this.open();return new Promise((r,n)=>{const a=e.transaction(S,"readonly").objectStore(S),s=[];let o=t.length;for(const c of t){const h=a.get(c);h.onsuccess=()=>{h.result&&s.push(h.result),o--,o===0&&r(s)},h.onerror=()=>n(h.error)}})}async getChunksBySession(t){const e=await this.open();return new Promise((r,n)=>{const s=e.transaction(S,"readonly").objectStore(S).index("sessionId").getAll(t);s.onsuccess=()=>{const o=s.result||[];o.sort((c,h)=>c.startedAt!==h.startedAt?c.startedAt-h.startedAt:c.sequence-h.sequence),r(o)},s.onerror=()=>n(s.error)})}async getAllChunks(){const t=await this.open();return new Promise((e,r)=>{const i=t.transaction(S,"readonly").objectStore(S).getAll();i.onsuccess=()=>e(i.result||[]),i.onerror=()=>r(i.error)})}async deleteChunks(t){if(t.length===0)return;const e=await this.open();return new Promise((r,n)=>{const i=e.transaction(S,"readwrite"),a=i.objectStore(S);for(const s of t)a.delete(s);i.oncomplete=()=>r(),i.onerror=()=>n(i.error)})}async putIncident(t){const e=await this.open();return new Promise((r,n)=>{const i=e.transaction(R,"readwrite");i.objectStore(R).put(t),i.oncomplete=()=>r(),i.onerror=()=>n(i.error)})}async getIncident(t){const e=await this.open();return new Promise((r,n)=>{const a=e.transaction(R,"readonly").objectStore(R).get(t);a.onsuccess=()=>r(a.result||null),a.onerror=()=>n(a.error)})}async getPendingIncidentForSession(t){const e=await this.open();return new Promise((r,n)=>{const s=e.transaction(R,"readonly").objectStore(R).index("sessionId").getAll(t);s.onsuccess=()=>{const c=(s.result||[]).find(h=>h.state==="pending");r(c||null)},s.onerror=()=>n(s.error)})}async listIncidents(){const t=await this.open();return new Promise((e,r)=>{const i=t.transaction(R,"readonly").objectStore(R).getAll();i.onsuccess=()=>{const s=(i.result||[]).map(o=>({id:o.id,reason:o.reason,startedAt:o.startedAt,triggeredAt:o.triggeredAt,finalizedAt:o.finalizedAt,eventCount:o.chunkIds.length,triggerCount:o.triggers.length}));s.sort((o,c)=>c.triggeredAt-o.triggeredAt),e(s)},i.onerror=()=>r(i.error)})}async deleteIncident(t){const e=await this.open();return new Promise((r,n)=>{const i=e.transaction(R,"readwrite");i.objectStore(R).delete(t),i.oncomplete=()=>r(),i.onerror=()=>n(i.error)})}async getAllIncidents(){const t=await this.open();return new Promise((e,r)=>{const i=t.transaction(R,"readonly").objectStore(R).getAll();i.onsuccess=()=>e(i.result||[]),i.onerror=()=>r(i.error)})}async estimateStorageBytes(){return(await this.getAllChunks()).reduce((e,r)=>e+(r.sizeBytes||0),0)}async clearAll(){const t=await this.open();return new Promise((e,r)=>{const n=t.transaction([$,S,R],"readwrite");n.objectStore($).clear(),n.objectStore(S).clear(),n.objectStore(R).clear(),n.oncomplete=()=>e(),n.onerror=()=>r(n.error)})}}const Y=50*1024*1024;function H(d,t){if(d>t)throw new Error("O conteúdo excede o limite máximo permitido de "+Math.round(t/1024/1024)+" MiB.")}async function nt(d,t=Y){const e=d.getReader(),r=[];let n=0;try{for(;;){const{done:s,value:o}=await e.read();if(s)break;n+=o.byteLength,H(n,t),r.push(o)}}catch(s){throw await e.cancel().catch(()=>{}),s}finally{e.releaseLock()}const i=new Uint8Array(n);let a=0;for(const s of r)i.set(s,a),a+=s.byteLength;return i}async function Wt(d,t=Y){var r,n,i;if(!d.ok)throw new Error("Falha ao baixar conteúdo ("+d.status+").");const e=Number((n=(r=d.headers)==null?void 0:r.get)==null?void 0:n.call(r,"content-length"));if(Number.isFinite(e)&&e>t&&(await((i=d.body)==null?void 0:i.cancel().catch(()=>{})),H(e,t)),d.body)return nt(d.body,t);if(typeof d.arrayBuffer=="function"){const a=await d.arrayBuffer(),s=new Uint8Array(a);return H(s.byteLength,t),s}if(typeof d.text=="function"){const a=await d.text(),s=new TextEncoder().encode(a);return H(s.byteLength,t),s}if(typeof d.json=="function"){const a=await d.json(),s=new TextEncoder().encode(JSON.stringify(a));return H(s.byteLength,t),s}throw new Error("Resposta sem conteúdo legível.")}function Ct(d){return d.length>=2&&d[0]===31&&d[1]===139}async function it(d){const t=typeof d=="string"?new TextEncoder().encode(d):d;if(typeof CompressionStream<"u"){const r=new Blob([t]).stream().pipeThrough(new CompressionStream("gzip")),i=await new Response(r).blob();return new Uint8Array(await i.arrayBuffer())}return t}async function J(d,t=Y){if(H(d.byteLength,t),!Ct(d))return new TextDecoder().decode(d);if(typeof DecompressionStream<"u"){const r=new Blob([d]).stream().pipeThrough(new DecompressionStream("gzip"));return new TextDecoder().decode(await nt(r,t))}throw new Error("Este navegador não suporta descompressão Gzip. Use um arquivo JSON ou um navegador compatível.")}async function Mt(d){const t=JSON.stringify(d);return it(t)}async function Gt(d,t=Y){let e;if(typeof d=="object"&&d!==null&&!(d instanceof ArrayBuffer)&&!(d instanceof Uint8Array)){const n=JSON.stringify(d);H(n.length,t),H(new TextEncoder().encode(n).byteLength,t),e=d}else if(typeof d=="string"){H(d.length,t),H(new TextEncoder().encode(d).byteLength,t);try{e=JSON.parse(d)}catch(n){throw new Error(`Falha ao converter dados em JSON: ${n instanceof Error?n.message:String(n)}`)}}else if(d instanceof ArrayBuffer||d instanceof Uint8Array){const n=d instanceof Uint8Array?d:new Uint8Array(d),i=await J(n,t);try{e=JSON.parse(i)}catch(a){throw new Error(`Falha ao converter dados em JSON: ${a instanceof Error?a.message:String(a)}`)}}else throw new Error("Formato de dados inválido para o artefato.");const r=q.validateFlightRecorderArtifact(e);if(!r.success)throw new Error(`Artefato inválido: ${r.errors.join(", ")}`);return r.data}class Tt{constructor(t,e,r,n,i){l(this,"db");l(this,"config");l(this,"sessionId");l(this,"tabId");l(this,"chunkSequence",0);l(this,"pendingTimelineEvents",[]);l(this,"pendingReplayEvents",[]);l(this,"timer",null);l(this,"writeChain",Promise.resolve());l(this,"pendingWritesCount",0);l(this,"onErrorCallback");l(this,"onChunkPersistedCallback");l(this,"pageHideHandler");l(this,"visibilityChangeHandler");l(this,"flushCount",0);l(this,"onFlushMetricsCallback");this.db=t,this.sessionId=e,this.tabId=r,this.config={flushIntervalMs:(n==null?void 0:n.flushIntervalMs)??1e3,maxBatchEvents:(n==null?void 0:n.maxBatchEvents)??250,chunkDurationMs:(n==null?void 0:n.chunkDurationMs)??6e4,initialChunkSequence:(n==null?void 0:n.initialChunkSequence)??0,onFlushMetrics:n==null?void 0:n.onFlushMetrics},this.chunkSequence=(n==null?void 0:n.initialChunkSequence)??0,this.onErrorCallback=i,this.onFlushMetricsCallback=n==null?void 0:n.onFlushMetrics,this.initLifecycleListeners()}getChunkSequence(){return this.chunkSequence}setOnFlushMetrics(t){this.onFlushMetricsCallback=t}setOnChunkPersisted(t){this.onChunkPersistedCallback=t}getPendingWrites(){return this.pendingWritesCount}addTimelineEvent(t){this.pendingTimelineEvents.push(t),this.checkThresholds()}addReplayEvent(t){this.pendingReplayEvents.push(t),this.checkThresholds()}checkThresholds(){this.pendingTimelineEvents.length+this.pendingReplayEvents.length>=this.config.maxBatchEvents?this.flush():this.timer||(this.timer=setTimeout(()=>{this.timer=null,this.flush()},this.config.flushIntervalMs))}flush(){if(this.timer&&(clearTimeout(this.timer),this.timer=null),this.pendingTimelineEvents.length===0&&this.pendingReplayEvents.length===0)return this.writeChain;const t=[...this.pendingTimelineEvents],e=[...this.pendingReplayEvents];this.pendingTimelineEvents=[],this.pendingReplayEvents=[];const r=Date.now(),n=[...t.map(f=>f.timestamp),...e.map(f=>f.timestamp)],i=n.length>0?Math.min(...n):r,a=n.length>0?Math.max(...n):r;this.chunkSequence++;const s=e.filter(f=>f.type===2).map(f=>f.timestamp),o={id:`chk_${this.sessionId}_${this.chunkSequence}_${i}`,sessionId:this.sessionId,tabId:this.tabId,sequence:this.chunkSequence,startedAt:i,endedAt:a,sizeBytes:0,hasFullSnapshot:s.length>0,snapshotTimestamps:s,timeline:t,replay:e},c=++this.flushCount,h=e.length,u=t.length,p=h,g=u,b=p+g;return this.pendingWritesCount++,this.writeChain=this.writeChain.then(async()=>{const f=performance.now();let m=0,k=0;const I=new TextEncoder().encode(JSON.stringify(o.timeline)).byteLength;if(o.replay.length>0)try{const M=performance.now(),T=JSON.stringify(o.replay),A=performance.now();m=A-M;const _=await it(T);k=performance.now()-A,o.replayCompressed=_,o.sizeBytes=_.byteLength+I,o.replay=[]}catch{const M=new TextEncoder().encode(JSON.stringify(o.replay)).byteLength;o.sizeBytes=M+I}else o.sizeBytes=I;const y=performance.now();await this.db.putChunk(o);const w=performance.now(),E=w-y,C=w-f;this.onFlushMetricsCallback&&this.onFlushMetricsCallback({flushIndex:c,durationMs:C,serializationMs:m,compressionMs:k,writeMs:E,chunkSizeBytes:o.sizeBytes,replayEventsInBatch:h,timelineEventsInBatch:u,totalReplayInChunk:p,totalTimelineInChunk:g,totalEventsInChunk:b,timestamp:Date.now()}),this.onChunkPersistedCallback&&this.onChunkPersistedCallback(o)}).catch(f=>{this.onErrorCallback&&this.onErrorCallback(f)}).finally(()=>{this.pendingWritesCount=Math.max(0,this.pendingWritesCount-1)}),this.writeChain}initLifecycleListeners(){typeof window<"u"&&typeof window.addEventListener=="function"&&(this.pageHideHandler=()=>{this.flush()},window.addEventListener("pagehide",this.pageHideHandler)),typeof document<"u"&&typeof document.addEventListener=="function"&&(this.visibilityChangeHandler=()=>{document.visibilityState==="hidden"&&this.flush()},document.addEventListener("visibilitychange",this.visibilityChangeHandler))}destroy(){this.timer&&(clearTimeout(this.timer),this.timer=null),typeof window<"u"&&typeof window.removeEventListener=="function"&&this.pageHideHandler&&(window.removeEventListener("pagehide",this.pageHideHandler),this.pageHideHandler=void 0),typeof document<"u"&&typeof document.removeEventListener=="function"&&this.visibilityChangeHandler&&(document.removeEventListener("visibilitychange",this.visibilityChangeHandler),this.visibilityChangeHandler=void 0)}}class At{constructor(t,e){l(this,"db");l(this,"config");this.db=t,this.config={bufferMinutes:(e==null?void 0:e.bufferMinutes)??5,maxStorageMb:(e==null?void 0:e.maxStorageMb)??50}}async prune(t=Date.now()){const e=await this.db.getAllIncidents(),r=new Set;for(const g of e)for(const b of g.chunkIds)r.add(b);const n=await this.db.getAllChunks(),i=this.config.bufferMinutes*60*1e3,a=t-i,s=[],o=[];for(const g of n)!r.has(g.id)&&g.endedAt<a?s.push(g):o.push(g);const c=this.config.maxStorageMb*1024*1024;let h=o.reduce((g,b)=>g+(b.sizeBytes||0),0);if(h>c){const g=o.filter(b=>!r.has(b.id)).sort((b,f)=>b.startedAt-f.startedAt);for(const b of g){if(h<=c)break;s.push(b),h-=b.sizeBytes||0}}const u=s.map(g=>g.id);let p=0;for(const g of s)p+=g.sizeBytes||0;return u.length>0&&await this.db.deleteChunks(u),{deletedChunkIds:u,reclaimedBytes:p,remainingBytes:h}}async emergencyPrune(){const t=await this.db.getAllIncidents(),e=new Set;for(const c of t)for(const h of c.chunkIds)e.add(h);const r=await this.db.getAllChunks(),n=[],i=[];for(const c of r)e.has(c.id)?i.push(c):n.push(c);const a=n.map(c=>c.id);let s=0;for(const c of n)s+=c.sizeBytes||0;a.length>0&&await this.db.deleteChunks(a);const o=i.reduce((c,h)=>c+(h.sizeBytes||0),0);return{deletedChunkIds:a,reclaimedBytes:s,remainingBytes:o}}async getStorageBreakdown(){const t=await this.db.getAllIncidents(),e=new Set;for(const o of t)for(const c of o.chunkIds)e.add(c);const r=await this.db.getAllChunks();let n=0,i=0;for(const o of r){const c=o.sizeBytes||0;e.has(o.id)?n+=c:i+=c}const a=n+i,s=this.config.maxStorageMb*1024*1024;return{totalBytes:a,protectedBytes:n,bufferBytes:i,maxStorageBytes:s,isOverLimit:a>s,protectedExceedsLimit:n>s,incidentCount:t.length}}}function tt(d,t,e){const r=typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():Math.random().toString(36).substring(2,10);return`${d}_${t}_${e}_${r}`}function at(d,t,e){const r=[];if(!d||d.length===0)return{events:[],replayWindow:{requestedStartedAt:t,requestedEndedAt:e,preparationEventCount:0},degradedReasons:r};const n=[...d].sort((b,f)=>b.timestamp-f.timestamp),i=n.filter(b=>b.timestamp>=t&&b.timestamp<=e),a=n.filter(b=>b.type===2&&b.timestamp<=t),s=a.length>0?a[a.length-1]:null;if(!s){r.push("Não há snapshot para reconstruir o início da gravação.");let b=0;if(!i.some(m=>m.type===4)){const m=n.filter(I=>I.type===4&&I.timestamp<=t),k=m.length>0?m[m.length-1]:null;if(k)return b=1,{events:[{...k,timestamp:t-1},...i],replayWindow:{requestedStartedAt:t,requestedEndedAt:e,preparationEventCount:b},degradedReasons:r};r.push("Não há evento de metadados (Meta) anterior ao início da gravação.")}return{events:i,replayWindow:{requestedStartedAt:t,requestedEndedAt:e,preparationEventCount:b},degradedReasons:r}}const o=n.lastIndexOf(s),c=n.filter((b,f)=>b.type===4&&f<=o&&b.timestamp<=t),h=c.length>0?c[c.length-1]:null,u=n.slice(o+1).filter(b=>b.timestamp<t&&b.type!==2&&b.type!==4),p=[];let g=0;h&&(p.push({...h,timestamp:t-1}),g++),p.push({...s,timestamp:t}),g++;for(const b of u)p.push({...b,timestamp:t}),g++;for(const b of i)b.type===2&&b.timestamp===s.timestamp||h&&b.type===4&&b.timestamp===h.timestamp||p.push(b);return{events:p,replayWindow:{requestedStartedAt:t,requestedEndedAt:e,preparationEventCount:g,baseSnapshotOriginalTimestamp:s.timestamp},degradedReasons:r}}function Vt(d,t,e){return at(d,t,e).events}class et{constructor(t,e,r,n,i){l(this,"db");l(this,"sessionId");l(this,"tabId");l(this,"environmentProvider");l(this,"fallbackEnvironment");l(this,"config");l(this,"pendingIncident",null);l(this,"hasExtendedOnce",!1);l(this,"finalizeTimer",null);l(this,"onIncidentPendingCallback");l(this,"onIncidentFinalizedCallback");l(this,"beforeFinalizeCallback");l(this,"onErrorCallback");l(this,"activeOperation",null);l(this,"recoveredBaseIncidentId");l(this,"baseRecoveredDroppedEvents",0);l(this,"isDestroyed",!1);this.db=t,this.sessionId=e,this.tabId=r,typeof n=="function"?(this.environmentProvider=n,this.fallbackEnvironment={url:typeof window<"u"?window.location.href:"http://localhost",userAgent:typeof window<"u"?window.navigator.userAgent:"node",viewport:{width:typeof window<"u"?window.innerWidth:1280,height:typeof window<"u"?window.innerHeight:720}}):(this.fallbackEnvironment=n,this.environmentProvider=()=>n),this.config={afterErrorSeconds:(i==null?void 0:i.afterErrorSeconds)??15,recorderVersion:(i==null?void 0:i.recorderVersion)??"0.1.0",context:i==null?void 0:i.context,getContext:i==null?void 0:i.getContext,getRecordingIssues:i==null?void 0:i.getRecordingIssues,getDroppedEventsCount:i==null?void 0:i.getDroppedEventsCount}}getEnvironment(){try{return this.environmentProvider()}catch{return this.fallbackEnvironment}}resolveFallbackEnvironment(t,e){const r=this.getEnvironment(),n=e.filter(a=>a.type==="navigation"&&a.timestamp<=t.triggeredAt),i=n.length>0?n[n.length-1]:null;return{...r,url:i?i.toUrl:r.url}}serializeOperation(t){if(this.isDestroyed)return Promise.reject(new Error("IncidentManager foi destruído."));let e;const r=async()=>{try{return await t()}catch(i){if(this.onErrorCallback)try{this.onErrorCallback(i)}catch{}throw i}finally{this.activeOperation===e&&(this.activeOperation=null)}};if(!this.activeOperation)return e=r(),this.activeOperation=e,e;const n=()=>r();return e=this.activeOperation.then(n,n),this.activeOperation=e,e}runExclusive(t){return this.serializeOperation(t)}computeCurrentDroppedEvents(t){var r,n;const e=((n=(r=this.config).getDroppedEventsCount)==null?void 0:n.call(r))??0;return this.recoveredBaseIncidentId===t.id?this.baseRecoveredDroppedEvents+e:typeof this.config.getDroppedEventsCount=="function"?e:t.droppedEvents??0}syncPendingIncidentDroppedEvents(){return this.serializeOperation(async()=>{if(!this.pendingIncident)return;const t=this.computeCurrentDroppedEvents(this.pendingIncident);this.pendingIncident.droppedEvents!==t&&(this.pendingIncident.droppedEvents=t,await this.db.putIncident(this.pendingIncident))})}async protectSessionChunks(){if(!this.pendingIncident)return;const t=await this.db.getChunksBySession(this.sessionId),e=new Set(this.pendingIncident.chunkIds);let r=!1;for(const i of t)e.has(i.id)||(this.pendingIncident.chunkIds.push(i.id),e.add(i.id),r=!0);const n=this.computeCurrentDroppedEvents(this.pendingIncident);this.pendingIncident.droppedEvents!==n&&(this.pendingIncident.droppedEvents=n,r=!0),r&&await this.db.putIncident(this.pendingIncident)}setOnError(t){this.onErrorCallback=t}setOnIncidentPending(t){this.onIncidentPendingCallback=t}setOnIncidentFinalized(t){this.onIncidentFinalizedCallback=t}setBeforeFinalize(t){this.beforeFinalizeCallback=t}getPendingIncident(){return this.pendingIncident}async init(){const t=await this.db.getPendingIncidentForSession(this.sessionId);if(!t)return;this.pendingIncident=t,this.recoveredBaseIncidentId=t.id,this.baseRecoveredDroppedEvents=t.droppedEvents??0;const e=Date.now();if(e>=t.finalizeAt)await this.executeFinalize(t.id);else{const r=t.finalizeAt-e;this.finalizeTimer=setTimeout(()=>{this.finalize(t.id).catch(()=>{})},r)}}trigger(t,e,r){return this.serializeOperation(()=>this.executeTrigger(t,e,r))}async executeTrigger(t,e,r){var o,c,h,u;const n=e.timestamp||Date.now();if(t==="manual")return this.createAndFinalizeManualIncident(e,n,r);if(!this.pendingIncident){this.recoveredBaseIncidentId=void 0,this.baseRecoveredDroppedEvents=0;const p=tt("inc",this.sessionId,n),g=await this.db.getChunksBySession(this.sessionId),b=g.length>0?g[0].startedAt:n,f=((c=(o=this.config).getDroppedEventsCount)==null?void 0:c.call(o))??0,m={id:p,sessionId:this.sessionId,tabId:this.tabId,reason:t,triggers:[e],startedAt:b,triggeredAt:n,finalizeAt:n+this.config.afterErrorSeconds*1e3,state:"pending",recordingIssues:((u=(h=this.config).getRecordingIssues)==null?void 0:u.call(h))??[],chunkIds:g.map(k=>k.id),environment:this.getEnvironment(),droppedEvents:f};return this.pendingIncident=m,this.hasExtendedOnce=!1,await this.db.putIncident(m),this.isDestroyed||(this.finalizeTimer=setTimeout(()=>{this.finalize(p).catch(()=>{})},this.config.afterErrorSeconds*1e3)),this.onIncidentPendingCallback&&this.onIncidentPendingCallback(m),p}const i=this.pendingIncident,a=i.triggers.some(p=>p.signature===e.signature&&n-p.timestamp<1e4);if(i.triggers.push(e),!a&&!this.hasExtendedOnce&&(this.hasExtendedOnce=!0,i.finalizeAt=Math.max(i.finalizeAt,n+this.config.afterErrorSeconds*1e3),this.finalizeTimer&&clearTimeout(this.finalizeTimer),!this.isDestroyed)){const p=i.finalizeAt-n;this.finalizeTimer=setTimeout(()=>{this.finalize(i.id).catch(()=>{})},p)}const s=await this.db.getChunksBySession(this.sessionId);return i.chunkIds=Array.from(new Set([...i.chunkIds,...s.map(p=>p.id)])),i.droppedEvents=this.computeCurrentDroppedEvents(i),await this.db.putIncident(i),i.id}async getChunkSnapshotTimestamps(t,e){if(t.snapshotTimestamps&&t.snapshotTimestamps.length>0)return t.snapshotTimestamps;if(t.replay&&t.replay.length>0){const r=t.replay.filter(n=>n.type===2).map(n=>n.timestamp);if(r.length>0)return r}if(t.replayCompressed&&t.replayCompressed.length>0)try{const r=await J(t.replayCompressed),i=JSON.parse(r).filter(a=>a.type===2).map(a=>a.timestamp);if(i.length>0)return i}catch{}return t.hasFullSnapshot&&(e==null||e()),[]}async createAndFinalizeManualIncident(t,e,r){var g,b,f,m;const n=tt("inc_manual",this.sessionId,e),i=await this.db.getChunksBySession(this.sessionId);i.sort((k,I)=>k.startedAt!==I.startedAt?k.startedAt-I.startedAt:k.sequence-I.sequence);const a=i.length>0?i[0].startedAt:e;let s=i,o=a,c=!1;if(r&&r>0){const k=r*1e3,I=Math.max(a,e-k);o=I;const y=await Promise.all(i.map(E=>this.getChunkSnapshotTimestamps(E,()=>{c=!0}))),w=[];for(let E=0;E<i.length;E++){const C=i[E];(C.endedAt||C.startedAt)>=I&&w.push(E)}if(w.length>0){const E=w[0],C=w[w.length-1];let M=-1;for(let A=i.length-1;A>=0;A--)if(y[A].some(B=>B<=I)){M=A;break}const T=M!==-1?Math.min(M,E):E;s=i.slice(T,C+1)}else if(i.length>0){const E=i.length-1;let C=-1;for(let T=i.length-1;T>=0;T--)if(y[T].length>0){C=T;break}const M=C!==-1?C:E;s=i.slice(M,E+1)}}const h=[...((b=(g=this.config).getRecordingIssues)==null?void 0:b.call(g))??[]];c&&h.push("Ausência de prova temporal para snapshot em lote legado com hasFullSnapshot.");const u=((m=(f=this.config).getDroppedEventsCount)==null?void 0:m.call(f))??0,p={id:n,sessionId:this.sessionId,tabId:this.tabId,reason:"manual",triggers:[t],startedAt:o,triggeredAt:e,finalizeAt:e,finalizedAt:e,state:"finalized",recordingIssues:h,chunkIds:s.map(k=>k.id),environment:this.getEnvironment(),droppedEvents:u};return await this.db.putIncident(p),this.onIncidentFinalizedCallback&&this.onIncidentFinalizedCallback(p),n}async executeManualTrigger(t,e){const r=t.timestamp||Date.now();return this.createAndFinalizeManualIncident(t,r,e)}finalize(t){return this.serializeOperation(()=>this.executeFinalize(t))}async executeFinalize(t){var o,c,h,u;if(this.beforeFinalizeCallback)try{await this.beforeFinalizeCallback()}catch{}this.finalizeTimer&&(clearTimeout(this.finalizeTimer),this.finalizeTimer=null);const e=await this.db.getIncident(t);if(!e||e.state==="finalized"){((o=this.pendingIncident)==null?void 0:o.id)===t&&(this.pendingIncident=null,this.hasExtendedOnce=!1);return}const r=Date.now(),n=e.finalizeAt?Math.min(r,e.finalizeAt):r,a=(await this.db.getChunksBySession(this.sessionId)).filter(p=>p.startedAt<=n),s=Array.from(new Set([...e.chunkIds,...a.map(p=>p.id)]));e.recordingIssues=[...new Set([...e.recordingIssues??[],...((h=(c=this.config).getRecordingIssues)==null?void 0:h.call(c))??[]])],e.state="finalized",e.finalizedAt=n,e.chunkIds=s,e.droppedEvents=this.computeCurrentDroppedEvents(e),await this.db.putIncident(e),((u=this.pendingIncident)==null?void 0:u.id)===t&&(this.pendingIncident=null,this.recoveredBaseIncidentId=void 0,this.baseRecoveredDroppedEvents=0,this.hasExtendedOnce=!1),this.onIncidentFinalizedCallback&&this.onIncidentFinalizedCallback(e)}async exportArtifact(t){var W,dt,lt,ht,ut,pt,gt,bt,ft;if(this.beforeFinalizeCallback)try{await this.beforeFinalizeCallback()}catch{}const e=await this.db.getIncident(t);if(!e)throw new Error(`Incidente "${t}" não encontrado.`);const r=new Set(e.recordingIssues??[]),n=await this.db.getChunksByIds(e.chunkIds),i=new Set(n.map(x=>x.id));let a=!1,s=!1;e.chunkIds.filter(x=>!i.has(x)).length>0&&(a=!0,r.add("Um ou mais lotes da gravação não foram encontrados.")),n.sort((x,z)=>x.startedAt!==z.startedAt?x.startedAt-z.startedAt:x.sequence-z.sequence);const c=n.flatMap(x=>x.timeline||[]),u=q.sortTimelineEvents(c).filter(x=>x.timestamp>=e.startedAt&&x.timestamp<=(e.finalizedAt??e.finalizeAt)),p=(await Promise.all(n.map(async x=>{if(x.replayCompressed&&x.replayCompressed.length>0)try{const z=await J(x.replayCompressed),mt=JSON.parse(z);if(!Array.isArray(mt))throw new Error("Replay inválido");return mt}catch{return s=!0,r.add("Parte do replay não pôde ser descomprimida; a gravação pode estar incompleta."),x.replay||[]}return x.replay||[]}))).flat(),{events:g,replayWindow:b,degradedReasons:f}=at(p,e.startedAt,e.finalizedAt??e.finalizeAt);for(const x of f)r.add(x);const m=n.reduce((x,z)=>x+(z.sizeBytes||0),0),k=e.droppedEvents??((dt=(W=this.config).getDroppedEventsCount)==null?void 0:dt.call(W))??0,I=a||s;let y;if(this.config.getContext)try{y=await this.config.getContext()}catch{}const w=this.config.context,E=(y==null?void 0:y.release)??(w==null?void 0:w.release)??((lt=e.environment)==null?void 0:lt.appVersion)??this.getEnvironment().appVersion,C=(y==null?void 0:y.environment)??(w==null?void 0:w.environment),M=(y==null?void 0:y.traceId)??(w==null?void 0:w.traceId),T=(y==null?void 0:y.spanId)??(w==null?void 0:w.spanId),A=typeof M=="string"&&/^[0-9a-f]{32}$/i.test(M)?M.toLowerCase():void 0,_=A&&typeof T=="string"&&/^[0-9a-f]{16}$/i.test(T)?T.toLowerCase():void 0,B=A?{traceId:A,..._?{spanId:_}:{}}:void 0;return{formatVersion:2,recorderVersion:this.config.recorderVersion,context:{sessionId:e.sessionId||this.sessionId,tabId:e.tabId||this.tabId,...E!==void 0?{release:E}:{},...C!==void 0?{environment:C}:{},...B?{correlation:B}:{}},incident:{id:e.id,reason:e.reason,triggers:e.triggers,startedAt:e.startedAt,triggeredAt:e.triggeredAt,finalizedAt:e.finalizedAt??e.finalizeAt,annotationImage:((pt=(ut=(ht=e.triggers)==null?void 0:ht.find(x=>{var z;return(z=x.detail)==null?void 0:z.annotationImage}))==null?void 0:ut.detail)==null?void 0:pt.annotationImage)||void 0,annotations:((ft=(bt=(gt=e.triggers)==null?void 0:gt.find(x=>{var z;return(z=x.detail)==null?void 0:z.annotations}))==null?void 0:bt.detail)==null?void 0:ft.annotations)||void 0},environment:e.environment??this.resolveFallbackEnvironment(e,u),replayWindow:b,timeline:u,replay:g,diagnostics:{droppedEvents:k,droppedEventsUnknown:I||r.size>0&&k===0,storageBytes:m,degraded:r.size>0,degradedReasons:[...r]}}}async listIncidents(){return this.db.listIncidents()}deleteIncident(t){return this.serializeOperation(()=>this.executeDeleteIncident(t))}async executeDeleteIncident(t){var e;((e=this.pendingIncident)==null?void 0:e.id)===t&&(this.finalizeTimer&&(clearTimeout(this.finalizeTimer),this.finalizeTimer=null),this.pendingIncident=null,this.recoveredBaseIncidentId=void 0,this.baseRecoveredDroppedEvents=0),await this.db.deleteIncident(t)}reset(){return this.serializeOperation(async()=>{this.finalizeTimer&&(clearTimeout(this.finalizeTimer),this.finalizeTimer=null),this.pendingIncident=null,this.recoveredBaseIncidentId=void 0,this.baseRecoveredDroppedEvents=0,this.hasExtendedOnce=!1})}async destroy(){if(this.pendingIncident&&!this.isDestroyed)try{await this.syncPendingIncidentDroppedEvents()}catch{}if(this.isDestroyed=!0,this.activeOperation)try{await this.activeOperation}catch{}this.finalizeTimer&&(clearTimeout(this.finalizeTimer),this.finalizeTimer=null),this.pendingIncident=null,this.recoveredBaseIncidentId=void 0,this.baseRecoveredDroppedEvents=0,this.hasExtendedOnce=!1}}const j="__backtrack_tab_id__",N="__backtrack_session_id__",st="__ffr_tab_id__",ot="__ffr_session_id__",kt="__backtrack_session_channel__";let F=null;const K=new Set;function L(d){if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")try{return`${d}_${crypto.randomUUID()}`}catch{}const t=Math.random().toString(36).substring(2,10),e=Date.now().toString(36);return`${d}_${e}_${t}`}function yt(d,t){K.add(d),d.addEventListener("message",e=>{const r=e.data;if(r&&r.type==="CLAIM_TAB_ID"&&r.tabId===t)try{d.postMessage({type:"TAB_ID_COLLISION",tabId:t,claimId:r.claimId})}catch{}})}function Z(d){if(d){try{d.close()}catch{}K.delete(d)}else{for(const t of K)try{t.close()}catch{}K.clear()}}typeof window<"u"&&typeof window.addEventListener=="function"&&window.addEventListener("beforeunload",()=>{Z()});function Bt(d){if(!d&&F)return{...F};const t=d||(typeof window<"u"?window.sessionStorage:void 0);if(!t)return{tabId:L("tab"),sessionId:L("sess")};let e=t.getItem(j)||t.getItem(st);if(!e){e=L("tab");try{t.setItem(j,e)}catch{}}let r=t.getItem(N)||t.getItem(ot);if(!r){r=L("sess");try{t.setItem(N,r)}catch{}}return{tabId:e,sessionId:r}}async function Rt(d){const t=(d==null?void 0:d.storage)||(typeof window<"u"?window.sessionStorage:void 0);if(!t){const u={tabId:L("tab"),sessionId:L("sess")};return F=u,u}let e=t.getItem(j)||t.getItem(st),r=t.getItem(N)||t.getItem(ot);const n=!(d!=null&&d.disableBroadcastChannel)&&(!!(d!=null&&d.channel)||typeof BroadcastChannel<"u");if(!e){e=L("tab"),r=r||L("sess");try{t.setItem(j,e),t.setItem(N,r)}catch{}if(n)try{const p=(d==null?void 0:d.channel)||new BroadcastChannel((d==null?void 0:d.channelName)||kt);yt(p,e)}catch{}const u={tabId:e,sessionId:r};return F=u,u}if(!n){r=r||L("sess");try{t.setItem(N,r)}catch{}const u={tabId:e,sessionId:r};return F=u,u}let i=null;try{i=(d==null?void 0:d.channel)||new BroadcastChannel((d==null?void 0:d.channelName)||kt)}catch{r=r||L("sess");const u={tabId:e,sessionId:r};return F=u,u}const a=L("claim"),s=(d==null?void 0:d.timeoutMs)??50;let o=!1;const c=u=>{const p=u.data;p&&p.type==="TAB_ID_COLLISION"&&p.tabId===e&&p.claimId===a&&(o=!0)};i.addEventListener("message",c);try{i.postMessage({type:"CLAIM_TAB_ID",tabId:e,claimId:a}),await new Promise(u=>{setTimeout(u,s)})}catch{}finally{i.removeEventListener("message",c)}if(o){e=L("tab"),r=L("sess");try{t.setItem(j,e),t.setItem(N,r)}catch{}}else if(!r){r=L("sess");try{t.setItem(N,r)}catch{}}yt(i,e);const h={tabId:e,sessionId:r};return F=h,h}function Xt(d){const t=d||(typeof window<"u"?window.sessionStorage:void 0);if(t)try{t.removeItem(j),t.removeItem(N),t.removeItem(st),t.removeItem(ot)}catch{}return F=null,Z(),Bt(d)}const Yt=new Set(["password","senha","token","authorization","cookie","secret","cvv","cvc","card","credit","cardnumber","securitycode","cpf","cnpj","email","phone","telefone","celular","otp","verificationcode","recoverycode","accesstoken","refreshtoken","apikey","pin"]),Kt=/Bearer\s+[A-Za-z0-9\-_=.]+/gi,Jt=/Basic\s+[A-Za-z0-9+/=]+/gi,Qt=/eyJ[A-Za-z0-9-_=]+\.eyJ[A-Za-z0-9-_=]+\.[A-Za-z0-9-_.+/=]*/gi,Zt=/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g,te=/\b\d{3}\.?\d{3}\.?\d{3}-?\d{2}\b/g,ee=/\b\d{2}\.?\d{3}\.?\d{3}\/?\d{4}-?\d{2}\b/g,re=/\b(?:\d[ -]*?){13,19}\b/g,ne=/(?:\+?55\s?)?(?:\(?\d{2}\)?\s?)?(?:9\d{4}|\d{4})[ -]?\d{4}/g,ie=/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi,ae=/\b\d{6,}\b/g,se={maxDepth:4,maxKeys:50,maxItems:50,maxStringLength:500};function X(d,t){try{const e=new URL(d,"http://localhost");if(t)return t(e);let r=e.pathname;r=r.replace(ie,":id"),r=r.replace(ae,":id");const n=Array.from(new Set(e.searchParams.keys())).sort(),i=n.length>0?`?${n.join("&")}`:"";return!d.startsWith("http://")&&!d.startsWith("https://")?`${r}${i}`:`${e.origin}${r}${i}`}catch{return"[INVALID_URL]"}}function D(d){if(!d||typeof d!="string")return d;let t=d;return t=t.replace(Kt,"Bearer [REDACTED_TOKEN]"),t=t.replace(Jt,"Basic [REDACTED_BASIC]"),t=t.replace(Qt,"[REDACTED_JWT]"),t=t.replace(Zt,"[REDACTED_EMAIL]"),t=t.replace(te,"[REDACTED_CPF]"),t=t.replace(ee,"[REDACTED_CNPJ]"),t=t.replace(re,"[REDACTED_CARD]"),t=t.replace(ne,"[REDACTED_PHONE]"),t}function oe(d){const t=d.toLowerCase().replace(/[^a-z0-9]/g,"");for(const e of Yt)if(t.includes(e))return!0;return!1}function ct(d,t){const e={...se,...t},r=new WeakSet;function n(i,a){try{if(i==null||typeof i=="boolean")return i;if(typeof i=="number")return Number.isNaN(i)?"[NaN]":i;if(typeof i=="bigint")return`${i.toString()}n`;if(typeof i=="function")return`[Function: ${i.name||"anonymous"}]`;if(typeof i=="symbol")return i.toString();if(typeof i=="string"){let s=D(i);return s.length>e.maxStringLength&&(s=`${s.substring(0,e.maxStringLength)}... [TRUNCATED]`),s}if(typeof i=="object"){if(r.has(i))return"[CIRCULAR]";if(r.add(i),a>=e.maxDepth)return"[MAX_DEPTH]";if(i instanceof Error)return{name:i.name,message:D(i.message),stack:i.stack?D(i.stack):void 0};if(i instanceof Date)return i.toISOString();if(i instanceof RegExp)return i.toString();if(typeof i.nodeType=="number"&&typeof i.tagName=="string"){const u=i;return`<${u.tagName.toLowerCase()}${u.id?` id="${u.id}"`:""}${u.className?` class="${u.className}"`:""}>`}if(Array.isArray(i)){const u=[],p=Math.min(i.length,e.maxItems);for(let g=0;g<p;g++)u.push(n(i[g],a+1));return i.length>e.maxItems&&u.push(`... [${i.length-e.maxItems} more items TRUNCATED]`),u}const s=i,o={},c=Object.keys(s),h=Math.min(c.length,e.maxKeys);for(let u=0;u<h;u++){const p=c[u];if(oe(p))o[p]="[REDACTED]";else try{o[p]=n(s[p],a+1)}catch{o[p]="[GETTER_ERROR]"}}return c.length>e.maxKeys&&(o.__truncated__=`[${c.length-e.maxKeys} more keys TRUNCATED]`),o}return"[UNRECOGNIZED_VALUE]"}catch{return"[SERIALIZATION_ERROR]"}}try{return n(d,0)}catch{return"[SERIALIZATION_FAILED]"}}function G(d,t=64*1024){if(!d||typeof d!="string")return"";let e=d;e.length>t&&(e=`${e.substring(0,t)}... [TRUNCATED ${d.length-t} BYTES]`);try{const r=JSON.parse(e),n=ct(r,{maxStringLength:2e3});return JSON.stringify(n,null,2)}catch{return D(e)}}function V(d){if(!d)return;const t={};let e=[];typeof Headers<"u"&&d instanceof Headers?e=Array.from(d.entries()):Array.isArray(d)?e=d:typeof d=="object"&&(e=Object.entries(d));for(const[r,n]of e){const i=String(r),a=String(n),s=i.toLowerCase();s.includes("auth")||s.includes("cookie")||s.includes("token")||s.includes("secret")||s.includes("key")?t[i]="[REDACTED]":t[i]=D(a)}return Object.keys(t).length>0?t:void 0}class Dt{constructor(t,e){l(this,"writer");l(this,"isRecording",!1);l(this,"sequenceProvider");l(this,"originalLog",null);l(this,"originalWarn",null);l(this,"originalError",null);l(this,"wrappedLog",null);l(this,"wrappedWarn",null);l(this,"wrappedError",null);l(this,"isInsideHook",!1);this.writer=t,this.sequenceProvider=e}start(){this.isRecording||(this.isRecording=!0,this.originalLog=console.log,this.originalWarn=console.warn,this.originalError=console.error,this.wrappedLog=(...t)=>{this.handleConsole("log",this.originalLog,t)},this.wrappedWarn=(...t)=>{this.handleConsole("warn",this.originalWarn,t)},this.wrappedError=(...t)=>{this.handleConsole("error",this.originalError,t)},console.log=this.wrappedLog,console.warn=this.wrappedWarn,console.error=this.wrappedError)}handleConsole(t,e,r){try{e.apply(console,r)}catch{}if(!(this.isInsideHook||!this.isRecording)){this.isInsideHook=!0;try{const n=r.map(a=>ct(a)),i={id:`con_${Date.now()}_${Math.random().toString(36).substring(2,7)}`,timestamp:Date.now(),sequence:this.sequenceProvider(),type:"console",level:t,args:n};this.writer.addTimelineEvent(i)}catch{}finally{this.isInsideHook=!1}}}stop(){this.isRecording&&(this.isRecording=!1,console.log===this.wrappedLog&&this.originalLog&&(console.log=this.originalLog),console.warn===this.wrappedWarn&&this.originalWarn&&(console.warn=this.originalWarn),console.error===this.wrappedError&&this.originalError&&(console.error=this.originalError),this.originalLog=null,this.originalWarn=null,this.originalError=null,this.wrappedLog=null,this.wrappedWarn=null,this.wrappedError=null)}}class Lt{constructor(t,e,r){l(this,"writer");l(this,"incidentManager");l(this,"sequenceProvider");l(this,"isRecording",!1);l(this,"errorHandler");l(this,"rejectionHandler");this.writer=t,this.incidentManager=e,this.sequenceProvider=r}start(){this.isRecording||(this.isRecording=!0,!(typeof window>"u")&&(this.errorHandler=t=>{this.handleGlobalError(t)},window.addEventListener("error",this.errorHandler,!0),this.rejectionHandler=t=>{this.handleUnhandledRejection(t)},window.addEventListener("unhandledrejection",this.rejectionHandler)))}handleGlobalError(t){if(this.isRecording)try{const e=t.error instanceof Error?t.error:null,r=(e==null?void 0:e.name)||"Error",n=D(t.message||(e==null?void 0:e.message)||"Unknown error"),i=e!=null&&e.stack?D(e.stack):void 0,a=t.filename||void 0,s=t.lineno||void 0,o=t.colno||void 0;this.recordAndTriggerError({source:"window",name:r,message:n,stack:i,filename:a,lineno:s,colno:o}).catch(()=>{})}catch{}}handleUnhandledRejection(t){if(this.isRecording)try{const e=t.reason;let r="UnhandledRejection",n="Promise rejeitada",i;e instanceof Error?(r=e.name,n=D(e.message),i=e.stack?D(e.stack):void 0):typeof e=="string"?n=D(e):e&&typeof e=="object"&&(n=D(JSON.stringify(e))),this.recordAndTriggerError({source:"unhandledrejection",name:r,message:n,stack:i}).catch(()=>{})}catch{}}captureException(t,e){if(this.isRecording)try{let r="Error",n="Exceção capturada",i,a;t instanceof Error?(r=t.name,n=D(t.message),i=t.stack?D(t.stack):void 0):typeof t=="string"&&(n=D(t)),e!=null&&e.componentStack&&(a=D(e.componentStack));const s=(e==null?void 0:e.source)==="react"?"react":"manual";return this.recordAndTriggerError({source:s,name:r,message:n,stack:i,componentStack:a}).catch(()=>{})}catch{}}recordAndTriggerError(t){var s;const e=Date.now(),r={id:`err_${e}_${Math.random().toString(36).substring(2,7)}`,timestamp:e,sequence:this.sequenceProvider(),type:"error",source:t.source,name:t.name,message:t.message,stack:t.stack,filename:t.filename,lineno:t.lineno,colno:t.colno,componentStack:t.componentStack};this.writer.addTimelineEvent(r);const n=t.stack&&((s=t.stack.split(`
1
+ "use strict";var Ft=Object.defineProperty;var jt=(d,t,e)=>t in d?Ft(d,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):d[t]=e;var l=(d,t,e)=>jt(d,typeof t!="symbol"?t+"":t,e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const q=require("./markdown-Ao5Ah9MF.cjs"),Ut=require("@rrweb/record");class xt{constructor(t="stopped"){l(this,"currentState","stopped");l(this,"degradedReasons",new Set);l(this,"previousOperationalState","stopped");this.currentState=t}getState(){return this.currentState}getDegradedReasons(){return Array.from(this.degradedReasons)}isDegraded(){return this.currentState==="degraded"}isRecording(){return this.currentState==="recording"||this.currentState==="incident_pending"||this.currentState==="degraded"&&(this.previousOperationalState==="recording"||this.previousOperationalState==="incident_pending")}transition(t){switch(t.type){case"START":this.currentState==="stopped"&&(this.currentState="recording");break;case"STOP":this.currentState="stopped",this.degradedReasons.clear(),this.previousOperationalState="stopped";break;case"TRIGGER_AUTO":this.currentState==="recording"?this.currentState="incident_pending":this.currentState==="degraded"&&(this.previousOperationalState="incident_pending");break;case"TRIGGER_MANUAL":break;case"FINALIZE_INCIDENT":this.currentState==="incident_pending"?this.currentState="recording":this.currentState==="degraded"&&(this.previousOperationalState="recording");break;case"DEGRADE":this.degradedReasons.add(t.reason),this.currentState!=="degraded"&&(this.previousOperationalState=this.currentState,this.currentState="degraded");break;case"RECOVER":this.degradedReasons.clear(),this.currentState==="degraded"&&(this.currentState=this.previousOperationalState==="stopped"?"stopped":this.previousOperationalState);break}return this.currentState}}const It="backtrack_db",Et=1,$="sessions",S="chunks",R="incidents";class St{constructor(t,e){l(this,"db",null);l(this,"idbFactory");l(this,"dbName");this.idbFactory=t||(typeof indexedDB<"u"?indexedDB:void 0),this.dbName=e||It}async open(){if(this.db)return this.db;if(!this.idbFactory)throw new Error("IndexedDB não está disponível neste ambiente.");return new Promise((t,e)=>{const r=this.idbFactory.open(this.dbName,Et);r.onupgradeneeded=n=>{const i=n.target.result;if(i.objectStoreNames.contains($)||i.createObjectStore($,{keyPath:"id"}).createIndex("startedAt","startedAt",{unique:!1}),!i.objectStoreNames.contains(S)){const a=i.createObjectStore(S,{keyPath:"id"});a.createIndex("sessionId","sessionId",{unique:!1}),a.createIndex("tabId","tabId",{unique:!1}),a.createIndex("sequence","sequence",{unique:!1}),a.createIndex("startedAt","startedAt",{unique:!1}),a.createIndex("endedAt","endedAt",{unique:!1})}if(!i.objectStoreNames.contains(R)){const a=i.createObjectStore(R,{keyPath:"id"});a.createIndex("sessionId","sessionId",{unique:!1}),a.createIndex("state","state",{unique:!1}),a.createIndex("triggeredAt","triggeredAt",{unique:!1})}},r.onsuccess=n=>{this.db=n.target.result,t(this.db)},r.onerror=n=>{e(n.target.error)}})}close(){this.db&&(this.db.close(),this.db=null)}async putSession(t){const e=await this.open();return new Promise((r,n)=>{const i=e.transaction($,"readwrite");i.objectStore($).put(t),i.oncomplete=()=>r(),i.onerror=()=>n(i.error)})}async getSession(t){const e=await this.open();return new Promise((r,n)=>{const a=e.transaction($,"readonly").objectStore($).get(t);a.onsuccess=()=>r(a.result||null),a.onerror=()=>n(a.error)})}async putChunk(t){const e=await this.open();return new Promise((r,n)=>{const i=e.transaction(S,"readwrite");i.objectStore(S).put(t),i.oncomplete=()=>r(),i.onerror=()=>n(i.error)})}async putChunks(t){if(t.length===0)return;const e=await this.open();return new Promise((r,n)=>{const i=e.transaction(S,"readwrite"),a=i.objectStore(S);for(const s of t)a.put(s);i.oncomplete=()=>r(),i.onerror=()=>n(i.error)})}async getChunk(t){const e=await this.open();return new Promise((r,n)=>{const a=e.transaction(S,"readonly").objectStore(S).get(t);a.onsuccess=()=>r(a.result||null),a.onerror=()=>n(a.error)})}async getChunksByIds(t){if(t.length===0)return[];const e=await this.open();return new Promise((r,n)=>{const a=e.transaction(S,"readonly").objectStore(S),s=[];let o=t.length;for(const c of t){const h=a.get(c);h.onsuccess=()=>{h.result&&s.push(h.result),o--,o===0&&r(s)},h.onerror=()=>n(h.error)}})}async getChunksBySession(t){const e=await this.open();return new Promise((r,n)=>{const s=e.transaction(S,"readonly").objectStore(S).index("sessionId").getAll(t);s.onsuccess=()=>{const o=s.result||[];o.sort((c,h)=>c.startedAt!==h.startedAt?c.startedAt-h.startedAt:c.sequence-h.sequence),r(o)},s.onerror=()=>n(s.error)})}async getAllChunks(){const t=await this.open();return new Promise((e,r)=>{const i=t.transaction(S,"readonly").objectStore(S).getAll();i.onsuccess=()=>e(i.result||[]),i.onerror=()=>r(i.error)})}async deleteChunks(t){if(t.length===0)return;const e=await this.open();return new Promise((r,n)=>{const i=e.transaction(S,"readwrite"),a=i.objectStore(S);for(const s of t)a.delete(s);i.oncomplete=()=>r(),i.onerror=()=>n(i.error)})}async putIncident(t){const e=await this.open();return new Promise((r,n)=>{const i=e.transaction(R,"readwrite");i.objectStore(R).put(t),i.oncomplete=()=>r(),i.onerror=()=>n(i.error)})}async getIncident(t){const e=await this.open();return new Promise((r,n)=>{const a=e.transaction(R,"readonly").objectStore(R).get(t);a.onsuccess=()=>r(a.result||null),a.onerror=()=>n(a.error)})}async getPendingIncidentForSession(t){const e=await this.open();return new Promise((r,n)=>{const s=e.transaction(R,"readonly").objectStore(R).index("sessionId").getAll(t);s.onsuccess=()=>{const c=(s.result||[]).find(h=>h.state==="pending");r(c||null)},s.onerror=()=>n(s.error)})}async listIncidents(){const t=await this.open();return new Promise((e,r)=>{const i=t.transaction(R,"readonly").objectStore(R).getAll();i.onsuccess=()=>{const s=(i.result||[]).map(o=>({id:o.id,reason:o.reason,trigger:o.triggers[0],startedAt:o.startedAt,triggeredAt:o.triggeredAt,finalizedAt:o.finalizedAt,eventCount:o.chunkIds.length,triggerCount:o.triggers.length}));s.sort((o,c)=>c.triggeredAt-o.triggeredAt),e(s)},i.onerror=()=>r(i.error)})}async deleteIncident(t){const e=await this.open();return new Promise((r,n)=>{const i=e.transaction(R,"readwrite");i.objectStore(R).delete(t),i.oncomplete=()=>r(),i.onerror=()=>n(i.error)})}async getAllIncidents(){const t=await this.open();return new Promise((e,r)=>{const i=t.transaction(R,"readonly").objectStore(R).getAll();i.onsuccess=()=>e(i.result||[]),i.onerror=()=>r(i.error)})}async estimateStorageBytes(){return(await this.getAllChunks()).reduce((e,r)=>e+(r.sizeBytes||0),0)}async clearAll(){const t=await this.open();return new Promise((e,r)=>{const n=t.transaction([$,S,R],"readwrite");n.objectStore($).clear(),n.objectStore(S).clear(),n.objectStore(R).clear(),n.oncomplete=()=>e(),n.onerror=()=>r(n.error)})}}const Y=50*1024*1024;function H(d,t){if(d>t)throw new Error("O conteúdo excede o limite máximo permitido de "+Math.round(t/1024/1024)+" MiB.")}async function nt(d,t=Y){const e=d.getReader(),r=[];let n=0;try{for(;;){const{done:s,value:o}=await e.read();if(s)break;n+=o.byteLength,H(n,t),r.push(o)}}catch(s){throw await e.cancel().catch(()=>{}),s}finally{e.releaseLock()}const i=new Uint8Array(n);let a=0;for(const s of r)i.set(s,a),a+=s.byteLength;return i}async function Wt(d,t=Y){var r,n,i;if(!d.ok)throw new Error("Falha ao baixar conteúdo ("+d.status+").");const e=Number((n=(r=d.headers)==null?void 0:r.get)==null?void 0:n.call(r,"content-length"));if(Number.isFinite(e)&&e>t&&(await((i=d.body)==null?void 0:i.cancel().catch(()=>{})),H(e,t)),d.body)return nt(d.body,t);if(typeof d.arrayBuffer=="function"){const a=await d.arrayBuffer(),s=new Uint8Array(a);return H(s.byteLength,t),s}if(typeof d.text=="function"){const a=await d.text(),s=new TextEncoder().encode(a);return H(s.byteLength,t),s}if(typeof d.json=="function"){const a=await d.json(),s=new TextEncoder().encode(JSON.stringify(a));return H(s.byteLength,t),s}throw new Error("Resposta sem conteúdo legível.")}function Ct(d){return d.length>=2&&d[0]===31&&d[1]===139}async function it(d){const t=typeof d=="string"?new TextEncoder().encode(d):d;if(typeof CompressionStream<"u"){const r=new Blob([t]).stream().pipeThrough(new CompressionStream("gzip")),i=await new Response(r).blob();return new Uint8Array(await i.arrayBuffer())}return t}async function J(d,t=Y){if(H(d.byteLength,t),!Ct(d))return new TextDecoder().decode(d);if(typeof DecompressionStream<"u"){const r=new Blob([d]).stream().pipeThrough(new DecompressionStream("gzip"));return new TextDecoder().decode(await nt(r,t))}throw new Error("Este navegador não suporta descompressão Gzip. Use um arquivo JSON ou um navegador compatível.")}async function Mt(d){const t=JSON.stringify(d);return it(t)}async function Gt(d,t=Y){let e;if(typeof d=="object"&&d!==null&&!(d instanceof ArrayBuffer)&&!(d instanceof Uint8Array)){const n=JSON.stringify(d);H(n.length,t),H(new TextEncoder().encode(n).byteLength,t),e=d}else if(typeof d=="string"){H(d.length,t),H(new TextEncoder().encode(d).byteLength,t);try{e=JSON.parse(d)}catch(n){throw new Error(`Falha ao converter dados em JSON: ${n instanceof Error?n.message:String(n)}`)}}else if(d instanceof ArrayBuffer||d instanceof Uint8Array){const n=d instanceof Uint8Array?d:new Uint8Array(d),i=await J(n,t);try{e=JSON.parse(i)}catch(a){throw new Error(`Falha ao converter dados em JSON: ${a instanceof Error?a.message:String(a)}`)}}else throw new Error("Formato de dados inválido para o artefato.");const r=q.validateFlightRecorderArtifact(e);if(!r.success)throw new Error(`Artefato inválido: ${r.errors.join(", ")}`);return r.data}class Tt{constructor(t,e,r,n,i){l(this,"db");l(this,"config");l(this,"sessionId");l(this,"tabId");l(this,"chunkSequence",0);l(this,"pendingTimelineEvents",[]);l(this,"pendingReplayEvents",[]);l(this,"timer",null);l(this,"writeChain",Promise.resolve());l(this,"pendingWritesCount",0);l(this,"onErrorCallback");l(this,"onChunkPersistedCallback");l(this,"pageHideHandler");l(this,"visibilityChangeHandler");l(this,"flushCount",0);l(this,"onFlushMetricsCallback");this.db=t,this.sessionId=e,this.tabId=r,this.config={flushIntervalMs:(n==null?void 0:n.flushIntervalMs)??1e3,maxBatchEvents:(n==null?void 0:n.maxBatchEvents)??250,chunkDurationMs:(n==null?void 0:n.chunkDurationMs)??6e4,initialChunkSequence:(n==null?void 0:n.initialChunkSequence)??0,onFlushMetrics:n==null?void 0:n.onFlushMetrics},this.chunkSequence=(n==null?void 0:n.initialChunkSequence)??0,this.onErrorCallback=i,this.onFlushMetricsCallback=n==null?void 0:n.onFlushMetrics,this.initLifecycleListeners()}getChunkSequence(){return this.chunkSequence}setOnFlushMetrics(t){this.onFlushMetricsCallback=t}setOnChunkPersisted(t){this.onChunkPersistedCallback=t}getPendingWrites(){return this.pendingWritesCount}addTimelineEvent(t){this.pendingTimelineEvents.push(t),this.checkThresholds()}addReplayEvent(t){this.pendingReplayEvents.push(t),this.checkThresholds()}checkThresholds(){this.pendingTimelineEvents.length+this.pendingReplayEvents.length>=this.config.maxBatchEvents?this.flush():this.timer||(this.timer=setTimeout(()=>{this.timer=null,this.flush()},this.config.flushIntervalMs))}flush(){if(this.timer&&(clearTimeout(this.timer),this.timer=null),this.pendingTimelineEvents.length===0&&this.pendingReplayEvents.length===0)return this.writeChain;const t=[...this.pendingTimelineEvents],e=[...this.pendingReplayEvents];this.pendingTimelineEvents=[],this.pendingReplayEvents=[];const r=Date.now(),n=[...t.map(f=>f.timestamp),...e.map(f=>f.timestamp)],i=n.length>0?Math.min(...n):r,a=n.length>0?Math.max(...n):r;this.chunkSequence++;const s=e.filter(f=>f.type===2).map(f=>f.timestamp),o={id:`chk_${this.sessionId}_${this.chunkSequence}_${i}`,sessionId:this.sessionId,tabId:this.tabId,sequence:this.chunkSequence,startedAt:i,endedAt:a,sizeBytes:0,hasFullSnapshot:s.length>0,snapshotTimestamps:s,timeline:t,replay:e},c=++this.flushCount,h=e.length,u=t.length,p=h,g=u,b=p+g;return this.pendingWritesCount++,this.writeChain=this.writeChain.then(async()=>{const f=performance.now();let m=0,k=0;const I=new TextEncoder().encode(JSON.stringify(o.timeline)).byteLength;if(o.replay.length>0)try{const M=performance.now(),T=JSON.stringify(o.replay),A=performance.now();m=A-M;const _=await it(T);k=performance.now()-A,o.replayCompressed=_,o.sizeBytes=_.byteLength+I,o.replay=[]}catch{const M=new TextEncoder().encode(JSON.stringify(o.replay)).byteLength;o.sizeBytes=M+I}else o.sizeBytes=I;const y=performance.now();await this.db.putChunk(o);const w=performance.now(),E=w-y,C=w-f;this.onFlushMetricsCallback&&this.onFlushMetricsCallback({flushIndex:c,durationMs:C,serializationMs:m,compressionMs:k,writeMs:E,chunkSizeBytes:o.sizeBytes,replayEventsInBatch:h,timelineEventsInBatch:u,totalReplayInChunk:p,totalTimelineInChunk:g,totalEventsInChunk:b,timestamp:Date.now()}),this.onChunkPersistedCallback&&this.onChunkPersistedCallback(o)}).catch(f=>{this.onErrorCallback&&this.onErrorCallback(f)}).finally(()=>{this.pendingWritesCount=Math.max(0,this.pendingWritesCount-1)}),this.writeChain}initLifecycleListeners(){typeof window<"u"&&typeof window.addEventListener=="function"&&(this.pageHideHandler=()=>{this.flush()},window.addEventListener("pagehide",this.pageHideHandler)),typeof document<"u"&&typeof document.addEventListener=="function"&&(this.visibilityChangeHandler=()=>{document.visibilityState==="hidden"&&this.flush()},document.addEventListener("visibilitychange",this.visibilityChangeHandler))}destroy(){this.timer&&(clearTimeout(this.timer),this.timer=null),typeof window<"u"&&typeof window.removeEventListener=="function"&&this.pageHideHandler&&(window.removeEventListener("pagehide",this.pageHideHandler),this.pageHideHandler=void 0),typeof document<"u"&&typeof document.removeEventListener=="function"&&this.visibilityChangeHandler&&(document.removeEventListener("visibilitychange",this.visibilityChangeHandler),this.visibilityChangeHandler=void 0)}}class At{constructor(t,e){l(this,"db");l(this,"config");this.db=t,this.config={bufferMinutes:(e==null?void 0:e.bufferMinutes)??5,maxStorageMb:(e==null?void 0:e.maxStorageMb)??50}}async prune(t=Date.now()){const e=await this.db.getAllIncidents(),r=new Set;for(const g of e)for(const b of g.chunkIds)r.add(b);const n=await this.db.getAllChunks(),i=this.config.bufferMinutes*60*1e3,a=t-i,s=[],o=[];for(const g of n)!r.has(g.id)&&g.endedAt<a?s.push(g):o.push(g);const c=this.config.maxStorageMb*1024*1024;let h=o.reduce((g,b)=>g+(b.sizeBytes||0),0);if(h>c){const g=o.filter(b=>!r.has(b.id)).sort((b,f)=>b.startedAt-f.startedAt);for(const b of g){if(h<=c)break;s.push(b),h-=b.sizeBytes||0}}const u=s.map(g=>g.id);let p=0;for(const g of s)p+=g.sizeBytes||0;return u.length>0&&await this.db.deleteChunks(u),{deletedChunkIds:u,reclaimedBytes:p,remainingBytes:h}}async emergencyPrune(){const t=await this.db.getAllIncidents(),e=new Set;for(const c of t)for(const h of c.chunkIds)e.add(h);const r=await this.db.getAllChunks(),n=[],i=[];for(const c of r)e.has(c.id)?i.push(c):n.push(c);const a=n.map(c=>c.id);let s=0;for(const c of n)s+=c.sizeBytes||0;a.length>0&&await this.db.deleteChunks(a);const o=i.reduce((c,h)=>c+(h.sizeBytes||0),0);return{deletedChunkIds:a,reclaimedBytes:s,remainingBytes:o}}async getStorageBreakdown(){const t=await this.db.getAllIncidents(),e=new Set;for(const o of t)for(const c of o.chunkIds)e.add(c);const r=await this.db.getAllChunks();let n=0,i=0;for(const o of r){const c=o.sizeBytes||0;e.has(o.id)?n+=c:i+=c}const a=n+i,s=this.config.maxStorageMb*1024*1024;return{totalBytes:a,protectedBytes:n,bufferBytes:i,maxStorageBytes:s,isOverLimit:a>s,protectedExceedsLimit:n>s,incidentCount:t.length}}}function tt(d,t,e){const r=typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():Math.random().toString(36).substring(2,10);return`${d}_${t}_${e}_${r}`}function at(d,t,e){const r=[];if(!d||d.length===0)return{events:[],replayWindow:{requestedStartedAt:t,requestedEndedAt:e,preparationEventCount:0},degradedReasons:r};const n=[...d].sort((b,f)=>b.timestamp-f.timestamp),i=n.filter(b=>b.timestamp>=t&&b.timestamp<=e),a=n.filter(b=>b.type===2&&b.timestamp<=t),s=a.length>0?a[a.length-1]:null;if(!s){r.push("Não há snapshot para reconstruir o início da gravação.");let b=0;if(!i.some(m=>m.type===4)){const m=n.filter(I=>I.type===4&&I.timestamp<=t),k=m.length>0?m[m.length-1]:null;if(k)return b=1,{events:[{...k,timestamp:t-1},...i],replayWindow:{requestedStartedAt:t,requestedEndedAt:e,preparationEventCount:b},degradedReasons:r};r.push("Não há evento de metadados (Meta) anterior ao início da gravação.")}return{events:i,replayWindow:{requestedStartedAt:t,requestedEndedAt:e,preparationEventCount:b},degradedReasons:r}}const o=n.lastIndexOf(s),c=n.filter((b,f)=>b.type===4&&f<=o&&b.timestamp<=t),h=c.length>0?c[c.length-1]:null,u=n.slice(o+1).filter(b=>b.timestamp<t&&b.type!==2&&b.type!==4),p=[];let g=0;h&&(p.push({...h,timestamp:t-1}),g++),p.push({...s,timestamp:t}),g++;for(const b of u)p.push({...b,timestamp:t}),g++;for(const b of i)b.type===2&&b.timestamp===s.timestamp||h&&b.type===4&&b.timestamp===h.timestamp||p.push(b);return{events:p,replayWindow:{requestedStartedAt:t,requestedEndedAt:e,preparationEventCount:g,baseSnapshotOriginalTimestamp:s.timestamp},degradedReasons:r}}function Vt(d,t,e){return at(d,t,e).events}class et{constructor(t,e,r,n,i){l(this,"db");l(this,"sessionId");l(this,"tabId");l(this,"environmentProvider");l(this,"fallbackEnvironment");l(this,"config");l(this,"pendingIncident",null);l(this,"hasExtendedOnce",!1);l(this,"finalizeTimer",null);l(this,"onIncidentPendingCallback");l(this,"onIncidentFinalizedCallback");l(this,"beforeFinalizeCallback");l(this,"onErrorCallback");l(this,"activeOperation",null);l(this,"recoveredBaseIncidentId");l(this,"baseRecoveredDroppedEvents",0);l(this,"isDestroyed",!1);this.db=t,this.sessionId=e,this.tabId=r,typeof n=="function"?(this.environmentProvider=n,this.fallbackEnvironment={url:typeof window<"u"?window.location.href:"http://localhost",userAgent:typeof window<"u"?window.navigator.userAgent:"node",viewport:{width:typeof window<"u"?window.innerWidth:1280,height:typeof window<"u"?window.innerHeight:720}}):(this.fallbackEnvironment=n,this.environmentProvider=()=>n),this.config={afterErrorSeconds:(i==null?void 0:i.afterErrorSeconds)??15,recorderVersion:(i==null?void 0:i.recorderVersion)??"0.1.0",context:i==null?void 0:i.context,getContext:i==null?void 0:i.getContext,getRecordingIssues:i==null?void 0:i.getRecordingIssues,getDroppedEventsCount:i==null?void 0:i.getDroppedEventsCount}}getEnvironment(){try{return this.environmentProvider()}catch{return this.fallbackEnvironment}}resolveFallbackEnvironment(t,e){const r=this.getEnvironment(),n=e.filter(a=>a.type==="navigation"&&a.timestamp<=t.triggeredAt),i=n.length>0?n[n.length-1]:null;return{...r,url:i?i.toUrl:r.url}}serializeOperation(t){if(this.isDestroyed)return Promise.reject(new Error("IncidentManager foi destruído."));let e;const r=async()=>{try{return await t()}catch(i){if(this.onErrorCallback)try{this.onErrorCallback(i)}catch{}throw i}finally{this.activeOperation===e&&(this.activeOperation=null)}};if(!this.activeOperation)return e=r(),this.activeOperation=e,e;const n=()=>r();return e=this.activeOperation.then(n,n),this.activeOperation=e,e}runExclusive(t){return this.serializeOperation(t)}computeCurrentDroppedEvents(t){var r,n;const e=((n=(r=this.config).getDroppedEventsCount)==null?void 0:n.call(r))??0;return this.recoveredBaseIncidentId===t.id?this.baseRecoveredDroppedEvents+e:typeof this.config.getDroppedEventsCount=="function"?e:t.droppedEvents??0}syncPendingIncidentDroppedEvents(){return this.serializeOperation(async()=>{if(!this.pendingIncident)return;const t=this.computeCurrentDroppedEvents(this.pendingIncident);this.pendingIncident.droppedEvents!==t&&(this.pendingIncident.droppedEvents=t,await this.db.putIncident(this.pendingIncident))})}async protectSessionChunks(){if(!this.pendingIncident)return;const t=await this.db.getChunksBySession(this.sessionId),e=new Set(this.pendingIncident.chunkIds);let r=!1;for(const i of t)e.has(i.id)||(this.pendingIncident.chunkIds.push(i.id),e.add(i.id),r=!0);const n=this.computeCurrentDroppedEvents(this.pendingIncident);this.pendingIncident.droppedEvents!==n&&(this.pendingIncident.droppedEvents=n,r=!0),r&&await this.db.putIncident(this.pendingIncident)}setOnError(t){this.onErrorCallback=t}setOnIncidentPending(t){this.onIncidentPendingCallback=t}setOnIncidentFinalized(t){this.onIncidentFinalizedCallback=t}setBeforeFinalize(t){this.beforeFinalizeCallback=t}getPendingIncident(){return this.pendingIncident}async init(){const t=await this.db.getPendingIncidentForSession(this.sessionId);if(!t)return;this.pendingIncident=t,this.recoveredBaseIncidentId=t.id,this.baseRecoveredDroppedEvents=t.droppedEvents??0;const e=Date.now();if(e>=t.finalizeAt)await this.executeFinalize(t.id);else{const r=t.finalizeAt-e;this.finalizeTimer=setTimeout(()=>{this.finalize(t.id).catch(()=>{})},r)}}trigger(t,e,r){return this.serializeOperation(()=>this.executeTrigger(t,e,r))}async executeTrigger(t,e,r){var o,c,h,u;const n=e.timestamp||Date.now();if(t==="manual")return this.createAndFinalizeManualIncident(e,n,r);if(!this.pendingIncident){this.recoveredBaseIncidentId=void 0,this.baseRecoveredDroppedEvents=0;const p=tt("inc",this.sessionId,n),g=await this.db.getChunksBySession(this.sessionId),b=g.length>0?g[0].startedAt:n,f=((c=(o=this.config).getDroppedEventsCount)==null?void 0:c.call(o))??0,m={id:p,sessionId:this.sessionId,tabId:this.tabId,reason:t,triggers:[e],startedAt:b,triggeredAt:n,finalizeAt:n+this.config.afterErrorSeconds*1e3,state:"pending",recordingIssues:((u=(h=this.config).getRecordingIssues)==null?void 0:u.call(h))??[],chunkIds:g.map(k=>k.id),environment:this.getEnvironment(),droppedEvents:f};return this.pendingIncident=m,this.hasExtendedOnce=!1,await this.db.putIncident(m),this.isDestroyed||(this.finalizeTimer=setTimeout(()=>{this.finalize(p).catch(()=>{})},this.config.afterErrorSeconds*1e3)),this.onIncidentPendingCallback&&this.onIncidentPendingCallback(m),p}const i=this.pendingIncident,a=i.triggers.some(p=>p.signature===e.signature&&n-p.timestamp<1e4);if(i.triggers.push(e),!a&&!this.hasExtendedOnce&&(this.hasExtendedOnce=!0,i.finalizeAt=Math.max(i.finalizeAt,n+this.config.afterErrorSeconds*1e3),this.finalizeTimer&&clearTimeout(this.finalizeTimer),!this.isDestroyed)){const p=i.finalizeAt-n;this.finalizeTimer=setTimeout(()=>{this.finalize(i.id).catch(()=>{})},p)}const s=await this.db.getChunksBySession(this.sessionId);return i.chunkIds=Array.from(new Set([...i.chunkIds,...s.map(p=>p.id)])),i.droppedEvents=this.computeCurrentDroppedEvents(i),await this.db.putIncident(i),i.id}async getChunkSnapshotTimestamps(t,e){if(t.snapshotTimestamps&&t.snapshotTimestamps.length>0)return t.snapshotTimestamps;if(t.replay&&t.replay.length>0){const r=t.replay.filter(n=>n.type===2).map(n=>n.timestamp);if(r.length>0)return r}if(t.replayCompressed&&t.replayCompressed.length>0)try{const r=await J(t.replayCompressed),i=JSON.parse(r).filter(a=>a.type===2).map(a=>a.timestamp);if(i.length>0)return i}catch{}return t.hasFullSnapshot&&(e==null||e()),[]}async createAndFinalizeManualIncident(t,e,r){var g,b,f,m;const n=tt("inc_manual",this.sessionId,e),i=await this.db.getChunksBySession(this.sessionId);i.sort((k,I)=>k.startedAt!==I.startedAt?k.startedAt-I.startedAt:k.sequence-I.sequence);const a=i.length>0?i[0].startedAt:e;let s=i,o=a,c=!1;if(r&&r>0){const k=r*1e3,I=Math.max(a,e-k);o=I;const y=await Promise.all(i.map(E=>this.getChunkSnapshotTimestamps(E,()=>{c=!0}))),w=[];for(let E=0;E<i.length;E++){const C=i[E];(C.endedAt||C.startedAt)>=I&&w.push(E)}if(w.length>0){const E=w[0],C=w[w.length-1];let M=-1;for(let A=i.length-1;A>=0;A--)if(y[A].some(B=>B<=I)){M=A;break}const T=M!==-1?Math.min(M,E):E;s=i.slice(T,C+1)}else if(i.length>0){const E=i.length-1;let C=-1;for(let T=i.length-1;T>=0;T--)if(y[T].length>0){C=T;break}const M=C!==-1?C:E;s=i.slice(M,E+1)}}const h=[...((b=(g=this.config).getRecordingIssues)==null?void 0:b.call(g))??[]];c&&h.push("Ausência de prova temporal para snapshot em lote legado com hasFullSnapshot.");const u=((m=(f=this.config).getDroppedEventsCount)==null?void 0:m.call(f))??0,p={id:n,sessionId:this.sessionId,tabId:this.tabId,reason:"manual",triggers:[t],startedAt:o,triggeredAt:e,finalizeAt:e,finalizedAt:e,state:"finalized",recordingIssues:h,chunkIds:s.map(k=>k.id),environment:this.getEnvironment(),droppedEvents:u};return await this.db.putIncident(p),this.onIncidentFinalizedCallback&&this.onIncidentFinalizedCallback(p),n}async executeManualTrigger(t,e){const r=t.timestamp||Date.now();return this.createAndFinalizeManualIncident(t,r,e)}finalize(t){return this.serializeOperation(()=>this.executeFinalize(t))}async executeFinalize(t){var o,c,h,u;if(this.beforeFinalizeCallback)try{await this.beforeFinalizeCallback()}catch{}this.finalizeTimer&&(clearTimeout(this.finalizeTimer),this.finalizeTimer=null);const e=await this.db.getIncident(t);if(!e||e.state==="finalized"){((o=this.pendingIncident)==null?void 0:o.id)===t&&(this.pendingIncident=null,this.hasExtendedOnce=!1);return}const r=Date.now(),n=e.finalizeAt?Math.min(r,e.finalizeAt):r,a=(await this.db.getChunksBySession(this.sessionId)).filter(p=>p.startedAt<=n),s=Array.from(new Set([...e.chunkIds,...a.map(p=>p.id)]));e.recordingIssues=[...new Set([...e.recordingIssues??[],...((h=(c=this.config).getRecordingIssues)==null?void 0:h.call(c))??[]])],e.state="finalized",e.finalizedAt=n,e.chunkIds=s,e.droppedEvents=this.computeCurrentDroppedEvents(e),await this.db.putIncident(e),((u=this.pendingIncident)==null?void 0:u.id)===t&&(this.pendingIncident=null,this.recoveredBaseIncidentId=void 0,this.baseRecoveredDroppedEvents=0,this.hasExtendedOnce=!1),this.onIncidentFinalizedCallback&&this.onIncidentFinalizedCallback(e)}async exportArtifact(t){var W,dt,lt,ht,ut,pt,gt,bt,ft;if(this.beforeFinalizeCallback)try{await this.beforeFinalizeCallback()}catch{}const e=await this.db.getIncident(t);if(!e)throw new Error(`Incidente "${t}" não encontrado.`);const r=new Set(e.recordingIssues??[]),n=await this.db.getChunksByIds(e.chunkIds),i=new Set(n.map(x=>x.id));let a=!1,s=!1;e.chunkIds.filter(x=>!i.has(x)).length>0&&(a=!0,r.add("Um ou mais lotes da gravação não foram encontrados.")),n.sort((x,z)=>x.startedAt!==z.startedAt?x.startedAt-z.startedAt:x.sequence-z.sequence);const c=n.flatMap(x=>x.timeline||[]),u=q.sortTimelineEvents(c).filter(x=>x.timestamp>=e.startedAt&&x.timestamp<=(e.finalizedAt??e.finalizeAt)),p=(await Promise.all(n.map(async x=>{if(x.replayCompressed&&x.replayCompressed.length>0)try{const z=await J(x.replayCompressed),mt=JSON.parse(z);if(!Array.isArray(mt))throw new Error("Replay inválido");return mt}catch{return s=!0,r.add("Parte do replay não pôde ser descomprimida; a gravação pode estar incompleta."),x.replay||[]}return x.replay||[]}))).flat(),{events:g,replayWindow:b,degradedReasons:f}=at(p,e.startedAt,e.finalizedAt??e.finalizeAt);for(const x of f)r.add(x);const m=n.reduce((x,z)=>x+(z.sizeBytes||0),0),k=e.droppedEvents??((dt=(W=this.config).getDroppedEventsCount)==null?void 0:dt.call(W))??0,I=a||s;let y;if(this.config.getContext)try{y=await this.config.getContext()}catch{}const w=this.config.context,E=(y==null?void 0:y.release)??(w==null?void 0:w.release)??((lt=e.environment)==null?void 0:lt.appVersion)??this.getEnvironment().appVersion,C=(y==null?void 0:y.environment)??(w==null?void 0:w.environment),M=(y==null?void 0:y.traceId)??(w==null?void 0:w.traceId),T=(y==null?void 0:y.spanId)??(w==null?void 0:w.spanId),A=typeof M=="string"&&/^[0-9a-f]{32}$/i.test(M)?M.toLowerCase():void 0,_=A&&typeof T=="string"&&/^[0-9a-f]{16}$/i.test(T)?T.toLowerCase():void 0,B=A?{traceId:A,..._?{spanId:_}:{}}:void 0;return{formatVersion:2,recorderVersion:this.config.recorderVersion,context:{sessionId:e.sessionId||this.sessionId,tabId:e.tabId||this.tabId,...E!==void 0?{release:E}:{},...C!==void 0?{environment:C}:{},...B?{correlation:B}:{}},incident:{id:e.id,reason:e.reason,triggers:e.triggers,startedAt:e.startedAt,triggeredAt:e.triggeredAt,finalizedAt:e.finalizedAt??e.finalizeAt,annotationImage:((pt=(ut=(ht=e.triggers)==null?void 0:ht.find(x=>{var z;return(z=x.detail)==null?void 0:z.annotationImage}))==null?void 0:ut.detail)==null?void 0:pt.annotationImage)||void 0,annotations:((ft=(bt=(gt=e.triggers)==null?void 0:gt.find(x=>{var z;return(z=x.detail)==null?void 0:z.annotations}))==null?void 0:bt.detail)==null?void 0:ft.annotations)||void 0},environment:e.environment??this.resolveFallbackEnvironment(e,u),replayWindow:b,timeline:u,replay:g,diagnostics:{droppedEvents:k,droppedEventsUnknown:I||r.size>0&&k===0,storageBytes:m,degraded:r.size>0,degradedReasons:[...r]}}}async listIncidents(){return this.db.listIncidents()}deleteIncident(t){return this.serializeOperation(()=>this.executeDeleteIncident(t))}async executeDeleteIncident(t){var e;((e=this.pendingIncident)==null?void 0:e.id)===t&&(this.finalizeTimer&&(clearTimeout(this.finalizeTimer),this.finalizeTimer=null),this.pendingIncident=null,this.recoveredBaseIncidentId=void 0,this.baseRecoveredDroppedEvents=0),await this.db.deleteIncident(t)}reset(){return this.serializeOperation(async()=>{this.finalizeTimer&&(clearTimeout(this.finalizeTimer),this.finalizeTimer=null),this.pendingIncident=null,this.recoveredBaseIncidentId=void 0,this.baseRecoveredDroppedEvents=0,this.hasExtendedOnce=!1})}async destroy(){if(this.pendingIncident&&!this.isDestroyed)try{await this.syncPendingIncidentDroppedEvents()}catch{}if(this.isDestroyed=!0,this.activeOperation)try{await this.activeOperation}catch{}this.finalizeTimer&&(clearTimeout(this.finalizeTimer),this.finalizeTimer=null),this.pendingIncident=null,this.recoveredBaseIncidentId=void 0,this.baseRecoveredDroppedEvents=0,this.hasExtendedOnce=!1}}const j="__backtrack_tab_id__",N="__backtrack_session_id__",st="__ffr_tab_id__",ot="__ffr_session_id__",kt="__backtrack_session_channel__";let F=null;const K=new Set;function L(d){if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")try{return`${d}_${crypto.randomUUID()}`}catch{}const t=Math.random().toString(36).substring(2,10),e=Date.now().toString(36);return`${d}_${e}_${t}`}function yt(d,t){K.add(d),d.addEventListener("message",e=>{const r=e.data;if(r&&r.type==="CLAIM_TAB_ID"&&r.tabId===t)try{d.postMessage({type:"TAB_ID_COLLISION",tabId:t,claimId:r.claimId})}catch{}})}function Z(d){if(d){try{d.close()}catch{}K.delete(d)}else{for(const t of K)try{t.close()}catch{}K.clear()}}typeof window<"u"&&typeof window.addEventListener=="function"&&window.addEventListener("beforeunload",()=>{Z()});function Bt(d){if(!d&&F)return{...F};const t=d||(typeof window<"u"?window.sessionStorage:void 0);if(!t)return{tabId:L("tab"),sessionId:L("sess")};let e=t.getItem(j)||t.getItem(st);if(!e){e=L("tab");try{t.setItem(j,e)}catch{}}let r=t.getItem(N)||t.getItem(ot);if(!r){r=L("sess");try{t.setItem(N,r)}catch{}}return{tabId:e,sessionId:r}}async function Rt(d){const t=(d==null?void 0:d.storage)||(typeof window<"u"?window.sessionStorage:void 0);if(!t){const u={tabId:L("tab"),sessionId:L("sess")};return F=u,u}let e=t.getItem(j)||t.getItem(st),r=t.getItem(N)||t.getItem(ot);const n=!(d!=null&&d.disableBroadcastChannel)&&(!!(d!=null&&d.channel)||typeof BroadcastChannel<"u");if(!e){e=L("tab"),r=r||L("sess");try{t.setItem(j,e),t.setItem(N,r)}catch{}if(n)try{const p=(d==null?void 0:d.channel)||new BroadcastChannel((d==null?void 0:d.channelName)||kt);yt(p,e)}catch{}const u={tabId:e,sessionId:r};return F=u,u}if(!n){r=r||L("sess");try{t.setItem(N,r)}catch{}const u={tabId:e,sessionId:r};return F=u,u}let i=null;try{i=(d==null?void 0:d.channel)||new BroadcastChannel((d==null?void 0:d.channelName)||kt)}catch{r=r||L("sess");const u={tabId:e,sessionId:r};return F=u,u}const a=L("claim"),s=(d==null?void 0:d.timeoutMs)??50;let o=!1;const c=u=>{const p=u.data;p&&p.type==="TAB_ID_COLLISION"&&p.tabId===e&&p.claimId===a&&(o=!0)};i.addEventListener("message",c);try{i.postMessage({type:"CLAIM_TAB_ID",tabId:e,claimId:a}),await new Promise(u=>{setTimeout(u,s)})}catch{}finally{i.removeEventListener("message",c)}if(o){e=L("tab"),r=L("sess");try{t.setItem(j,e),t.setItem(N,r)}catch{}}else if(!r){r=L("sess");try{t.setItem(N,r)}catch{}}yt(i,e);const h={tabId:e,sessionId:r};return F=h,h}function Xt(d){const t=d||(typeof window<"u"?window.sessionStorage:void 0);if(t)try{t.removeItem(j),t.removeItem(N),t.removeItem(st),t.removeItem(ot)}catch{}return F=null,Z(),Bt(d)}const Yt=new Set(["password","senha","token","authorization","cookie","secret","cvv","cvc","card","credit","cardnumber","securitycode","cpf","cnpj","email","phone","telefone","celular","otp","verificationcode","recoverycode","accesstoken","refreshtoken","apikey","pin"]),Kt=/Bearer\s+[A-Za-z0-9\-_=.]+/gi,Jt=/Basic\s+[A-Za-z0-9+/=]+/gi,Qt=/eyJ[A-Za-z0-9-_=]+\.eyJ[A-Za-z0-9-_=]+\.[A-Za-z0-9-_.+/=]*/gi,Zt=/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g,te=/\b\d{3}\.?\d{3}\.?\d{3}-?\d{2}\b/g,ee=/\b\d{2}\.?\d{3}\.?\d{3}\/?\d{4}-?\d{2}\b/g,re=/\b(?:\d[ -]*?){13,19}\b/g,ne=/(?:\+?55\s?)?(?:\(?\d{2}\)?\s?)?(?:9\d{4}|\d{4})[ -]?\d{4}/g,ie=/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi,ae=/\b\d{6,}\b/g,se={maxDepth:4,maxKeys:50,maxItems:50,maxStringLength:500};function X(d,t){try{const e=new URL(d,"http://localhost");if(t)return t(e);let r=e.pathname;r=r.replace(ie,":id"),r=r.replace(ae,":id");const n=Array.from(new Set(e.searchParams.keys())).sort(),i=n.length>0?`?${n.join("&")}`:"";return!d.startsWith("http://")&&!d.startsWith("https://")?`${r}${i}`:`${e.origin}${r}${i}`}catch{return"[INVALID_URL]"}}function D(d){if(!d||typeof d!="string")return d;let t=d;return t=t.replace(Kt,"Bearer [REDACTED_TOKEN]"),t=t.replace(Jt,"Basic [REDACTED_BASIC]"),t=t.replace(Qt,"[REDACTED_JWT]"),t=t.replace(Zt,"[REDACTED_EMAIL]"),t=t.replace(te,"[REDACTED_CPF]"),t=t.replace(ee,"[REDACTED_CNPJ]"),t=t.replace(re,"[REDACTED_CARD]"),t=t.replace(ne,"[REDACTED_PHONE]"),t}function oe(d){const t=d.toLowerCase().replace(/[^a-z0-9]/g,"");for(const e of Yt)if(t.includes(e))return!0;return!1}function ct(d,t){const e={...se,...t},r=new WeakSet;function n(i,a){try{if(i==null||typeof i=="boolean")return i;if(typeof i=="number")return Number.isNaN(i)?"[NaN]":i;if(typeof i=="bigint")return`${i.toString()}n`;if(typeof i=="function")return`[Function: ${i.name||"anonymous"}]`;if(typeof i=="symbol")return i.toString();if(typeof i=="string"){let s=D(i);return s.length>e.maxStringLength&&(s=`${s.substring(0,e.maxStringLength)}... [TRUNCATED]`),s}if(typeof i=="object"){if(r.has(i))return"[CIRCULAR]";if(r.add(i),a>=e.maxDepth)return"[MAX_DEPTH]";if(i instanceof Error)return{name:i.name,message:D(i.message),stack:i.stack?D(i.stack):void 0};if(i instanceof Date)return i.toISOString();if(i instanceof RegExp)return i.toString();if(typeof i.nodeType=="number"&&typeof i.tagName=="string"){const u=i;return`<${u.tagName.toLowerCase()}${u.id?` id="${u.id}"`:""}${u.className?` class="${u.className}"`:""}>`}if(Array.isArray(i)){const u=[],p=Math.min(i.length,e.maxItems);for(let g=0;g<p;g++)u.push(n(i[g],a+1));return i.length>e.maxItems&&u.push(`... [${i.length-e.maxItems} more items TRUNCATED]`),u}const s=i,o={},c=Object.keys(s),h=Math.min(c.length,e.maxKeys);for(let u=0;u<h;u++){const p=c[u];if(oe(p))o[p]="[REDACTED]";else try{o[p]=n(s[p],a+1)}catch{o[p]="[GETTER_ERROR]"}}return c.length>e.maxKeys&&(o.__truncated__=`[${c.length-e.maxKeys} more keys TRUNCATED]`),o}return"[UNRECOGNIZED_VALUE]"}catch{return"[SERIALIZATION_ERROR]"}}try{return n(d,0)}catch{return"[SERIALIZATION_FAILED]"}}function G(d,t=64*1024){if(!d||typeof d!="string")return"";let e=d;e.length>t&&(e=`${e.substring(0,t)}... [TRUNCATED ${d.length-t} BYTES]`);try{const r=JSON.parse(e),n=ct(r,{maxStringLength:2e3});return JSON.stringify(n,null,2)}catch{return D(e)}}function V(d){if(!d)return;const t={};let e=[];typeof Headers<"u"&&d instanceof Headers?e=Array.from(d.entries()):Array.isArray(d)?e=d:typeof d=="object"&&(e=Object.entries(d));for(const[r,n]of e){const i=String(r),a=String(n),s=i.toLowerCase();s.includes("auth")||s.includes("cookie")||s.includes("token")||s.includes("secret")||s.includes("key")?t[i]="[REDACTED]":t[i]=D(a)}return Object.keys(t).length>0?t:void 0}class Dt{constructor(t,e){l(this,"writer");l(this,"isRecording",!1);l(this,"sequenceProvider");l(this,"originalLog",null);l(this,"originalWarn",null);l(this,"originalError",null);l(this,"wrappedLog",null);l(this,"wrappedWarn",null);l(this,"wrappedError",null);l(this,"isInsideHook",!1);this.writer=t,this.sequenceProvider=e}start(){this.isRecording||(this.isRecording=!0,this.originalLog=console.log,this.originalWarn=console.warn,this.originalError=console.error,this.wrappedLog=(...t)=>{this.handleConsole("log",this.originalLog,t)},this.wrappedWarn=(...t)=>{this.handleConsole("warn",this.originalWarn,t)},this.wrappedError=(...t)=>{this.handleConsole("error",this.originalError,t)},console.log=this.wrappedLog,console.warn=this.wrappedWarn,console.error=this.wrappedError)}handleConsole(t,e,r){try{e.apply(console,r)}catch{}if(!(this.isInsideHook||!this.isRecording)){this.isInsideHook=!0;try{const n=r.map(a=>ct(a)),i={id:`con_${Date.now()}_${Math.random().toString(36).substring(2,7)}`,timestamp:Date.now(),sequence:this.sequenceProvider(),type:"console",level:t,args:n};this.writer.addTimelineEvent(i)}catch{}finally{this.isInsideHook=!1}}}stop(){this.isRecording&&(this.isRecording=!1,console.log===this.wrappedLog&&this.originalLog&&(console.log=this.originalLog),console.warn===this.wrappedWarn&&this.originalWarn&&(console.warn=this.originalWarn),console.error===this.wrappedError&&this.originalError&&(console.error=this.originalError),this.originalLog=null,this.originalWarn=null,this.originalError=null,this.wrappedLog=null,this.wrappedWarn=null,this.wrappedError=null)}}class Lt{constructor(t,e,r){l(this,"writer");l(this,"incidentManager");l(this,"sequenceProvider");l(this,"isRecording",!1);l(this,"errorHandler");l(this,"rejectionHandler");this.writer=t,this.incidentManager=e,this.sequenceProvider=r}start(){this.isRecording||(this.isRecording=!0,!(typeof window>"u")&&(this.errorHandler=t=>{this.handleGlobalError(t)},window.addEventListener("error",this.errorHandler,!0),this.rejectionHandler=t=>{this.handleUnhandledRejection(t)},window.addEventListener("unhandledrejection",this.rejectionHandler)))}handleGlobalError(t){if(this.isRecording)try{const e=t.error instanceof Error?t.error:null,r=(e==null?void 0:e.name)||"Error",n=D(t.message||(e==null?void 0:e.message)||"Unknown error"),i=e!=null&&e.stack?D(e.stack):void 0,a=t.filename||void 0,s=t.lineno||void 0,o=t.colno||void 0;this.recordAndTriggerError({source:"window",name:r,message:n,stack:i,filename:a,lineno:s,colno:o}).catch(()=>{})}catch{}}handleUnhandledRejection(t){if(this.isRecording)try{const e=t.reason;let r="UnhandledRejection",n="Promise rejeitada",i;e instanceof Error?(r=e.name,n=D(e.message),i=e.stack?D(e.stack):void 0):typeof e=="string"?n=D(e):e&&typeof e=="object"&&(n=D(JSON.stringify(e))),this.recordAndTriggerError({source:"unhandledrejection",name:r,message:n,stack:i}).catch(()=>{})}catch{}}captureException(t,e){if(this.isRecording)try{let r="Error",n="Exceção capturada",i,a;t instanceof Error?(r=t.name,n=D(t.message),i=t.stack?D(t.stack):void 0):typeof t=="string"&&(n=D(t)),e!=null&&e.componentStack&&(a=D(e.componentStack));const s=(e==null?void 0:e.source)==="react"?"react":"manual";return this.recordAndTriggerError({source:s,name:r,message:n,stack:i,componentStack:a}).catch(()=>{})}catch{}}recordAndTriggerError(t){var s;const e=Date.now(),r={id:`err_${e}_${Math.random().toString(36).substring(2,7)}`,timestamp:e,sequence:this.sequenceProvider(),type:"error",source:t.source,name:t.name,message:t.message,stack:t.stack,filename:t.filename,lineno:t.lineno,colno:t.colno,componentStack:t.componentStack};this.writer.addTimelineEvent(r);const n=t.stack&&((s=t.stack.split(`
2
2
  `)[1])==null?void 0:s.trim())||"",i=`${t.name}:${t.message}:${n}`,a=t.source==="react"?"react":t.source==="unhandledrejection"?"unhandledrejection":"error";return this.incidentManager.trigger(a,{id:`trig_${e}_${Math.random().toString(36).substring(2,7)}`,timestamp:e,type:a,signature:i,detail:{source:t.source,message:t.message,filename:t.filename}})}stop(){this.isRecording&&(this.isRecording=!1,typeof window<"u"&&(this.errorHandler&&(window.removeEventListener("error",this.errorHandler,!0),this.errorHandler=void 0),this.rejectionHandler&&(window.removeEventListener("unhandledrejection",this.rejectionHandler),this.rejectionHandler=void 0)))}}class zt{constructor(t,e,r,n){l(this,"writer");l(this,"incidentManager");l(this,"sequenceProvider");l(this,"config");l(this,"isRecording",!1);l(this,"originalFetch",null);l(this,"wrappedFetch",null);l(this,"originalXHROpen",null);l(this,"originalXHRSend",null);l(this,"originalXHRSetHeader",null);l(this,"xhrMetadata",new WeakMap);this.writer=t,this.incidentManager=e,this.sequenceProvider=r,this.config={captureHttpStatus:(n==null?void 0:n.captureHttpStatus)??[500,502,503,504],ignoredUrls:(n==null?void 0:n.ignoredUrls)??[],sanitizeUrlCallback:n==null?void 0:n.sanitizeUrlCallback,capturePayloads:(n==null?void 0:n.capturePayloads)??!1,maxPayloadSize:Math.max(0,(n==null?void 0:n.maxPayloadSize)??64*1024)}}start(){this.isRecording||(this.isRecording=!0,this.instrumentFetch(),this.instrumentXHR())}shouldIgnoreUrl(t){if(!t||t.startsWith("data:")||t.startsWith("blob:")||t.startsWith("chrome-extension:")||t.startsWith("moz-extension:")||t.includes(":5173")||t.includes("localhost:5173")||t.includes("127.0.0.1:5173")||t.includes("__backtrack_")||t.includes("__ffr_"))return!0;if(this.config.ignoredUrls){for(const e of this.config.ignoredUrls)if(typeof e=="string"&&t.includes(e)||e instanceof RegExp&&e.test(t))return!0}return!1}instrumentFetch(){if(typeof window>"u"||!window.fetch)return;this.originalFetch=window.fetch;const t=this;this.wrappedFetch=async function(e,r){var p;let n="",i=(r==null?void 0:r.method)||"GET",a=r==null?void 0:r.headers,s;if(typeof e=="string")n=e;else if(e instanceof URL)n=e.href;else if(e&&typeof e.url=="string"){const g=e;n=g.url,i=g.method||i,a=a||g.headers}if(t.config.capturePayloads&&(r!=null&&r.body))try{typeof r.body=="string"?s=r.body:typeof URLSearchParams<"u"&&r.body instanceof URLSearchParams&&(s=r.body.toString())}catch{}if(!t.isRecording||t.shouldIgnoreUrl(n))return t.originalFetch.call(this,e,r);const o=Date.now(),c=X(n,t.config.sanitizeUrlCallback),h=V(a),u=t.config.capturePayloads&&s?G(s,t.config.maxPayloadSize):void 0;try{const g=await t.originalFetch.call(this,e,r),b=Date.now()-o,f=g.status,m=f>=400?"error":"success";let k;try{k=V(g.headers)}catch{}let I;if(t.config.capturePayloads)try{const y=((p=g.headers)==null?void 0:p.get("content-type"))||"";if(y.includes("json")||y.includes("text")||y.includes("xml")||y.includes("javascript")||y.includes("form")){const E=await g.clone().text();I=G(E,t.config.maxPayloadSize)}}catch{}return t.recordNetworkEvent({method:i.toUpperCase(),url:c,status:f,durationMs:b,result:m,requestHeaders:h,requestBody:u,responseHeaders:k,responseBody:I}),g}catch(g){const b=Date.now()-o,m=g instanceof DOMException&&g.name==="AbortError"?"abort":"error";throw t.recordNetworkEvent({method:i.toUpperCase(),url:c,status:0,durationMs:b,result:m,requestHeaders:h,requestBody:u}),g}},window.fetch=this.wrappedFetch}instrumentXHR(){if(typeof window>"u"||!window.XMLHttpRequest)return;const t=this,e=window.XMLHttpRequest.prototype;this.originalXHROpen=e.open,this.originalXHRSend=e.send,this.originalXHRSetHeader=e.setRequestHeader,e.open=function(r,n,i=!0,a,s){if(t.isRecording){const o=typeof n=="string"?n:n.href;t.xhrMetadata.set(this,{method:(r||"GET").toUpperCase(),url:o,startTime:0,requestHeaders:{}})}return t.originalXHROpen.call(this,r,n,i,a,s)},e.setRequestHeader=function(r,n){const i=t.xhrMetadata.get(this);return i&&i.requestHeaders&&(i.requestHeaders[r]=n),t.originalXHRSetHeader.call(this,r,n)},e.send=function(r){const n=t.xhrMetadata.get(this);if(t.isRecording&&n&&!t.shouldIgnoreUrl(n.url)){n.startTime=Date.now();const i=X(n.url,t.config.sanitizeUrlCallback);t.config.capturePayloads&&typeof r=="string"&&(n.requestBody=r);let a=!1;const s=(o,c)=>{if(a)return;a=!0;const h=n.startTime?Date.now()-n.startTime:0;let u;try{const g=this.getAllResponseHeaders();if(g){const b={};for(const f of g.trim().split(/[\r\n]+/)){const m=f.split(": "),k=m.shift(),I=m.join(": ");k&&(b[k]=I)}u=V(b)}}catch{}let p;if(t.config.capturePayloads)try{(this.responseType===""||this.responseType==="text")&&typeof this.responseText=="string"&&(p=G(this.responseText,t.config.maxPayloadSize))}catch{}t.recordNetworkEvent({method:n.method,url:i,status:c,durationMs:h,result:o,requestHeaders:V(n.requestHeaders),requestBody:t.config.capturePayloads&&n.requestBody?G(n.requestBody,t.config.maxPayloadSize):void 0,responseHeaders:u,responseBody:p})};this.addEventListener("loadend",()=>{const o=this.status||0,c=o===0||o>=400?"error":"success";s(c,o)},{once:!0}),this.addEventListener("error",()=>s("error",this.status||0),{once:!0}),this.addEventListener("timeout",()=>s("timeout",0),{once:!0}),this.addEventListener("abort",()=>s("abort",0),{once:!0});try{return t.originalXHRSend.call(this,r)}catch(o){throw s("error",0),o}}return t.originalXHRSend.call(this,r)}}recordNetworkEvent(t){const e=Date.now(),r={id:`net_${e}_${Math.random().toString(36).substring(2,7)}`,timestamp:e,sequence:this.sequenceProvider(),type:"network",method:t.method,url:t.url,status:t.status,durationMs:t.durationMs,result:t.result,requestHeaders:t.requestHeaders,requestBody:t.requestBody,responseHeaders:t.responseHeaders,responseBody:t.responseBody};this.writer.addTimelineEvent(r),(this.config.captureHttpStatus.includes(t.status)||t.status===0&&t.result==="error")&&this.incidentManager.trigger("http",{id:`trig_http_${e}_${Math.random().toString(36).substring(2,7)}`,timestamp:e,type:"http",signature:`HTTP ${t.status===0?"CORS/ERR":t.status} ${t.method} ${t.url}`,detail:{method:t.method,url:t.url,status:t.status,result:t.result}}).catch(()=>{})}stop(){this.isRecording&&(this.isRecording=!1,typeof window<"u"&&(window.fetch===this.wrappedFetch&&this.originalFetch&&(window.fetch=this.originalFetch),window.XMLHttpRequest&&(window.XMLHttpRequest.prototype.open!==this.originalXHROpen&&this.originalXHROpen&&(window.XMLHttpRequest.prototype.open=this.originalXHROpen),window.XMLHttpRequest.prototype.send!==this.originalXHRSend&&this.originalXHRSend&&(window.XMLHttpRequest.prototype.send=this.originalXHRSend))),this.originalFetch=null,this.wrappedFetch=null,this.originalXHROpen=null,this.originalXHRSend=null)}}class Pt{constructor(t,e,r){l(this,"writer");l(this,"sequenceProvider");l(this,"config");l(this,"isRecording",!1);l(this,"currentUrl","");l(this,"originalPushState",null);l(this,"originalReplaceState",null);l(this,"popstateHandler");l(this,"hashchangeHandler");this.writer=t,this.sequenceProvider=e,this.config=r||{}}start(){if(this.isRecording||(this.isRecording=!0,typeof window>"u"))return;this.currentUrl=window.location.href,this.recordNavigation("initial",this.currentUrl);const t=this,e=window.history;this.originalPushState=e.pushState,this.originalReplaceState=e.replaceState,e.pushState=function(...r){t.originalPushState.apply(this,r);const n=window.location.href;t.recordNavigation("pushState",n)},e.replaceState=function(...r){t.originalReplaceState.apply(this,r);const n=window.location.href;t.recordNavigation("replaceState",n)},this.popstateHandler=()=>{this.recordNavigation("popstate",window.location.href)},window.addEventListener("popstate",this.popstateHandler),this.hashchangeHandler=()=>{this.recordNavigation("hashchange",window.location.href)},window.addEventListener("hashchange",this.hashchangeHandler)}recordNavigation(t,e){if(!this.isRecording)return;const r=this.currentUrl?X(this.currentUrl,this.config.sanitizeUrlCallback):void 0,n=X(e,this.config.sanitizeUrlCallback);this.currentUrl=e;const i={id:`nav_${Date.now()}_${Math.random().toString(36).substring(2,7)}`,timestamp:Date.now(),sequence:this.sequenceProvider(),type:"navigation",kind:t,fromUrl:r,toUrl:n};this.writer.addTimelineEvent(i)}stop(){this.isRecording&&(this.isRecording=!1,typeof window<"u"&&(this.originalPushState&&(window.history.pushState=this.originalPushState),this.originalReplaceState&&(window.history.replaceState=this.originalReplaceState),this.popstateHandler&&window.removeEventListener("popstate",this.popstateHandler),this.hashchangeHandler&&window.removeEventListener("hashchange",this.hashchangeHandler)),this.originalPushState=null,this.originalReplaceState=null,this.popstateHandler=void 0,this.hashchangeHandler=void 0)}}function Ht(d){if(d==="*"||d==="/*")return/^.*$/;const r=(d.startsWith("/")||d.startsWith("*")?d:`/${d}`).replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"§DOUBLE_STAR§").replace(/\*/g,"[^/]*").replace(/§DOUBLE_STAR§/g,".*");return new RegExp(`^${r}/?(?:\\?|#|$)`,"i")}function _t(d,t){if(!t||t.length===0)return!1;let e=d;try{d.includes("://")?e=new URL(d).pathname:e=d.split("?")[0].split("#")[0]}catch{}e.startsWith("/")||(e=`/${e}`);for(const r of t)if(typeof r=="function")try{if(r(e))return!0}catch{}else if(r instanceof RegExp){if(r.test(e))return!0}else if(typeof r=="string"&&(r===e||Ht(r).test(e)))return!0;return!1}class $t{constructor(t,e){l(this,"writer");l(this,"config");l(this,"isRecording",!1);l(this,"stopRecordFn",null);l(this,"droppedEventsCount",0);this.writer=t,this.config=e||{}}getDroppedEventsCount(){return this.droppedEventsCount}start(){if(!this.isRecording&&!(typeof window>"u"||typeof document>"u")){this.isRecording=!0;try{const t=this.config.privacy||{},e=[t.blockSelector,".backtrack-block",".ffr-block","[data-backtrack-block]","#__backtrack_annotator_overlay__","#__backtrack_widget_host__",".backtrack-ignore",".rr-ignore",".rr-block","[data-rr-ignore]","[data-backtrack-ignore]"].filter(Boolean).join(", "),r=[t.maskTextSelector,".backtrack-mask",".ffr-mask","[data-backtrack-mask]"].filter(Boolean).join(", ");this.stopRecordFn=Ut.record({emit:(n,i)=>{if(this.isRecording)try{const a=n;i&&this.writer.flush(),this.writer.addReplayEvent(a)}catch{this.droppedEventsCount++}},maskAllInputs:t.maskAllInputs!==!1,maskTextSelector:r||void 0,blockSelector:e||void 0,blockClass:"backtrack-block",ignoreClass:"backtrack-ignore",maskTextClass:"backtrack-mask",maskTextFn:n=>t.maskAllText||typeof window<"u"&&_t(window.location.pathname,t.sensitiveRoutes)?n.replace(/[^\s]/g,"*"):n,checkoutEveryNms:this.config.checkoutEveryNms??3e4,sampling:{mousemove:50,mouseInteraction:!0,scroll:150,input:"last"},recordCanvas:t.recordCanvas??t.blockMedia===!1,collectFonts:!1})||null}catch{this.droppedEventsCount++,this.isRecording=!1}}}stop(){if(this.isRecording&&(this.isRecording=!1,this.stopRecordFn)){try{this.stopRecordFn()}catch{}this.stopRecordFn=null}}}class Ot{constructor(t,e,r){l(this,"writer");l(this,"sequenceProvider");l(this,"observer",null);l(this,"isRecording",!1);l(this,"thresholdMs");this.writer=t,this.sequenceProvider=e,this.thresholdMs=(r==null?void 0:r.longTaskThresholdMs)??50}start(){if(!this.isRecording&&(this.isRecording=!0,!(typeof PerformanceObserver>"u")))try{if(!(PerformanceObserver.supportedEntryTypes||[]).includes("longtask"))return;this.observer=new PerformanceObserver(e=>{if(!this.isRecording)return;const r=e.getEntries();for(const n of r)if(n.duration>=this.thresholdMs){const i=Date.now(),a={id:`perf_${i}_${Math.random().toString(36).substring(2,7)}`,timestamp:i,sequence:this.sequenceProvider(),type:"performance",metric:"longtask",durationMs:Math.round(n.duration),details:n.name||"Main thread blocked"};this.writer.addTimelineEvent(a)}}),this.observer.observe({entryTypes:["longtask"]})}catch{this.observer=null}}stop(){if(this.isRecording=!1,this.observer){try{this.observer.disconnect()}catch{}this.observer=null}}}async function rt(d,t){if(!t||!t.trim())throw new Error('GitHub Token não fornecido. Gere um token com o escopo "gist".');const e=t.trim(),r=`backtrack-${d.incident.id}.ffr.json`,n=`Backtrack Incident Replay [${d.incident.id}]: ${d.incident.reason}`,i=JSON.stringify(d,null,2);if(new TextEncoder().encode(i).length>10*1024*1024)throw new Error("O artefato excede o limite máximo de 10 MB suportado para upload.");const s={description:n,public:!1,files:{[r]:{content:i}}},o=await fetch("https://api.github.com/gists",{method:"POST",headers:{Authorization:`Bearer ${e}`,Accept:"application/vnd.github+json","Content-Type":"application/json"},body:JSON.stringify(s)});if(!o.ok){let u="";try{const p=await o.json();u=p.message||JSON.stringify(p)}catch{u=o.statusText}throw o.status===401?new Error(`Falha de autenticação no GitHub (401). Verifique se o seu token possui o escopo 'gist': ${u}`):o.status===422?new Error(`O arquivo excede o limite suportado pelo GitHub Gist (10MB): ${u}`):new Error(`Erro ao criar Gist no GitHub (${o.status}): ${u}`)}const c=await o.json(),h=c.files&&(c.files[r]||Object.values(c.files)[0]);return{gistId:c.id,gistUrl:c.html_url,rawUrl:(h==null?void 0:h.raw_url)||c.html_url}}class qt{constructor(){l(this,"overlay",null);l(this,"canvas",null);l(this,"ctx",null);l(this,"tool","pen");l(this,"color","#ef4444");l(this,"items",[]);l(this,"historyStack",[]);l(this,"selectedItemId",null);l(this,"isMouseDown",!1);l(this,"isDraggingItem",!1);l(this,"dragStartX",0);l(this,"dragStartY",0);l(this,"activeDrawStart",{x:0,y:0});l(this,"activePoints",[]);l(this,"activePopover",null);l(this,"onComplete",null)}open(t){if(this.overlay)return;this.onComplete=t,this.items=[],this.historyStack=[[]],this.selectedItemId=null;const e=document.createElement("div");e.id="__backtrack_annotator_overlay__",e.className="backtrack-ignore backtrack-block rr-ignore rr-block",e.setAttribute("data-rr-ignore","true"),e.setAttribute("data-backtrack-ignore","true"),e.style.cssText=`
3
3
  position: fixed;
4
4
  top: 0;
@@ -1332,8 +1332,8 @@
1332
1332
  white-space: nowrap;
1333
1333
  border-width: 0;
1334
1334
  }
1335
- `,wt="https://backtrack-viewer.pages.dev",O=class O{constructor(t,e){l(this,"recorder");l(this,"options");l(this,"container",null);l(this,"shadow",null);l(this,"isOpen",!1);l(this,"selectedDurationSeconds",300);l(this,"isCapturing",!1);l(this,"incidents",[]);l(this,"health",null);l(this,"isCustomDuration",!1);l(this,"toast",null);l(this,"banner",null);l(this,"toastTimer",null);l(this,"isHeaderMenuOpen",!1);l(this,"selectedIncidentId",null);l(this,"exportModalIncidentId",null);l(this,"exportModalIncludeLink",!1);l(this,"isExportingMarkdown",!1);l(this,"exportModalError",null);l(this,"downloadModalIncidentId",null);l(this,"downloadModalFormat",null);l(this,"isDownloading",!1);l(this,"downloadModalError",null);l(this,"showHideConfirmModal",!1);l(this,"wasDragged",!1);l(this,"pollTimer",null);l(this,"handleGlobalKey");this.recorder=t,this.options={position:(e==null?void 0:e.position)??"bottom-left",zIndex:(e==null?void 0:e.zIndex)??999999,defaultViewerUrl:(e==null?void 0:e.defaultViewerUrl)??wt}}mount(){if(this.container||typeof document>"u")return;const t=document.createElement("div");t.id="__backtrack_widget_host__",t.className="backtrack-ignore rr-ignore",t.setAttribute("data-rr-ignore","true"),this.applyHostPosition(t);try{typeof localStorage<"u"&&localStorage.getItem("backtrack_widget_hidden")==="true"&&(t.style.display="none")}catch{}this.shadow=t.attachShadow({mode:"open"}),this.container=t,document.body.appendChild(t),this.handleGlobalKey=e=>{if(e.key==="Escape"||e.key==="Esc"){if(this.showHideConfirmModal){e.preventDefault(),this.showHideConfirmModal=!1,this.render();return}if(this.exportModalIncidentId){e.preventDefault(),this.closeExportModal();return}if(this.downloadModalIncidentId){e.preventDefault(),this.closeDownloadModal();return}if(this.isHeaderMenuOpen){e.preventDefault(),this.isHeaderMenuOpen=!1,this.render();return}if(this.banner){e.preventDefault(),this.dismissBanner();return}if(this.selectedIncidentId){e.preventDefault(),this.selectedIncidentId=null,this.render();return}if(this.isOpen){e.preventDefault(),this.toggleOpen();return}}(e.ctrlKey||e.metaKey)&&e.shiftKey&&(e.key==="B"||e.key==="b")&&(e.preventDefault(),this.toggle())},window.addEventListener("keydown",this.handleGlobalKey),this.render(),this.updateData()}unmount(){this.handleGlobalKey&&typeof window<"u"&&(window.removeEventListener("keydown",this.handleGlobalKey),this.handleGlobalKey=void 0),this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null),this.toastTimer&&(clearTimeout(this.toastTimer),this.toastTimer=null),this.container&&this.container.parentNode&&this.container.parentNode.removeChild(this.container),this.container=null,this.shadow=null}hide(){this.showHideConfirmModal=!1,this.isHeaderMenuOpen=!1,this.container&&(this.container.style.display="none");try{typeof localStorage<"u"&&localStorage.setItem("backtrack_widget_hidden","true")}catch{}console.log("%c[Backtrack]%c Widget ocultado. Para reexibir, use %cBacktrack.show()%c no console ou tecle %cCtrl+Shift+B%c.","color: #38bdf8; font-weight: bold;","color: inherit;","color: #22c55e; font-weight: bold;","color: inherit;","color: #f59e0b; font-weight: bold;","color: inherit;")}show(){this.container&&(this.container.style.display="");try{typeof localStorage<"u"&&localStorage.removeItem("backtrack_widget_hidden")}catch{}console.log("%c[Backtrack]%c Widget exibido!","color: #38bdf8; font-weight: bold;","color: inherit;")}toggle(){var e;return((e=this.container)==null?void 0:e.style.display)==="none"||typeof localStorage<"u"&&localStorage.getItem("backtrack_widget_hidden")==="true"?(this.show(),!0):(this.hide(),!1)}isVisible(){return this.container?this.container.style.display!=="none":!1}applyHostPosition(t){const e=this.options.position||"bottom-left";t.style.position="fixed",t.style.zIndex=String(this.options.zIndex||999999),e==="bottom-left"?(t.style.bottom="16px",t.style.left="16px"):e==="bottom-right"?(t.style.bottom="16px",t.style.right="16px"):e==="top-left"?(t.style.top="16px",t.style.left="16px"):e==="top-right"&&(t.style.top="16px",t.style.right="16px")}getViewerUrl(){try{if(typeof localStorage<"u"){const t=localStorage.getItem("backtrack_viewer_url");if(t&&t.trim())return t.trim().replace(/\/+$/,"")}}catch{}return(this.options.defaultViewerUrl||wt).replace(/\/+$/,"")}async updateData(){try{this.health=this.recorder.getHealth(),this.incidents=await this.recorder.listIncidents(),this.updateDomValues()}catch{}}showToast(t,e="success",r=2800){var i;this.toastTimer&&(clearTimeout(this.toastTimer),this.toastTimer=null),this.toast={message:t,type:e};const n=(i=this.shadow)==null?void 0:i.querySelector(".backtrack-panel");if(n){const a=n.querySelector(".backtrack-toast-wrap");a&&a.remove();const s=document.createElement("div");s.innerHTML=this.renderToastHtml(),s.firstElementChild&&n.appendChild(s.firstElementChild)}else this.render();this.toastTimer=setTimeout(()=>{var s;this.toast=null,this.toastTimer=null;const a=(s=this.shadow)==null?void 0:s.querySelector(".backtrack-toast-wrap");a&&a.remove()},r)}showBanner(t,e="danger"){var n,i,a;this.banner={message:t,type:e};const r=(n=this.shadow)==null?void 0:n.querySelector(".backtrack-panel-body");if(r){const s=r.querySelector(".backtrack-banner");s&&s.remove();const o=document.createElement("div");o.innerHTML=this.renderBannerHtml(),o.firstElementChild&&(r.insertBefore(o.firstElementChild,r.firstChild),(a=(i=this.shadow)==null?void 0:i.getElementById("btn-dismiss-banner"))==null||a.addEventListener("click",()=>{this.dismissBanner()}))}else this.render()}dismissBanner(){var e;this.banner=null;const t=(e=this.shadow)==null?void 0:e.querySelector(".backtrack-banner");t&&t.remove()}async handleCapture(){if(!this.isCapturing){this.isCapturing=!0,this.render();try{const t=this.selectedDurationSeconds>0?this.selectedDurationSeconds:void 0;await this.recorder.capture("manual",t),await this.updateData(),this.showToast("Gravação salva.","success")}catch{this.showBanner("Não foi possível salvar a gravação. Tente novamente.","danger")}finally{this.isCapturing=!1,this.render()}}}async handleClear(){try{if(typeof window<"u"&&typeof window.confirm=="function"&&!window.confirm("Deseja realmente limpar todas as gravações e o buffer da sessão?"))return;await this.recorder.clear(),this.selectedIncidentId=null,await this.updateData(),this.showToast("Gravações limpas.","success")}catch{this.showBanner("Não foi possível limpar as gravações.","danger")}}async handleViewIncident(t){try{const e=await this.recorder.getArtifact(t);this.openInViewer(e)}catch{this.showBanner("Não foi possível carregar o replay. Tente novamente.","danger")}}handleDownloadIncident(t){this.openDownloadModal(t)}openDownloadModal(t){this.downloadModalIncidentId=t,this.downloadModalFormat=null,this.downloadModalError=null,this.isDownloading=!1,this.render()}closeDownloadModal(){this.isDownloading||(this.downloadModalIncidentId=null,this.downloadModalFormat=null,this.downloadModalError=null,this.render())}async confirmDownload(){const t=this.downloadModalIncidentId;if(t){if(!this.downloadModalFormat){this.downloadModalError="Escolha uma opção antes de baixar",this.render();return}this.isDownloading=!0,this.downloadModalError=null,this.render();try{const e=this.downloadModalFormat==="ai",r=this.downloadModalFormat==="gzip";await this.recorder.exportIncident(t,{compress:r,aiOptimized:e}),this.showToast("Download iniciado.","success")}catch{this.downloadModalError="Falha ao exportar incidente.",this.isDownloading=!1,this.render();return}finally{this.isDownloading=!1}this.downloadModalIncidentId=null,this.downloadModalFormat=null,this.downloadModalError=null,this.render()}}handleCopyMarkdown(t){this.openExportModal(t)}openExportModal(t){this.exportModalIncidentId=t,this.exportModalIncludeLink=!1,this.exportModalError=null,this.isExportingMarkdown=!1,this.render()}closeExportModal(){this.isExportingMarkdown||(this.exportModalIncidentId=null,this.exportModalError=null,this.render())}async confirmCopyMarkdown(){const t=this.exportModalIncidentId;if(t){this.isExportingMarkdown=!0,this.exportModalError=null,this.render();try{const e=await this.recorder.getArtifact(t);let r;if(this.exportModalIncludeLink){const a=new TextEncoder().encode(JSON.stringify(e)).byteLength,s=10*1024*1024;if(a>s)throw new Error("O artefato excede o limite máximo permitido pelo GitHub Gist (10 MB).");let o=O.sessionGithubToken;if(!o||!o.trim()){const p=prompt('Insira seu GitHub Personal Access Token (com permissão "gist") para gerar o link compartilhado:');if(!p||!p.trim()){this.isExportingMarkdown=!1,this.render();return}o=p.trim(),O.sessionGithubToken=o}const c=await rt(e,o);r=`${this.getViewerUrl()}/?gist=${c.gistId}`;const u=Math.floor(Math.max(0,(e.incident.triggeredAt||e.incident.finalizedAt)-e.incident.startedAt)/1e3);r&&u>0&&!r.includes("&t=")&&!r.includes("?t=")&&(r+=(r.includes("?")?"&":"?")+`t=${u}`)}const n=q.formatIncidentMarkdown(e,{replayUrl:r});let i=!1;if(typeof navigator<"u"&&navigator.clipboard&&navigator.clipboard.writeText)try{await navigator.clipboard.writeText(n),i=!0}catch{}if(!i&&typeof document<"u")try{const a=document.createElement("textarea");a.value=n,a.style.position="fixed",a.style.opacity="0",document.body.appendChild(a),a.focus(),a.select(),i=document.execCommand("copy"),document.body.removeChild(a)}catch{i=!1}i?this.showToast(this.exportModalIncludeLink?"Link copiado.":"Markdown copiado.","success"):this.showToast("Área de transferência indisponível.","danger")}catch(e){const r=e instanceof Error?e.message:String(e);r.includes("401")&&(O.sessionGithubToken=null),this.exportModalError=`Falha: ${r}`,this.isExportingMarkdown=!1,this.render();return}finally{this.isExportingMarkdown=!1}this.exportModalIncidentId=null,this.exportModalError=null,this.render()}}async handleShareGist(t){let e=O.sessionGithubToken;if(!e||!e.trim()){const r=prompt(`Insira seu GitHub Personal Access Token (com permissão "gist") para gerar o link não listado:
1336
- (O token será mantido apenas em memória nesta sessão)`);if(!r||!r.trim())return;e=r.trim(),O.sessionGithubToken=e}try{const r=await this.recorder.getArtifact(t),n=await rt(r,e),a=`${this.getViewerUrl()}/?gist=${n.gistId}`;let s=!1;if(typeof navigator<"u"&&navigator.clipboard&&navigator.clipboard.writeText)try{await navigator.clipboard.writeText(a),s=!0}catch{}if(!s&&typeof document<"u")try{const o=document.createElement("textarea");o.value=a,o.style.position="fixed",o.style.opacity="0",document.body.appendChild(o),o.focus(),o.select(),s=document.execCommand("copy"),document.body.removeChild(o)}catch{s=!1}s?this.showToast("Link copiado.","success"):prompt("Link compartilhado gerado com sucesso:",a)}catch(r){(r instanceof Error?r.message:String(r)).includes("401")&&(O.sessionGithubToken=null),this.showBanner("Não foi possível gerar o link. Tente novamente.","danger")}}handleAnnotate(){this.isOpen=!1,this.render(),new qt().open(async e=>{var r;if(!e){this.isOpen=!0,this.render();return}try{this.isCapturing=!0,this.isOpen=!0,this.render();const n=(r=e.notes)!=null&&r.trim()?`Anotação do QA: ${e.notes.trim()}`:"Anotação visual de bug na tela",i=this.selectedDurationSeconds>0?this.selectedDurationSeconds:void 0;await this.recorder.capture(n,i,{annotationImage:e.dataUrl,notes:e.notes}),await this.updateData(),this.showToast("Gravação salva.","success")}catch{this.showBanner("Não foi possível salvar a gravação com anotação.","danger")}finally{this.isCapturing=!1,this.render()}})}async handleDeleteIncident(t){try{if(typeof window<"u"&&typeof window.confirm=="function"&&!window.confirm("Deseja realmente excluir esta gravação?"))return;await this.recorder.deleteIncident(t),this.selectedIncidentId===t&&(this.selectedIncidentId=null),await this.updateData(),this.showToast("Gravação excluída.","success")}catch{this.showBanner("Não foi possível excluir a gravação.","danger")}}openInViewer(t){const e=this.getViewerUrl();let r="*",n=e;try{const p=new URL(e,window.location.href);r=p.origin,p.searchParams.set("openerOrigin",window.location.origin),n=p.toString()}catch{}const i=window.open(n,"backtrack_viewer");if(!i){this.showBanner("Pop-up bloqueado. Permita pop-ups no navegador.","danger");return}try{i.focus()}catch{}let a=!1,s=null;const o=()=>{s&&(clearInterval(s),s=null),window.removeEventListener("message",h)},c=()=>{if(a||i.closed){o();return}try{i.postMessage({type:"LOAD_BACKTRACK_ARTIFACT",artifact:t},r)}catch{}},h=p=>{var g,b,f,m;p.source===i&&(r!=="*"&&p.origin!==r||(((g=p.data)==null?void 0:g.type)==="BACKTRACK_VIEWER_READY"||((b=p.data)==null?void 0:b.type)==="FFR_VIEWER_READY"?c():(((f=p.data)==null?void 0:f.type)==="BACKTRACK_ARTIFACT_RECEIVED"||((m=p.data)==null?void 0:m.type)==="FFR_ARTIFACT_RECEIVED")&&(a=!0,o())))};window.addEventListener("message",h),c();const u=Date.now();s=setInterval(()=>{a||i.closed||Date.now()-u>4e3?o():c()},250)}toggleOpen(){this.isOpen=!this.isOpen,this.isHeaderMenuOpen=!1,this.selectedIncidentId=null,this.isOpen?(this.updateData(),this.pollTimer||(this.pollTimer=setInterval(()=>this.updateData(),5e3))):this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null),this.render()}formatBytes(t){if(t===0)return"0 KB";const e=t/1024;return e<1024?`${e.toFixed(1)} KB`:`${(e/1024).toFixed(1)} MB`}formatIncidentTitle(t){return!t||t==="manual"?"Sessão manual iniciada":t==="unhandled-error"?"Erro não tratado na aplicação":t==="http-error"?"Falha na requisição de rede":t}renderBannerHtml(){if(!this.banner)return"";const t=this.banner.type==="success";return`
1335
+ `,wt="https://backtrack-viewer.netlify.app",O=class O{constructor(t,e){l(this,"recorder");l(this,"options");l(this,"container",null);l(this,"shadow",null);l(this,"isOpen",!1);l(this,"selectedDurationSeconds",300);l(this,"isCapturing",!1);l(this,"incidents",[]);l(this,"health",null);l(this,"isCustomDuration",!1);l(this,"toast",null);l(this,"banner",null);l(this,"toastTimer",null);l(this,"isHeaderMenuOpen",!1);l(this,"selectedIncidentId",null);l(this,"exportModalIncidentId",null);l(this,"exportModalIncludeLink",!1);l(this,"isExportingMarkdown",!1);l(this,"exportModalError",null);l(this,"downloadModalIncidentId",null);l(this,"downloadModalFormat",null);l(this,"isDownloading",!1);l(this,"downloadModalError",null);l(this,"showHideConfirmModal",!1);l(this,"wasDragged",!1);l(this,"pollTimer",null);l(this,"handleGlobalKey");this.recorder=t,this.options={position:(e==null?void 0:e.position)??"bottom-left",zIndex:(e==null?void 0:e.zIndex)??999999,defaultViewerUrl:(e==null?void 0:e.defaultViewerUrl)??wt}}mount(){if(this.container||typeof document>"u")return;const t=document.createElement("div");t.id="__backtrack_widget_host__",t.className="backtrack-ignore rr-ignore",t.setAttribute("data-rr-ignore","true"),this.applyHostPosition(t);try{typeof localStorage<"u"&&localStorage.getItem("backtrack_widget_hidden")==="true"&&(t.style.display="none")}catch{}this.shadow=t.attachShadow({mode:"open"}),this.container=t,document.body.appendChild(t),this.handleGlobalKey=e=>{if(e.key==="Escape"||e.key==="Esc"){if(this.showHideConfirmModal){e.preventDefault(),this.showHideConfirmModal=!1,this.render();return}if(this.exportModalIncidentId){e.preventDefault(),this.closeExportModal();return}if(this.downloadModalIncidentId){e.preventDefault(),this.closeDownloadModal();return}if(this.isHeaderMenuOpen){e.preventDefault(),this.isHeaderMenuOpen=!1,this.render();return}if(this.banner){e.preventDefault(),this.dismissBanner();return}if(this.selectedIncidentId){e.preventDefault(),this.selectedIncidentId=null,this.render();return}if(this.isOpen){e.preventDefault(),this.toggleOpen();return}}(e.ctrlKey||e.metaKey)&&e.shiftKey&&(e.key==="B"||e.key==="b")&&(e.preventDefault(),this.toggle())},window.addEventListener("keydown",this.handleGlobalKey),this.render(),this.updateData()}unmount(){this.handleGlobalKey&&typeof window<"u"&&(window.removeEventListener("keydown",this.handleGlobalKey),this.handleGlobalKey=void 0),this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null),this.toastTimer&&(clearTimeout(this.toastTimer),this.toastTimer=null),this.container&&this.container.parentNode&&this.container.parentNode.removeChild(this.container),this.container=null,this.shadow=null}hide(){this.showHideConfirmModal=!1,this.isHeaderMenuOpen=!1,this.container&&(this.container.style.display="none");try{typeof localStorage<"u"&&localStorage.setItem("backtrack_widget_hidden","true")}catch{}console.log("%c[Backtrack]%c Widget ocultado. Para reexibir, use %cBacktrack.show()%c no console ou tecle %cCtrl+Shift+B%c.","color: #38bdf8; font-weight: bold;","color: inherit;","color: #22c55e; font-weight: bold;","color: inherit;","color: #f59e0b; font-weight: bold;","color: inherit;")}show(){this.container&&(this.container.style.display="");try{typeof localStorage<"u"&&localStorage.removeItem("backtrack_widget_hidden")}catch{}console.log("%c[Backtrack]%c Widget exibido!","color: #38bdf8; font-weight: bold;","color: inherit;")}toggle(){var e;return((e=this.container)==null?void 0:e.style.display)==="none"||typeof localStorage<"u"&&localStorage.getItem("backtrack_widget_hidden")==="true"?(this.show(),!0):(this.hide(),!1)}isVisible(){return this.container?this.container.style.display!=="none":!1}applyHostPosition(t){const e=this.options.position||"bottom-left";t.style.position="fixed",t.style.zIndex=String(this.options.zIndex||999999),e==="bottom-left"?(t.style.bottom="16px",t.style.left="16px"):e==="bottom-right"?(t.style.bottom="16px",t.style.right="16px"):e==="top-left"?(t.style.top="16px",t.style.left="16px"):e==="top-right"&&(t.style.top="16px",t.style.right="16px")}getViewerUrl(){try{if(typeof localStorage<"u"){const t=localStorage.getItem("backtrack_viewer_url");if(t&&t.trim())return t.trim().replace(/\/+$/,"")}}catch{}return(this.options.defaultViewerUrl||wt).replace(/\/+$/,"")}async updateData(){try{this.health=this.recorder.getHealth(),this.incidents=await this.recorder.listIncidents(),this.updateDomValues()}catch{}}showToast(t,e="success",r=2800){var i;this.toastTimer&&(clearTimeout(this.toastTimer),this.toastTimer=null),this.toast={message:t,type:e};const n=(i=this.shadow)==null?void 0:i.querySelector(".backtrack-panel");if(n){const a=n.querySelector(".backtrack-toast-wrap");a&&a.remove();const s=document.createElement("div");s.innerHTML=this.renderToastHtml(),s.firstElementChild&&n.appendChild(s.firstElementChild)}else this.render();this.toastTimer=setTimeout(()=>{var s;this.toast=null,this.toastTimer=null;const a=(s=this.shadow)==null?void 0:s.querySelector(".backtrack-toast-wrap");a&&a.remove()},r)}showBanner(t,e="danger"){var n,i,a;this.banner={message:t,type:e};const r=(n=this.shadow)==null?void 0:n.querySelector(".backtrack-panel-body");if(r){const s=r.querySelector(".backtrack-banner");s&&s.remove();const o=document.createElement("div");o.innerHTML=this.renderBannerHtml(),o.firstElementChild&&(r.insertBefore(o.firstElementChild,r.firstChild),(a=(i=this.shadow)==null?void 0:i.getElementById("btn-dismiss-banner"))==null||a.addEventListener("click",()=>{this.dismissBanner()}))}else this.render()}dismissBanner(){var e;this.banner=null;const t=(e=this.shadow)==null?void 0:e.querySelector(".backtrack-banner");t&&t.remove()}async handleCapture(){if(!this.isCapturing){this.isCapturing=!0,this.render();try{const t=this.selectedDurationSeconds>0?this.selectedDurationSeconds:void 0;await this.recorder.capture("manual",t),await this.updateData(),this.showToast("Gravação salva.","success")}catch{this.showBanner("Não foi possível salvar a gravação. Tente novamente.","danger")}finally{this.isCapturing=!1,this.render()}}}async handleClear(){try{if(typeof window<"u"&&typeof window.confirm=="function"&&!window.confirm("Deseja realmente limpar todas as gravações e o buffer da sessão?"))return;await this.recorder.clear(),this.selectedIncidentId=null,await this.updateData(),this.showToast("Gravações limpas.","success")}catch{this.showBanner("Não foi possível limpar as gravações.","danger")}}async handleViewIncident(t){try{const e=await this.recorder.getArtifact(t);this.openInViewer(e)}catch{this.showBanner("Não foi possível carregar o replay. Tente novamente.","danger")}}handleDownloadIncident(t){this.openDownloadModal(t)}openDownloadModal(t){this.downloadModalIncidentId=t,this.downloadModalFormat=null,this.downloadModalError=null,this.isDownloading=!1,this.render()}closeDownloadModal(){this.isDownloading||(this.downloadModalIncidentId=null,this.downloadModalFormat=null,this.downloadModalError=null,this.render())}async confirmDownload(){const t=this.downloadModalIncidentId;if(t){if(!this.downloadModalFormat){this.downloadModalError="Escolha uma opção antes de baixar",this.render();return}this.isDownloading=!0,this.downloadModalError=null,this.render();try{const e=this.downloadModalFormat==="ai",r=this.downloadModalFormat==="gzip";await this.recorder.exportIncident(t,{compress:r,aiOptimized:e}),this.showToast("Download iniciado.","success")}catch{this.downloadModalError="Falha ao exportar incidente.",this.isDownloading=!1,this.render();return}finally{this.isDownloading=!1}this.downloadModalIncidentId=null,this.downloadModalFormat=null,this.downloadModalError=null,this.render()}}handleCopyMarkdown(t){this.openExportModal(t)}openExportModal(t){this.exportModalIncidentId=t,this.exportModalIncludeLink=!1,this.exportModalError=null,this.isExportingMarkdown=!1,this.render()}closeExportModal(){this.isExportingMarkdown||(this.exportModalIncidentId=null,this.exportModalError=null,this.render())}async confirmCopyMarkdown(){const t=this.exportModalIncidentId;if(t){this.isExportingMarkdown=!0,this.exportModalError=null,this.render();try{const e=await this.recorder.getArtifact(t);let r;if(this.exportModalIncludeLink){const a=new TextEncoder().encode(JSON.stringify(e)).byteLength,s=10*1024*1024;if(a>s)throw new Error("O artefato excede o limite máximo permitido pelo GitHub Gist (10 MB).");let o=O.sessionGithubToken;if(!o||!o.trim()){const p=prompt('Insira seu GitHub Personal Access Token (com permissão "gist") para gerar o link compartilhado:');if(!p||!p.trim()){this.isExportingMarkdown=!1,this.render();return}o=p.trim(),O.sessionGithubToken=o}const c=await rt(e,o);r=`${this.getViewerUrl()}/?gist=${c.gistId}`;const u=Math.floor(Math.max(0,(e.incident.triggeredAt||e.incident.finalizedAt)-e.incident.startedAt)/1e3);r&&u>0&&!r.includes("&t=")&&!r.includes("?t=")&&(r+=(r.includes("?")?"&":"?")+`t=${u}`)}const n=q.formatIncidentMarkdown(e,{replayUrl:r});let i=!1;if(typeof navigator<"u"&&navigator.clipboard&&navigator.clipboard.writeText)try{await navigator.clipboard.writeText(n),i=!0}catch{}if(!i&&typeof document<"u")try{const a=document.createElement("textarea");a.value=n,a.style.position="fixed",a.style.opacity="0",document.body.appendChild(a),a.focus(),a.select(),i=document.execCommand("copy"),document.body.removeChild(a)}catch{i=!1}i?this.showToast(this.exportModalIncludeLink?"Link copiado.":"Markdown copiado.","success"):this.showToast("Área de transferência indisponível.","danger")}catch(e){const r=e instanceof Error?e.message:String(e);r.includes("401")&&(O.sessionGithubToken=null),this.exportModalError=`Falha: ${r}`,this.isExportingMarkdown=!1,this.render();return}finally{this.isExportingMarkdown=!1}this.exportModalIncidentId=null,this.exportModalError=null,this.render()}}async handleShareGist(t){let e=O.sessionGithubToken;if(!e||!e.trim()){const r=prompt(`Insira seu GitHub Personal Access Token (com permissão "gist") para gerar o link não listado:
1336
+ (O token será mantido apenas em memória nesta sessão)`);if(!r||!r.trim())return;e=r.trim(),O.sessionGithubToken=e}try{const r=await this.recorder.getArtifact(t),n=await rt(r,e),a=`${this.getViewerUrl()}/?gist=${n.gistId}`;let s=!1;if(typeof navigator<"u"&&navigator.clipboard&&navigator.clipboard.writeText)try{await navigator.clipboard.writeText(a),s=!0}catch{}if(!s&&typeof document<"u")try{const o=document.createElement("textarea");o.value=a,o.style.position="fixed",o.style.opacity="0",document.body.appendChild(o),o.focus(),o.select(),s=document.execCommand("copy"),document.body.removeChild(o)}catch{s=!1}s?this.showToast("Link copiado.","success"):prompt("Link compartilhado gerado com sucesso:",a)}catch(r){(r instanceof Error?r.message:String(r)).includes("401")&&(O.sessionGithubToken=null),this.showBanner("Não foi possível gerar o link. Tente novamente.","danger")}}handleAnnotate(){this.isOpen=!1,this.render(),new qt().open(async e=>{var r;if(!e){this.isOpen=!0,this.render();return}try{this.isCapturing=!0,this.isOpen=!0,this.render();const n=(r=e.notes)!=null&&r.trim()?`Anotação do QA: ${e.notes.trim()}`:"Anotação visual de bug na tela",i=this.selectedDurationSeconds>0?this.selectedDurationSeconds:void 0;await this.recorder.capture(n,i,{annotationImage:e.dataUrl,notes:e.notes}),await this.updateData(),this.showToast("Gravação salva.","success")}catch{this.showBanner("Não foi possível salvar a gravação com anotação.","danger")}finally{this.isCapturing=!1,this.render()}})}async handleDeleteIncident(t){try{if(typeof window<"u"&&typeof window.confirm=="function"&&!window.confirm("Deseja realmente excluir esta gravação?"))return;await this.recorder.deleteIncident(t),this.selectedIncidentId===t&&(this.selectedIncidentId=null),await this.updateData(),this.showToast("Gravação excluída.","success")}catch{this.showBanner("Não foi possível excluir a gravação.","danger")}}openInViewer(t){const e=this.getViewerUrl();let r="*",n=e;try{const p=new URL(e,window.location.href);r=p.origin,p.searchParams.set("openerOrigin",window.location.origin),n=p.toString()}catch{}const i=window.open(n,"backtrack_viewer");if(!i){this.showBanner("Pop-up bloqueado. Permita pop-ups no navegador.","danger");return}try{i.focus()}catch{}let a=!1,s=null;const o=()=>{s&&(clearInterval(s),s=null),window.removeEventListener("message",h)},c=()=>{if(a||i.closed){o();return}try{i.postMessage({type:"LOAD_BACKTRACK_ARTIFACT",artifact:t},r)}catch{}},h=p=>{var g,b,f,m;p.source===i&&(r!=="*"&&p.origin!==r||(((g=p.data)==null?void 0:g.type)==="BACKTRACK_VIEWER_READY"||((b=p.data)==null?void 0:b.type)==="FFR_VIEWER_READY"?c():(((f=p.data)==null?void 0:f.type)==="BACKTRACK_ARTIFACT_RECEIVED"||((m=p.data)==null?void 0:m.type)==="FFR_ARTIFACT_RECEIVED")&&(a=!0,o())))};window.addEventListener("message",h),c();const u=Date.now();s=setInterval(()=>{a||i.closed||Date.now()-u>4e3?o():c()},250)}toggleOpen(){this.isOpen=!this.isOpen,this.isHeaderMenuOpen=!1,this.selectedIncidentId=null,this.isOpen?(this.updateData(),this.pollTimer||(this.pollTimer=setInterval(()=>this.updateData(),5e3))):this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null),this.render()}formatBytes(t){if(t===0)return"0 KB";const e=t/1024;return e<1024?`${e.toFixed(1)} KB`:`${(e/1024).toFixed(1)} MB`}formatIncidentTitle(t){const{reason:e,trigger:r}=t;if(!e||e==="manual")return"Sessão manual iniciada";let i={error:"Erro na aplicação","unhandled-error":"Erro não tratado na aplicação",unhandledrejection:"Promise não tratada",react:"Erro no React",http:"Falha na requisição de rede","http-error":"Falha na requisição de rede"}[e]||e;const a=r==null?void 0:r.detail;if(e==="http"&&a){if(i=typeof a.status=="number"&&a.status>0?`HTTP ${a.status}`:"Falha de rede",typeof a.method=="string"&&typeof a.url=="string")try{const s=new URL(a.url,"http://localhost").pathname;i+=` · ${a.method.toUpperCase()} ${s}`}catch{}}else typeof(a==null?void 0:a.message)=="string"&&a.message.trim()&&(i+=` · ${a.message.trim()}`);return i.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;")}renderBannerHtml(){if(!this.banner)return"";const t=this.banner.type==="success";return`
1337
1337
  <div class="backtrack-banner backtrack-banner-${this.banner.type}" role="alert">
1338
1338
  <span class="backtrack-banner-icon">
1339
1339
  ${t?'<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14" /><polyline points="22 4 12 14.01 9 11.01" /></svg>':'<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="10" /><line x1="12" y1="8" x2="12" y2="12" /><line x1="12" y1="16" x2="12.01" y2="16" /></svg>'}
@@ -1585,7 +1585,7 @@
1585
1585
  <div class="backtrack-empty-title">Nenhuma gravação ainda</div>
1586
1586
  <div class="backtrack-empty-desc">Clique em Salvar para capturar os últimos 5 minutos</div>
1587
1587
  </div>
1588
- `:this.incidents.slice(0,8).map(e=>{const r=new Date(e.startedAt).toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"}),n=e.finalizedAt?Math.max(1,Math.round((e.finalizedAt-e.startedAt)/1e3)):0,i=this.formatIncidentTitle(e.reason);return`
1588
+ `:this.incidents.slice(0,8).map(e=>{const r=new Date(e.startedAt).toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"}),n=e.finalizedAt?Math.max(1,Math.round((e.finalizedAt-e.startedAt)/1e3)):0,i=this.formatIncidentTitle(e);return`
1589
1589
  <div class="backtrack-list-item" data-open-detail-id="${e.id}" role="button" tabindex="0" aria-label="${i}">
1590
1590
  <div class="backtrack-item-content">
1591
1591
  <span class="backtrack-item-title">${i}</span>
@@ -1612,7 +1612,7 @@
1612
1612
 
1613
1613
  <!-- 2. Card de resumo da sessão -->
1614
1614
  <div class="backtrack-detail-card">
1615
- <div class="backtrack-detail-title">${this.formatIncidentTitle(t.reason)}</div>
1615
+ <div class="backtrack-detail-title">${this.formatIncidentTitle(t)}</div>
1616
1616
  <div class="backtrack-detail-meta">${e} · ${r}s · ${t.id.length>20?t.id.substring(0,18)+"...":t.id}</div>
1617
1617
  </div>
1618
1618
 
@@ -1798,5 +1798,4 @@
1798
1798
  </div>
1799
1799
  </div>
1800
1800
  </div>
1801
- `}updateDomValues(){var i,a;if(!this.shadow)return;const t=this.shadow.querySelector(".backtrack-panel");if(this.isOpen&&!t){this.render();return}if(!this.isOpen&&t){this.render();return}const e=((i=this.health)==null?void 0:i.state)==="recording"?"backtrack-status-recording":((a=this.health)==null?void 0:a.state)==="degraded"?"backtrack-status-degraded":"backtrack-status-idle",r=this.shadow.querySelector(".backtrack-launcher-status-dot");r&&(r.className=`backtrack-launcher-status-dot ${e}`);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&&t){const s=this.shadow.getElementById("backtrack-saved-count-title");if(s&&(s.textContent=String(this.incidents.length)),!this.selectedIncidentId){const o=this.shadow.getElementById("backtrack-incident-list-container");if(o){const c=Array.from(o.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&&(o.innerHTML=this.renderIncidentsHtml(),this.attachIncidentListeners())}}}}attachIncidentListeners(){var t;this.shadow&&(this.shadow.querySelectorAll("[data-open-detail-id]").forEach(e=>{e.addEventListener("click",r=>{const n=r.currentTarget.getAttribute("data-open-detail-id");n&&(this.selectedIncidentId=n,this.render())})}),(t=this.shadow.getElementById("btn-back-to-list"))==null||t.addEventListener("click",()=>{this.selectedIncidentId=null,this.render()}),this.shadow.querySelectorAll("[data-view-id]").forEach(e=>{e.addEventListener("click",r=>{const n=r.currentTarget.getAttribute("data-view-id");n&&this.handleViewIncident(n)})}),this.shadow.querySelectorAll("[data-share-gist-id]").forEach(e=>{e.addEventListener("click",r=>{const n=r.currentTarget.getAttribute("data-share-gist-id");n&&this.handleShareGist(n)})}),this.shadow.querySelectorAll("[data-download-id]").forEach(e=>{e.addEventListener("click",r=>{const n=r.currentTarget.getAttribute("data-download-id");n&&this.handleDownloadIncident(n)})}),this.shadow.querySelectorAll("[data-copy-id]").forEach(e=>{e.addEventListener("click",r=>{const n=r.currentTarget.getAttribute("data-copy-id");n&&this.handleCopyMarkdown(n)})}),this.shadow.querySelectorAll("[data-delete-id]").forEach(e=>{e.addEventListener("click",r=>{const n=r.currentTarget.getAttribute("data-delete-id");n&&this.handleDeleteIncident(n)})}))}attachLauncherListeners(t){if(t.dataset.hasListeners)return;t.dataset.hasListeners="true";let e=0,r=0,n=0,i=0,a=!1;t.addEventListener("touchstart",s=>{if(s.touches.length===1&&this.container){const o=s.touches[0];e=o.clientX,r=o.clientY;const c=this.container.getBoundingClientRect();n=c.left,i=c.top,a=!1}},{passive:!0}),t.addEventListener("touchmove",s=>{if(s.touches.length===1&&this.container){const o=s.touches[0],c=o.clientX-e,h=o.clientY-r;(Math.abs(c)>5||Math.abs(h)>5)&&(a=!0,this.container.style.left=`${n+c}px`,this.container.style.top=`${i+h}px`,this.container.style.bottom="auto",this.container.style.right="auto")}},{passive:!0}),t.addEventListener("touchend",()=>{a&&(this.wasDragged=!0,setTimeout(()=>{this.wasDragged=!1},150))}),t.addEventListener("click",s=>{if(this.wasDragged){s.preventDefault(),s.stopPropagation();return}this.toggleOpen()})}attachPanelListeners(){var e,r,n,i,a,s,o,c,h,u,p,g,b,f,m,k,I,y,w,E,C,M,T,A,_;if(!this.shadow)return;(e=this.shadow.getElementById("btn-close"))==null||e.addEventListener("click",()=>{this.toggleOpen()}),(r=this.shadow.getElementById("btn-dismiss-banner"))==null||r.addEventListener("click",()=>{this.dismissBanner()}),(n=this.shadow.getElementById("btn-header-menu"))==null||n.addEventListener("click",B=>{B.stopPropagation(),this.isHeaderMenuOpen=!this.isHeaderMenuOpen,this.render()}),(i=this.shadow.getElementById("btn-hide-widget"))==null||i.addEventListener("click",B=>{B.stopPropagation(),this.isHeaderMenuOpen=!1,this.showHideConfirmModal=!0,this.render()}),(a=this.shadow.getElementById("btn-duration-60"))==null||a.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()}),(o=this.shadow.getElementById("btn-duration-all"))==null||o.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 t=this.shadow.getElementById("input-custom-duration");t&&(t.addEventListener("input",B=>{const P=parseInt(B.target.value,10);isNaN(P)||(this.selectedDurationSeconds=Math.max(5,Math.min(900,P)))}),t.addEventListener("change",B=>{const P=parseInt(B.target.value,10),W=isNaN(P)?60:Math.max(5,Math.min(900,P));this.selectedDurationSeconds=W,t.value=String(W)})),(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()}),(f=this.shadow.getElementById("check-include-incident-link"))==null||f.addEventListener("change",B=>{this.exportModalIncludeLink=B.target.checked,this.render()}),(m=this.shadow.getElementById("btn-confirm-export-modal"))==null||m.addEventListener("click",()=>{this.confirmCopyMarkdown()})),this.downloadModalIncidentId&&((k=this.shadow.getElementById("btn-close-download-modal"))==null||k.addEventListener("click",()=>{this.closeDownloadModal()}),(I=this.shadow.getElementById("btn-cancel-download-modal"))==null||I.addEventListener("click",()=>{this.closeDownloadModal()}),(y=this.shadow.getElementById("radio-format-ai"))==null||y.addEventListener("change",()=>{this.downloadModalFormat="ai",this.downloadModalError=null,this.render()}),(w=this.shadow.getElementById("radio-format-gzip"))==null||w.addEventListener("change",()=>{this.downloadModalFormat="gzip",this.downloadModalError=null,this.render()}),(E=this.shadow.getElementById("radio-format-uncompressed"))==null||E.addEventListener("change",()=>{this.downloadModalFormat="uncompressed",this.downloadModalError=null,this.render()}),(C=this.shadow.getElementById("btn-confirm-download-modal"))==null||C.addEventListener("click",()=>{this.confirmDownload()})),this.showHideConfirmModal&&((M=this.shadow.getElementById("btn-close-hide-modal"))==null||M.addEventListener("click",()=>{this.showHideConfirmModal=!1,this.render()}),(T=this.shadow.getElementById("btn-cancel-hide-modal"))==null||T.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",B=>{if(this.isHeaderMenuOpen){const P=B.target;P!=null&&P.closest(".backtrack-header-menu-wrap")||(this.isHeaderMenuOpen=!1,this.render())}})}};l(O,"sessionGithubToken",null);let Q=O;const vt="0.5.1",v=class v{constructor(t,e){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 r,n,i,a,s,o,c,h,u,p,g;this.options={bufferMinutes:(t==null?void 0:t.bufferMinutes)??5,afterErrorSeconds:(t==null?void 0:t.afterErrorSeconds)??15,maxStorageMb:(t==null?void 0:t.maxStorageMb)??50,captureHttpStatus:(t==null?void 0:t.captureHttpStatus)??[500,502,503,504],showWidget:(t==null?void 0:t.showWidget)??!1,widgetOptions:t==null?void 0:t.widgetOptions,metadata:t==null?void 0:t.metadata,recorderVersion:t==null?void 0:t.recorderVersion,ignoredUrls:t==null?void 0:t.ignoredUrls,network:{capturePayloads:((r=t==null?void 0:t.network)==null?void 0:r.capturePayloads)??!1,maxPayloadSize:((n=t==null?void 0:t.network)==null?void 0:n.maxPayloadSize)??64*1024},privacy:{maskAllInputs:((i=t==null?void 0:t.privacy)==null?void 0:i.maskAllInputs)??!0,maskAllText:((a=t==null?void 0:t.privacy)==null?void 0:a.maskAllText)??!1,blockMedia:((s=t==null?void 0:t.privacy)==null?void 0:s.blockMedia)??!0,blockSelector:(o=t==null?void 0:t.privacy)==null?void 0:o.blockSelector,maskTextSelector:(c=t==null?void 0:t.privacy)==null?void 0:c.maskTextSelector,sanitizeUrl:(h=t==null?void 0:t.privacy)==null?void 0:h.sanitizeUrl,sensitiveRoutes:(u=t==null?void 0:t.privacy)==null?void 0:u.sensitiveRoutes,autoMaskPII:(p=t==null?void 0:t.privacy)==null?void 0:p.autoMaskPII,recordCanvas:(g=t==null?void 0:t.privacy)==null?void 0:g.recordCanvas},storage:t==null?void 0:t.storage,sessionOptions:t==null?void 0:t.sessionOptions,batchWriterConfig:t==null?void 0:t.batchWriterConfig,transport:t==null?void 0:t.transport,beforeSend:t==null?void 0:t.beforeSend,context:t==null?void 0:t.context,getContext:t==null?void 0:t.getContext},this.stateMachine=new xt("stopped"),this.db=e||new St,this.retention=new At(this.db,{bufferMinutes:this.options.bufferMinutes,maxStorageMb:this.options.maxStorageMb})}static async init(t,e){if(v.activeInstance)return v.activeInstance;const r=new v(t,e);if(await r.start(),v.activeInstance=r,typeof window<"u"){const n=window;n.Backtrack=v,n.flightRecorder=r,n.hideBacktrack=()=>v.hideWidget(),n.showBacktrack=()=>v.showWidget(),n.toggleBacktrack=()=>v.toggleWidget()}return r}static hideWidget(){const t=v.activeInstance;if(t!=null&&t.widget)t.widget.hide();else try{if(typeof localStorage<"u"&&localStorage.setItem("backtrack_widget_hidden","true"),typeof document<"u"){const e=document.getElementById("__backtrack_widget_host__");e&&(e.style.display="none")}}catch{}}static showWidget(){const t=v.activeInstance;if(t!=null&&t.widget)t.widget.show();else try{if(typeof localStorage<"u"&&localStorage.removeItem("backtrack_widget_hidden"),typeof document<"u"){const e=document.getElementById("__backtrack_widget_host__");e&&(e.style.display="")}}catch{}}static toggleWidget(){const t=v.activeInstance;return t!=null&&t.widget?t.widget.toggle():typeof localStorage<"u"&&localStorage.getItem("backtrack_widget_hidden")==="true"?(v.showWidget(),!0):(v.hideWidget(),!1)}static hide(){v.hideWidget()}static show(){v.showWidget()}static toggle(){return v.toggleWidget()}static async resetInstance(){v.activeInstance&&(await v.activeInstance.stop(),v.activeInstance=null)}static getInstance(){return v.activeInstance}hideWidget(){this.widget?this.widget.hide():v.hideWidget()}showWidget(){this.widget?this.widget.show():v.showWidget()}toggleWidget(){return this.widget?this.widget.toggle():v.toggleWidget()}getEnvironmentMetadata(){const t=this.options.metadata;if(typeof window>"u")return{url:"http://localhost",userAgent:"node",viewport:{width:1280,height:720},...t};const e=window;return{url:window.location.href,userAgent:window.navigator.userAgent,viewport:{width:window.innerWidth,height:window.innerHeight},appVersion:(t==null?void 0:t.appVersion)??e.__APP_VERSION__??e.__UTICKET_APP_VERSION__,gitBranch:(t==null?void 0:t.gitBranch)??e.__GIT_BRANCH__??e.__UTICKET_GIT_BRANCH__,gitCommit:(t==null?void 0:t.gitCommit)??e.__GIT_COMMIT__??e.__UTICKET_GIT_COMMIT__,...t}}async start(){var t,e,r,n;if(!this.stateMachine.isRecording())try{await this.db.open();const i=await Rt({...this.options.sessionOptions,...this.options.storage?{storage:this.options.storage}:{}}),a=await this.db.getChunksBySession(i.sessionId),s=Math.max(0,...a.flatMap(c=>(c.timeline||[]).map(h=>h.sequence))),o=Math.max(0,...a.map(c=>c.sequence));this.sequence=s,this.writer=new Tt(this.db,i.sessionId,i.tabId,{...this.options.batchWriterConfig,initialChunkSequence:o},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 et(this.db,i.sessionId,i.tabId,()=>this.getEnvironmentMetadata(),{afterErrorSeconds:this.options.afterErrorSeconds,recorderVersion:this.options.recorderVersion??vt,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 Dt(this.writer,this.nextSequence),this.errorCapturer=new Lt(this.writer,this.incidentManager,this.nextSequence),this.networkCapturer=new zt(this.writer,this.incidentManager,this.nextSequence,{captureHttpStatus:this.options.captureHttpStatus,ignoredUrls:this.options.ignoredUrls,sanitizeUrlCallback:(t=this.options.privacy)==null?void 0:t.sanitizeUrl,capturePayloads:(e=this.options.network)==null?void 0:e.capturePayloads,maxPayloadSize:(r=this.options.network)==null?void 0:r.maxPayloadSize}),this.navigationCapturer=new Pt(this.writer,this.nextSequence,{sanitizeUrlCallback:(n=this.options.privacy)==null?void 0:n.sanitizeUrl}),this.rrwebCapturer=new $t(this.writer,{privacy:this.options.privacy}),this.performanceCapturer=new Ot(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 Q(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(i){this.stateMachine.transition({type:"DEGRADE",reason:`Falha ao iniciar recorder: ${i instanceof Error?i.message:String(i)}`})}}scheduleRetention(){return this.retentionPromise?this.retentionPromise:(this.retentionPromise=(async()=>{try{this.incidentManager?await this.incidentManager.runExclusive(async()=>{var t;await((t=this.incidentManager)==null?void 0:t.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 t=await this.retention.getStorageBreakdown().catch(()=>null),r=(t?t.bufferBytes===0&&t.protectedBytes>0:!1)||t!=null&&t.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:r})}async updateStatsCache(){try{const t=await this.retention.getStorageBreakdown();if(this.cachedStorageBytes=t.totalBytes,this.cachedProtectedBytes=t.protectedBytes,this.cachedIncidentCount=t.incidentCount,typeof navigator<"u"&&navigator.storage&&typeof navigator.storage.estimate=="function")try{const e=await navigator.storage.estimate();this.cachedBrowserEstimateBytes=e.usage,this.cachedBrowserQuotaBytes=e.quota}catch{}if(t.protectedExceedsLimit)this.stateMachine.transition({type:"DEGRADE",reason:"O armazenamento protegido por incidentes excede o limite configurado (maxStorageMb)."});else if(!t.isOverLimit&&this.stateMachine.isDegraded()){const e=this.stateMachine.getDegradedReasons();e.every(n=>n.includes("maxStorageMb")||n.includes("quota")||n.includes("Quota")||n.includes("armazenamento"))&&e.length>0&&this.stateMachine.transition({type:"RECOVER"})}}catch{}}async sendIncident(t){const e=this.options.transport;if(e)try{const r=await this.getArtifact(t),n=this.options.beforeSend?await this.options.beforeSend(r):r;n&&await e.send(n)}catch{}}stopCapturers(){var t,e,r,n,i,a;(t=this.rrwebCapturer)==null||t.stop(),(e=this.navigationCapturer)==null||e.stop(),(r=this.networkCapturer)==null||r.stop(),(n=this.errorCapturer)==null||n.stop(),(i=this.consoleCapturer)==null||i.stop(),(a=this.performanceCapturer)==null||a.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 t;if(this.stopCapturers(),this.retentionIntervalTimer&&(clearInterval(this.retentionIntervalTimer),this.retentionIntervalTimer=null),this.widget&&(this.widget.unmount(),this.widget=null),v.activeInstance===this&&(v.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(),(t=this.writer)==null||t.destroy(),this.incidentManager&&(await this.incidentManager.syncPendingIncidentDroppedEvents().catch(()=>{}),await this.incidentManager.destroy()),Z(),this.clearRuntimeReferences(),this.stateMachine.transition({type:"STOP"})})();try{await this.stoppingPromise}finally{this.stoppingPromise=void 0}}}async capture(t="manual",e,r){if(!this.incidentManager||!this.writer)throw new Error("FlightRecorder não está em execução.");const n=await this.incidentManager.runExclusive(async()=>{const i=Date.now();return this.writer.addTimelineEvent({id:`marker_manual_${i}`,timestamp:i,sequence:this.nextSequence(),type:"marker",label:`Captura manual: ${t}`}),await this.writer.flush(),this.incidentManager.executeManualTrigger({id:`trig_manual_${i}`,timestamp:i,type:"manual",signature:`manual_capture_${t}`,detail:{userReason:t,windowSeconds:e,annotationImage:r==null?void 0:r.annotationImage,notes:r==null?void 0:r.notes,annotations:r==null?void 0:r.annotations}},e)});return await this.updateStatsCache(),n}captureException(t,e){if(this.errorCapturer)try{return this.errorCapturer.captureException(t,e)}catch{}}async listIncidents(){try{return await this.db.listIncidents()}catch{return[]}}async getArtifact(t){return this.incidentManager?this.incidentManager.exportArtifact(t):new et(this.db,"","",()=>this.getEnvironmentMetadata(),{recorderVersion:this.options.recorderVersion??vt,context:this.options.context,getContext:this.options.getContext,getRecordingIssues:()=>this.stateMachine.getDegradedReasons()}).exportArtifact(t)}async exportIncident(t,e){const r=await this.getArtifact(t),n=new Date(r.incident.triggeredAt).toISOString().replace(/:/g,"-").replace(/\..+/,""),i=(e==null?void 0:e.aiOptimized)??!1,a=!i&&((e==null?void 0:e.compress)??!1),s=i?".ai.json":a?".ffr.json.gz":".ffr.json",o=`flight-recorder-${n}-${r.incident.reason}-${t}${s}`,c=i?{...r,replay:[],_aiNote:"Replay visual removido para otimizacao de IA. Timeline, erros de console e rede preservados."}:r;if(typeof window<"u"&&typeof document<"u"){let h;if(a){const g=await Mt(r);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=o,document.body.appendChild(p),p.click(),document.body.removeChild(p),URL.revokeObjectURL(u)}return c}async deleteIncident(t){this.incidentManager?(await this.incidentManager.deleteIncident(t),await this.incidentManager.runExclusive(async()=>{await this.retention.prune(),await this.updateStatsCache()})):(await this.db.deleteIncident(t),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 r,n;const t=((r=this.rrwebCapturer)==null?void 0:r.getDroppedEventsCount())??0,e=(this.options.maxStorageMb??50)*1024*1024;return{state:this.stateMachine.getState(),droppedEvents:t,storageBytes:this.cachedStorageBytes,protectedStorageBytes:this.cachedProtectedBytes,storageLimitBytes:e,storageLimitExceeded:this.cachedStorageBytes>e,protectedStorageExceeded:this.cachedProtectedBytes>e,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(v,"activeInstance",null);let U=v;function Nt(d){return new U(d)}exports.formatIncidentMarkdown=q.formatIncidentMarkdown;exports.getUtf8ByteLength=q.getUtf8ByteLength;exports.isReplayEvent=q.isReplayEvent;exports.isValidAnnotationImage=q.isValidAnnotationImage;exports.sortTimelineEvents=q.sortTimelineEvents;exports.validateFlightRecorderArtifact=q.validateFlightRecorderArtifact;exports.Backtrack=U;exports.BacktrackImpl=U;exports.BacktrackWidget=Q;exports.BatchWriter=Tt;exports.ConsoleCapturer=Dt;exports.DB_NAME=It;exports.DB_VERSION=Et;exports.ErrorCapturer=Lt;exports.FlightRecorderDB=St;exports.FlightRecorderImpl=U;exports.IncidentManager=et;exports.MAX_ARTIFACT_BYTES=Y;exports.NavigationCapturer=Pt;exports.NetworkCapturer=zt;exports.PerformanceCapturer=Ot;exports.RecorderStateMachine=xt;exports.RetentionEngine=At;exports.RrwebCapturer=$t;exports.STORE_CHUNKS=S;exports.STORE_INCIDENTS=R;exports.STORE_SESSIONS=$;exports.ScreenAnnotator=qt;exports.claimSessionContext=Rt;exports.closeSessionChannel=Z;exports.compressArtifact=Mt;exports.compressGzip=it;exports.createBacktrack=Nt;exports.createFlightRecorder=Nt;exports.decompressArtifact=Gt;exports.decompressGzip=J;exports.generateIncidentId=tt;exports.getOrCreateSessionContext=Bt;exports.globToRegex=Ht;exports.isGzip=Ct;exports.matchesSensitiveRoute=_t;exports.readLimitedStream=nt;exports.readResponseBytes=Wt;exports.redactSensitiveString=D;exports.resetSessionContext=Xt;exports.sanitizeAndSerialize=ct;exports.sanitizeHeaders=V;exports.sanitizePayloadString=G;exports.sanitizeUrl=X;exports.sliceReplayEventsForWindow=Vt;exports.sliceReplayEventsWithMetadata=at;exports.uploadArtifactToGist=rt;
1802
- //# sourceMappingURL=index.cjs.map
1801
+ `}updateDomValues(){var i,a;if(!this.shadow)return;const t=this.shadow.querySelector(".backtrack-panel");if(this.isOpen&&!t){this.render();return}if(!this.isOpen&&t){this.render();return}const e=((i=this.health)==null?void 0:i.state)==="recording"?"backtrack-status-recording":((a=this.health)==null?void 0:a.state)==="degraded"?"backtrack-status-degraded":"backtrack-status-idle",r=this.shadow.querySelector(".backtrack-launcher-status-dot");r&&(r.className=`backtrack-launcher-status-dot ${e}`);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&&t){const s=this.shadow.getElementById("backtrack-saved-count-title");if(s&&(s.textContent=String(this.incidents.length)),!this.selectedIncidentId){const o=this.shadow.getElementById("backtrack-incident-list-container");if(o){const c=Array.from(o.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&&(o.innerHTML=this.renderIncidentsHtml(),this.attachIncidentListeners())}}}}attachIncidentListeners(){var t;this.shadow&&(this.shadow.querySelectorAll("[data-open-detail-id]").forEach(e=>{e.addEventListener("click",r=>{const n=r.currentTarget.getAttribute("data-open-detail-id");n&&(this.selectedIncidentId=n,this.render())})}),(t=this.shadow.getElementById("btn-back-to-list"))==null||t.addEventListener("click",()=>{this.selectedIncidentId=null,this.render()}),this.shadow.querySelectorAll("[data-view-id]").forEach(e=>{e.addEventListener("click",r=>{const n=r.currentTarget.getAttribute("data-view-id");n&&this.handleViewIncident(n)})}),this.shadow.querySelectorAll("[data-share-gist-id]").forEach(e=>{e.addEventListener("click",r=>{const n=r.currentTarget.getAttribute("data-share-gist-id");n&&this.handleShareGist(n)})}),this.shadow.querySelectorAll("[data-download-id]").forEach(e=>{e.addEventListener("click",r=>{const n=r.currentTarget.getAttribute("data-download-id");n&&this.handleDownloadIncident(n)})}),this.shadow.querySelectorAll("[data-copy-id]").forEach(e=>{e.addEventListener("click",r=>{const n=r.currentTarget.getAttribute("data-copy-id");n&&this.handleCopyMarkdown(n)})}),this.shadow.querySelectorAll("[data-delete-id]").forEach(e=>{e.addEventListener("click",r=>{const n=r.currentTarget.getAttribute("data-delete-id");n&&this.handleDeleteIncident(n)})}))}attachLauncherListeners(t){if(t.dataset.hasListeners)return;t.dataset.hasListeners="true";let e=0,r=0,n=0,i=0,a=!1;t.addEventListener("touchstart",s=>{if(s.touches.length===1&&this.container){const o=s.touches[0];e=o.clientX,r=o.clientY;const c=this.container.getBoundingClientRect();n=c.left,i=c.top,a=!1}},{passive:!0}),t.addEventListener("touchmove",s=>{if(s.touches.length===1&&this.container){const o=s.touches[0],c=o.clientX-e,h=o.clientY-r;(Math.abs(c)>5||Math.abs(h)>5)&&(a=!0,this.container.style.left=`${n+c}px`,this.container.style.top=`${i+h}px`,this.container.style.bottom="auto",this.container.style.right="auto")}},{passive:!0}),t.addEventListener("touchend",()=>{a&&(this.wasDragged=!0,setTimeout(()=>{this.wasDragged=!1},150))}),t.addEventListener("click",s=>{if(this.wasDragged){s.preventDefault(),s.stopPropagation();return}this.toggleOpen()})}attachPanelListeners(){var e,r,n,i,a,s,o,c,h,u,p,g,b,f,m,k,I,y,w,E,C,M,T,A,_;if(!this.shadow)return;(e=this.shadow.getElementById("btn-close"))==null||e.addEventListener("click",()=>{this.toggleOpen()}),(r=this.shadow.getElementById("btn-dismiss-banner"))==null||r.addEventListener("click",()=>{this.dismissBanner()}),(n=this.shadow.getElementById("btn-header-menu"))==null||n.addEventListener("click",B=>{B.stopPropagation(),this.isHeaderMenuOpen=!this.isHeaderMenuOpen,this.render()}),(i=this.shadow.getElementById("btn-hide-widget"))==null||i.addEventListener("click",B=>{B.stopPropagation(),this.isHeaderMenuOpen=!1,this.showHideConfirmModal=!0,this.render()}),(a=this.shadow.getElementById("btn-duration-60"))==null||a.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()}),(o=this.shadow.getElementById("btn-duration-all"))==null||o.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 t=this.shadow.getElementById("input-custom-duration");t&&(t.addEventListener("input",B=>{const P=parseInt(B.target.value,10);isNaN(P)||(this.selectedDurationSeconds=Math.max(5,Math.min(900,P)))}),t.addEventListener("change",B=>{const P=parseInt(B.target.value,10),W=isNaN(P)?60:Math.max(5,Math.min(900,P));this.selectedDurationSeconds=W,t.value=String(W)})),(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()}),(f=this.shadow.getElementById("check-include-incident-link"))==null||f.addEventListener("change",B=>{this.exportModalIncludeLink=B.target.checked,this.render()}),(m=this.shadow.getElementById("btn-confirm-export-modal"))==null||m.addEventListener("click",()=>{this.confirmCopyMarkdown()})),this.downloadModalIncidentId&&((k=this.shadow.getElementById("btn-close-download-modal"))==null||k.addEventListener("click",()=>{this.closeDownloadModal()}),(I=this.shadow.getElementById("btn-cancel-download-modal"))==null||I.addEventListener("click",()=>{this.closeDownloadModal()}),(y=this.shadow.getElementById("radio-format-ai"))==null||y.addEventListener("change",()=>{this.downloadModalFormat="ai",this.downloadModalError=null,this.render()}),(w=this.shadow.getElementById("radio-format-gzip"))==null||w.addEventListener("change",()=>{this.downloadModalFormat="gzip",this.downloadModalError=null,this.render()}),(E=this.shadow.getElementById("radio-format-uncompressed"))==null||E.addEventListener("change",()=>{this.downloadModalFormat="uncompressed",this.downloadModalError=null,this.render()}),(C=this.shadow.getElementById("btn-confirm-download-modal"))==null||C.addEventListener("click",()=>{this.confirmDownload()})),this.showHideConfirmModal&&((M=this.shadow.getElementById("btn-close-hide-modal"))==null||M.addEventListener("click",()=>{this.showHideConfirmModal=!1,this.render()}),(T=this.shadow.getElementById("btn-cancel-hide-modal"))==null||T.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",B=>{if(this.isHeaderMenuOpen){const P=B.target;P!=null&&P.closest(".backtrack-header-menu-wrap")||(this.isHeaderMenuOpen=!1,this.render())}})}};l(O,"sessionGithubToken",null);let Q=O;const vt="0.5.3",v=class v{constructor(t,e){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 r,n,i,a,s,o,c,h,u,p,g;this.options={bufferMinutes:(t==null?void 0:t.bufferMinutes)??5,afterErrorSeconds:(t==null?void 0:t.afterErrorSeconds)??15,maxStorageMb:(t==null?void 0:t.maxStorageMb)??50,captureHttpStatus:(t==null?void 0:t.captureHttpStatus)??[500,502,503,504],showWidget:(t==null?void 0:t.showWidget)??!1,widgetOptions:t==null?void 0:t.widgetOptions,metadata:t==null?void 0:t.metadata,recorderVersion:t==null?void 0:t.recorderVersion,ignoredUrls:t==null?void 0:t.ignoredUrls,network:{capturePayloads:((r=t==null?void 0:t.network)==null?void 0:r.capturePayloads)??!1,maxPayloadSize:((n=t==null?void 0:t.network)==null?void 0:n.maxPayloadSize)??64*1024},privacy:{maskAllInputs:((i=t==null?void 0:t.privacy)==null?void 0:i.maskAllInputs)??!0,maskAllText:((a=t==null?void 0:t.privacy)==null?void 0:a.maskAllText)??!1,blockMedia:((s=t==null?void 0:t.privacy)==null?void 0:s.blockMedia)??!0,blockSelector:(o=t==null?void 0:t.privacy)==null?void 0:o.blockSelector,maskTextSelector:(c=t==null?void 0:t.privacy)==null?void 0:c.maskTextSelector,sanitizeUrl:(h=t==null?void 0:t.privacy)==null?void 0:h.sanitizeUrl,sensitiveRoutes:(u=t==null?void 0:t.privacy)==null?void 0:u.sensitiveRoutes,autoMaskPII:(p=t==null?void 0:t.privacy)==null?void 0:p.autoMaskPII,recordCanvas:(g=t==null?void 0:t.privacy)==null?void 0:g.recordCanvas},storage:t==null?void 0:t.storage,sessionOptions:t==null?void 0:t.sessionOptions,batchWriterConfig:t==null?void 0:t.batchWriterConfig,transport:t==null?void 0:t.transport,beforeSend:t==null?void 0:t.beforeSend,context:t==null?void 0:t.context,getContext:t==null?void 0:t.getContext},this.stateMachine=new xt("stopped"),this.db=e||new St,this.retention=new At(this.db,{bufferMinutes:this.options.bufferMinutes,maxStorageMb:this.options.maxStorageMb})}static async init(t,e){if(v.activeInstance)return v.activeInstance;const r=new v(t,e);if(await r.start(),v.activeInstance=r,typeof window<"u"){const n=window;n.Backtrack=v,n.flightRecorder=r,n.hideBacktrack=()=>v.hideWidget(),n.showBacktrack=()=>v.showWidget(),n.toggleBacktrack=()=>v.toggleWidget()}return r}static hideWidget(){const t=v.activeInstance;if(t!=null&&t.widget)t.widget.hide();else try{if(typeof localStorage<"u"&&localStorage.setItem("backtrack_widget_hidden","true"),typeof document<"u"){const e=document.getElementById("__backtrack_widget_host__");e&&(e.style.display="none")}}catch{}}static showWidget(){const t=v.activeInstance;if(t!=null&&t.widget)t.widget.show();else try{if(typeof localStorage<"u"&&localStorage.removeItem("backtrack_widget_hidden"),typeof document<"u"){const e=document.getElementById("__backtrack_widget_host__");e&&(e.style.display="")}}catch{}}static toggleWidget(){const t=v.activeInstance;return t!=null&&t.widget?t.widget.toggle():typeof localStorage<"u"&&localStorage.getItem("backtrack_widget_hidden")==="true"?(v.showWidget(),!0):(v.hideWidget(),!1)}static hide(){v.hideWidget()}static show(){v.showWidget()}static toggle(){return v.toggleWidget()}static async resetInstance(){v.activeInstance&&(await v.activeInstance.stop(),v.activeInstance=null)}static getInstance(){return v.activeInstance}hideWidget(){this.widget?this.widget.hide():v.hideWidget()}showWidget(){this.widget?this.widget.show():v.showWidget()}toggleWidget(){return this.widget?this.widget.toggle():v.toggleWidget()}getEnvironmentMetadata(){const t=this.options.metadata;if(typeof window>"u")return{url:"http://localhost",userAgent:"node",viewport:{width:1280,height:720},...t};const e=window;return{url:window.location.href,userAgent:window.navigator.userAgent,viewport:{width:window.innerWidth,height:window.innerHeight},appVersion:(t==null?void 0:t.appVersion)??e.__APP_VERSION__??e.__UTICKET_APP_VERSION__,gitBranch:(t==null?void 0:t.gitBranch)??e.__GIT_BRANCH__??e.__UTICKET_GIT_BRANCH__,gitCommit:(t==null?void 0:t.gitCommit)??e.__GIT_COMMIT__??e.__UTICKET_GIT_COMMIT__,...t}}async start(){var t,e,r,n;if(!this.stateMachine.isRecording())try{await this.db.open();const i=await Rt({...this.options.sessionOptions,...this.options.storage?{storage:this.options.storage}:{}}),a=await this.db.getChunksBySession(i.sessionId),s=Math.max(0,...a.flatMap(c=>(c.timeline||[]).map(h=>h.sequence))),o=Math.max(0,...a.map(c=>c.sequence));this.sequence=s,this.writer=new Tt(this.db,i.sessionId,i.tabId,{...this.options.batchWriterConfig,initialChunkSequence:o},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 et(this.db,i.sessionId,i.tabId,()=>this.getEnvironmentMetadata(),{afterErrorSeconds:this.options.afterErrorSeconds,recorderVersion:this.options.recorderVersion??vt,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 Dt(this.writer,this.nextSequence),this.errorCapturer=new Lt(this.writer,this.incidentManager,this.nextSequence),this.networkCapturer=new zt(this.writer,this.incidentManager,this.nextSequence,{captureHttpStatus:this.options.captureHttpStatus,ignoredUrls:this.options.ignoredUrls,sanitizeUrlCallback:(t=this.options.privacy)==null?void 0:t.sanitizeUrl,capturePayloads:(e=this.options.network)==null?void 0:e.capturePayloads,maxPayloadSize:(r=this.options.network)==null?void 0:r.maxPayloadSize}),this.navigationCapturer=new Pt(this.writer,this.nextSequence,{sanitizeUrlCallback:(n=this.options.privacy)==null?void 0:n.sanitizeUrl}),this.rrwebCapturer=new $t(this.writer,{privacy:this.options.privacy}),this.performanceCapturer=new Ot(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 Q(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(i){this.stateMachine.transition({type:"DEGRADE",reason:`Falha ao iniciar recorder: ${i instanceof Error?i.message:String(i)}`})}}scheduleRetention(){return this.retentionPromise?this.retentionPromise:(this.retentionPromise=(async()=>{try{this.incidentManager?await this.incidentManager.runExclusive(async()=>{var t;await((t=this.incidentManager)==null?void 0:t.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 t=await this.retention.getStorageBreakdown().catch(()=>null),r=(t?t.bufferBytes===0&&t.protectedBytes>0:!1)||t!=null&&t.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:r})}async updateStatsCache(){try{const t=await this.retention.getStorageBreakdown();if(this.cachedStorageBytes=t.totalBytes,this.cachedProtectedBytes=t.protectedBytes,this.cachedIncidentCount=t.incidentCount,typeof navigator<"u"&&navigator.storage&&typeof navigator.storage.estimate=="function")try{const e=await navigator.storage.estimate();this.cachedBrowserEstimateBytes=e.usage,this.cachedBrowserQuotaBytes=e.quota}catch{}if(t.protectedExceedsLimit)this.stateMachine.transition({type:"DEGRADE",reason:"O armazenamento protegido por incidentes excede o limite configurado (maxStorageMb)."});else if(!t.isOverLimit&&this.stateMachine.isDegraded()){const e=this.stateMachine.getDegradedReasons();e.every(n=>n.includes("maxStorageMb")||n.includes("quota")||n.includes("Quota")||n.includes("armazenamento"))&&e.length>0&&this.stateMachine.transition({type:"RECOVER"})}}catch{}}async sendIncident(t){const e=this.options.transport;if(e)try{const r=await this.getArtifact(t),n=this.options.beforeSend?await this.options.beforeSend(r):r;n&&await e.send(n)}catch{}}stopCapturers(){var t,e,r,n,i,a;(t=this.rrwebCapturer)==null||t.stop(),(e=this.navigationCapturer)==null||e.stop(),(r=this.networkCapturer)==null||r.stop(),(n=this.errorCapturer)==null||n.stop(),(i=this.consoleCapturer)==null||i.stop(),(a=this.performanceCapturer)==null||a.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 t;if(this.stopCapturers(),this.retentionIntervalTimer&&(clearInterval(this.retentionIntervalTimer),this.retentionIntervalTimer=null),this.widget&&(this.widget.unmount(),this.widget=null),v.activeInstance===this&&(v.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(),(t=this.writer)==null||t.destroy(),this.incidentManager&&(await this.incidentManager.syncPendingIncidentDroppedEvents().catch(()=>{}),await this.incidentManager.destroy()),Z(),this.clearRuntimeReferences(),this.stateMachine.transition({type:"STOP"})})();try{await this.stoppingPromise}finally{this.stoppingPromise=void 0}}}async capture(t="manual",e,r){if(!this.incidentManager||!this.writer)throw new Error("FlightRecorder não está em execução.");const n=await this.incidentManager.runExclusive(async()=>{const i=Date.now();return this.writer.addTimelineEvent({id:`marker_manual_${i}`,timestamp:i,sequence:this.nextSequence(),type:"marker",label:`Captura manual: ${t}`}),await this.writer.flush(),this.incidentManager.executeManualTrigger({id:`trig_manual_${i}`,timestamp:i,type:"manual",signature:`manual_capture_${t}`,detail:{userReason:t,windowSeconds:e,annotationImage:r==null?void 0:r.annotationImage,notes:r==null?void 0:r.notes,annotations:r==null?void 0:r.annotations}},e)});return await this.updateStatsCache(),n}captureException(t,e){if(this.errorCapturer)try{return this.errorCapturer.captureException(t,e)}catch{}}async listIncidents(){try{return await this.db.listIncidents()}catch{return[]}}async getArtifact(t){return this.incidentManager?this.incidentManager.exportArtifact(t):new et(this.db,"","",()=>this.getEnvironmentMetadata(),{recorderVersion:this.options.recorderVersion??vt,context:this.options.context,getContext:this.options.getContext,getRecordingIssues:()=>this.stateMachine.getDegradedReasons()}).exportArtifact(t)}async exportIncident(t,e){const r=await this.getArtifact(t),n=new Date(r.incident.triggeredAt).toISOString().replace(/:/g,"-").replace(/\..+/,""),i=(e==null?void 0:e.aiOptimized)??!1,a=!i&&((e==null?void 0:e.compress)??!1),s=i?".ai.json":a?".ffr.json.gz":".ffr.json",o=`flight-recorder-${n}-${r.incident.reason}-${t}${s}`,c=i?{...r,replay:[],_aiNote:"Replay visual removido para otimizacao de IA. Timeline, erros de console e rede preservados."}:r;if(typeof window<"u"&&typeof document<"u"){let h;if(a){const g=await Mt(r);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=o,document.body.appendChild(p),p.click(),document.body.removeChild(p),URL.revokeObjectURL(u)}return c}async deleteIncident(t){this.incidentManager?(await this.incidentManager.deleteIncident(t),await this.incidentManager.runExclusive(async()=>{await this.retention.prune(),await this.updateStatsCache()})):(await this.db.deleteIncident(t),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 r,n;const t=((r=this.rrwebCapturer)==null?void 0:r.getDroppedEventsCount())??0,e=(this.options.maxStorageMb??50)*1024*1024;return{state:this.stateMachine.getState(),droppedEvents:t,storageBytes:this.cachedStorageBytes,protectedStorageBytes:this.cachedProtectedBytes,storageLimitBytes:e,storageLimitExceeded:this.cachedStorageBytes>e,protectedStorageExceeded:this.cachedProtectedBytes>e,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(v,"activeInstance",null);let U=v;function Nt(d){return new U(d)}exports.formatIncidentMarkdown=q.formatIncidentMarkdown;exports.getUtf8ByteLength=q.getUtf8ByteLength;exports.isReplayEvent=q.isReplayEvent;exports.isValidAnnotationImage=q.isValidAnnotationImage;exports.sortTimelineEvents=q.sortTimelineEvents;exports.validateFlightRecorderArtifact=q.validateFlightRecorderArtifact;exports.Backtrack=U;exports.BacktrackImpl=U;exports.BacktrackWidget=Q;exports.BatchWriter=Tt;exports.ConsoleCapturer=Dt;exports.DB_NAME=It;exports.DB_VERSION=Et;exports.ErrorCapturer=Lt;exports.FlightRecorderDB=St;exports.FlightRecorderImpl=U;exports.IncidentManager=et;exports.MAX_ARTIFACT_BYTES=Y;exports.NavigationCapturer=Pt;exports.NetworkCapturer=zt;exports.PerformanceCapturer=Ot;exports.RecorderStateMachine=xt;exports.RetentionEngine=At;exports.RrwebCapturer=$t;exports.STORE_CHUNKS=S;exports.STORE_INCIDENTS=R;exports.STORE_SESSIONS=$;exports.ScreenAnnotator=qt;exports.claimSessionContext=Rt;exports.closeSessionChannel=Z;exports.compressArtifact=Mt;exports.compressGzip=it;exports.createBacktrack=Nt;exports.createFlightRecorder=Nt;exports.decompressArtifact=Gt;exports.decompressGzip=J;exports.generateIncidentId=tt;exports.getOrCreateSessionContext=Bt;exports.globToRegex=Ht;exports.isGzip=Ct;exports.matchesSensitiveRoute=_t;exports.readLimitedStream=nt;exports.readResponseBytes=Wt;exports.redactSensitiveString=D;exports.resetSessionContext=Xt;exports.sanitizeAndSerialize=ct;exports.sanitizeHeaders=V;exports.sanitizePayloadString=G;exports.sanitizeUrl=X;exports.sliceReplayEventsForWindow=Vt;exports.sliceReplayEventsWithMetadata=at;exports.uploadArtifactToGist=rt;
package/dist/index.d.ts CHANGED
@@ -14,4 +14,3 @@ import { FlightRecorderImpl, createFlightRecorder } from './core/flight-recorder
14
14
  import type { FlightRecorder, FlightRecorderOptions } from './types/options';
15
15
  export { FlightRecorderImpl as Backtrack, FlightRecorderImpl as BacktrackImpl, createFlightRecorder as createBacktrack };
16
16
  export type { FlightRecorder as BacktrackRecorder, FlightRecorderOptions as BacktrackOptions };
17
- //# sourceMappingURL=index.d.ts.map