@ihyeon/browser-error-log 0.1.18 → 0.1.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.ko.md CHANGED
@@ -76,7 +76,7 @@ errorLog.clearBreadcrumbs(); // 새 흐름 시작; 이미 수집한 오류는
76
76
 
77
77
  클라이언트마다 최근 20개 작업을 UTF-8 JSON 기준 12,000바이트 안에서 유지합니다. 작업 추가만으로 별도 이벤트를 보내지 않으며 이후 오류에 오래된 순서의 복사본을 붙입니다. 각 작업에는 SDK가 만든 UTC 시각, 분류(기본 `manual`, 최대 40자), 메시지(최대 256자), 선택적인 단일 값 데이터(6개 키, 키 80자·문자열 값 200자)가 있습니다. 기존 민감 키·URL·텍스트 필터와 `beforeSend`가 적용되며 `event.breadcrumbs`를 수정하거나 제거할 수 있습니다. `clearBreadcrumbs()`는 이후 수집에 적용되고 `destroy()`도 로컬 작업 기록을 비웁니다.
78
78
 
79
- `init()`은 기존 `BrowserErrorLogClient`를 확장한 `BrowserErrorLogBreadcrumbClient`를 반환합니다. 기존 클라이언트와 React Error Boundary 모형은 원래 인터페이스를 유지할 수 있습니다. 새 메서드를 쓰는 클라이언트의 타입을 직접 선언할 때는 확장 타입을 사용하세요.
79
+ `init()`은 `BrowserErrorLogBreadcrumbClient`와 원래 `BrowserErrorLogClient`를 확장한 `BrowserErrorLogDiagnosticsClient`를 반환합니다. 기존 클라이언트와 React Error Boundary 모형은 원래 인터페이스를 유지할 수 있습니다. 작업 기록이나 진단 메서드를 쓰는 클라이언트의 타입을 직접 선언할 때는 해당 확장 타입을 사용하세요.
80
80
 
81
81
  뷰어는 두 오류 상세 화면에 이 기록을 표시하고 히스토리 JSON에도 보존합니다. 자체 호스팅 수집기·뷰어는 작업 기록 지원 버전(0.1.16부터)에서 이 선택 필드를 저장·표시합니다. 이전 수집기는 이벤트를 받아도 작업 기록을 생략할 수 있습니다. 자체 백엔드는 `@ihyeon/browser-error-log-protocol`의 `isBreadcrumbTrail`로 작업 기록을 검증할 수 있습니다.
82
82
 
@@ -144,6 +144,46 @@ currentAppSection = 'account'; // 이후 이벤트에는 현재 값을 사용
144
144
 
145
145
  사용자 지정 `transport(batch, { signal })`에서는 요청에 `signal`을 전달하고 전송 실패 시 reject하세요. 자동 네트워크 오류 수집이나 요청 기록을 원하면 자기 전송을 제외할 `endpoint`를 지정해야 합니다. 없으면 사용자 지정 transport에서 두 경로를 모두 끕니다. 기본 전송은 credentials를 보내지 않습니다.
146
146
 
147
+ ## 오류 폭주 제한
148
+
149
+ ```ts
150
+ const errorLog = init({
151
+ project: 'my-web',
152
+ endpoint: '/api/events',
153
+ maxEventsPerMinute: 60,
154
+ });
155
+ ```
156
+
157
+ `maxEventsPerMinute`는 클라이언트별로 직전 60초 동안 큐에 새로 담는 이벤트 수를 제한하는 선택 옵션입니다. 기본값은 제한 없음입니다. 유한한 값은 소수점을 내리고 1~1,000 범위로 조정하며, 생략하거나 유한하지 않은 값을 지정하면 제한을 끕니다. 수동·React 수집, 전역 오류, Promise, console, 선택한 HTTP·네트워크 실패가 같은 한도를 공유합니다. 초과 이벤트는 나중에 보내도록 보관하지 않고 즉시 제외하며 `getStats().dropped`에 반영합니다. 각 이벤트를 큐에 담은 지 60초가 지나면 그만큼 다시 수집할 수 있습니다.
158
+
159
+ 큐를 비우는 flush로 한도가 초기화되지 않습니다. 재시도와 beacon 전송은 이미 담긴 이벤트를 사용하므로 추가 한도를 쓰지 않고, 작업 기록도 한도를 쓰지 않습니다. 같은 Error 객체의 중복 수집과 `beforeSend`가 제외한 이벤트는 한도를 쓰지 않습니다. 한도가 가득 차면 초과 이벤트의 `beforeSend` 호출을 생략합니다. 큐에 담긴 이벤트가 나중에 큐에서 밀려나거나 전송에 실패해도 사용한 한도는 유지합니다.
160
+
161
+ 한도는 현재 문서의 해당 클라이언트에 속하며 새 클라이언트나 전체 페이지 로드에서는 새로 시작합니다. 큐 진입 건수를 제한하므로 HTTP 요청 수·바이트·서버 전체 트래픽이나 이벤트 생성 작업량의 상한을 뜻하지는 않습니다. 수집기에는 별도의 서버 측 제한을 적용하세요.
162
+
163
+ ## SDK 수집·전송 진단
164
+
165
+ ```ts
166
+ await errorLog.flush();
167
+ const diagnostics = errorLog.getDiagnostics();
168
+ console.log(diagnostics.inFlight, diagnostics.filtered, diagnostics.deduplicated);
169
+ console.table(diagnostics.droppedByReason);
170
+ ```
171
+
172
+ `getDiagnostics()`는 기존 `queued`·`sent`·`dropped`에 `inFlight`(재시도 대기를 포함한 전송 배치 내 이벤트 수), `filtered`(`beforeSend`가 `false` 또는 `null`을 반환한 횟수), `deduplicated`(`captureException`의 기존 동일 객체 중복 제외 횟수)와 다음 원인별 건수를 더해 반환합니다.
173
+
174
+ | `droppedByReason` 키 | 집계하는 이벤트 |
175
+ | --- | --- |
176
+ | `rateLimit` | `maxEventsPerMinute` 초과로 제외 |
177
+ | `queueOverflow` | 큐가 가득 차서 밀려남 |
178
+ | `payloadTooLarge` | 이벤트 또는 배치 바이트 한도 초과 |
179
+ | `processingError` | 관측한 전처리·민감정보 필터·콜백 실패로 제외 |
180
+ | `deliveryError` | 영구 전송 실패 또는 재시도 소진 |
181
+ | `destroyed` | `destroy()`로 큐나 진행 중인 전송에서 폐기 |
182
+
183
+ 원인별 건수의 합은 `dropped`입니다. `filtered`와 `deduplicated`는 별도 항목으로 기존 `getStats()` 동작을 유지합니다. 재시도 횟수는 최종 전송 실패 전에는 버린 이벤트로 세지 않으며, beacon 시도가 실패하면 큐를 유지합니다. `sent`도 기존처럼 브라우저 beacon 큐의 수락을 포함하므로 수집기의 저장 완료를 보장하지 않습니다.
184
+
185
+ 호출마다 로컬 숫자 통계만 담은 독립 복사본을 반환합니다. 추가 이벤트를 전송하거나 수집 콜백을 실행하지 않고 URL·오류 원문·본문을 포함하지 않습니다. 통계는 클라이언트 수명 동안 누적되며 `destroy()` 후에도 읽을 수 있고 이때 `inFlight`는 0입니다. flush나 작업 기록 정리로 초기화하지 않으며 비활성·SSR 클라이언트는 0으로 시작합니다. 제외한 수집기 요청·의도적인 취소·선택하지 않은 HTTP 상태·무시한 작업 기록 입력은 통계를 늘리지 않습니다. SDK가 관측한 판단의 통계이므로 초기화 전 오류나 서버 전체 수신 여부를 보여주지는 않습니다. 수집기 갱신은 필요 없으며 기존 `getStats()`는 세 필드를 그대로 반환합니다.
186
+
147
187
  ## 전달 제한
148
188
 
149
189
  기본 큐는 50건, flush 주기는 10초입니다. 배치는 최대 20건 또는 48,000바이트입니다. 각 시도는 5초 제한이고 재시도 가능한 실패는 최대 두 번 재시도합니다. `maxQueueSize`, `flushIntervalMs`, `transportTimeoutMs`는 정해진 범위 안에서 조정할 수 있습니다. 오프라인, 탭 종료, 버퍼 초과, 재시도 소진으로 이벤트가 유실될 수 있습니다. 영속 오프라인 큐나 정확히 한 번의 전달 보장은 없습니다.
package/README.md CHANGED
@@ -76,7 +76,7 @@ errorLog.clearBreadcrumbs(); // start a new flow; captured errors keep their sna
76
76
 
