@ihyeon/browser-error-log 0.2.1 → 0.2.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.
- package/README.ko.md +33 -1
- package/README.md +33 -1
- package/dist/index.cjs +4 -4
- package/dist/index.cjs.map +3 -3
- package/dist/index.d.ts +4 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -4
- package/dist/index.js.map +3 -3
- package/package.json +2 -2
package/README.ko.md
CHANGED
|
@@ -219,6 +219,38 @@ const errorLog = init({
|
|
|
219
219
|
|
|
220
220
|
한도는 현재 문서의 해당 클라이언트에 속하며 새 클라이언트나 전체 페이지 로드에서는 새로 시작합니다. 큐 진입 건수를 제한하므로 HTTP 요청 수·바이트·서버 전체 트래픽이나 이벤트 생성 작업량의 상한을 뜻하지는 않습니다. 수집기에는 별도의 서버 측 제한을 적용하세요.
|
|
221
221
|
|
|
222
|
+
## 같은 내용의 반복 오류 제한
|
|
223
|
+
|
|
224
|
+
```ts
|
|
225
|
+
const errorLog = init({
|
|
226
|
+
project: 'my-web',
|
|
227
|
+
endpoint: '/api/events',
|
|
228
|
+
dedupeIntervalMs: 5_000,
|
|
229
|
+
});
|
|
230
|
+
```
|
|
231
|
+
|
|
232
|
+
클라이언트가 설정 시간 안에 큐에 담은 이벤트와 최종 정제 내용이 같으면 새 이벤트를 제외하는 선택 옵션입니다. 기본값은 꺼짐이며 유한한 값은 소수점을 내리고 0~60,000ms로 조정합니다. 0·생략·숫자가 아닌 값·유한하지 않은 값은 제한을 끕니다. 유형·이름·메시지·스택·컴포넌트 스택·프로젝트·환경·릴리스·페이지·런타임·브라우저·키를 정렬한 단일 값 context·네트워크 메서드/URL/상태를 비교합니다. ID·시각·순서·경과 시간·작업 기록·요청 소요 시간은 비교에서 제외합니다. context의 리소스 URL이나 다른 비교 값이 다르면 별도로 수집합니다.
|
|
233
|
+
|
|
234
|
+
`beforeSend`와 크기 검사를 통과한 뒤 비교합니다. 기존 `maxEventsPerMinute`의 사전 검사는 먼저 실행하므로 한도가 가득 차면 `beforeSend`나 내용 비교 없이 분당 한도 초과로 집계합니다. 그 외 중복은 `getDiagnostics().deduplicated`에 한 번 반영하고 폐기 건수나 큐 진입 한도에 더하지 않으며 제한 시간을 연장하지 않습니다. `captureException`에서 같은 Error 객체를 클라이언트 수명 동안 제외하던 동작도 별도로 유지합니다.
|
|
235
|
+
|
|
236
|
+
클라이언트마다 정제된 비교 값을 메모리에 최대 50개 보관합니다. 이후 후보가 생길 때 만료를 확인하고, 한도에 닿으면 가장 오래 전에 담은 값을 제거합니다. flush·재시도·beacon 전송·작업 기록 정리는 이 버퍼를 초기화하지 않습니다. 큐에 담긴 이벤트가 나중에 밀려나거나 전송에 실패해도 설정 시간 동안 비교 기준으로 남으며 `destroy()`는 버퍼를 비웁니다. 서버에서 발생 횟수를 합치는 기능이 아니므로 수집 건수가 전체 발생 빈도를 뜻하지는 않습니다. 전송 필드 변경이나 수집기 갱신은 필요 없습니다.
|
|
237
|
+
|
|
238
|
+
## 오프라인 동안 큐 보관
|
|
239
|
+
|
|
240
|
+
```ts
|
|
241
|
+
const errorLog = init({
|
|
242
|
+
project: 'my-web',
|
|
243
|
+
endpoint: '/api/events',
|
|
244
|
+
pauseWhileOffline: true,
|
|
245
|
+
});
|
|
246
|
+
```
|
|
247
|
+
|
|
248
|
+
기본값은 꺼짐이며 초기화할 때 설정을 한 번 읽습니다. 옵션을 켜고 `navigator.onLine`이 정확히 `false`이면 새 전송 배치나 숨겨진 페이지의 beacon을 시작하지 않고 큐를 메모리에 보관합니다. 이 상태에서 시작한 flush는 큐를 보내거나 제거하지 않고 완료됩니다. 기본·사용자 지정 transport에 모두 적용합니다. 이미 시작한 배치는 기존 재시도와 시간 제한을 따르며 오프라인 전환으로 중단하거나 큐에 되돌리지 않습니다. 그 뒤의 큐 배치는 대기합니다.
|
|
249
|
+
|
|
250
|
+
브라우저의 `online` 이벤트가 발생하고 오프라인 표시가 해제되면 주기까지 기다리지 않고 전송합니다. 보관한 이벤트의 ID·발생 시각·context·작업 기록은 수집 당시 값을 유지합니다. 수집·`beforeSend`·큐 초과·분당 한도·중복 제외는 기존 동작을 따르고, 오프라인 대기 자체는 `dropped`에 더하지 않습니다. `destroy()`는 재연결 리스너를 제거하고 기존처럼 대기 이벤트를 폐기합니다.
|
|
251
|
+
|
|
252
|
+
브라우저의 연결 상태 표시만 쓰며 접속 확인 요청을 보내지 않습니다. 상태가 없거나 읽을 수 없으면 일반 전송을 허용합니다. [HTML 표준의 설명](https://html.spec.whatwg.org/multipage/system-state.html#navigator.online)처럼 온라인 표시는 인터넷이나 수집기 접속을 보장하지 않으므로 일반 전송 실패는 재시도를 소진할 수 있습니다. 메모리에만 보관하므로 큐 초과·새로고침·탭 종료·클라이언트 종료 시 유실될 수 있습니다. 전송 필드 변경이나 수집기 갱신은 필요 없습니다.
|
|
253
|
+
|
|
222
254
|
## SDK 수집·전송 진단
|
|
223
255
|
|
|
224
256
|
```ts
|
|
@@ -228,7 +260,7 @@ console.log(diagnostics.inFlight, diagnostics.filtered, diagnostics.deduplicated
|
|
|
228
260
|
console.table(diagnostics.droppedByReason);
|
|
229
261
|
```
|
|
230
262
|
|
|
231
|
-
`getDiagnostics()`는 기존 `queued`·`sent`·`dropped`에 `inFlight`(재시도 대기를 포함한 전송 배치 내 이벤트 수), `filtered`(`beforeSend`가 `false` 또는 `null`을 반환한 횟수), `deduplicated`(
|
|
263
|
+
`getDiagnostics()`는 기존 `queued`·`sent`·`dropped`에 `inFlight`(재시도 대기를 포함한 전송 배치 내 이벤트 수), `filtered`(`beforeSend`가 `false` 또는 `null`을 반환한 횟수), `deduplicated`(동일 객체 및 선택적인 시간 구간 내 내용 중복 제외 횟수)와 다음 원인별 건수를 더해 반환합니다.
|
|
232
264
|
|
|
233
265
|
| `droppedByReason` 키 | 집계하는 이벤트 |
|
|
234
266
|
| --- | --- |
|
package/README.md
CHANGED
|
@@ -219,6 +219,38 @@ Flushing an empty queue does not reset the budget. Retries and beacon delivery r
|
|
|
219
219
|
|
|
220
220
|
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.
|
|
221
221
|
|
|
222
|
+
## Suppress repeated equivalent errors
|
|
223
|
+
|
|
224
|
+
```ts
|
|
225
|
+
const errorLog = init({
|
|
226
|
+
project: 'my-web',
|
|
227
|
+
endpoint: '/api/events',
|
|
228
|
+
dedupeIntervalMs: 5_000,
|
|
229
|
+
});
|
|
230
|
+
```
|
|
231
|
+
|
|
232
|
+
This optional setting suppresses new events whose final sanitized content matches an event admitted by this client within the interval. It is off by default. Finite values are rounded down and clamped to 0–60,000 ms; zero, omitted, non-number, and non-finite values disable it. The SDK compares type, name, message, stack, component stack, project, environment, release, page, runtime, browser, sorted scalar context, and network method/URL/status. IDs, timestamps, sequence, elapsed time, breadcrumbs, and request duration do not distinguish equivalent events. Different resource URLs in context or other compared context values remain separate.
|
|
233
|
+
|
|
234
|
+
Matching happens after `beforeSend` and the payload-size check. The existing early `maxEventsPerMinute` gate still runs first: when it is full, the candidate counts as a rate-limit drop without running `beforeSend` or value comparison. Otherwise, suppressing a match increments `getDiagnostics().deduplicated` once, does not count as dropped or consume admission capacity, and does not extend the interval. The same Error object's existing lifetime suppression in `captureException` remains independent of this option.
|
|
235
|
+
|
|
236
|
+
Each client retains at most 50 sanitized fingerprints in memory. Expiration is checked lazily on later candidates; the oldest admitted fingerprints are evicted at capacity. Flush, retries, beacon delivery, and breadcrumb cleanup do not reset the cache. An admitted event remains a reference during its interval even if it is later evicted from the queue or fails delivery. `destroy()` clears the cache. This reduces captured occurrences rather than aggregating them on the server; captured counts are not the full occurrence frequency. The option changes no wire fields and needs no collector upgrade.
|
|
237
|
+
|
|
238
|
+
## Keep queued errors while offline
|
|
239
|
+
|
|
240
|
+
```ts
|
|
241
|
+
const errorLog = init({
|
|
242
|
+
project: 'my-web',
|
|
243
|
+
endpoint: '/api/events',
|
|
244
|
+
pauseWhileOffline: true,
|
|
245
|
+
});
|
|
246
|
+
```
|
|
247
|
+
|
|
248
|
+
This option is off by default and is read once at initialization. When enabled and `navigator.onLine` is exactly `false`, the SDK keeps queued events in memory instead of starting another delivery batch or hidden-page beacon. A flush started in that state resolves without sending or removing queued events. Both the default and custom transports follow this gate. An already active batch, including its retries and timeout, continues under the existing delivery policy; going offline does not abort or requeue it. Later queued batches wait.
|
|
249
|
+
|
|
250
|
+
The browser's `online` event starts a flush when it no longer reports offline, without waiting for the interval. Pending events keep their original IDs, timestamps, context, and breadcrumb snapshots. Collection, `beforeSend`, queue overflow, rate limits, and deduplication keep their usual behavior; merely waiting offline does not increase `dropped`. `destroy()` removes the reconnect listener and discards pending events as usual.
|
|
251
|
+
|
|
252
|
+
This uses only the browser's connectivity hint and sends no reachability probes. Missing or unreadable status permits normal delivery. As the [HTML standard explains](https://html.spec.whatwg.org/multipage/system-state.html#navigator.online), online status does not prove Internet or collector access, so ordinary delivery failures can still exhaust retries. Storage remains memory-only: queue overflow, page reload/closure, or destruction can lose events. No wire fields or collector upgrade are required.
|
|
253
|
+
|
|
222
254
|
## Inspect SDK collection and delivery
|
|
223
255
|
|
|
224
256
|
```ts
|
|
@@ -228,7 +260,7 @@ console.log(diagnostics.inFlight, diagnostics.filtered, diagnostics.deduplicated
|
|
|
228
260
|
console.table(diagnostics.droppedByReason);
|
|
229
261
|
```
|
|
230
262
|
|
|
231
|
-
`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` (
|
|
263
|
+
`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` (same-object suppression and optional interval-based suppression), and these drop reasons:
|
|
232
264
|
|
|
233
265
|
| `droppedByReason` key | Events counted |
|
|
234
266
|
| --- | --- |
|
package/dist/index.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
"use strict";var P=Object.defineProperty;var W=Object.getOwnPropertyDescriptor;var K=Object.getOwnPropertyNames;var J=Object.prototype.hasOwnProperty;var Y=(o,e,t)=>e in o?P(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t;var Z=(o,e)=>{for(var t in e)P(o,t,{get:e[t],enumerable:!0})},G=(o,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of K(e))!J.call(o,n)&&n!==t&&P(o,n,{get:()=>e[n],enumerable:!(r=W(e,n))||r.enumerable});return o};var Q=o=>G(P({},"__esModule",{value:!0}),o);var h=(o,e,t)=>Y(o,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,U=48e3,te=10,re=24e3,M=[250,500],_=/(?:password|passwd|token|secret|authorization|cookie|session|api.?key|credential|bearer|private.?key)/i,F=new Set(["javascript","promise","react","console","http","network","manual","resource"]),H=new Set(["browser","webview-ios","webview-android","unknown"]),ne=0;function s(o,e){try{return o==null?void 0:Reflect.get(Object(o),e)}catch{return}}function w(o){try{return String(o)}catch{return"[unavailable]"}}function oe(o,e){return w(o).slice(0,e)}function S(){try{return performance.now()}catch{return Date.now()}}function z(){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 j(o,e){try{if(e?.aborted)return!0}catch{}return s(o,"name")==="AbortError"||s(o,"code")===20}function $(o){if(o==null)return{message:"Unknown error"};let e=s(o,"message"),t=s(o,"name"),r=s(o,"stack");return{message:e==null?w(o):w(e),...t==null?{}:{name:w(t)},...r==null?{}:{stack:w(r)}}}function C(o){return new TextEncoder().encode(o).length}function T(o,e,t,r){return typeof o=="number"&&Number.isFinite(o)?Math.min(t,Math.max(e,Math.floor(o))):r}var I=class extends Error{constructor(t){super(`Collector responded ${t}`);h(this,"status",t)}},R=class extends Error{},L=class extends Error{},q=class{constructor(e){h(this,"active");h(this,"endpoint");h(this,"options");h(this,"networkCaptureEnabled");h(this,"networkBreadcrumbCaptureEnabled");h(this,"navigationCaptureEnabled");h(this,"captureErrorCause");h(this,"resourceCaptureEnabled");h(this,"transportTimeoutMs");h(this,"startedAt",S());h(this,"viewId",z());h(this,"seenErrors",new WeakSet);h(this,"queue",[]);h(this,"breadcrumbs",[]);h(this,"recordingBreadcrumb",!1);h(this,"maxQueueSize");h(this,"maxEventsPerMinute");h(this,"admittedAt",[]);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,"filtered",0);h(this,"deduplicated",0);h(this,"droppedByReason",{rateLimit:0,queueOverflow:0,payloadTooLarge:0,processingError:0,deliveryError:0,destroyed:0});h(this,"destroyed",!1);h(this,"lastAdmissionClock");h(this,"onError",e=>{try{if(!(s(e,"target")instanceof Window))return;let t=s(e,"filename"),r=s(e,"lineno"),n=s(e,"colno"),i={};typeof t=="string"&&t.trim()&&(i.filename=this.cleanUrl(t)),typeof r=="number"&&Number.isFinite(r)&&r>0&&(i.lineno=r),typeof n=="number"&&Number.isFinite(n)&&n>0&&(i.colno=n),this.captureException(s(e,"error")??s(e,"message")??"Script error",{type:"javascript",...Object.keys(i).length?{context:i}:{}})}catch{this.recordDrop("processingError")}});h(this,"onResourceError",e=>{if(!(this.destroyed||!this.active))try{let t=s(e,"target");if(s(t,"ownerDocument")!==document||!document.contains(t)||s(t,"namespaceURI")!=="http://www.w3.org/1999/xhtml")return;let r=s(t,"localName");if(r!=="script"&&r!=="link"&&r!=="img")return;let n=s(t,"getAttribute");if(typeof n!="function")return;let i=c=>{try{return Reflect.apply(n,t,[c])}catch{return}},d=r,l;if(d==="script"){let c=i("src");if(typeof c!="string"||!c.trim())return;l=s(t,"src")}else if(d==="link"){let c=s(t,"rel");if(typeof c!="string"||!c.split(/\s+/).some(m=>m.toLowerCase()==="stylesheet"))return;let f=i("href");if(typeof f!="string"||!f.trim())return;l=s(t,"href")}else{let c=s(t,"currentSrc");if(typeof c=="string"&&c.trim())l=c;else{let f=i("src");if(typeof f!="string"||!f.trim())return;l=s(t,"src")}}if(typeof l!="string"||!l.trim())return;let a;try{a=new URL(l,window.location.href)}catch{return}if(a.protocol!=="http:"&&a.protocol!=="https:"||this.isCollectorUrl(a.href))return;let u=this.cleanUrl(a.href),p;try{p=new URL(u)}catch{throw new R("Invalid resource URL")}if(p.protocol!=="http:"&&p.protocol!=="https:"||p.username||p.password||p.search||p.hash)throw new R("Unsafe resource URL");this.enqueue(this.makeEvent("resource",`Failed to load ${d} resource`,{name:"ResourceLoadError",context:{resourceTag:d,resourceUrl:u}}))}catch(t){(t instanceof R||t instanceof L)&&this.recordDrop("processingError")}});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 t=!e.transport||!!e.endpoint;if(this.networkCaptureEnabled=e.captureNetwork!==!1&&t,this.networkBreadcrumbCaptureEnabled=e.captureNetworkBreadcrumbs===!0&&t,this.navigationCaptureEnabled=e.captureNavigation===!0,this.captureErrorCause=e.captureErrorCause===!0,this.resourceCaptureEnabled=e.captureResourceErrors===!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),this.resourceCaptureEnabled&&window.addEventListener("error",this.onResourceError,!0),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()},T(e.flushIntervalMs,10,6e4,1e4))}}captureException(e,t={}){if(!(!this.active||this.destroyed||j(e)))try{if(e!==null&&(typeof e=="object"||typeof e=="function")&&this.seenErrors.has(e)){this.deduplicated++;return}let r=this.exceptionFields(e),n=F.has(t.type)?t.type:"manual",i=this.makeEvent(n,r.message,{name:r.name,stack:r.stack,componentStack:t.componentStack,context:t.context});this.enqueue(i)&&e!==null&&(typeof e=="object"||typeof e=="function")&&this.seenErrors.add(e)}catch(r){(r instanceof R||r instanceof L)&&this.recordDrop("processingError")}}reportNetwork(e,t,r,n,i,d=!0){if(this.destroyed||!this.active||this.isCollectorUrl(t)||j(i))return;let l=this.networkCaptureEnabled&&d;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 a=this.cleanBreadcrumbUrl(t);if(a.url){let u={method:this.cleanNetworkBreadcrumbMethod(e),url:a.url,durationMs:T(n,0,36e5,0)};r!==void 0&&Number.isInteger(r)&&r>=0&&r<=599&&(u.status=r),this.appendBreadcrumb({occurredAt:new Date().toISOString(),category:r===void 0?"network":"http",message:r===void 0?"Network failure":"HTTP response",data:u})}else if(l&&!a.safeForError){this.recordDrop("processingError");return}}catch{l&&this.recordDrop("processingError");return}if(l)try{let a={method:oe(e||"GET",16).toUpperCase(),url:t,status:r,durationMs:n},u=i===void 0?void 0:$(i),p=this.makeEvent(r===void 0?"network":"http",r===void 0?u?.message||"Network request failed":`HTTP ${r}`,{name:u?.name,network:a});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 n of e){let i=!1;try{i=n instanceof Error}catch{}if(i){r=this.exceptionFields(n);break}}this.enqueue(this.makeEvent("console",t,{name:r?.name,stack:r?.stack}))}catch{this.recordDrop("processingError")}}addBreadcrumb(e){if(!(!this.active||this.destroyed||this.recordingBreadcrumb))try{let t=this.cleanBreadcrumb(e,new Date().toISOString());if(!t)return;this.appendBreadcrumb(t)}catch{}}appendBreadcrumb(e){if(!(this.recordingBreadcrumb||this.destroyed)){if(!this.options.beforeBreadcrumb){this.breadcrumbs.push(e),this.boundBreadcrumbs(this.breadcrumbs);return}this.recordingBreadcrumb=!0;try{let t={...e,...e.data?{data:{...e.data}}:{}},r=this.options.beforeBreadcrumb(t);if(r===!1||r===null)return;let n=this.cleanBreadcrumb(r===void 0?t:r,e.occurredAt);if(!n||this.destroyed)return;this.breadcrumbs.push(n),this.boundBreadcrumbs(this.breadcrumbs)}catch{}finally{this.recordingBreadcrumb=!1}}}reportNavigation(e,t,r){if(!(!this.active||this.destroyed||!this.navigationCaptureEnabled))try{let n=this.cleanBreadcrumbUrl(e).url,i=this.cleanBreadcrumbUrl(t).url;if(!n||!i||n===i)return;this.appendBreadcrumb({occurredAt:new Date().toISOString(),category:"navigation",message:"Navigation",data:{from:n,to:i,trigger:r}})}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),this.resourceCaptureEnabled&&window.removeEventListener("error",this.onResourceError,!0),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(V)}}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 R("URL sanitizer failed")}if(typeof t!="string"||!t)throw new R("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 n=w(e);return r&&(n=n.replace(/https?:\/\/[^\s<>"'()[\]]+/gi,i=>this.cleanUrl(i)),n=n.replace(/(^|[\s"'(\[=])((?:\/(?!\/)|\.{1,2}\/)[^\s<>"'()[\]?#]*[?#][^\s<>"'()[\]]+|[a-z][\w.-]*(?:\/[^\s<>"'()[\]?#]*)?(?:\?[a-z0-9_.-]+=[^\s<>"'()[\]]+|#[^\s<>"'()[\]]+)|\?[a-z0-9_.-]+=[^\s<>"'()[\]]+)/gi,(i,d,l)=>{let a=/[.,;!]+$/.exec(l)?.[0]??"",u=l.slice(0,l.length-a.length),p=this.options.sanitizeUrl?this.cleanUrl(u):u.startsWith("?")?"[redacted query]":this.cleanText(u.split(/[?#]/,1)[0],1024,!1);return`${d}${p}${a}`})),n.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)}exceptionFields(e){let t=$(e);if(!this.captureErrorCause||e===null||typeof e!="object"&&typeof e!="function")return t;let r=new WeakSet([e]),n=[],i=e;for(let l=0;l<4;l++){let a=s(i,"cause");if(a===null||typeof a!="object"&&typeof a!="function"||r.has(a))break;r.add(a);let u=s(a,"message"),p=s(a,"stack");if(typeof u!="string"&&typeof p!="string")break;let c=s(a,"name"),f=this.cleanText(typeof c=="string"?c:"Error",100),m=typeof u=="string"?this.cleanText(u,256):"",g=typeof p=="string"?this.cleanText(p,480):"";n.push(`Caused by: ${f}: ${m}${g?`
|
|
2
|
-
${g}`:""}`.slice(0,480)),
|
|
3
|
-
${
|
|
4
|
-
`)}`}}cleanContext(e){if(!e||typeof e!="object")return;let t={},r;try{r=Object.keys(e)}catch{return}for(let n of r){if(Object.keys(t).length>=12)break;if(_.test(n))continue;let i=s(e,n),d=this.cleanText(n,80);typeof i=="string"?t[d]=this.cleanText(i,500):(typeof i=="number"&&Number.isFinite(i)||typeof i=="boolean"||i===null)&&(t[d]=i)}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 n=s(e,"category"),i=s(e,"message");if(n!==void 0&&typeof n!="string"||typeof i!="string")return;let d=this.cleanText(n??(t?"manual":""),k.category),l=this.cleanText(i,k.message);if(!d.trim()||!l.trim())return;let a=s(e,"data"),u={};if(a&&typeof a=="object"){let p;try{p=Object.keys(a)}catch{p=[]}for(let c of p){if(Object.keys(u).length>=k.dataKeys)break;if(_.test(c))continue;let f=this.cleanText(c,k.dataKey),m=s(a,c);typeof m=="string"?u[f]=this.cleanText(m,k.dataString):(typeof m=="number"&&Number.isFinite(m)||typeof m=="boolean"||m===null)&&(u[f]=m)}}return{occurredAt:r,category:d,message:l,...Object.keys(u).length?{data:u}:{}}}boundBreadcrumbs(e){for(;e.length>k.count||C(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 n=Math.max(0,t-k.count);n<t;n++){let i=this.cleanBreadcrumb(s(e,n));i&&(r.push(i),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 n=s(navigator,"userAgent"),i=this.cleanContext(r.context),d;try{d=this.options.getContext?.()}catch{throw new L("Context resolver failed")}let l=this.cleanContext(d),a=this.cleanContext(this.options.context),u=i;if(l||a){u={...i};for(let c of[l,a])if(c)for(let f of Object.keys(c)){if(Object.keys(u).length>=12)break;Object.prototype.hasOwnProperty.call(u,f)||(u[f]=c[f])}}let p=this.cleanNetwork(r.network);return{schemaVersion:1,eventId:z(),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.2.1",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:H.has(this.options.runtime)?this.options.runtime:"browser",...typeof n=="string"?{browser:this.cleanText(n,300)}:{},...u?{context:u}:{},...this.breadcrumbs.length?{breadcrumbs:this.breadcrumbs.map(c=>({...c,...c.data?{data:{...c.data}}:{}}))}:{},...p?{network:p}:{}}}sanitizeReplacement(e,t){let r=s(e,"type"),n=s(e,"runtime"),i=s(e,"name"),d=s(e,"stack"),l=s(e,"componentStack"),a=s(e,"browser"),u=this.cleanContext(s(e,"context")),p=this.cleanBreadcrumbTrail(s(e,"breadcrumbs")),c=this.cleanNetwork(s(e,"network"));return{...t,type:F.has(r)?r:t.type,message:this.cleanText(s(e,"message")??t.message,1024),...i===void 0?{name:t.name}:{name:this.cleanText(i,100)},...d===void 0?{stack:void 0}:{stack:this.cleanText(d,4096)},...l===void 0?{componentStack:t.componentStack}:{componentStack:this.cleanText(l,2048)},page:this.cleanUrl(s(e,"page")??t.page),runtime:H.has(n)?n:t.runtime,...a===void 0?{browser:t.browser}:{browser:this.cleanText(a,300)},...u?{context:u}:{context:void 0},...p?{breadcrumbs:p}:{breadcrumbs:void 0},...c?{network:c}:{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 n={...e,context:e.context&&{...e.context},breadcrumbs:e.breadcrumbs?.map(d=>({...d,data:d.data&&{...d.data}})),network:e.network&&{...e.network}},i=this.options.beforeSend(n);if(i===!1||i===null)return this.filtered++,!1;t=this.sanitizeReplacement(i===void 0?n:i,e)}catch{return this.recordDrop("processingError"),!1}if(C(JSON.stringify(t))>U)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=U){let r=[],n=C('{"schemaVersion":1,"events":[]}');for(;this.queue.length&&r.length<e;){let i=this.queue[0],d=C(JSON.stringify(i))+(r.length?1:0);if(r.length&&n+d>t)break;if(!r.length&&n+d>t){this.queue.shift(),this.recordDrop("payloadTooLarge");continue}r.push(this.queue.shift()),n+=d}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 n,i=new Promise((l,a)=>{n=setTimeout(()=>{r.abort(),a(new Error("Collector transport timed out"))},this.transportTimeoutMs)}),d;try{if(await Promise.race([this.send(e,r.signal),i,this.destroySignal])===V||this.destroyed)return;this.sent+=e.events.length;return}catch(l){if(this.destroyed)return;let a=s(l,"status");if(!(typeof a!="number"||a===429||a>=500)||t===M.length)break;d=M[t]}finally{n&&clearTimeout(n),this.controllers.delete(r)}d!==void 0&&await this.wait(d)}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(n),this.cancelWaits.delete(r),t()},n=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 n=JSON.stringify({schemaVersion:1,events:t});if(C(n)<=re){navigator.sendBeacon(this.endpoint,new Blob([n],{type:"application/json"}))&&(this.queue.splice(0,t.length),this.sent+=t.length);return}t.pop()}}catch{}}},V=Symbol("destroyed"),A,N,D;function ie(o){D||(D=ae()),D?.clients.add(o)}function se(o){let e=D;e&&(e.clients.delete(o),e.clients.size||(e.cleanup(),D=void 0))}function X(o,e){let t=new Set,r=Object.getPrototypeOf(o);for(;r&&!t.has(r);){t.add(r);let n=Object.getOwnPropertyDescriptor(r,e);if(n)return n;r=Object.getPrototypeOf(r)}}function ae(){let o,e,t,r,n,i,d,l;try{if(o=window.history,e=window.location.href,n=Object.getOwnPropertyDescriptor(o,"pushState"),i=Object.getOwnPropertyDescriptor(o,"replaceState"),d=n?void 0:X(o,"pushState"),l=i?void 0:X(o,"replaceState"),n&&!("value"in n)||i&&!("value"in i)||!n&&(!d||!("value"in d)||d.writable!==!0)||!i&&(!l||!("value"in l)||l.writable!==!0)||(t=n?n.value:o.pushState,r=i?i.value:o.replaceState,typeof t!="function"||typeof r!="function"))return;let b=y=>y?y.configurable===!0||y.writable===!0:Object.isExtensible(o);if(!b(n)||!b(i))return}catch{return}let a=new Set,u=b=>{try{let y=window.location.href;if(y===e)return;let B=e;e=y;for(let v of a)try{v.reportNavigation(B,y,b)}catch{}}catch{}},p=function(...b){let y=Reflect.apply(t,this,b);return u("pushState"),y},c=function(...b){let y=Reflect.apply(r,this,b);return u("replaceState"),y},f=()=>{u("popstate")},m=()=>{u("hashchange")},g=(b,y,B)=>{try{let v=Object.getOwnPropertyDescriptor(o,b);if(!v||!("value"in v)||v.value!==y)return;B?Object.defineProperty(o,b,B):Reflect.deleteProperty(o,b)}catch{}},E=!1,x=!1;try{Object.defineProperty(o,"pushState",{configurable:n?.configurable??!0,enumerable:n?.enumerable??!1,writable:n?.writable??!0,value:p}),E=!0,Object.defineProperty(o,"replaceState",{configurable:i?.configurable??!0,enumerable:i?.enumerable??!1,writable:i?.writable??!0,value:c}),x=!0,window.addEventListener("popstate",f),window.addEventListener("hashchange",m)}catch{try{window.removeEventListener("hashchange",m)}catch{}try{window.removeEventListener("popstate",f)}catch{}x&&g("replaceState",c,i),E&&g("pushState",p,n);return}return{clients:a,cleanup(){try{window.removeEventListener("popstate",f)}catch{}try{window.removeEventListener("hashchange",m)}catch{}g("pushState",p,n),g("replaceState",c,i)}}}function ce(o){A||(A=le()),A.clients.add(o)}function ue(o){let e=A;e&&(e.clients.delete(o),e.clients.size||(e.cleanup(),A=void 0))}function de(o,e){let t;if(typeof Request<"u"&&o!==null&&typeof o=="object")if(o instanceof Request)t=s(o,"url");else try{t=Object.getOwnPropertyDescriptor(Request.prototype,"url")?.get?.call(o)}catch{}let r=s(e,"signal");return{url:t??w(o),method:w(s(e,"method")??(t===void 0?void 0:s(o,"method"))??"GET"),signal:r===void 0?t===void 0?void 0:s(o,"signal"):r}}function le(){let o=new Set,e=window.fetch,t;typeof e=="function"&&(t=function(...p){if(!o.size)return Reflect.apply(e,this,p);let c=S(),f;try{f=de(p[0],p[1])}catch{f={url:"",method:"GET"}}let m;try{m=Reflect.apply(e,this,p)}catch(g){if(!j(g,f.signal))for(let E of o)E.reportNetwork(f.method,f.url,void 0,S()-c,g);throw g}return m.then(g=>{try{let E=g.status;for(let x of o)x.reportNetwork(f.method,f.url,E,S()-c)}catch{}return g},g=>{if(!j(g,f.signal))for(let E of o)E.reportNetwork(f.method,f.url,void 0,S()-c,g);throw g})},window.fetch=t);let r=typeof XMLHttpRequest>"u"?void 0:XMLHttpRequest.prototype,n=r?.open,i=r?.send,d=new WeakMap,l=new WeakMap,a,u;return r&&n&&i&&(a=(function(...p){let c=Reflect.apply(n,this,p);l.get(this)?.();try{d.set(this,{method:w(p[0]),url:w(p[1])})}catch{}return c}),u=function(...p){if(!o.size)return Reflect.apply(i,this,p);let c=d.get(this);if(!c)return Reflect.apply(i,this,p);let f=S(),m=!1,g=!1,E=!1,x=()=>{m=!0},b=()=>{g=!0},y=()=>{this.removeEventListener("abort",x),this.removeEventListener("error",b),this.removeEventListener("timeout",b),this.removeEventListener("loadend",B),l.get(this)===y&&l.delete(this)},B=()=>{if(E=!0,y(),!m)try{let v=this.status;if(v===0&&!g){for(let O of o)O.reportZeroStatusCompletion(c.method,c.url,S()-f);return}for(let O of o)O.reportNetwork(c.method,c.url,v===0?void 0:v,S()-f)}catch{}};try{this.addEventListener("abort",x),this.addEventListener("error",b),this.addEventListener("timeout",b),this.addEventListener("loadend",B)}catch{return y(),Reflect.apply(i,this,p)}try{let v=Reflect.apply(i,this,p);return E||l.set(this,y),v}catch(v){throw y(),v}},r.open=a,r.send=u),{clients:o,cleanup(){t&&window.fetch===t&&(window.fetch=e),r&&a&&r.open===a&&(r.open=n),r&&u&&r.send===u&&(r.send=i)}}}function pe(o){N||(N=fe()),N.clients.add(o)}function he(o){let e=N;e&&(e.clients.delete(o),e.clients.size||(e.cleanup(),N=void 0))}function fe(){let o=new Set,e=console.error,t=function(...r){try{return Reflect.apply(e,this,r)}finally{for(let n of o)n.captureConsole(r)}};return console.error=t,{clients:o,cleanup(){console.error===t&&(console.error=e)}}}function me(o){return new q(o)}
|
|
1
|
+
"use strict";var N=Object.defineProperty;var X=Object.getOwnPropertyDescriptor;var K=Object.getOwnPropertyNames;var J=Object.prototype.hasOwnProperty;var Y=(n,e,t)=>e in n?N(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var Z=(n,e)=>{for(var t in e)N(n,t,{get:e[t],enumerable:!0})},G=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of K(e))!J.call(n,i)&&i!==t&&N(n,i,{get:()=>e[i],enumerable:!(r=X(e,i))||r.enumerable});return n};var Q=n=>G(N({},"__esModule",{value:!0}),n);var d=(n,e,t)=>Y(n,typeof e!="symbol"?e+"":e,t);var ye={};Z(ye,{init:()=>ge});module.exports=Q(ye);var S={count:20,bytes:12e3,category:40,message:256,dataKeys:6,dataKey:80,dataString:200};var ee=20,U=48e3,te=10,re=24e3,j=[250,500],F=/(?:password|passwd|token|secret|authorization|cookie|session|api.?key|credential|bearer|private.?key)/i,_=new Set(["javascript","promise","react","console","http","network","manual","resource"]),H=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 k(){try{return performance.now()}catch{return Date.now()}}function z(){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 $(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 T(n){return new TextEncoder().encode(n).length}function R(n,e,t,r){return typeof n=="number"&&Number.isFinite(n)?Math.min(t,Math.max(e,Math.floor(n))):r}function oe(n){return JSON.stringify([n.type,n.name??null,n.message,n.stack??null,n.componentStack??null,n.project,n.environment,n.release,n.page,n.runtime,n.browser??null,n.context===void 0?null:Object.keys(n.context).sort().map(e=>[e,n.context[e]]),n.network===void 0?null:[n.network.method,n.network.url,n.network.status??null]])}var I=class extends Error{constructor(t){super(`Collector responded ${t}`);d(this,"status",t)}},x=class extends Error{},L=class extends Error{},q=class{constructor(e){d(this,"active");d(this,"endpoint");d(this,"options");d(this,"networkCaptureEnabled");d(this,"networkBreadcrumbCaptureEnabled");d(this,"navigationCaptureEnabled");d(this,"captureErrorCause");d(this,"resourceCaptureEnabled");d(this,"pauseWhileOffline");d(this,"transportTimeoutMs");d(this,"startedAt",k());d(this,"viewId",z());d(this,"seenErrors",new WeakSet);d(this,"queue",[]);d(this,"breadcrumbs",[]);d(this,"recordingBreadcrumb",!1);d(this,"maxQueueSize");d(this,"maxEventsPerMinute");d(this,"dedupeIntervalMs");d(this,"dedupeCache",new Map);d(this,"lastDedupeClock");d(this,"admittedAt",[]);d(this,"cancelWaits",new Set);d(this,"controllers",new Set);d(this,"destroySignal");d(this,"resolveDestroy");d(this,"interval");d(this,"flushing");d(this,"onlineFlushRequested",!1);d(this,"sequence",0);d(this,"inFlight",0);d(this,"sent",0);d(this,"dropped",0);d(this,"filtered",0);d(this,"deduplicated",0);d(this,"droppedByReason",{rateLimit:0,queueOverflow:0,payloadTooLarge:0,processingError:0,deliveryError:0,destroyed:0});d(this,"destroyed",!1);d(this,"lastAdmissionClock");d(this,"onError",e=>{try{if(!(s(e,"target")instanceof Window))return;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")}});d(this,"onResourceError",e=>{if(!(this.destroyed||!this.active))try{let t=s(e,"target");if(s(t,"ownerDocument")!==document||!document.contains(t)||s(t,"namespaceURI")!=="http://www.w3.org/1999/xhtml")return;let r=s(t,"localName");if(r!=="script"&&r!=="link"&&r!=="img")return;let i=s(t,"getAttribute");if(typeof i!="function")return;let o=u=>{try{return Reflect.apply(i,t,[u])}catch{return}},l=r,c;if(l==="script"){let u=o("src");if(typeof u!="string"||!u.trim())return;c=s(t,"src")}else if(l==="link"){let u=s(t,"rel");if(typeof u!="string"||!u.split(/\s+/).some(m=>m.toLowerCase()==="stylesheet"))return;let f=o("href");if(typeof f!="string"||!f.trim())return;c=s(t,"href")}else{let u=s(t,"currentSrc");if(typeof u=="string"&&u.trim())c=u;else{let f=o("src");if(typeof f!="string"||!f.trim())return;c=s(t,"src")}}if(typeof c!="string"||!c.trim())return;let a;try{a=new URL(c,window.location.href)}catch{return}if(a.protocol!=="http:"&&a.protocol!=="https:"||this.isCollectorUrl(a.href))return;let p=this.cleanUrl(a.href),h;try{h=new URL(p)}catch{throw new x("Invalid resource URL")}if(h.protocol!=="http:"&&h.protocol!=="https:"||h.username||h.password||h.search||h.hash)throw new x("Unsafe resource URL");this.enqueue(this.makeEvent("resource",`Failed to load ${l} resource`,{name:"ResourceLoadError",context:{resourceTag:l,resourceUrl:p}}))}catch(t){(t instanceof x||t instanceof L)&&this.recordDrop("processingError")}});d(this,"onRejection",e=>{this.captureException(e.reason,{type:"promise"})});d(this,"onVisibility",()=>{document.visibilityState==="hidden"&&this.tryBeacon()});d(this,"onOnline",()=>{!this.active||this.destroyed||!this.queue.length||this.isExplicitlyOffline()||(this.flushing?this.onlineFlushRequested=!0:this.flush())});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.captureErrorCause=e.captureErrorCause===!0,this.resourceCaptureEnabled=e.captureResourceErrors===!0,this.pauseWhileOffline=e.pauseWhileOffline===!0,this.maxQueueSize=R(e.maxQueueSize,1,100,50),this.maxEventsPerMinute=typeof e.maxEventsPerMinute=="number"&&Number.isFinite(e.maxEventsPerMinute)?R(e.maxEventsPerMinute,1,1e3,1):void 0,this.dedupeIntervalMs=R(e.dedupeIntervalMs,0,6e4,0),this.transportTimeoutMs=R(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),this.resourceCaptureEnabled&&window.addEventListener("error",this.onResourceError,!0),window.addEventListener("unhandledrejection",this.onRejection),document.addEventListener("visibilitychange",this.onVisibility),this.pauseWhileOffline&&window.addEventListener("online",this.onOnline),(this.networkCaptureEnabled||this.networkBreadcrumbCaptureEnabled)&&ue(this),e.captureConsole===!0&&he(this),this.navigationCaptureEnabled&&se(this),this.interval=setInterval(()=>{this.flush()},R(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=this.exceptionFields(e),i=_.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 x||r instanceof L)&&this.recordDrop("processingError")}}reportNetwork(e,t,r,i,o,l=!0){if(this.destroyed||!this.active||this.isCollectorUrl(t)||P(o))return;let c=this.networkCaptureEnabled&&l;if(c&&r!==void 0)try{c=this.options.shouldCaptureHttp?this.options.shouldCaptureHttp(r,t,e):r>=500}catch{this.recordDrop("processingError");return}if(this.networkBreadcrumbCaptureEnabled)try{let a=this.cleanBreadcrumbUrl(t);if(a.url){let p={method:this.cleanNetworkBreadcrumbMethod(e),url:a.url,durationMs:R(i,0,36e5,0)};r!==void 0&&Number.isInteger(r)&&r>=0&&r<=599&&(p.status=r),this.appendBreadcrumb({occurredAt:new Date().toISOString(),category:r===void 0?"network":"http",message:r===void 0?"Network failure":"HTTP response",data:p})}else if(c&&!a.safeForError){this.recordDrop("processingError");return}}catch{c&&this.recordDrop("processingError");return}if(c)try{let a={method:ie(e||"GET",16).toUpperCase(),url:t,status:r,durationMs:i},p=o===void 0?void 0:$(o),h=this.makeEvent(r===void 0?"network":"http",r===void 0?p?.message||"Network request failed":`HTTP ${r}`,{name:p?.name,network:a});this.enqueue(h)}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){let o=!1;try{o=i instanceof Error}catch{}if(o){r=this.exceptionFields(i);break}}this.enqueue(this.makeEvent("console",t,{name:r?.name,stack:r?.stack}))}catch{this.recordDrop("processingError")}}addBreadcrumb(e){if(!(!this.active||this.destroyed||this.recordingBreadcrumb))try{let t=this.cleanBreadcrumb(e,new Date().toISOString());if(!t)return;this.appendBreadcrumb(t)}catch{}}appendBreadcrumb(e){if(!(this.recordingBreadcrumb||this.destroyed)){if(!this.options.beforeBreadcrumb){this.breadcrumbs.push(e),this.boundBreadcrumbs(this.breadcrumbs);return}this.recordingBreadcrumb=!0;try{let t={...e,...e.data?{data:{...e.data}}:{}},r=this.options.beforeBreadcrumb(t);if(r===!1||r===null)return;let i=this.cleanBreadcrumb(r===void 0?t:r,e.occurredAt);if(!i||this.destroyed)return;this.breadcrumbs.push(i),this.boundBreadcrumbs(this.breadcrumbs)}catch{}finally{this.recordingBreadcrumb=!1}}}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.appendBreadcrumb({occurredAt:new Date().toISOString(),category:"navigation",message:"Navigation",data:{from:i,to:o,trigger:r}})}catch{}}clearBreadcrumbs(){!this.active||this.destroyed||(this.breadcrumbs.length=0)}flush(){if(!this.active||this.destroyed)return Promise.resolve();if(this.flushing)return this.flushing;let e,t=new Promise(r=>{e=r});return this.flushing=t.finally(()=>{this.flushing=void 0,this.onlineFlushRequested&&(this.onlineFlushRequested=!1,!this.destroyed&&this.queue.length&&!this.isExplicitlyOffline()&&this.flush())}),e(this.drain()),this.flushing}destroy(){if(!this.destroyed){this.destroyed=!0,this.interval&&clearInterval(this.interval),this.active&&(window.removeEventListener("error",this.onError),this.resourceCaptureEnabled&&window.removeEventListener("error",this.onResourceError,!0),window.removeEventListener("unhandledrejection",this.onRejection),document.removeEventListener("visibilitychange",this.onVisibility),this.pauseWhileOffline&&window.removeEventListener("online",this.onOnline),(this.networkCaptureEnabled||this.networkBreadcrumbCaptureEnabled)&&de(this),this.options.captureConsole===!0&&fe(this),this.navigationCaptureEnabled&&ae(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,this.dedupeCache.clear(),this.lastDedupeClock=void 0;for(let e of this.cancelWaits)e();for(let e of this.controllers)e.abort();this.resolveDestroy(W)}}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}isExplicitlyOffline(){if(!this.pauseWhileOffline)return!1;try{return typeof navigator<"u"&&navigator.onLine===!1}catch{return!1}}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 x("URL sanitizer failed")}if(typeof t!="string"||!t)throw new x("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,S.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,l,c)=>{let a=/[.,;!]+$/.exec(c)?.[0]??"",p=c.slice(0,c.length-a.length),h=this.options.sanitizeUrl?this.cleanUrl(p):p.startsWith("?")?"[redacted query]":this.cleanText(p.split(/[?#]/,1)[0],1024,!1);return`${l}${h}${a}`})),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)}exceptionFields(e){let t=$(e);if(!this.captureErrorCause||e===null||typeof e!="object"&&typeof e!="function")return t;let r=new WeakSet([e]),i=[],o=e;for(let c=0;c<4;c++){let a=s(o,"cause");if(a===null||typeof a!="object"&&typeof a!="function"||r.has(a))break;r.add(a);let p=s(a,"message"),h=s(a,"stack");if(typeof p!="string"&&typeof h!="string")break;let u=s(a,"name"),f=this.cleanText(typeof u=="string"?u:"Error",100),m=typeof p=="string"?this.cleanText(p,256):"",g=typeof h=="string"?this.cleanText(h,480):"";i.push(`Caused by: ${f}: ${m}${g?`
|
|
2
|
+
${g}`:""}`.slice(0,480)),o=a}if(!i.length)return t;let l=t.stack===void 0?`${this.cleanText(t.name??"Error",100)}: ${this.cleanText(t.message,256)}`:this.cleanText(t.stack,2048);return{...t,stack:`${l}
|
|
3
|
+
${i.join(`
|
|
4
|
+
`)}`}}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(F.test(i))continue;let o=s(e,i),l=this.cleanText(i,80);typeof o=="string"?t[l]=this.cleanText(o,500):(typeof o=="number"&&Number.isFinite(o)||typeof o=="boolean"||o===null)&&(t[l]=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 l=this.cleanText(i??(t?"manual":""),S.category),c=this.cleanText(o,S.message);if(!l.trim()||!c.trim())return;let a=s(e,"data"),p={};if(a&&typeof a=="object"){let h;try{h=Object.keys(a)}catch{h=[]}for(let u of h){if(Object.keys(p).length>=S.dataKeys)break;if(F.test(u))continue;let f=this.cleanText(u,S.dataKey),m=s(a,u);typeof m=="string"?p[f]=this.cleanText(m,S.dataString):(typeof m=="number"&&Number.isFinite(m)||typeof m=="boolean"||m===null)&&(p[f]=m)}}return{occurredAt:r,category:l,message:c,...Object.keys(p).length?{data:p}:{}}}boundBreadcrumbs(e){for(;e.length>S.count||T(JSON.stringify(e))>S.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-S.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:R(s(e,"durationMs"),0,36e5,0)}}makeEvent(e,t,r={}){let i=s(navigator,"userAgent"),o=this.cleanContext(r.context),l;try{l=this.options.getContext?.()}catch{throw new L("Context resolver failed")}let c=this.cleanContext(l),a=this.cleanContext(this.options.context),p=o;if(c||a){p={...o};for(let u of[c,a])if(u)for(let f of Object.keys(u)){if(Object.keys(p).length>=12)break;Object.prototype.hasOwnProperty.call(p,f)||(p[f]=u[f])}}let h=this.cleanNetwork(r.network);return{schemaVersion:1,eventId:z(),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.2.3",occurredAt:new Date().toISOString(),viewId:this.viewId,sequence:++this.sequence,elapsedMs:R(k()-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:H.has(this.options.runtime)?this.options.runtime:"browser",...typeof i=="string"?{browser:this.cleanText(i,300)}:{},...p?{context:p}:{},...this.breadcrumbs.length?{breadcrumbs:this.breadcrumbs.map(u=>({...u,...u.data?{data:{...u.data}}:{}}))}:{},...h?{network:h}:{}}}sanitizeReplacement(e,t){let r=s(e,"type"),i=s(e,"runtime"),o=s(e,"name"),l=s(e,"stack"),c=s(e,"componentStack"),a=s(e,"browser"),p=this.cleanContext(s(e,"context")),h=this.cleanBreadcrumbTrail(s(e,"breadcrumbs")),u=this.cleanNetwork(s(e,"network"));return{...t,type:_.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)},...l===void 0?{stack:void 0}:{stack:this.cleanText(l,4096)},...c===void 0?{componentStack:t.componentStack}:{componentStack:this.cleanText(c,2048)},page:this.cleanUrl(s(e,"page")??t.page),runtime:H.has(i)?i:t.runtime,...a===void 0?{browser:t.browser}:{browser:this.cleanText(a,300)},...p?{context:p}:{context:void 0},...h?{breadcrumbs:h}:{breadcrumbs:void 0},...u?{network:u}:{network:void 0}}}admissionTime(){let e=k(),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}dedupeTime(){let e=k(),t=Number.isFinite(e)?Math.max(0,e,this.lastDedupeClock??0):this.lastDedupeClock??0;return this.lastDedupeClock=t,t}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 l={...e,context:e.context&&{...e.context},breadcrumbs:e.breadcrumbs?.map(a=>({...a,data:a.data&&{...a.data}})),network:e.network&&{...e.network}},c=this.options.beforeSend(l);if(c===!1||c===null)return this.filtered++,!1;t=this.sanitizeReplacement(c===void 0?l:c,e)}catch{return this.recordDrop("processingError"),!1}if(this.destroyed)return!1;if(T(JSON.stringify(t))>U)return this.recordDrop("payloadTooLarge"),!1;let r,i;if(this.dedupeIntervalMs>0){i=this.dedupeTime();for(let[l,c]of this.dedupeCache)i-c>=this.dedupeIntervalMs&&this.dedupeCache.delete(l);if(r=oe(t),this.dedupeCache.has(r))return this.deduplicated++,!1}let o=this.maxEventsPerMinute===void 0?void 0:this.admissionTime();return this.maxEventsPerMinute!==void 0&&o===void 0?(this.recordDrop("rateLimit"),!1):(this.queue.length>=this.maxQueueSize&&(this.queue.shift(),this.recordDrop("queueOverflow")),this.queue.push(t),o!==void 0&&this.admittedAt.push(o),r!==void 0&&i!==void 0&&(this.dedupeCache.set(r,i),this.dedupeCache.size>50&&this.dedupeCache.delete(this.dedupeCache.keys().next().value)),this.queue.length>=this.maxQueueSize&&this.flush(),!0)}takeBatch(e=ee,t=U){let r=[],i=T('{"schemaVersion":1,"events":[]}');for(;this.queue.length&&r.length<e;){let o=this.queue[0],l=T(JSON.stringify(o))+(r.length?1:0);if(r.length&&i+l>t)break;if(!r.length&&i+l>t){this.queue.shift(),this.recordDrop("payloadTooLarge");continue}r.push(this.queue.shift()),i+=l}return{schemaVersion:1,events:r}}async drain(){for(;!this.destroyed&&this.queue.length&&!this.isExplicitlyOffline();){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<=j.length&&!this.destroyed;t++){let r=new AbortController;this.controllers.add(r);let i,o=new Promise((c,a)=>{i=setTimeout(()=>{r.abort(),a(new Error("Collector transport timed out"))},this.transportTimeoutMs)}),l;try{if(await Promise.race([this.send(e,r.signal),o,this.destroySignal])===W||this.destroyed)return;this.sent+=e.events.length;return}catch(c){if(this.destroyed)return;let a=s(c,"status");if(!(typeof a!="number"||a===429||a>=500)||t===j.length)break;l=j[t]}finally{i&&clearTimeout(i),this.controllers.delete(r)}l!==void 0&&await this.wait(l)}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||this.isExplicitlyOffline()))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(T(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{}}},W=Symbol("destroyed"),A,O,D;function se(n){D||(D=ce()),D?.clients.add(n)}function ae(n){let e=D;e&&(e.clients.delete(n),e.clients.size||(e.cleanup(),D=void 0))}function V(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 ce(){let n,e,t,r,i,o,l,c;try{if(n=window.history,e=window.location.href,i=Object.getOwnPropertyDescriptor(n,"pushState"),o=Object.getOwnPropertyDescriptor(n,"replaceState"),l=i?void 0:V(n,"pushState"),c=o?void 0:V(n,"replaceState"),i&&!("value"in i)||o&&!("value"in o)||!i&&(!l||!("value"in l)||l.writable!==!0)||!o&&(!c||!("value"in c)||c.writable!==!0)||(t=i?i.value:n.pushState,r=o?o.value:n.replaceState,typeof t!="function"||typeof r!="function"))return;let b=y=>y?y.configurable===!0||y.writable===!0:Object.isExtensible(n);if(!b(i)||!b(o))return}catch{return}let a=new Set,p=b=>{try{let y=window.location.href;if(y===e)return;let B=e;e=y;for(let v of a)try{v.reportNavigation(B,y,b)}catch{}}catch{}},h=function(...b){let y=Reflect.apply(t,this,b);return p("pushState"),y},u=function(...b){let y=Reflect.apply(r,this,b);return p("replaceState"),y},f=()=>{p("popstate")},m=()=>{p("hashchange")},g=(b,y,B)=>{try{let v=Object.getOwnPropertyDescriptor(n,b);if(!v||!("value"in v)||v.value!==y)return;B?Object.defineProperty(n,b,B):Reflect.deleteProperty(n,b)}catch{}},E=!1,C=!1;try{Object.defineProperty(n,"pushState",{configurable:i?.configurable??!0,enumerable:i?.enumerable??!1,writable:i?.writable??!0,value:h}),E=!0,Object.defineProperty(n,"replaceState",{configurable:o?.configurable??!0,enumerable:o?.enumerable??!1,writable:o?.writable??!0,value:u}),C=!0,window.addEventListener("popstate",f),window.addEventListener("hashchange",m)}catch{try{window.removeEventListener("hashchange",m)}catch{}try{window.removeEventListener("popstate",f)}catch{}C&&g("replaceState",u,o),E&&g("pushState",h,i);return}return{clients:a,cleanup(){try{window.removeEventListener("popstate",f)}catch{}try{window.removeEventListener("hashchange",m)}catch{}g("pushState",h,i),g("replaceState",u,o)}}}function ue(n){A||(A=pe()),A.clients.add(n)}function de(n){let e=A;e&&(e.clients.delete(n),e.clients.size||(e.cleanup(),A=void 0))}function le(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 pe(){let n=new Set,e=window.fetch,t;typeof e=="function"&&(t=function(...h){if(!n.size)return Reflect.apply(e,this,h);let u=k(),f;try{f=le(h[0],h[1])}catch{f={url:"",method:"GET"}}let m;try{m=Reflect.apply(e,this,h)}catch(g){if(!P(g,f.signal))for(let E of n)E.reportNetwork(f.method,f.url,void 0,k()-u,g);throw g}return m.then(g=>{try{let E=g.status;for(let C of n)C.reportNetwork(f.method,f.url,E,k()-u)}catch{}return g},g=>{if(!P(g,f.signal))for(let E of n)E.reportNetwork(f.method,f.url,void 0,k()-u,g);throw g})},window.fetch=t);let r=typeof XMLHttpRequest>"u"?void 0:XMLHttpRequest.prototype,i=r?.open,o=r?.send,l=new WeakMap,c=new WeakMap,a,p;return r&&i&&o&&(a=(function(...h){let u=Reflect.apply(i,this,h);c.get(this)?.();try{l.set(this,{method:w(h[0]),url:w(h[1])})}catch{}return u}),p=function(...h){if(!n.size)return Reflect.apply(o,this,h);let u=l.get(this);if(!u)return Reflect.apply(o,this,h);let f=k(),m=!1,g=!1,E=!1,C=()=>{m=!0},b=()=>{g=!0},y=()=>{this.removeEventListener("abort",C),this.removeEventListener("error",b),this.removeEventListener("timeout",b),this.removeEventListener("loadend",B),c.get(this)===y&&c.delete(this)},B=()=>{if(E=!0,y(),!m)try{let v=this.status;if(v===0&&!g){for(let M of n)M.reportZeroStatusCompletion(u.method,u.url,k()-f);return}for(let M of n)M.reportNetwork(u.method,u.url,v===0?void 0:v,k()-f)}catch{}};try{this.addEventListener("abort",C),this.addEventListener("error",b),this.addEventListener("timeout",b),this.addEventListener("loadend",B)}catch{return y(),Reflect.apply(o,this,h)}try{let v=Reflect.apply(o,this,h);return E||c.set(this,y),v}catch(v){throw y(),v}},r.open=a,r.send=p),{clients:n,cleanup(){t&&window.fetch===t&&(window.fetch=e),r&&a&&r.open===a&&(r.open=i),r&&p&&r.send===p&&(r.send=o)}}}function he(n){O||(O=me()),O.clients.add(n)}function fe(n){let e=O;e&&(e.clients.delete(n),e.clients.size||(e.cleanup(),O=void 0))}function me(){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 ge(n){return new q(n)}
|
|
5
5
|
//# sourceMappingURL=index.cjs.map
|