77
77
  Each client keeps the latest 20 recorded steps, within a 12,000-byte UTF-8 JSON budget. Adding a step does not send a separate event; subsequent errors include an oldest-first snapshot. Steps have an SDK-generated UTC timestamp, a category (default `manual`, up to 40 characters), a message (up to 256 characters), and optional scalar data (six keys, 80 characters per key and 200 per string value). The existing sensitive-key, URL, and text filters apply; `beforeSend` can edit or remove `event.breadcrumbs`. `clearBreadcrumbs()` affects future captures, and `destroy()` also clears the local trail.
78
78
 
79
- `init()` returns `BrowserErrorLogBreadcrumbClient`, extending the existing `BrowserErrorLogClient` contract. Existing clients and React Error Boundary mocks can keep the original interface; use the extended type when explicitly typing a client that calls the new methods.
79
+ `init()` returns `BrowserErrorLogDiagnosticsClient`, extending `BrowserErrorLogBreadcrumbClient` and the original `BrowserErrorLogClient`. Existing clients and React Error Boundary mocks can keep their original interfaces; use the corresponding extended type when explicitly typing a client that calls breadcrumb or diagnostic methods.
80
80
 
81
81
  The viewer shows these steps in both error detail views and preserves them in history JSON. Use a collector and viewer with breadcrumb support (introduced in 0.1.16) to retain and display this optional field; older collectors may accept an event while omitting its breadcrumbs. Custom backends can validate the trail with `isBreadcrumbTrail` from `@ihyeon/browser-error-log-protocol`.
82
82
 
@@ -144,6 +144,46 @@ By default, HTTP capture records 5xx responses and network failures, excludes in
144
144
 
145
145
  For a custom `transport(batch, { signal })`, pass `signal` to your request and reject on delivery failure. Include `endpoint` for collector exclusion when using automatic network error capture or network breadcrumbs; otherwise both are disabled for a custom transport. The default transport omits credentials.
146
146
 
147
+ ## Limit error bursts
148
+
149
+ ```ts
150
+ const errorLog = init({
151
+ project: 'my-web',
152
+ endpoint: '/api/events',
153
+ maxEventsPerMinute: 60,
154
+ });
155
+ ```
156
+
157
+ `maxEventsPerMinute` optionally caps new events admitted to each client's queue over the preceding 60 seconds. It is disabled by default. Finite values are rounded down and clamped to 1–1,000; omitted or non-finite values disable the limit. All error types share the same budget, including manual and React captures, global errors, promises, console, and selected HTTP/network failures. Excess events are discarded immediately and increase `getStats().dropped`; they are not delayed for later delivery. Capacity returns as each admitted event reaches 60 seconds of age.
158
+
159
+ Flushing an empty queue does not reset the budget. Retries and beacon delivery reuse admitted events without consuming more capacity; breadcrumbs do not consume it. Duplicate Error objects and events filtered by `beforeSend` do not consume capacity. Once the budget is full, `beforeSend` is skipped for excess events. Admitted events still consume capacity if they are later evicted from the queue or fail delivery.
160
+
161
+ The budget belongs to this client in the current document; a new client or full page load starts a new one. It limits queue admission, not HTTP request counts, bytes, server-wide traffic, or the work done to construct an event. Use independent server-side limits for your collector.
162
+
163
+ ## Inspect SDK collection and delivery
164
+
165
+ ```ts
166
+ await errorLog.flush();
167
+ const diagnostics = errorLog.getDiagnostics();
168
+ console.log(diagnostics.inFlight, diagnostics.filtered, diagnostics.deduplicated);
169
+ console.table(diagnostics.droppedByReason);
170
+ ```
171
+
172
+ `getDiagnostics()` returns the existing `queued`, `sent`, and `dropped` counts, plus `inFlight` (events in a delivery batch, including retry waits), `filtered` (`beforeSend` returned `false` or `null`), `deduplicated` (the existing same-object suppression in `captureException`), and these drop reasons:
173
+
174
+ | `droppedByReason` key | Events counted |
175
+ | --- | --- |
176
+ | `rateLimit` | Rejected by `maxEventsPerMinute` |
177
+ | `queueOverflow` | Evicted from a full queue |
178
+ | `payloadTooLarge` | Exceeded the event or batch byte budget |
179
+ | `processingError` | Dropped by an observed preprocessing, sanitizer, or callback failure |
180
+ | `deliveryError` | Failed permanently or exhausted delivery retries |
181
+ | `destroyed` | Discarded from the queue or an active delivery by `destroy()` |
182
+
183
+ The reason counts sum to `dropped`. `filtered` and `deduplicated` are separate and preserve the existing `getStats()` behavior. Retry attempts do not count as dropped events unless delivery finally fails; a failed beacon attempt keeps the queue. `sent` retains its best-effort meaning, including browser beacon-queue acceptance rather than proof of collector storage.
184
+
185
+ Each call returns independent copies containing only local counters. It does not send events, invoke capture hooks, or include URLs, error text, or payloads. Counts belong to this client for its lifetime, remain readable after `destroy()` (with `inFlight: 0`), and are not reset by flush or breadcrumb cleanup. Disabled/SSR clients start with zero counts. Excluded collector requests, intentional aborts, unselected HTTP statuses, and ignored breadcrumb input do not increment these counters. These counters cover SDK-observed decisions, not errors before initialization or proof of complete server ingestion. No collector upgrade is needed, and `getStats()` keeps its original three-field shape.
186
+
147
187
  ## Delivery limits
148
188
 
149
189
  The default queue holds 50 events and flushes every 10 seconds. Batches contain up to 20 events or 48,000 bytes. Each attempt has a 5-second deadline; retryable failures get up to two retries. `maxQueueSize`, `flushIntervalMs`, and `transportTimeoutMs` are configurable within bounded ranges. These are best-effort limits: offline operation, tab closure, buffer overflow, or exhausted retries can lose events. There is no persistent offline queue or exactly-once guarantee.
package/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var j=Object.defineProperty;var $=Object.getOwnPropertyDescriptor;var W=Object.getOwnPropertyNames;var J=Object.prototype.hasOwnProperty;var Y=(r,e,n)=>e in r?j(r,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):r[e]=n;var Z=(r,e)=>{for(var n in e)j(r,n,{get:e[n],enumerable:!0})},G=(r,e,n,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of W(e))!J.call(r,o)&&o!==n&&j(r,o,{get:()=>e[o],enumerable:!(t=$(e,o))||t.enumerable});return r};var Q=r=>G(j({},"__esModule",{value:!0}),r);var h=(r,e,n)=>Y(r,typeof e!="symbol"?e+"":e,n);var ye={};Z(ye,{init:()=>me});module.exports=Q(ye);var k={count:20,bytes:12e3,category:40,message:256,dataKeys:6,dataKey:80,dataString:200};var ee=20,_=48e3,te=10,ne=24e3,q=[250,500],H=/(?:password|passwd|token|secret|authorization|cookie|session|api.?key|credential|bearer|private.?key)/i,F=new Set(["javascript","promise","react","console","http","network","manual"]),z=new Set(["browser","webview-ios","webview-android","unknown"]),re=0;function s(r,e){try{return r==null?void 0:Reflect.get(Object(r),e)}catch{return}}function w(r){try{return String(r)}catch{return"[unavailable]"}}function oe(r,e){return w(r).slice(0,e)}function S(){try{return performance.now()}catch{return Date.now()}}function V(){try{if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID()}catch{}return`${Date.now().toString(36)}-${(++re).toString(36)}-${Math.random().toString(36).slice(2,10)}`}function O(r,e){try{if(e?.aborted)return!0}catch{}return s(r,"name")==="AbortError"||s(r,"code")===20}function M(r){if(r==null)return{message:"Unknown error"};let e=s(r,"message"),n=s(r,"name"),t=s(r,"stack");return{message:e==null?w(r):w(e),...n==null?{}:{name:w(n)},...t==null?{}:{stack:w(t)}}}function C(r){return new TextEncoder().encode(r).length}function x(r,e,n,t){return typeof r=="number"&&Number.isFinite(r)?Math.min(n,Math.max(e,Math.floor(r))):t}var U=class extends Error{constructor(n){super(`Collector responded ${n}`);h(this,"status",n)}},B=class extends Error{},P=class extends Error{},D=class{constructor(e){h(this,"active");h(this,"endpoint");h(this,"options");h(this,"networkCaptureEnabled");h(this,"networkBreadcrumbCaptureEnabled");h(this,"navigationCaptureEnabled");h(this,"transportTimeoutMs");h(this,"startedAt",S());h(this,"viewId",V());h(this,"seenErrors",new WeakSet);h(this,"queue",[]);h(this,"breadcrumbs",[]);h(this,"maxQueueSize");h(this,"cancelWaits",new Set);h(this,"controllers",new Set);h(this,"destroySignal");h(this,"resolveDestroy");h(this,"interval");h(this,"flushing");h(this,"sequence",0);h(this,"inFlight",0);h(this,"sent",0);h(this,"dropped",0);h(this,"destroyed",!1);h(this,"onError",e=>{try{let n=s(e,"filename"),t=s(e,"lineno"),o=s(e,"colno"),i={};typeof n=="string"&&n.trim()&&(i.filename=this.cleanUrl(n)),typeof t=="number"&&Number.isFinite(t)&&t>0&&(i.lineno=t),typeof o=="number"&&Number.isFinite(o)&&o>0&&(i.colno=o),this.captureException(s(e,"error")??s(e,"message")??"Script error",{type:"javascript",...Object.keys(i).length?{context:i}:{}})}catch{this.dropped++}});h(this,"onRejection",e=>{this.captureException(e.reason,{type:"promise"})});h(this,"onVisibility",()=>{document.visibilityState==="hidden"&&this.tryBeacon()});this.options=e,this.active=e.enabled!==!1&&typeof window<"u"&&typeof document<"u";let n=!e.transport||!!e.endpoint;if(this.networkCaptureEnabled=e.captureNetwork!==!1&&n,this.networkBreadcrumbCaptureEnabled=e.captureNetworkBreadcrumbs===!0&&n,this.navigationCaptureEnabled=e.captureNavigation===!0,this.maxQueueSize=x(e.maxQueueSize,1,100,50),this.transportTimeoutMs=x(e.transportTimeoutMs,250,6e4,5e3),this.destroySignal=new Promise(t=>{this.resolveDestroy=t}),!!this.active){if(!e.project||typeof e.project!="string")throw new Error("project is required");if(!e.transport&&!e.endpoint)throw new Error("endpoint or transport is required");this.endpoint=e.endpoint?this.absoluteUrl(e.endpoint):void 0,window.addEventListener("error",this.onError),window.addEventListener("unhandledrejection",this.onRejection),document.addEventListener("visibilitychange",this.onVisibility),(this.networkCaptureEnabled||this.networkBreadcrumbCaptureEnabled)&&ce(this),e.captureConsole===!0&&pe(this),this.navigationCaptureEnabled&&ie(this),this.interval=setInterval(()=>{this.flush()},x(e.flushIntervalMs,10,6e4,1e4))}}captureException(e,n={}){if(!(!this.active||this.destroyed||O(e)))try{if(e!==null&&(typeof e=="object"||typeof e=="function")&&this.seenErrors.has(e))return;let t=M(e),o=F.has(n.type)?n.type:"manual",i=this.makeEvent(o,t.message,{name:t.name,stack:t.stack,componentStack:n.componentStack,context:n.context});this.enqueue(i)&&e!==null&&(typeof e=="object"||typeof e=="function")&&this.seenErrors.add(e)}catch(t){(t instanceof B||t instanceof P)&&this.dropped++}}reportNetwork(e,n,t,o,i,u=!0){if(this.destroyed||!this.active||this.isCollectorUrl(n)||O(i))return;let d=this.networkCaptureEnabled&&u;if(d&&t!==void 0)try{d=this.options.shouldCaptureHttp?this.options.shouldCaptureHttp(t,n,e):t>=500}catch{this.dropped++;return}if(this.networkBreadcrumbCaptureEnabled)try{let c=this.cleanBreadcrumbUrl(n);if(c.url){let a={method:this.cleanNetworkBreadcrumbMethod(e),url:c.url,durationMs:x(o,0,36e5,0)};t!==void 0&&Number.isInteger(t)&&t>=0&&t<=599&&(a.status=t),this.breadcrumbs.push({occurredAt:new Date().toISOString(),category:t===void 0?"network":"http",message:t===void 0?"Network failure":"HTTP response",data:a}),this.boundBreadcrumbs(this.breadcrumbs)}else if(d&&!c.safeForError){this.dropped++;return}}catch{d&&this.dropped++;return}if(d)try{let c={method:oe(e||"GET",16).toUpperCase(),url:n,status:t,durationMs:o},a=i===void 0?void 0:M(i),l=this.makeEvent(t===void 0?"network":"http",t===void 0?a?.message||"Network request failed":`HTTP ${t}`,{name:a?.name,network:c});this.enqueue(l)}catch{this.dropped++}}reportZeroStatusCompletion(e,n,t){this.networkBreadcrumbCaptureEnabled&&this.reportNetwork(e,n,0,t,void 0,!1)}captureConsole(e){if(!(!this.active||this.destroyed))try{let n=e.map(w).join(" "),t;for(let o of e)try{if(o instanceof Error){t=M(o);break}}catch{}this.enqueue(this.makeEvent("console",n,{name:t?.name,stack:t?.stack}))}catch{this.dropped++}}addBreadcrumb(e){if(!(!this.active||this.destroyed))try{let n=this.cleanBreadcrumb(e,new Date().toISOString());if(!n)return;this.breadcrumbs.push(n),this.boundBreadcrumbs(this.breadcrumbs)}catch{}}reportNavigation(e,n,t){if(!(!this.active||this.destroyed||!this.navigationCaptureEnabled))try{let o=this.cleanBreadcrumbUrl(e).url,i=this.cleanBreadcrumbUrl(n).url;if(!o||!i||o===i)return;this.breadcrumbs.push({occurredAt:new Date().toISOString(),category:"navigation",message:"Navigation",data:{from:o,to:i,trigger:t}}),this.boundBreadcrumbs(this.breadcrumbs)}catch{}}clearBreadcrumbs(){!this.active||this.destroyed||(this.breadcrumbs.length=0)}flush(){return!this.active||this.destroyed?Promise.resolve():this.flushing?this.flushing:(this.flushing=this.drain().finally(()=>{this.flushing=void 0}),this.flushing)}destroy(){if(!this.destroyed){this.destroyed=!0,this.interval&&clearInterval(this.interval),this.active&&(window.removeEventListener("error",this.onError),window.removeEventListener("unhandledrejection",this.onRejection),document.removeEventListener("visibilitychange",this.onVisibility),(this.networkCaptureEnabled||this.networkBreadcrumbCaptureEnabled)&&ue(this),this.options.captureConsole===!0&&he(this),this.navigationCaptureEnabled&&se(this)),this.dropped+=this.queue.length+this.inFlight,this.queue.length=0,this.breadcrumbs.length=0;for(let e of this.cancelWaits)e();for(let e of this.controllers)e.abort();this.resolveDestroy(X)}}getStats(){return{queued:this.queue.length,sent:this.sent,dropped:this.dropped}}absoluteUrl(e){try{return new URL(e,window.location.href).href}catch{return e}}isCollectorUrl(e){if(!this.endpoint)return!1;try{let n=new URL(e,window.location.href),t=new URL(this.endpoint,window.location.href);return n.origin===t.origin&&n.pathname===t.pathname}catch{return e===this.endpoint}}cleanUrl(e){let n=w(e);if(this.options.sanitizeUrl){try{n=this.options.sanitizeUrl(n)}catch{throw new B("URL sanitizer failed")}if(typeof n!="string"||!n)throw new B("URL sanitizer returned no URL")}try{let t=new URL(n,window.location.href);return t.protocol!=="http:"&&t.protocol!=="https:"?"[unsupported URL]":(t.username="",t.password="",t.search="",t.hash="",this.cleanText(t.href,1024,!1))}catch{return this.cleanText(n,1024,!1).split(/[?#]/,1)[0]}}cleanBreadcrumbUrl(e){let n=this.cleanUrl(e);if(n==="[unsupported URL]")return{safeForError:!0};try{let t=new URL(n);return t.protocol!=="http:"&&t.protocol!=="https:"||t.username||t.password||t.search||t.hash?{safeForError:!1}:{url:n.slice(0,k.dataString),safeForError:!0}}catch{return{safeForError:!1}}}cleanNetworkBreadcrumbMethod(e){let n=w(e||"GET").trim().toUpperCase();return/^[A-Z0-9!#$%&'*+.^_`|~-]{1,16}$/.test(n)?n:"GET"}cleanText(e,n,t=!0){let o=w(e);return t&&(o=o.replace(/https?:\/\/[^\s<>"'()[\]]+/gi,i=>this.cleanUrl(i)),o=o.replace(/(^|[\s"'(\[=])((?:\/(?!\/)|\.{1,2}\/)[^\s<>"'()[\]?#]*[?#][^\s<>"'()[\]]+|[a-z][\w.-]*(?:\/[^\s<>"'()[\]?#]*)?(?:\?[a-z0-9_.-]+=[^\s<>"'()[\]]+|#[^\s<>"'()[\]]+)|\?[a-z0-9_.-]+=[^\s<>"'()[\]]+)/gi,(i,u,d)=>{let c=/[.,;!]+$/.exec(d)?.[0]??"",a=d.slice(0,d.length-c.length),l=this.options.sanitizeUrl?this.cleanUrl(a):a.startsWith("?")?"[redacted query]":this.cleanText(a.split(/[?#]/,1)[0],1024,!1);return`${u}${l}${c}`})),o.replace(/\bBearer\s+[A-Za-z0-9._~+\/-]+/gi,"Bearer [REDACTED]").replace(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/gi,"[REDACTED_EMAIL]").slice(0,n)}cleanContext(e){if(!e||typeof e!="object")return;let n={},t;try{t=Object.keys(e)}catch{return}for(let o of t){if(Object.keys(n).length>=12)break;if(H.test(o))continue;let i=s(e,o),u=this.cleanText(o,80);typeof i=="string"?n[u]=this.cleanText(i,500):(typeof i=="number"&&Number.isFinite(i)||typeof i=="boolean"||i===null)&&(n[u]=i)}return Object.keys(n).length?n:void 0}cleanBreadcrumb(e,n){if(!e||typeof e!="object")return;let t=n??s(e,"occurredAt");if(typeof t!="string")return;try{if(new Date(t).toISOString()!==t)return}catch{return}let o=s(e,"category"),i=s(e,"message");if(o!==void 0&&typeof o!="string"||typeof i!="string")return;let u=this.cleanText(o??(n?"manual":""),k.category),d=this.cleanText(i,k.message);if(!u.trim()||!d.trim())return;let c=s(e,"data"),a={};if(c&&typeof c=="object"){let l;try{l=Object.keys(c)}catch{l=[]}for(let p of l){if(Object.keys(a).length>=k.dataKeys)break;if(H.test(p))continue;let f=this.cleanText(p,k.dataKey),y=s(c,p);typeof y=="string"?a[f]=this.cleanText(y,k.dataString):(typeof y=="number"&&Number.isFinite(y)||typeof y=="boolean"||y===null)&&(a[f]=y)}}return{occurredAt:t,category:u,message:d,...Object.keys(a).length?{data:a}:{}}}boundBreadcrumbs(e){for(;e.length>k.count||C(JSON.stringify(e))>k.bytes;)e.shift()}cleanBreadcrumbTrail(e){let n;try{if(!Array.isArray(e))return;n=e.length}catch{return}if(!Number.isSafeInteger(n)||n<0)return;let t=[];for(let o=Math.max(0,n-k.count);o<n;o++){let i=this.cleanBreadcrumb(s(e,o));i&&(t.push(i),this.boundBreadcrumbs(t))}return t.length?t:void 0}cleanNetwork(e){if(!e||typeof e!="object")return;let n=s(e,"status"),t=typeof n=="number"&&Number.isInteger(n)&&n>=100&&n<=599?n:void 0;return{method:this.cleanText(s(e,"method")??"GET",16).toUpperCase(),url:this.cleanUrl(s(e,"url")??""),...t===void 0?{}:{status:t},durationMs:x(s(e,"durationMs"),0,36e5,0)}}makeEvent(e,n,t={}){let o=s(navigator,"userAgent"),i=this.cleanContext(t.context),u;try{u=this.options.getContext?.()}catch{throw new P("Context resolver failed")}let d=this.cleanContext(u),c=this.cleanContext(this.options.context),a=i;if(d||c){a={...i};for(let p of[d,c])if(p)for(let f of Object.keys(p)){if(Object.keys(a).length>=12)break;Object.prototype.hasOwnProperty.call(a,f)||(a[f]=p[f])}}let l=this.cleanNetwork(t.network);return{schemaVersion:1,eventId:V(),project:this.cleanText(this.options.project,80),environment:this.cleanText(this.options.environment??"development",80),release:this.cleanText(this.options.release??"unknown",120),sdkVersion:"0.1.18",occurredAt:new Date().toISOString(),viewId:this.viewId,sequence:++this.sequence,elapsedMs:x(S()-this.startedAt,0,36e5,0),type:e,message:this.cleanText(n,1024),...t.name===void 0?{}:{name:this.cleanText(t.name,100)},...t.stack===void 0?{}:{stack:this.cleanText(t.stack,4096)},...t.componentStack===void 0?{}:{componentStack:this.cleanText(t.componentStack,2048)},page:this.cleanUrl(window.location.href),runtime:z.has(this.options.runtime)?this.options.runtime:"browser",...typeof o=="string"?{browser:this.cleanText(o,300)}:{},...a?{context:a}:{},...this.breadcrumbs.length?{breadcrumbs:this.breadcrumbs.map(p=>({...p,...p.data?{data:{...p.data}}:{}}))}:{},...l?{network:l}:{}}}sanitizeReplacement(e,n){let t=s(e,"type"),o=s(e,"runtime"),i=s(e,"name"),u=s(e,"stack"),d=s(e,"componentStack"),c=s(e,"browser"),a=this.cleanContext(s(e,"context")),l=this.cleanBreadcrumbTrail(s(e,"breadcrumbs")),p=this.cleanNetwork(s(e,"network"));return{...n,type:F.has(t)?t:n.type,message:this.cleanText(s(e,"message")??n.message,1024),...i===void 0?{name:n.name}:{name:this.cleanText(i,100)},...u===void 0?{stack:n.stack}:{stack:this.cleanText(u,4096)},...d===void 0?{componentStack:n.componentStack}:{componentStack:this.cleanText(d,2048)},page:this.cleanUrl(s(e,"page")??n.page),runtime:z.has(o)?o:n.runtime,...c===void 0?{browser:n.browser}:{browser:this.cleanText(c,300)},...a?{context:a}:{context:void 0},...l?{breadcrumbs:l}:{breadcrumbs:void 0},...p?{network:p}:{network:void 0}}}enqueue(e){if(this.destroyed)return!1;let n=e;if(this.options.beforeSend)try{let t={...e,context:e.context&&{...e.context},breadcrumbs:e.breadcrumbs?.map(i=>({...i,data:i.data&&{...i.data}})),network:e.network&&{...e.network}},o=this.options.beforeSend(t);if(o===!1||o===null)return!1;n=this.sanitizeReplacement(o===void 0?t:o,e)}catch{return this.dropped++,!1}return C(JSON.stringify(n))>_?(this.dropped++,!1):(this.queue.length>=this.maxQueueSize&&(this.queue.shift(),this.dropped++),this.queue.push(n),this.queue.length>=this.maxQueueSize&&this.flush(),!0)}takeBatch(e=ee,n=_){let t=[],o=C('{"schemaVersion":1,"events":[]}');for(;this.queue.length&&t.length<e;){let i=this.queue[0],u=C(JSON.stringify(i))+(t.length?1:0);if(t.length&&o+u>n)break;if(!t.length&&o+u>n){this.queue.shift(),this.dropped++;continue}t.push(this.queue.shift()),o+=u}return{schemaVersion:1,events:t}}async drain(){for(;!this.destroyed&&this.queue.length;){let e=this.takeBatch();if(e.events.length){this.inFlight+=e.events.length;try{await this.sendWithRetry(e)}finally{this.inFlight-=e.events.length}}}}async sendWithRetry(e){for(let n=0;n<=q.length&&!this.destroyed;n++){let t=new AbortController;this.controllers.add(t);let o,i=new Promise((d,c)=>{o=setTimeout(()=>{t.abort(),c(new Error("Collector transport timed out"))},this.transportTimeoutMs)}),u;try{if(await Promise.race([this.send(e,t.signal),i,this.destroySignal])===X||this.destroyed)return;this.sent+=e.events.length;return}catch(d){if(this.destroyed)return;let c=s(d,"status");if(!(typeof c!="number"||c===429||c>=500)||n===q.length)break;u=q[n]}finally{o&&clearTimeout(o),this.controllers.delete(t)}u!==void 0&&await this.wait(u)}this.destroyed||(this.dropped+=e.events.length)}async send(e,n){if(this.options.transport){await this.options.transport(e,{signal:n});return}let t=await window.fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),credentials:"omit",signal:n});if(!t.ok)throw new U(t.status)}wait(e){return new Promise(n=>{let t=()=>{clearTimeout(o),this.cancelWaits.delete(t),n()},o=setTimeout(t,e);this.cancelWaits.add(t)})}tryBeacon(){if(!(this.destroyed||this.options.transport||!this.endpoint||!this.queue.length))try{let e=new URL(this.endpoint);if(e.origin!==window.location.origin||e.search||e.hash||e.username||e.password||typeof navigator.sendBeacon!="function")return;let n=this.queue.slice(0,te);for(;n.length>0;){let o=JSON.stringify({schemaVersion:1,events:n});if(C(o)<=ne){navigator.sendBeacon(this.endpoint,new Blob([o],{type:"application/json"}))&&(this.queue.splice(0,n.length),this.sent+=n.length);return}n.pop()}}catch{}}},X=Symbol("destroyed"),N,A,L;function ie(r){L||(L=ae()),L?.clients.add(r)}function se(r){let e=L;e&&(e.clients.delete(r),e.clients.size||(e.cleanup(),L=void 0))}function K(r,e){let n=new Set,t=Object.getPrototypeOf(r);for(;t&&!n.has(t);){n.add(t);let o=Object.getOwnPropertyDescriptor(t,e);if(o)return o;t=Object.getPrototypeOf(t)}}function ae(){let r,e,n,t,o,i,u,d;try{if(r=window.history,e=window.location.href,o=Object.getOwnPropertyDescriptor(r,"pushState"),i=Object.getOwnPropertyDescriptor(r,"replaceState"),u=o?void 0:K(r,"pushState"),d=i?void 0:K(r,"replaceState"),o&&!("value"in o)||i&&!("value"in i)||!o&&(!u||!("value"in u)||u.writable!==!0)||!i&&(!d||!("value"in d)||d.writable!==!0)||(n=o?o.value:r.pushState,t=i?i.value:r.replaceState,typeof n!="function"||typeof t!="function"))return;let b=m=>m?m.configurable===!0||m.writable===!0:Object.isExtensible(r);if(!b(o)||!b(i))return}catch{return}let c=new Set,a=b=>{try{let m=window.location.href;if(m===e)return;let T=e;e=m;for(let v of c)try{v.reportNavigation(T,m,b)}catch{}}catch{}},l=function(...b){let m=Reflect.apply(n,this,b);return a("pushState"),m},p=function(...b){let m=Reflect.apply(t,this,b);return a("replaceState"),m},f=()=>{a("popstate")},y=()=>{a("hashchange")},g=(b,m,T)=>{try{let v=Object.getOwnPropertyDescriptor(r,b);if(!v||!("value"in v)||v.value!==m)return;T?Object.defineProperty(r,b,T):Reflect.deleteProperty(r,b)}catch{}},E=!1,R=!1;try{Object.defineProperty(r,"pushState",{configurable:o?.configurable??!0,enumerable:o?.enumerable??!1,writable:o?.writable??!0,value:l}),E=!0,Object.defineProperty(r,"replaceState",{configurable:i?.configurable??!0,enumerable:i?.enumerable??!1,writable:i?.writable??!0,value:p}),R=!0,window.addEventListener("popstate",f),window.addEventListener("hashchange",y)}catch{try{window.removeEventListener("hashchange",y)}catch{}try{window.removeEventListener("popstate",f)}catch{}R&&g("replaceState",p,i),E&&g("pushState",l,o);return}return{clients:c,cleanup(){try{window.removeEventListener("popstate",f)}catch{}try{window.removeEventListener("hashchange",y)}catch{}g("pushState",l,o),g("replaceState",p,i)}}}function ce(r){N||(N=le()),N.clients.add(r)}function ue(r){let e=N;e&&(e.clients.delete(r),e.clients.size||(e.cleanup(),N=void 0))}function de(r,e){let n;if(typeof Request<"u"&&r!==null&&typeof r=="object")if(r instanceof Request)n=s(r,"url");else try{n=Object.getOwnPropertyDescriptor(Request.prototype,"url")?.get?.call(r)}catch{}let t=s(e,"signal");return{url:n??w(r),method:w(s(e,"method")??(n===void 0?void 0:s(r,"method"))??"GET"),signal:t===void 0?n===void 0?void 0:s(r,"signal"):t}}function le(){let r=new Set,e=window.fetch,n;typeof e=="function"&&(n=function(...l){if(!r.size)return Reflect.apply(e,this,l);let p=S(),f;try{f=de(l[0],l[1])}catch{f={url:"",method:"GET"}}let y;try{y=Reflect.apply(e,this,l)}catch(g){if(!O(g,f.signal))for(let E of r)E.reportNetwork(f.method,f.url,void 0,S()-p,g);throw g}return y.then(g=>{try{let E=g.status;for(let R of r)R.reportNetwork(f.method,f.url,E,S()-p)}catch{}return g},g=>{if(!O(g,f.signal))for(let E of r)E.reportNetwork(f.method,f.url,void 0,S()-p,g);throw g})},window.fetch=n);let t=typeof XMLHttpRequest>"u"?void 0:XMLHttpRequest.prototype,o=t?.open,i=t?.send,u=new WeakMap,d=new WeakMap,c,a;return t&&o&&i&&(c=(function(...l){let p=Reflect.apply(o,this,l);d.get(this)?.();try{u.set(this,{method:w(l[0]),url:w(l[1])})}catch{}return p}),a=function(...l){if(!r.size)return Reflect.apply(i,this,l);let p=u.get(this);if(!p)return Reflect.apply(i,this,l);let f=S(),y=!1,g=!1,E=!1,R=()=>{y=!0},b=()=>{g=!0},m=()=>{this.removeEventListener("abort",R),this.removeEventListener("error",b),this.removeEventListener("timeout",b),this.removeEventListener("loadend",T),d.get(this)===m&&d.delete(this)},T=()=>{if(E=!0,m(),!y)try{let v=this.status;if(v===0&&!g){for(let I of r)I.reportZeroStatusCompletion(p.method,p.url,S()-f);return}for(let I of r)I.reportNetwork(p.method,p.url,v===0?void 0:v,S()-f)}catch{}};try{this.addEventListener("abort",R),this.addEventListener("error",b),this.addEventListener("timeout",b),this.addEventListener("loadend",T)}catch{return m(),Reflect.apply(i,this,l)}try{let v=Reflect.apply(i,this,l);return E||d.set(this,m),v}catch(v){throw m(),v}},t.open=c,t.send=a),{clients:r,cleanup(){n&&window.fetch===n&&(window.fetch=e),t&&c&&t.open===c&&(t.open=o),t&&a&&t.send===a&&(t.send=i)}}}function pe(r){A||(A=fe()),A.clients.add(r)}function he(r){let e=A;e&&(e.clients.delete(r),e.clients.size||(e.cleanup(),A=void 0))}function fe(){let r=new Set,e=console.error,n=function(...t){try{return Reflect.apply(e,this,t)}finally{for(let o of r)o.captureConsole(t)}};return console.error=n,{clients:r,cleanup(){console.error===n&&(console.error=e)}}}function me(r){return new D(r)}
1
+ "use strict";var D=Object.defineProperty;var $=Object.getOwnPropertyDescriptor;var W=Object.getOwnPropertyNames;var J=Object.prototype.hasOwnProperty;var Y=(n,e,t)=>e in n?D(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var Z=(n,e)=>{for(var t in e)D(n,t,{get:e[t],enumerable:!0})},G=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of W(e))!J.call(n,i)&&i!==t&&D(n,i,{get:()=>e[i],enumerable:!(r=$(e,i))||r.enumerable});return n};var Q=n=>G(D({},"__esModule",{value:!0}),n);var u=(n,e,t)=>Y(n,typeof e!="symbol"?e+"":e,t);var ge={};Z(ge,{init:()=>me});module.exports=Q(ge);var k={count:20,bytes:12e3,category:40,message:256,dataKeys:6,dataKey:80,dataString:200};var ee=20,_=48e3,te=10,re=24e3,M=[250,500],H=/(?:password|passwd|token|secret|authorization|cookie|session|api.?key|credential|bearer|private.?key)/i,F=new Set(["javascript","promise","react","console","http","network","manual"]),z=new Set(["browser","webview-ios","webview-android","unknown"]),ne=0;function s(n,e){try{return n==null?void 0:Reflect.get(Object(n),e)}catch{return}}function w(n){try{return String(n)}catch{return"[unavailable]"}}function ie(n,e){return w(n).slice(0,e)}function S(){try{return performance.now()}catch{return Date.now()}}function V(){try{if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID()}catch{}return`${Date.now().toString(36)}-${(++ne).toString(36)}-${Math.random().toString(36).slice(2,10)}`}function P(n,e){try{if(e?.aborted)return!0}catch{}return s(n,"name")==="AbortError"||s(n,"code")===20}function q(n){if(n==null)return{message:"Unknown error"};let e=s(n,"message"),t=s(n,"name"),r=s(n,"stack");return{message:e==null?w(n):w(e),...t==null?{}:{name:w(t)},...r==null?{}:{stack:w(r)}}}function B(n){return new TextEncoder().encode(n).length}function T(n,e,t,r){return typeof n=="number"&&Number.isFinite(n)?Math.min(t,Math.max(e,Math.floor(n))):r}var I=class extends Error{constructor(t){super(`Collector responded ${t}`);u(this,"status",t)}},C=class extends Error{},O=class extends Error{},U=class{constructor(e){u(this,"active");u(this,"endpoint");u(this,"options");u(this,"networkCaptureEnabled");u(this,"networkBreadcrumbCaptureEnabled");u(this,"navigationCaptureEnabled");u(this,"transportTimeoutMs");u(this,"startedAt",S());u(this,"viewId",V());u(this,"seenErrors",new WeakSet);u(this,"queue",[]);u(this,"breadcrumbs",[]);u(this,"maxQueueSize");u(this,"maxEventsPerMinute");u(this,"admittedAt",[]);u(this,"cancelWaits",new Set);u(this,"controllers",new Set);u(this,"destroySignal");u(this,"resolveDestroy");u(this,"interval");u(this,"flushing");u(this,"sequence",0);u(this,"inFlight",0);u(this,"sent",0);u(this,"dropped",0);u(this,"filtered",0);u(this,"deduplicated",0);u(this,"droppedByReason",{rateLimit:0,queueOverflow:0,payloadTooLarge:0,processingError:0,deliveryError:0,destroyed:0});u(this,"destroyed",!1);u(this,"lastAdmissionClock");u(this,"onError",e=>{try{let t=s(e,"filename"),r=s(e,"lineno"),i=s(e,"colno"),o={};typeof t=="string"&&t.trim()&&(o.filename=this.cleanUrl(t)),typeof r=="number"&&Number.isFinite(r)&&r>0&&(o.lineno=r),typeof i=="number"&&Number.isFinite(i)&&i>0&&(o.colno=i),this.captureException(s(e,"error")??s(e,"message")??"Script error",{type:"javascript",...Object.keys(o).length?{context:o}:{}})}catch{this.recordDrop("processingError")}});u(this,"onRejection",e=>{this.captureException(e.reason,{type:"promise"})});u(this,"onVisibility",()=>{document.visibilityState==="hidden"&&this.tryBeacon()});this.options=e,this.active=e.enabled!==!1&&typeof window<"u"&&typeof document<"u";let t=!e.transport||!!e.endpoint;if(this.networkCaptureEnabled=e.captureNetwork!==!1&&t,this.networkBreadcrumbCaptureEnabled=e.captureNetworkBreadcrumbs===!0&&t,this.navigationCaptureEnabled=e.captureNavigation===!0,this.maxQueueSize=T(e.maxQueueSize,1,100,50),this.maxEventsPerMinute=typeof e.maxEventsPerMinute=="number"&&Number.isFinite(e.maxEventsPerMinute)?T(e.maxEventsPerMinute,1,1e3,1):void 0,this.transportTimeoutMs=T(e.transportTimeoutMs,250,6e4,5e3),this.destroySignal=new Promise(r=>{this.resolveDestroy=r}),!!this.active){if(!e.project||typeof e.project!="string")throw new Error("project is required");if(!e.transport&&!e.endpoint)throw new Error("endpoint or transport is required");this.endpoint=e.endpoint?this.absoluteUrl(e.endpoint):void 0,window.addEventListener("error",this.onError),window.addEventListener("unhandledrejection",this.onRejection),document.addEventListener("visibilitychange",this.onVisibility),(this.networkCaptureEnabled||this.networkBreadcrumbCaptureEnabled)&&ce(this),e.captureConsole===!0&&pe(this),this.navigationCaptureEnabled&&oe(this),this.interval=setInterval(()=>{this.flush()},T(e.flushIntervalMs,10,6e4,1e4))}}captureException(e,t={}){if(!(!this.active||this.destroyed||P(e)))try{if(e!==null&&(typeof e=="object"||typeof e=="function")&&this.seenErrors.has(e)){this.deduplicated++;return}let r=q(e),i=F.has(t.type)?t.type:"manual",o=this.makeEvent(i,r.message,{name:r.name,stack:r.stack,componentStack:t.componentStack,context:t.context});this.enqueue(o)&&e!==null&&(typeof e=="object"||typeof e=="function")&&this.seenErrors.add(e)}catch(r){(r instanceof C||r instanceof O)&&this.recordDrop("processingError")}}reportNetwork(e,t,r,i,o,c=!0){if(this.destroyed||!this.active||this.isCollectorUrl(t)||P(o))return;let l=this.networkCaptureEnabled&&c;if(l&&r!==void 0)try{l=this.options.shouldCaptureHttp?this.options.shouldCaptureHttp(r,t,e):r>=500}catch{this.recordDrop("processingError");return}if(this.networkBreadcrumbCaptureEnabled)try{let d=this.cleanBreadcrumbUrl(t);if(d.url){let a={method:this.cleanNetworkBreadcrumbMethod(e),url:d.url,durationMs:T(i,0,36e5,0)};r!==void 0&&Number.isInteger(r)&&r>=0&&r<=599&&(a.status=r),this.breadcrumbs.push({occurredAt:new Date().toISOString(),category:r===void 0?"network":"http",message:r===void 0?"Network failure":"HTTP response",data:a}),this.boundBreadcrumbs(this.breadcrumbs)}else if(l&&!d.safeForError){this.recordDrop("processingError");return}}catch{l&&this.recordDrop("processingError");return}if(l)try{let d={method:ie(e||"GET",16).toUpperCase(),url:t,status:r,durationMs:i},a=o===void 0?void 0:q(o),p=this.makeEvent(r===void 0?"network":"http",r===void 0?a?.message||"Network request failed":`HTTP ${r}`,{name:a?.name,network:d});this.enqueue(p)}catch{this.recordDrop("processingError")}}reportZeroStatusCompletion(e,t,r){this.networkBreadcrumbCaptureEnabled&&this.reportNetwork(e,t,0,r,void 0,!1)}captureConsole(e){if(!(!this.active||this.destroyed))try{let t=e.map(w).join(" "),r;for(let i of e)try{if(i instanceof Error){r=q(i);break}}catch{}this.enqueue(this.makeEvent("console",t,{name:r?.name,stack:r?.stack}))}catch{this.recordDrop("processingError")}}addBreadcrumb(e){if(!(!this.active||this.destroyed))try{let t=this.cleanBreadcrumb(e,new Date().toISOString());if(!t)return;this.breadcrumbs.push(t),this.boundBreadcrumbs(this.breadcrumbs)}catch{}}reportNavigation(e,t,r){if(!(!this.active||this.destroyed||!this.navigationCaptureEnabled))try{let i=this.cleanBreadcrumbUrl(e).url,o=this.cleanBreadcrumbUrl(t).url;if(!i||!o||i===o)return;this.breadcrumbs.push({occurredAt:new Date().toISOString(),category:"navigation",message:"Navigation",data:{from:i,to:o,trigger:r}}),this.boundBreadcrumbs(this.breadcrumbs)}catch{}}clearBreadcrumbs(){!this.active||this.destroyed||(this.breadcrumbs.length=0)}flush(){return!this.active||this.destroyed?Promise.resolve():this.flushing?this.flushing:(this.flushing=this.drain().finally(()=>{this.flushing=void 0}),this.flushing)}destroy(){if(!this.destroyed){this.destroyed=!0,this.interval&&clearInterval(this.interval),this.active&&(window.removeEventListener("error",this.onError),window.removeEventListener("unhandledrejection",this.onRejection),document.removeEventListener("visibilitychange",this.onVisibility),(this.networkCaptureEnabled||this.networkBreadcrumbCaptureEnabled)&&ue(this),this.options.captureConsole===!0&&he(this),this.navigationCaptureEnabled&&se(this)),this.recordDrop("destroyed",this.queue.length+this.inFlight),this.queue.length=0,this.breadcrumbs.length=0,this.admittedAt.length=0,this.lastAdmissionClock=void 0;for(let e of this.cancelWaits)e();for(let e of this.controllers)e.abort();this.resolveDestroy(X)}}getStats(){return{queued:this.queue.length,sent:this.sent,dropped:this.dropped}}getDiagnostics(){return{...this.getStats(),inFlight:this.destroyed?0:this.inFlight,filtered:this.filtered,deduplicated:this.deduplicated,droppedByReason:{...this.droppedByReason}}}recordDrop(e,t=1){this.dropped+=t,this.droppedByReason[e]+=t}absoluteUrl(e){try{return new URL(e,window.location.href).href}catch{return e}}isCollectorUrl(e){if(!this.endpoint)return!1;try{let t=new URL(e,window.location.href),r=new URL(this.endpoint,window.location.href);return t.origin===r.origin&&t.pathname===r.pathname}catch{return e===this.endpoint}}cleanUrl(e){let t=w(e);if(this.options.sanitizeUrl){try{t=this.options.sanitizeUrl(t)}catch{throw new C("URL sanitizer failed")}if(typeof t!="string"||!t)throw new C("URL sanitizer returned no URL")}try{let r=new URL(t,window.location.href);return r.protocol!=="http:"&&r.protocol!=="https:"?"[unsupported URL]":(r.username="",r.password="",r.search="",r.hash="",this.cleanText(r.href,1024,!1))}catch{return this.cleanText(t,1024,!1).split(/[?#]/,1)[0]}}cleanBreadcrumbUrl(e){let t=this.cleanUrl(e);if(t==="[unsupported URL]")return{safeForError:!0};try{let r=new URL(t);return r.protocol!=="http:"&&r.protocol!=="https:"||r.username||r.password||r.search||r.hash?{safeForError:!1}:{url:t.slice(0,k.dataString),safeForError:!0}}catch{return{safeForError:!1}}}cleanNetworkBreadcrumbMethod(e){let t=w(e||"GET").trim().toUpperCase();return/^[A-Z0-9!#$%&'*+.^_`|~-]{1,16}$/.test(t)?t:"GET"}cleanText(e,t,r=!0){let i=w(e);return r&&(i=i.replace(/https?:\/\/[^\s<>"'()[\]]+/gi,o=>this.cleanUrl(o)),i=i.replace(/(^|[\s"'(\[=])((?:\/(?!\/)|\.{1,2}\/)[^\s<>"'()[\]?#]*[?#][^\s<>"'()[\]]+|[a-z][\w.-]*(?:\/[^\s<>"'()[\]?#]*)?(?:\?[a-z0-9_.-]+=[^\s<>"'()[\]]+|#[^\s<>"'()[\]]+)|\?[a-z0-9_.-]+=[^\s<>"'()[\]]+)/gi,(o,c,l)=>{let d=/[.,;!]+$/.exec(l)?.[0]??"",a=l.slice(0,l.length-d.length),p=this.options.sanitizeUrl?this.cleanUrl(a):a.startsWith("?")?"[redacted query]":this.cleanText(a.split(/[?#]/,1)[0],1024,!1);return`${c}${p}${d}`})),i.replace(/\bBearer\s+[A-Za-z0-9._~+\/-]+/gi,"Bearer [REDACTED]").replace(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/gi,"[REDACTED_EMAIL]").slice(0,t)}cleanContext(e){if(!e||typeof e!="object")return;let t={},r;try{r=Object.keys(e)}catch{return}for(let i of r){if(Object.keys(t).length>=12)break;if(H.test(i))continue;let o=s(e,i),c=this.cleanText(i,80);typeof o=="string"?t[c]=this.cleanText(o,500):(typeof o=="number"&&Number.isFinite(o)||typeof o=="boolean"||o===null)&&(t[c]=o)}return Object.keys(t).length?t:void 0}cleanBreadcrumb(e,t){if(!e||typeof e!="object")return;let r=t??s(e,"occurredAt");if(typeof r!="string")return;try{if(new Date(r).toISOString()!==r)return}catch{return}let i=s(e,"category"),o=s(e,"message");if(i!==void 0&&typeof i!="string"||typeof o!="string")return;let c=this.cleanText(i??(t?"manual":""),k.category),l=this.cleanText(o,k.message);if(!c.trim()||!l.trim())return;let d=s(e,"data"),a={};if(d&&typeof d=="object"){let p;try{p=Object.keys(d)}catch{p=[]}for(let h of p){if(Object.keys(a).length>=k.dataKeys)break;if(H.test(h))continue;let f=this.cleanText(h,k.dataKey),g=s(d,h);typeof g=="string"?a[f]=this.cleanText(g,k.dataString):(typeof g=="number"&&Number.isFinite(g)||typeof g=="boolean"||g===null)&&(a[f]=g)}}return{occurredAt:r,category:c,message:l,...Object.keys(a).length?{data:a}:{}}}boundBreadcrumbs(e){for(;e.length>k.count||B(JSON.stringify(e))>k.bytes;)e.shift()}cleanBreadcrumbTrail(e){let t;try{if(!Array.isArray(e))return;t=e.length}catch{return}if(!Number.isSafeInteger(t)||t<0)return;let r=[];for(let i=Math.max(0,t-k.count);i<t;i++){let o=this.cleanBreadcrumb(s(e,i));o&&(r.push(o),this.boundBreadcrumbs(r))}return r.length?r:void 0}cleanNetwork(e){if(!e||typeof e!="object")return;let t=s(e,"status"),r=typeof t=="number"&&Number.isInteger(t)&&t>=100&&t<=599?t:void 0;return{method:this.cleanText(s(e,"method")??"GET",16).toUpperCase(),url:this.cleanUrl(s(e,"url")??""),...r===void 0?{}:{status:r},durationMs:T(s(e,"durationMs"),0,36e5,0)}}makeEvent(e,t,r={}){let i=s(navigator,"userAgent"),o=this.cleanContext(r.context),c;try{c=this.options.getContext?.()}catch{throw new O("Context resolver failed")}let l=this.cleanContext(c),d=this.cleanContext(this.options.context),a=o;if(l||d){a={...o};for(let h of[l,d])if(h)for(let f of Object.keys(h)){if(Object.keys(a).length>=12)break;Object.prototype.hasOwnProperty.call(a,f)||(a[f]=h[f])}}let p=this.cleanNetwork(r.network);return{schemaVersion:1,eventId:V(),project:this.cleanText(this.options.project,80),environment:this.cleanText(this.options.environment??"development",80),release:this.cleanText(this.options.release??"unknown",120),sdkVersion:"0.1.20",occurredAt:new Date().toISOString(),viewId:this.viewId,sequence:++this.sequence,elapsedMs:T(S()-this.startedAt,0,36e5,0),type:e,message:this.cleanText(t,1024),...r.name===void 0?{}:{name:this.cleanText(r.name,100)},...r.stack===void 0?{}:{stack:this.cleanText(r.stack,4096)},...r.componentStack===void 0?{}:{componentStack:this.cleanText(r.componentStack,2048)},page:this.cleanUrl(window.location.href),runtime:z.has(this.options.runtime)?this.options.runtime:"browser",...typeof i=="string"?{browser:this.cleanText(i,300)}:{},...a?{context:a}:{},...this.breadcrumbs.length?{breadcrumbs:this.breadcrumbs.map(h=>({...h,...h.data?{data:{...h.data}}:{}}))}:{},...p?{network:p}:{}}}sanitizeReplacement(e,t){let r=s(e,"type"),i=s(e,"runtime"),o=s(e,"name"),c=s(e,"stack"),l=s(e,"componentStack"),d=s(e,"browser"),a=this.cleanContext(s(e,"context")),p=this.cleanBreadcrumbTrail(s(e,"breadcrumbs")),h=this.cleanNetwork(s(e,"network"));return{...t,type:F.has(r)?r:t.type,message:this.cleanText(s(e,"message")??t.message,1024),...o===void 0?{name:t.name}:{name:this.cleanText(o,100)},...c===void 0?{stack:t.stack}:{stack:this.cleanText(c,4096)},...l===void 0?{componentStack:t.componentStack}:{componentStack:this.cleanText(l,2048)},page:this.cleanUrl(s(e,"page")??t.page),runtime:z.has(i)?i:t.runtime,...d===void 0?{browser:t.browser}:{browser:this.cleanText(d,300)},...a?{context:a}:{context:void 0},...p?{breadcrumbs:p}:{breadcrumbs:void 0},...h?{network:h}:{network:void 0}}}admissionTime(){let e=S(),t=Number.isFinite(e)?Math.max(0,e,this.lastAdmissionClock??0):this.lastAdmissionClock??0;for(this.lastAdmissionClock=t;this.admittedAt.length&&t-this.admittedAt[0]>=6e4;)this.admittedAt.shift();return this.admittedAt.length<this.maxEventsPerMinute?t:void 0}enqueue(e){if(this.destroyed)return!1;if(this.maxEventsPerMinute!==void 0&&this.admissionTime()===void 0)return this.recordDrop("rateLimit"),!1;let t=e;if(this.options.beforeSend)try{let i={...e,context:e.context&&{...e.context},breadcrumbs:e.breadcrumbs?.map(c=>({...c,data:c.data&&{...c.data}})),network:e.network&&{...e.network}},o=this.options.beforeSend(i);if(o===!1||o===null)return this.filtered++,!1;t=this.sanitizeReplacement(o===void 0?i:o,e)}catch{return this.recordDrop("processingError"),!1}if(B(JSON.stringify(t))>_)return this.recordDrop("payloadTooLarge"),!1;let r=this.maxEventsPerMinute===void 0?void 0:this.admissionTime();return this.maxEventsPerMinute!==void 0&&r===void 0?(this.recordDrop("rateLimit"),!1):(this.queue.length>=this.maxQueueSize&&(this.queue.shift(),this.recordDrop("queueOverflow")),this.queue.push(t),r!==void 0&&this.admittedAt.push(r),this.queue.length>=this.maxQueueSize&&this.flush(),!0)}takeBatch(e=ee,t=_){let r=[],i=B('{"schemaVersion":1,"events":[]}');for(;this.queue.length&&r.length<e;){let o=this.queue[0],c=B(JSON.stringify(o))+(r.length?1:0);if(r.length&&i+c>t)break;if(!r.length&&i+c>t){this.queue.shift(),this.recordDrop("payloadTooLarge");continue}r.push(this.queue.shift()),i+=c}return{schemaVersion:1,events:r}}async drain(){for(;!this.destroyed&&this.queue.length;){let e=this.takeBatch();if(e.events.length){this.inFlight+=e.events.length;try{await this.sendWithRetry(e)}finally{this.inFlight-=e.events.length}}}}async sendWithRetry(e){for(let t=0;t<=M.length&&!this.destroyed;t++){let r=new AbortController;this.controllers.add(r);let i,o=new Promise((l,d)=>{i=setTimeout(()=>{r.abort(),d(new Error("Collector transport timed out"))},this.transportTimeoutMs)}),c;try{if(await Promise.race([this.send(e,r.signal),o,this.destroySignal])===X||this.destroyed)return;this.sent+=e.events.length;return}catch(l){if(this.destroyed)return;let d=s(l,"status");if(!(typeof d!="number"||d===429||d>=500)||t===M.length)break;c=M[t]}finally{i&&clearTimeout(i),this.controllers.delete(r)}c!==void 0&&await this.wait(c)}this.destroyed||this.recordDrop("deliveryError",e.events.length)}async send(e,t){if(this.options.transport){await this.options.transport(e,{signal:t});return}let r=await window.fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),credentials:"omit",signal:t});if(!r.ok)throw new I(r.status)}wait(e){return new Promise(t=>{let r=()=>{clearTimeout(i),this.cancelWaits.delete(r),t()},i=setTimeout(r,e);this.cancelWaits.add(r)})}tryBeacon(){if(!(this.destroyed||this.options.transport||!this.endpoint||!this.queue.length))try{let e=new URL(this.endpoint);if(e.origin!==window.location.origin||e.search||e.hash||e.username||e.password||typeof navigator.sendBeacon!="function")return;let t=this.queue.slice(0,te);for(;t.length>0;){let i=JSON.stringify({schemaVersion:1,events:t});if(B(i)<=re){navigator.sendBeacon(this.endpoint,new Blob([i],{type:"application/json"}))&&(this.queue.splice(0,t.length),this.sent+=t.length);return}t.pop()}}catch{}}},X=Symbol("destroyed"),L,A,N;function oe(n){N||(N=ae()),N?.clients.add(n)}function se(n){let e=N;e&&(e.clients.delete(n),e.clients.size||(e.cleanup(),N=void 0))}function K(n,e){let t=new Set,r=Object.getPrototypeOf(n);for(;r&&!t.has(r);){t.add(r);let i=Object.getOwnPropertyDescriptor(r,e);if(i)return i;r=Object.getPrototypeOf(r)}}function ae(){let n,e,t,r,i,o,c,l;try{if(n=window.history,e=window.location.href,i=Object.getOwnPropertyDescriptor(n,"pushState"),o=Object.getOwnPropertyDescriptor(n,"replaceState"),c=i?void 0:K(n,"pushState"),l=o?void 0:K(n,"replaceState"),i&&!("value"in i)||o&&!("value"in o)||!i&&(!c||!("value"in c)||c.writable!==!0)||!o&&(!l||!("value"in l)||l.writable!==!0)||(t=i?i.value:n.pushState,r=o?o.value:n.replaceState,typeof t!="function"||typeof r!="function"))return;let b=m=>m?m.configurable===!0||m.writable===!0:Object.isExtensible(n);if(!b(i)||!b(o))return}catch{return}let d=new Set,a=b=>{try{let m=window.location.href;if(m===e)return;let x=e;e=m;for(let v of d)try{v.reportNavigation(x,m,b)}catch{}}catch{}},p=function(...b){let m=Reflect.apply(t,this,b);return a("pushState"),m},h=function(...b){let m=Reflect.apply(r,this,b);return a("replaceState"),m},f=()=>{a("popstate")},g=()=>{a("hashchange")},y=(b,m,x)=>{try{let v=Object.getOwnPropertyDescriptor(n,b);if(!v||!("value"in v)||v.value!==m)return;x?Object.defineProperty(n,b,x):Reflect.deleteProperty(n,b)}catch{}},E=!1,R=!1;try{Object.defineProperty(n,"pushState",{configurable:i?.configurable??!0,enumerable:i?.enumerable??!1,writable:i?.writable??!0,value:p}),E=!0,Object.defineProperty(n,"replaceState",{configurable:o?.configurable??!0,enumerable:o?.enumerable??!1,writable:o?.writable??!0,value:h}),R=!0,window.addEventListener("popstate",f),window.addEventListener("hashchange",g)}catch{try{window.removeEventListener("hashchange",g)}catch{}try{window.removeEventListener("popstate",f)}catch{}R&&y("replaceState",h,o),E&&y("pushState",p,i);return}return{clients:d,cleanup(){try{window.removeEventListener("popstate",f)}catch{}try{window.removeEventListener("hashchange",g)}catch{}y("pushState",p,i),y("replaceState",h,o)}}}function ce(n){L||(L=le()),L.clients.add(n)}function ue(n){let e=L;e&&(e.clients.delete(n),e.clients.size||(e.cleanup(),L=void 0))}function de(n,e){let t;if(typeof Request<"u"&&n!==null&&typeof n=="object")if(n instanceof Request)t=s(n,"url");else try{t=Object.getOwnPropertyDescriptor(Request.prototype,"url")?.get?.call(n)}catch{}let r=s(e,"signal");return{url:t??w(n),method:w(s(e,"method")??(t===void 0?void 0:s(n,"method"))??"GET"),signal:r===void 0?t===void 0?void 0:s(n,"signal"):r}}function le(){let n=new Set,e=window.fetch,t;typeof e=="function"&&(t=function(...p){if(!n.size)return Reflect.apply(e,this,p);let h=S(),f;try{f=de(p[0],p[1])}catch{f={url:"",method:"GET"}}let g;try{g=Reflect.apply(e,this,p)}catch(y){if(!P(y,f.signal))for(let E of n)E.reportNetwork(f.method,f.url,void 0,S()-h,y);throw y}return g.then(y=>{try{let E=y.status;for(let R of n)R.reportNetwork(f.method,f.url,E,S()-h)}catch{}return y},y=>{if(!P(y,f.signal))for(let E of n)E.reportNetwork(f.method,f.url,void 0,S()-h,y);throw y})},window.fetch=t);let r=typeof XMLHttpRequest>"u"?void 0:XMLHttpRequest.prototype,i=r?.open,o=r?.send,c=new WeakMap,l=new WeakMap,d,a;return r&&i&&o&&(d=(function(...p){let h=Reflect.apply(i,this,p);l.get(this)?.();try{c.set(this,{method:w(p[0]),url:w(p[1])})}catch{}return h}),a=function(...p){if(!n.size)return Reflect.apply(o,this,p);let h=c.get(this);if(!h)return Reflect.apply(o,this,p);let f=S(),g=!1,y=!1,E=!1,R=()=>{g=!0},b=()=>{y=!0},m=()=>{this.removeEventListener("abort",R),this.removeEventListener("error",b),this.removeEventListener("timeout",b),this.removeEventListener("loadend",x),l.get(this)===m&&l.delete(this)},x=()=>{if(E=!0,m(),!g)try{let v=this.status;if(v===0&&!y){for(let j of n)j.reportZeroStatusCompletion(h.method,h.url,S()-f);return}for(let j of n)j.reportNetwork(h.method,h.url,v===0?void 0:v,S()-f)}catch{}};try{this.addEventListener("abort",R),this.addEventListener("error",b),this.addEventListener("timeout",b),this.addEventListener("loadend",x)}catch{return m(),Reflect.apply(o,this,p)}try{let v=Reflect.apply(o,this,p);return E||l.set(this,m),v}catch(v){throw m(),v}},r.open=d,r.send=a),{clients:n,cleanup(){t&&window.fetch===t&&(window.fetch=e),r&&d&&r.open===d&&(r.open=i),r&&a&&r.send===a&&(r.send=o)}}}function pe(n){A||(A=fe()),A.clients.add(n)}function he(n){let e=A;e&&(e.clients.delete(n),e.clients.size||(e.cleanup(),A=void 0))}function fe(){let n=new Set,e=console.error,t=function(...r){try{return Reflect.apply(e,this,r)}finally{for(let i of n)i.captureConsole(r)}};return console.error=t,{clients:n,cleanup(){console.error===t&&(console.error=e)}}}function me(n){return new U(n)}
2
2
  //# sourceMappingURL=index.cjs.map