@runtimescope/sdk 0.9.1 → 0.9.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/dist/index.js CHANGED
@@ -1,5 +1,8 @@
1
- var oe=Object.defineProperty;var ie=(e,t,s)=>t in e?oe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s;var p=(e,t,s)=>ie(e,typeof t!="symbol"?t+"":t,s);var k=console.debug.bind(console),R=class R{constructor(t){p(this,"ws",null);p(this,"batch",[]);p(this,"offlineQueue",[]);p(this,"flushTimer",null);p(this,"reconnectTimer",null);p(this,"reconnectDelay",500);p(this,"reconnectAttempt",0);p(this,"connected",!1);p(this,"stopped",!1);p(this,"config");p(this,"commandHandler",null);p(this,"hasEverConnected",!1);p(this,"connectionWarningTimer",null);p(this,"visibilityHandler",null);p(this,"onlineHandler",null);this.config=t}connect(){this.stopped=!1,this.doConnect(),this.connectionWarningTimer=setTimeout(()=>{!this.hasEverConnected&&!this.stopped&&console.warn(`[RuntimeScope] SDK has not connected to ${this.config.serverUrl} after 10s. Is the collector running? Start it with: npx @runtimescope/collector`)},R.CONNECTION_WARNING_DELAY),typeof document<"u"&&(this.visibilityHandler=()=>{document.visibilityState==="visible"&&!this.connected&&!this.stopped&&(k("[RuntimeScope] Tab visible \u2014 attempting immediate reconnect"),this.resetReconnectState(),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.doConnect())},document.addEventListener("visibilitychange",this.visibilityHandler)),typeof window<"u"&&(this.onlineHandler=()=>{!this.connected&&!this.stopped&&(k("[RuntimeScope] Network online \u2014 attempting immediate reconnect"),this.resetReconnectState(),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.doConnect())},window.addEventListener("online",this.onlineHandler))}doConnect(){if(!this.stopped){try{this.ws=new WebSocket(this.config.serverUrl)}catch{this.scheduleReconnect();return}this.ws.onmessage=t=>{try{let s=JSON.parse(String(t.data));s.type==="command"&&s.payload&&this.commandHandler&&this.commandHandler(s.payload),s.type==="__server_restart"&&(k("[RuntimeScope] Server restart notice received \u2014 will reconnect immediately"),this.resetReconnectState()),s.type==="error"&&s.payload?.code==="AUTH_FAILED"&&(k("[RuntimeScope] Authentication failed \u2014 stopping reconnection"),this.stopped=!0)}catch{}},this.ws.onopen=()=>{if(this.connected=!0,this.hasEverConnected=!0,this.resetReconnectState(),k(`[RuntimeScope] Connected to ${this.config.serverUrl}`),this.sendRaw({type:"handshake",payload:{appName:this.config.appName,sdkVersion:this.config.sdkVersion,sessionId:this.config.sessionId,...this.config.authToken?{authToken:this.config.authToken}:{},...this.config.projectId?{projectId:this.config.projectId}:{}},timestamp:Date.now(),sessionId:this.config.sessionId}),this.offlineQueue.length>0){let t=this.offlineQueue.splice(0);for(let s of t)this.batch.push(s);this.flush()}this.flushTimer=setInterval(()=>this.flush(),this.config.flushIntervalMs)},this.ws.onclose=()=>{this.connected=!1,this.clearFlushTimer(),this.stopped||(k("[RuntimeScope] Disconnected, will reconnect..."),this.scheduleReconnect())},this.ws.onerror=()=>{k(`[RuntimeScope] WebSocket error connecting to ${this.config.serverUrl}`)}}}send(t){this.connected?(this.batch.push(t),this.batch.length>=this.config.batchSize&&this.flush()):this.offlineQueue.length<R.MAX_OFFLINE_QUEUE&&this.offlineQueue.push(t)}flush(){if(this.batch.length===0||!this.connected||!this.ws)return;let t=this.batch.splice(0);this.sendRaw({type:"event",payload:{events:t},timestamp:Date.now(),sessionId:this.config.sessionId})}sendRaw(t){if(this.ws&&this.ws.readyState===WebSocket.OPEN)try{this.ws.send(JSON.stringify(t))}catch{}}scheduleReconnect(){if(this.stopped||this.reconnectTimer)return;this.reconnectAttempt++;let t;if(this.reconnectAttempt<=R.FAST_RETRY_COUNT)t=R.FAST_RETRY_DELAY;else{let s=this.reconnectDelay*.25*(Math.random()*2-1);t=Math.min(this.reconnectDelay+s,R.MAX_RECONNECT_DELAY),this.reconnectDelay=Math.min(this.reconnectDelay*2,R.MAX_RECONNECT_DELAY)}this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.doConnect()},t)}resetReconnectState(){this.reconnectDelay=500,this.reconnectAttempt=0}clearFlushTimer(){this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null)}onCommand(t){this.commandHandler=t}sendCommandResponse(t,s,n){this.sendRaw({type:"command_response",requestId:t,command:s,payload:n,timestamp:Date.now(),sessionId:this.config.sessionId})}disconnect(){this.stopped=!0,this.clearFlushTimer(),this.connectionWarningTimer&&(clearTimeout(this.connectionWarningTimer),this.connectionWarningTimer=null),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.visibilityHandler&&typeof document<"u"&&(document.removeEventListener("visibilitychange",this.visibilityHandler),this.visibilityHandler=null),this.onlineHandler&&typeof window<"u"&&(window.removeEventListener("online",this.onlineHandler),this.onlineHandler=null),this.flush(),this.ws&&(this.ws.onclose=null,this.ws.onerror=null,this.ws.close(),this.ws=null),this.connected=!1,this.batch=[],this.offlineQueue=[]}};p(R,"MAX_OFFLINE_QUEUE",1e3),p(R,"MAX_RECONNECT_DELAY",3e4),p(R,"CONNECTION_WARNING_DELAY",1e4),p(R,"FAST_RETRY_COUNT",3),p(R,"FAST_RETRY_DELAY",500);var M=R;function m(){let e=new Uint8Array(8);return crypto.getRandomValues(e),Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}function X(){let e=new Uint8Array(16);return crypto.getRandomValues(e),Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}var ae=1e3,ce=1e4,ue=5e3,C=new Map,H=null,F=0;function de(){F++,!H&&(H=setInterval(()=>{let e=Date.now()-ce;for(let[t,s]of C)s<e&&C.delete(t)},ue))}function le(){F--,F<=0&&H&&(clearInterval(H),H=null,F=0)}function $(e,t,s,n){let r=window.fetch,c=new Set(s.map(a=>a.toLowerCase())),i=n?.captureBody??!1,o=n?.maxBodySize??65536;return de(),window.fetch=async function(a,u){let d=performance.now(),l=typeof a=="string"?a:a instanceof URL?a.href:a.url,f=(u?.method??"GET").toUpperCase(),b=pe(u?.headers,c),g=me(u?.body),T=ve(u?.body),x;i&&u?.body&&(x=he(u.body,o));let z=`${f}:${l}:${d}`;if(C.size>=ae){let h=C.keys().next().value;h!==void 0&&C.delete(h)}C.set(z,Date.now());try{let h=await r.call(window,a,u),_=performance.now()-d,L=parseInt(h.headers.get("content-length")||"0",10),I=fe(h.headers,c),v;if(i)try{let O=await h.clone().text();v=O.length>o?O.slice(0,o):O}catch{}let w={eventId:m(),sessionId:t,timestamp:Date.now(),eventType:"network",url:l,method:f,status:h.status,requestHeaders:b,responseHeaders:I,requestBodySize:g,responseBodySize:L,duration:_,ttfb:_,graphqlOperation:T,requestBody:x,responseBody:v,source:"fetch"};if(n?.beforeSend){let S=n.beforeSend(w);S&&e(S)}else e(w);return h}catch(h){let _=performance.now()-d,L="error",I="";h instanceof DOMException&&h.name==="AbortError"?(L="abort",I="Request aborted"):h instanceof Error&&(I=h.message);let v={eventId:m(),sessionId:t,timestamp:Date.now(),eventType:"network",url:l,method:f,status:0,requestHeaders:b,responseHeaders:{},requestBodySize:g,responseBodySize:0,duration:_,ttfb:0,graphqlOperation:T,requestBody:x,errorPhase:L,errorMessage:I,source:"fetch"};if(n?.beforeSend){let w=n.beforeSend(v);w&&e(w)}else e(v);throw h}},()=>{window.fetch=r,le()}}function pe(e,t){let s={};if(!e)return s;if(e instanceof Headers)e.forEach((n,r)=>{s[r]=t.has(r.toLowerCase())?"[REDACTED]":n});else if(Array.isArray(e))for(let[n,r]of e)s[n]=t.has(n.toLowerCase())?"[REDACTED]":r;else for(let[n,r]of Object.entries(e))s[n]=t.has(n.toLowerCase())?"[REDACTED]":r;return s}function fe(e,t){let s={};return e.forEach((n,r)=>{s[r]=t.has(r.toLowerCase())?"[REDACTED]":n}),s}function me(e){return e?typeof e=="string"?new Blob([e]).size:e instanceof Blob?e.size:e instanceof ArrayBuffer||ArrayBuffer.isView(e)?e.byteLength:e instanceof FormData?0:e instanceof URLSearchParams?new Blob([e.toString()]).size:0:0}function he(e,t){if(e){if(typeof e=="string")return e.length>t?e.slice(0,t):e;if(e instanceof URLSearchParams){let s=e.toString();return s.length>t?s.slice(0,t):s}if(e instanceof FormData)return"[FormData]";if(e instanceof Blob)return`[Blob ${e.size} bytes]`;if(e instanceof ArrayBuffer)return`[ArrayBuffer ${e.byteLength} bytes]`;if(ArrayBuffer.isView(e))return`[TypedArray ${e.byteLength} bytes]`}}function ve(e){if(!(!e||typeof e!="string"))try{let t=JSON.parse(e);if(typeof t.query=="string"){let s=t.query.trim(),n="query";s.startsWith("mutation")?n="mutation":s.startsWith("subscription")&&(n="subscription");let r=t.operationName||ge(s)||"anonymous";return{type:n,name:r}}}catch{}}function ge(e){return e.match(/^(?:query|mutation|subscription)\s+(\w+)/)?.[1]}function y(e,t=5){let s=new WeakSet;function n(r,c){if(c>t)return"[max depth]";if(r==null)return r;if(typeof r=="function")return`[Function: ${r.name||"anonymous"}]`;if(typeof r=="symbol"||typeof r=="bigint")return r.toString();if(typeof r!="object")return r;if(r instanceof Error)return{name:r.name,message:r.message,stack:r.stack};if(r instanceof Date)return r.toISOString();if(r instanceof RegExp)return r.toString();if(s.has(r))return"[Circular]";if(s.add(r),Array.isArray(r))return r.map(u=>n(u,c+1));let i={},o;try{o=Object.keys(r)}catch{return"[Object]"}let a=50;for(let u=0;u<Math.min(o.length,a);u++)try{i[o[u]]=n(r[o[u]],c+1)}catch{i[o[u]]="[Error accessing property]"}return o.length>a&&(i["..."]=`${o.length-a} more keys`),i}return n(e,0)}var W=["log","warn","error","info","debug","trace"];function V(e,t,s){let n={};for(let r of W)n[r]=console[r].bind(console),console[r]=(...c)=>{let i=c.map(a=>typeof a=="string"?a:ye(a)).join(" "),o={eventId:m(),sessionId:t,timestamp:Date.now(),eventType:"console",level:r,message:i,args:c.map(a=>y(a,3)),stackTrace:r==="error"||r==="trace"?new Error().stack?.split(`
1
+ var ce=Object.defineProperty;var ue=(t,e,r)=>e in t?ce(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var f=(t,e,r)=>ue(t,typeof e!="symbol"?e+"":e,r);var D=console.debug.bind(console),S=class S{constructor(e){f(this,"ws",null);f(this,"batch",[]);f(this,"offlineQueue",[]);f(this,"flushTimer",null);f(this,"reconnectTimer",null);f(this,"reconnectDelay",500);f(this,"reconnectAttempt",0);f(this,"connected",!1);f(this,"stopped",!1);f(this,"config");f(this,"commandHandler",null);f(this,"hasEverConnected",!1);f(this,"connectionWarningTimer",null);f(this,"visibilityHandler",null);f(this,"onlineHandler",null);this.config=e}connect(){this.stopped=!1,this.doConnect(),this.connectionWarningTimer=setTimeout(()=>{!this.hasEverConnected&&!this.stopped&&console.warn(`[RuntimeScope] SDK has not connected to ${this.config.serverUrl} after 10s. Is the collector running? Start it with: npx @runtimescope/collector`)},S.CONNECTION_WARNING_DELAY),typeof document<"u"&&(this.visibilityHandler=()=>{document.visibilityState==="visible"&&!this.connected&&!this.stopped&&(D("[RuntimeScope] Tab visible \u2014 attempting immediate reconnect"),this.resetReconnectState(),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.doConnect())},document.addEventListener("visibilitychange",this.visibilityHandler)),typeof window<"u"&&(this.onlineHandler=()=>{!this.connected&&!this.stopped&&(D("[RuntimeScope] Network online \u2014 attempting immediate reconnect"),this.resetReconnectState(),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.doConnect())},window.addEventListener("online",this.onlineHandler))}doConnect(){if(!this.stopped){try{this.ws=new WebSocket(this.config.serverUrl)}catch{this.scheduleReconnect();return}this.ws.onmessage=e=>{try{let r=JSON.parse(String(e.data));r.type==="command"&&r.payload&&this.commandHandler&&this.commandHandler(r.payload),r.type==="__server_restart"&&(D("[RuntimeScope] Server restart notice received \u2014 will reconnect immediately"),this.resetReconnectState()),r.type==="error"&&r.payload?.code==="AUTH_FAILED"&&(D("[RuntimeScope] Authentication failed \u2014 stopping reconnection"),this.stopped=!0)}catch{}},this.ws.onopen=()=>{if(this.connected=!0,this.hasEverConnected=!0,this.resetReconnectState(),D(`[RuntimeScope] Connected to ${this.config.serverUrl}`),this.sendRaw({type:"handshake",payload:{appName:this.config.appName,sdkVersion:this.config.sdkVersion,sessionId:this.config.sessionId,...this.config.authToken?{authToken:this.config.authToken}:{},...this.config.projectId?{projectId:this.config.projectId}:{}},timestamp:Date.now(),sessionId:this.config.sessionId}),this.offlineQueue.length>0){let e=this.offlineQueue.splice(0);for(let r of e)this.batch.push(r);this.flush()}this.flushTimer=setInterval(()=>this.flush(),this.config.flushIntervalMs)},this.ws.onclose=()=>{this.connected=!1,this.clearFlushTimer(),this.stopped||(D("[RuntimeScope] Disconnected, will reconnect..."),this.scheduleReconnect())},this.ws.onerror=()=>{D(`[RuntimeScope] WebSocket error connecting to ${this.config.serverUrl}`)}}}send(e){this.connected?(this.batch.push(e),this.batch.length>=this.config.batchSize&&this.flush()):this.offlineQueue.length<S.MAX_OFFLINE_QUEUE&&this.offlineQueue.push(e)}flush(){if(this.batch.length===0||!this.connected||!this.ws)return;let e=this.batch.splice(0);this.sendRaw({type:"event",payload:{events:e},timestamp:Date.now(),sessionId:this.config.sessionId})}sendRaw(e){if(this.ws&&this.ws.readyState===WebSocket.OPEN)try{this.ws.send(JSON.stringify(e))}catch{}}scheduleReconnect(){if(this.stopped||this.reconnectTimer)return;this.reconnectAttempt++;let e;if(this.reconnectAttempt<=S.FAST_RETRY_COUNT)e=S.FAST_RETRY_DELAY;else{let r=this.reconnectDelay*.25*(Math.random()*2-1);e=Math.min(this.reconnectDelay+r,S.MAX_RECONNECT_DELAY),this.reconnectDelay=Math.min(this.reconnectDelay*2,S.MAX_RECONNECT_DELAY)}this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.doConnect()},e)}resetReconnectState(){this.reconnectDelay=500,this.reconnectAttempt=0}clearFlushTimer(){this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null)}onCommand(e){this.commandHandler=e}sendCommandResponse(e,r,s){this.sendRaw({type:"command_response",requestId:e,command:r,payload:s,timestamp:Date.now(),sessionId:this.config.sessionId})}disconnect(){this.stopped=!0,this.clearFlushTimer(),this.connectionWarningTimer&&(clearTimeout(this.connectionWarningTimer),this.connectionWarningTimer=null),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.visibilityHandler&&typeof document<"u"&&(document.removeEventListener("visibilitychange",this.visibilityHandler),this.visibilityHandler=null),this.onlineHandler&&typeof window<"u"&&(window.removeEventListener("online",this.onlineHandler),this.onlineHandler=null),this.flush(),this.ws&&(this.ws.onclose=null,this.ws.onerror=null,this.ws.close(),this.ws=null),this.connected=!1,this.batch=[],this.offlineQueue=[]}};f(S,"MAX_OFFLINE_QUEUE",1e3),f(S,"MAX_RECONNECT_DELAY",3e4),f(S,"CONNECTION_WARNING_DELAY",1e4),f(S,"FAST_RETRY_COUNT",3),f(S,"FAST_RETRY_DELAY",500);var M=S;function m(){let t=new Uint8Array(8);return crypto.getRandomValues(t),Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}function X(){let t=new Uint8Array(16);return crypto.getRandomValues(t),Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}var de=1e3,pe=1e4,le=5e3,L=new Map,H=null,P=0;function fe(){P++,!H&&(H=setInterval(()=>{let t=Date.now()-pe;for(let[e,r]of L)r<t&&L.delete(e)},le))}function me(){P--,P<=0&&H&&(clearInterval(H),H=null,P=0)}function W(t,e,r,s){let n=window.fetch,c=new Set(r.map(o=>o.toLowerCase())),a=s?.captureBody??!1,i=s?.maxBodySize??65536;return fe(),window.fetch=async function(o,u){let p=performance.now(),l=typeof o=="string"?o:o instanceof URL?o.href:o.url,d=(u?.method??"GET").toUpperCase(),h=he(u?.headers,c),g=ve(u?.body),b=ye(u?.body),E;a&&u?.body&&(E=we(u.body,i));let _=`${d}:${l}:${p}`;if(L.size>=de){let v=L.keys().next().value;v!==void 0&&L.delete(v)}L.set(_,Date.now());try{let v=await n.call(window,o,u),k=performance.now()-p,x=parseInt(v.headers.get("content-length")||"0",10),C=ge(v.headers,c),w;if(a)try{let O=await v.clone().text();w=O.length>i?O.slice(0,i):O}catch{}let R={eventId:m(),sessionId:e,timestamp:Date.now(),eventType:"network",url:l,method:d,status:v.status,requestHeaders:h,responseHeaders:C,requestBodySize:g,responseBodySize:x,duration:k,ttfb:k,graphqlOperation:b,requestBody:E,responseBody:w,source:"fetch"};if(s?.beforeSend){let I=s.beforeSend(R);I&&t(I)}else t(R);return v}catch(v){let k=performance.now()-p,x="error",C="";v instanceof DOMException&&v.name==="AbortError"?(x="abort",C="Request aborted"):v instanceof Error&&(C=v.message);let w={eventId:m(),sessionId:e,timestamp:Date.now(),eventType:"network",url:l,method:d,status:0,requestHeaders:h,responseHeaders:{},requestBodySize:g,responseBodySize:0,duration:k,ttfb:0,graphqlOperation:b,requestBody:E,errorPhase:x,errorMessage:C,source:"fetch"};if(s?.beforeSend){let R=s.beforeSend(w);R&&t(R)}else t(w);throw v}},()=>{window.fetch=n,me()}}function he(t,e){let r={};if(!t)return r;if(t instanceof Headers)t.forEach((s,n)=>{r[n]=e.has(n.toLowerCase())?"[REDACTED]":s});else if(Array.isArray(t))for(let[s,n]of t)r[s]=e.has(s.toLowerCase())?"[REDACTED]":n;else for(let[s,n]of Object.entries(t))r[s]=e.has(s.toLowerCase())?"[REDACTED]":n;return r}function ge(t,e){let r={};return t.forEach((s,n)=>{r[n]=e.has(n.toLowerCase())?"[REDACTED]":s}),r}function ve(t){return t?typeof t=="string"?new Blob([t]).size:t instanceof Blob?t.size:t instanceof ArrayBuffer||ArrayBuffer.isView(t)?t.byteLength:t instanceof FormData?0:t instanceof URLSearchParams?new Blob([t.toString()]).size:0:0}function we(t,e){if(t){if(typeof t=="string")return t.length>e?t.slice(0,e):t;if(t instanceof URLSearchParams){let r=t.toString();return r.length>e?r.slice(0,e):r}if(t instanceof FormData)return"[FormData]";if(t instanceof Blob)return`[Blob ${t.size} bytes]`;if(t instanceof ArrayBuffer)return`[ArrayBuffer ${t.byteLength} bytes]`;if(ArrayBuffer.isView(t))return`[TypedArray ${t.byteLength} bytes]`}}function ye(t){if(!(!t||typeof t!="string"))try{let e=JSON.parse(t);if(typeof e.query=="string"){let r=e.query.trim(),s="query";r.startsWith("mutation")?s="mutation":r.startsWith("subscription")&&(s="subscription");let n=e.operationName||Ee(r)||"anonymous";return{type:s,name:n}}}catch{}}function Ee(t){return t.match(/^(?:query|mutation|subscription)\s+(\w+)/)?.[1]}function y(t,e=5){let r=new WeakSet;function s(n,c){if(c>e)return"[max depth]";if(n==null)return n;if(typeof n=="function")return`[Function: ${n.name||"anonymous"}]`;if(typeof n=="symbol"||typeof n=="bigint")return n.toString();if(typeof n!="object")return n;if(n instanceof Error)return{name:n.name,message:n.message,stack:n.stack};if(n instanceof Date)return n.toISOString();if(n instanceof RegExp)return n.toString();if(r.has(n))return"[Circular]";if(r.add(n),Array.isArray(n))return n.map(u=>s(u,c+1));let a={},i;try{i=Object.keys(n)}catch{return"[Object]"}let o=50;for(let u=0;u<Math.min(i.length,o);u++)try{a[i[u]]=s(n[i[u]],c+1)}catch{a[i[u]]="[Error accessing property]"}return i.length>o&&(a["..."]=`${i.length-o} more keys`),a}return s(t,0)}var V=["log","warn","error","info","debug","trace"];function G(t){if(!t)return;let e=t.split(`
2
+ `).slice(3);for(let r of e){let s=r.match(/(?:at\s+)?(?:.*?\()?(.+?):(\d+):(\d+)\)?/);if(s&&!s[1].includes("interceptor")&&!s[1].includes("runtimescope"))return`${s[1]}:${s[2]}`}}function K(t,e,r){let s={},n=new Map,c=new Map;for(let d of V)s[d]=console[d].bind(console),console[d]=(...h)=>{let g=new Error().stack,b=h.map(_=>typeof _=="string"?_:Q(_)).join(" "),E={eventId:m(),sessionId:e,timestamp:Date.now(),eventType:"console",level:d,message:b,args:h.map(_=>y(_,3)),stackTrace:d==="error"||d==="trace"?g?.split(`
2
3
  `).slice(2).join(`
3
- `):void 0,sourceFile:void 0};if(s){let a=s(o);a&&e(a)}else e(o);n[r](...c)};return()=>{for(let r of W)console[r]=n[r]}}function ye(e){try{return JSON.stringify(e)}catch{return String(e)}}function G(e,t,s,n){let r=new Set(s.map(l=>l.toLowerCase())),c=n?.captureBody??!1,i=n?.maxBodySize??65536,o=new AbortController,a=XMLHttpRequest.prototype.open,u=XMLHttpRequest.prototype.setRequestHeader,d=XMLHttpRequest.prototype.send;return XMLHttpRequest.prototype.open=function(l,f){return this.__rs_method=l.toUpperCase(),this.__rs_url=typeof f=="string"?f:f.href,this.__rs_headers={},a.apply(this,arguments)},XMLHttpRequest.prototype.setRequestHeader=function(l,f){return this.__rs_headers&&(this.__rs_headers[l.toLowerCase()]=r.has(l.toLowerCase())?"[REDACTED]":f),u.call(this,l,f)},XMLHttpRequest.prototype.send=function(l){let f=this.__rs_method??"GET",b=this.__rs_url??"",g=`${f}:${b}`,T=!1;for(let v of C.keys())if(v.startsWith(g)){T=!0;break}if(T)return this.__rs_fetchIntercepted=!0,d.call(this,l);let x={...this.__rs_headers??{}},z=performance.now(),h,_=0;if(l){if(typeof l=="string")_=new Blob([l]).size,c&&(h=l.length>i?l.slice(0,i):l);else if(l instanceof Blob)_=l.size,c&&(h=`[Blob ${l.size} bytes]`);else if(l instanceof ArrayBuffer)_=l.byteLength,c&&(h=`[ArrayBuffer ${l.byteLength} bytes]`);else if(l instanceof FormData)c&&(h="[FormData]");else if(l instanceof URLSearchParams){let v=l.toString();_=new Blob([v]).size,c&&(h=v.length>i?v.slice(0,i):v)}}let L=Re(l),I=v=>{let w={eventId:m(),sessionId:t,timestamp:Date.now(),eventType:"network",url:b,method:f,status:0,requestHeaders:x,responseHeaders:{},requestBodySize:_,responseBodySize:0,duration:0,ttfb:0,graphqlOperation:L,requestBody:h,source:"xhr",...v};if(n?.beforeSend){let S=n.beforeSend(w);S&&e(S)}else e(w)};return this.addEventListener("loadend",()=>{let v=performance.now()-z;if(this.status>0){let w=we(this.getAllResponseHeaders(),r),S=parseInt(this.getResponseHeader("content-length")||"0",10),O;if(c&&(this.responseType===""||this.responseType==="text"))try{let j=this.responseText;O=j.length>i?j.slice(0,i):j}catch{}I({status:this.status,responseHeaders:w,responseBodySize:S,responseBody:O,duration:v,ttfb:v})}else{let w="error",S="Network error";this.readyState===0||this.status,this.timeout>0&&v>=this.timeout&&(w="timeout",S=`Request timed out after ${this.timeout}ms`),I({duration:v,errorPhase:w,errorMessage:S})}},{once:!0,signal:o.signal}),d.call(this,l)},()=>{o.abort(),XMLHttpRequest.prototype.open=a,XMLHttpRequest.prototype.setRequestHeader=u,XMLHttpRequest.prototype.send=d}}function we(e,t){let s={};if(!e)return s;for(let n of e.trim().split(/[\r\n]+/)){let r=n.indexOf(":");if(r===-1)continue;let c=n.slice(0,r).trim().toLowerCase(),i=n.slice(r+1).trim();s[c]=t.has(c)?"[REDACTED]":i}return s}function Re(e){if(!(!e||typeof e!="string"))try{let t=JSON.parse(e);if(typeof t.query=="string"){let s=t.query.trim(),n="query";s.startsWith("mutation")?n="mutation":s.startsWith("subscription")&&(n="subscription");let r=t.operationName||Ee(s)||"anonymous";return{type:n,name:r}}}catch{}}function Ee(e){return e.match(/^(?:query|mutation|subscription)\s+(\w+)/)?.[1]}function K(e,t,s,n){let r=[],c=new Map;for(let[i,o]of Object.entries(s)){let a=Se(o);if(a==="zustand"){let u=o;P(e,t,n?.beforeSend,{storeId:i,library:a,phase:"init",state:y(u.getState(),4)});let d=u.subscribe((l,f)=>{let b=Q(f,l);P(e,t,n?.beforeSend,{storeId:i,library:a,phase:"update",state:y(l,4),previousState:y(f,4),diff:b?y(b,3):void 0})});r.push(d)}else if(a==="redux"){let u=o;P(e,t,n?.beforeSend,{storeId:i,library:a,phase:"init",state:y(u.getState(),4)});let d,l=u.dispatch.bind(u);c.set(i,l),u.dispatch=g=>(g&&typeof g=="object"&&"type"in g&&(d={type:String(g.type),payload:g.payload}),l(g));let f=u.getState(),b=u.subscribe(()=>{let g=u.getState(),T=Q(f,g);P(e,t,n?.beforeSend,{storeId:i,library:a,phase:"update",state:y(g,4),previousState:y(f,4),diff:T?y(T,3):void 0,action:d?y(d,3):void 0}),f=g,d=void 0});r.push(b)}}return()=>{for(let i of r)i();for(let[i,o]of c){let a=s[i];a&&(a.dispatch=o)}}}function Se(e){if(!e||typeof e!="object")return"unknown";let t=e;return typeof t.getState=="function"&&typeof t.setState=="function"&&typeof t.subscribe=="function"?"zustand":typeof t.dispatch=="function"&&typeof t.getState=="function"&&typeof t.subscribe=="function"?"redux":"unknown"}function Q(e,t){if(!e||!t||typeof e!="object"||typeof t!="object")return null;let s={},n=e,r=t,c=new Set([...Object.keys(n),...Object.keys(r)]);for(let i of c)n[i]!==r[i]&&(s[i]={from:n[i],to:r[i]});return Object.keys(s).length>0?s:null}function P(e,t,s,n){let r={eventId:m(),sessionId:t,timestamp:Date.now(),eventType:"state",...n};if(s){let c=s(r);c&&e(c)}else e(r)}var be={LCP:[2500,4e3],FCP:[1800,3e3],CLS:[.1,.25],TTFB:[800,1800],FID:[100,300],INP:[200,500]};function _e(e,t){let[s,n]=be[e]??[1/0,1/0];return t<=s?"good":t<=n?"needs-improvement":"poor"}var A=null;function Y(e,t,s){if(A)for(let o of A)try{o.disconnect()}catch{}let n=[];A=n;let r=(o,a,u)=>{let d={eventId:m(),sessionId:t,timestamp:Date.now(),eventType:"performance",metricName:o,value:Math.round(a*100)/100,rating:_e(o,a),element:u};if(s?.beforeSend){let l=s.beforeSend(d);l&&e(l)}else e(d)};N(n,"largest-contentful-paint",o=>{let a=o[o.length-1];if(!a)return;let u=a.element;r("LCP",a.startTime,u?.tagName?.toLowerCase())}),N(n,"paint",o=>{for(let a of o)a.name==="first-contentful-paint"&&r("FCP",a.startTime)});let c=0;N(n,"layout-shift",o=>{for(let a of o){let u=a;!u.hadRecentInput&&u.value&&(c+=u.value,r("CLS",c))}}),N(n,"first-input",o=>{let a=o[0];if(!a)return;let u=a;u.processingStart&&r("FID",u.processingStart-a.startTime)}),N(n,"navigation",o=>{let a=o[0];a&&r("TTFB",a.responseStart-a.requestStart)});let i=0;return N(n,"event",o=>{for(let a of o)a.duration>i&&(i=a.duration,r("INP",i))},{durationThreshold:16}),()=>{for(let o of n)try{o.disconnect()}catch{}A===n&&(A=null)}}function N(e,t,s,n){try{let r=new PerformanceObserver(c=>{s(c.getEntries())});r.observe({type:t,buffered:!0,...n}),e.push(r)}catch{}}var Te=0,Ie=1,ee=1e4,J=100,Ce=6e4,Z=500;function te(e,t,s){let n=new Map,r=s?.snapshotIntervalMs??5e3,c=null,i=ke();if(!i)return()=>{};let o=i.onCommitFiberRoot;return i._runtimescope_original=o,i.onCommitFiberRoot=(a,u)=>{if(o)try{o(a,u)}catch{}u.current&&U(u.current,n)},c=setInterval(()=>{xe(n,e,t,s?.beforeSend)},r),()=>{c&&(clearInterval(c),c=null),i&&(i._runtimescope_original?i.onCommitFiberRoot=i._runtimescope_original:delete i.onCommitFiberRoot,delete i._runtimescope_original)}}function ke(){if(typeof window>"u")return null;let e=window;return e.__REACT_DEVTOOLS_GLOBAL_HOOK__||(e.__REACT_DEVTOOLS_GLOBAL_HOOK__={}),e.__REACT_DEVTOOLS_GLOBAL_HOOK__}function U(e,t){Le(e,t),e.child&&U(e.child,t),e.sibling&&U(e.sibling,t)}function Le(e,t){if(e.tag!==Te&&e.tag!==Ie)return;let s=Oe(e);if(!s)return;let n=Date.now(),r=e.alternate===null,c=e.actualDuration??0,i=Ne(e,r),o=t.get(s);o||(o={renderCount:0,totalDuration:0,lastRenderTime:0,lastRenderPhase:"mount",lastRenderCause:"unknown",renderTimestamps:[]},t.set(s,o)),o.renderCount++,o.totalDuration+=c,o.lastRenderTime=n,o.lastRenderPhase=r?"mount":"update",o.lastRenderCause=i??"unknown",o.renderTimestamps.push(n),o.renderTimestamps.length>J&&(o.renderTimestamps=o.renderTimestamps.slice(-J))}function Oe(e){if(e.type&&typeof e.type!="string")return e.type.displayName||e.type.name||void 0}function Ne(e,t){return t?"props":e.alternate?e.memoizedProps!==e.alternate.memoizedProps?"props":e.memoizedState!==e.alternate.memoizedState?"state":"parent":"unknown"}function De(e){if(e.length<2)return 0;let t=Date.now(),s=t-ee,n=e.filter(c=>c>=s);if(n.length<2)return 0;let r=t-n[0];return r===0?0:n.length/(r/1e3)}function xe(e,t,s,n){if(e.size===0)return;let r=[],c=[],i=0;for(let[u,d]of e){let l=De(d.renderTimestamps),f=l>4||d.renderCount>20;r.push({componentName:u,renderCount:d.renderCount,totalDuration:Math.round(d.totalDuration*100)/100,avgDuration:d.renderCount>0?Math.round(d.totalDuration/d.renderCount*100)/100:0,lastRenderPhase:d.lastRenderPhase,lastRenderCause:d.lastRenderCause,renderVelocity:Math.round(l*100)/100,suspicious:f}),f&&c.push(u),i+=d.renderCount}r.sort((u,d)=>d.renderCount-u.renderCount);let o={eventId:m(),sessionId:s,timestamp:Date.now(),eventType:"render",profiles:r,snapshotWindowMs:ee,totalRenders:i,suspiciousComponents:c};if(n){let u=n(o);u&&t(u)}else t(o);let a=Date.now();for(let[u,d]of e)a-d.lastRenderTime>Ce?e.delete(u):(d.renderCount=0,d.totalDuration=0);if(e.size>Z){let u=[...e.entries()].sort((l,f)=>l[1].lastRenderTime-f[1].lastRenderTime),d=e.size-Z;for(let l=0;l<d;l++)e.delete(u[l][0])}}function ne(e,t,s){let n=c=>{let i,o,a;if(c instanceof ErrorEvent)i=c.message||"Uncaught error",o=c.error?.stack,a=c.filename?`${c.filename}:${c.lineno}:${c.colno}`:void 0;else{let d=c.target;if(d&&d!==window){let l=d.tagName?.toLowerCase()??"unknown",f=d.src??d.src??d.href??"unknown";i=`Failed to load resource: <${l}> ${f}`}else return}let u={eventId:m(),sessionId:t,timestamp:Date.now(),eventType:"console",level:"error",message:`[Uncaught] ${i}`,args:[y(i,3)],stackTrace:o,sourceFile:a};if(s){let d=s(u);d&&e(d)}else e(u)},r=c=>{let i=c.reason,o,a;if(i instanceof Error)o=i.message,a=i.stack;else if(typeof i=="string")o=i;else try{o=JSON.stringify(i)}catch{o=String(i)}let u={eventId:m(),sessionId:t,timestamp:Date.now(),eventType:"console",level:"error",message:`[Unhandled Rejection] ${o}`,args:[y(i,3)],stackTrace:a,sourceFile:void 0};if(s){let d=s(u);d&&e(d)}else e(u)};return window.addEventListener("error",n,!0),window.addEventListener("unhandledrejection",r),()=>{window.removeEventListener("error",n,!0),window.removeEventListener("unhandledrejection",r)}}function re(e,t){let s=window.location.href;function n(a,u){let d=s;d!==a&&(s=a,e({eventId:m(),sessionId:t,timestamp:Date.now(),eventType:"navigation",from:d,to:a,trigger:u}))}let r=history.pushState.bind(history),c=history.replaceState.bind(history);history.pushState=function(...a){r(...a),n(window.location.href,"pushState")},history.replaceState=function(...a){c(...a),n(window.location.href,"replaceState")};let i=()=>n(window.location.href,"popstate");window.addEventListener("popstate",i);let o=()=>n(window.location.href,"hashchange");return window.addEventListener("hashchange",o),()=>{history.pushState=r,history.replaceState=c,window.removeEventListener("popstate",i),window.removeEventListener("hashchange",o)}}function se(e,t){let s=n=>{let r=n.target;if(!(r instanceof Element)||r.closest("[data-runtimescope]"))return;let c=He(r),i=Ae(r),o={eventId:m(),sessionId:t,timestamp:Date.now(),eventType:"ui",action:"click",target:c,...i&&{text:i}};e(o)};return document.addEventListener("click",s,!0),()=>{document.removeEventListener("click",s,!0)}}function He(e){let t=e.tagName.toLowerCase();if(e.id)return`${t}#${e.id}`;let s=e.getAttribute("data-testid")??e.getAttribute("data-test-id");if(s)return`${t}[data-testid="${s}"]`;let n=e.getAttribute("role"),r=e.getAttribute("aria-label");if(n&&r)return`${t}[role="${n}"][aria-label="${r}"]`;let c=e.className;if(typeof c=="string"&&c.trim()){let o=c.split(/\s+/).find(a=>a.length>2&&!a.startsWith("_")&&!a.includes("__"));if(o)return`${t}.${o}`}let i=e.parentElement;if(i){let o=i.children,a=Array.from(o).filter(u=>u.tagName===e.tagName);if(a.length>1){let u=a.indexOf(e)+1;return`${t}:nth-child(${u})`}}return t}function Ae(e){let t=e.getAttribute("aria-label");if(t)return t.slice(0,80);let s=e.innerText??e.textContent;if(!s)return;let n=s.trim().replace(/\s+/g," ");if(n.length!==0)return n.length>80?n.slice(0,77)+"...":n}var B="0.9.1",D=console.debug.bind(console),q=Symbol.for("__runtimescope_originals__");function Me(){let e=globalThis;return e[q]||(e[q]={fetch:window.fetch,xhrOpen:XMLHttpRequest.prototype.open,xhrSend:XMLHttpRequest.prototype.send,xhrSetRequestHeader:XMLHttpRequest.prototype.setRequestHeader,consoleMethods:{log:console.log.bind(console),warn:console.warn.bind(console),error:console.error.bind(console),info:console.info.bind(console),debug:console.debug.bind(console),trace:console.trace.bind(console)}}),e[q]}var E=class{static get sessionId(){return this._sessionId}static get isConnected(){return this._state==="started"}static shouldSample(){if(this._sampleRate<1&&Math.random()>this._sampleRate)return!1;if(this._maxEventsPerSecond!==void 0){let t=Date.now();if(t-this._windowStart>=1e3&&(this._windowCount=0,this._windowStart=t),this._windowCount>=this._maxEventsPerSecond)return!1;this._windowCount++}return!0}static connect(t={}){if(t.enabled===!1)return;if(!!!(t.serverUrl||t.endpoint)&&typeof window<"u"){let o=window.location?.hostname;if(o&&o!=="localhost"&&o!=="127.0.0.1"&&!o.startsWith("192.168.")&&!o.startsWith("10.")){D("[RuntimeScope] No endpoint configured and not on localhost \u2014 SDK disabled for production");return}}this._state==="started"&&(D("[RuntimeScope] Already connected \u2014 disconnecting before re-init"),this.disconnect());let n={serverUrl:t.serverUrl??t.endpoint??"ws://localhost:9090",appName:t.appName??"unknown",captureNetwork:t.captureNetwork??!0,captureConsole:t.captureConsole??!0,captureXhr:t.captureXhr??!0,captureBody:t.captureBody??!1,maxBodySize:t.maxBodySize??65536,capturePerformance:t.capturePerformance??!0,captureRenders:t.captureRenders??!0,captureNavigation:t.captureNavigation??!0,captureClicks:t.captureClicks??!0,stores:t.stores??{},beforeSend:t.beforeSend,redactHeaders:t.redactHeaders??["authorization","cookie"],batchSize:t.batchSize??50,flushIntervalMs:t.flushIntervalMs??100};Me(),this._sessionId=X(),this._state="started",this.transport=new M({serverUrl:n.serverUrl,appName:n.appName,sessionId:this._sessionId,sdkVersion:B,authToken:t.authToken,projectId:t.projectId,batchSize:n.batchSize,flushIntervalMs:n.flushIntervalMs}),this._sampleRate=t.sampleRate??1,this._maxEventsPerSecond=t.maxEventsPerSecond,this._windowCount=0,this._windowStart=Date.now(),this._user=t.user,this.transport.connect(),D(`[RuntimeScope] SDK v${B} initializing \u2014 app: ${n.appName}, server: ${n.serverUrl}`);let r=o=>{o.eventType!=="session"&&o.eventType!=="custom"&&o.eventType!=="ui"&&!this.shouldSample()||this.transport?.send(o)};r({eventId:m(),sessionId:this._sessionId,timestamp:Date.now(),eventType:"session",appName:n.appName,connectedAt:Date.now(),sdkVersion:B,buildMeta:t.buildMeta,user:this._user,projectId:t.projectId});let c=this._sessionId;this.transport.onCommand(o=>{this.handleCommand(o,r,c)}),n.captureNetwork&&this.restoreFns.push($(r,this._sessionId,n.redactHeaders,{captureBody:n.captureBody,maxBodySize:n.maxBodySize,beforeSend:n.beforeSend})),n.captureXhr&&this.restoreFns.push(G(r,this._sessionId,n.redactHeaders,{captureBody:n.captureBody,maxBodySize:n.maxBodySize,beforeSend:n.beforeSend})),n.captureConsole&&(this.restoreFns.push(V(r,this._sessionId,n.beforeSend)),this.restoreFns.push(ne(r,this._sessionId,n.beforeSend))),Object.keys(n.stores).length>0&&this.restoreFns.push(K(r,this._sessionId,n.stores,{beforeSend:n.beforeSend})),n.capturePerformance&&this.restoreFns.push(Y(r,this._sessionId,{beforeSend:n.beforeSend})),n.captureRenders&&this.restoreFns.push(te(r,this._sessionId,{beforeSend:n.beforeSend})),n.captureNavigation&&this.restoreFns.push(re(r,this._sessionId)),n.captureClicks&&this.restoreFns.push(se(r,this._sessionId));let i=[n.captureNetwork&&"fetch",n.captureXhr&&"xhr",n.captureConsole&&"console, errors",Object.keys(n.stores).length>0&&"state",n.capturePerformance&&"performance",n.captureRenders&&"renders",n.captureNavigation&&"navigation",n.captureClicks&&"clicks"].filter(Boolean);D(`[RuntimeScope] Interceptors active \u2014 ${i.join(", ")}`),this._sampleRate<1&&D(`[RuntimeScope] Sampling at ${(this._sampleRate*100).toFixed(0)}%`),this._maxEventsPerSecond!==void 0&&D(`[RuntimeScope] Rate limited to ${this._maxEventsPerSecond} events/sec`)}static handleCommand(t,s,n){if(t.command==="capture_dom_snapshot"){let r=t.params?.maxSize??5e5,c=document.documentElement.outerHTML,i=c.length>r;i&&(c=c.slice(0,r));let o={eventId:m(),sessionId:n,timestamp:Date.now(),eventType:"dom_snapshot",html:c,url:window.location.href,viewport:{width:window.innerWidth,height:window.innerHeight},scrollPosition:{x:window.scrollX,y:window.scrollY},elementCount:document.querySelectorAll("*").length,truncated:i};s(o),this.transport?.sendCommandResponse(t.requestId,t.command,o)}else this.transport?.sendCommandResponse(t.requestId,t.command,{error:"Unknown command"})}static init(t={}){return this.connect(t)}static track(t,s){if(!this.transport||!this._sessionId)return;let n={eventId:m(),sessionId:this._sessionId,timestamp:Date.now(),eventType:"custom",name:t,properties:s};this.transport.send(n)}static setUser(t){this._user=t??void 0,this.transport&&this._sessionId&&this.transport.send({eventId:m(),sessionId:this._sessionId,timestamp:Date.now(),eventType:"session",appName:"user_update",connectedAt:Date.now(),sdkVersion:B,user:this._user})}static addBreadcrumb(t,s){if(!this.transport||!this._sessionId)return;let n={eventId:m(),sessionId:this._sessionId,timestamp:Date.now(),eventType:"ui",action:"breadcrumb",target:"manual",text:t,...s&&{data:s}};this.transport.send(n)}static disconnect(){for(let s of this.restoreFns)try{s()}catch{}this.restoreFns=[];let t=globalThis[q];if(t){window.fetch!==t.fetch&&(window.fetch=t.fetch);for(let[s,n]of Object.entries(t.consoleMethods)){let r=console;r[s]!==n&&(r[s]=n)}}this.transport?.disconnect(),this.transport=null,this._sessionId=null,this._state="stopped"}};p(E,"transport",null),p(E,"restoreFns",[]),p(E,"_sessionId",null),p(E,"_state","stopped"),p(E,"_sampleRate",1),p(E,"_maxEventsPerSecond"),p(E,"_windowCount",0),p(E,"_windowStart",0),p(E,"_user");var Et=E;export{E as RuntimeScope,Et as default};
4
+ `):void 0,sourceFile:G(g),source:"browser"};if(r){let _=r(E);_&&t(_)}else t(E);s[d](...h)};let a=console.assert?.bind(console);a&&(console.assert=(d,...h)=>{if(!d){let g=new Error().stack,b=`Assertion failed: ${h.map(E=>typeof E=="string"?E:Q(E)).join(" ")}`;t({eventId:m(),sessionId:e,timestamp:Date.now(),eventType:"console",level:"error",message:b,args:h.map(E=>y(E,3)),stackTrace:g?.split(`
5
+ `).slice(2).join(`
6
+ `),sourceFile:G(g),source:"browser"})}a(d,...h)});let i=console.time?.bind(console),o=console.timeEnd?.bind(console);i&&(console.time=(d="default")=>{n.set(d,performance.now()),i(d)}),o&&(console.timeEnd=(d="default")=>{let h=n.get(d);if(h!==void 0){let g=performance.now()-h;n.delete(d),t({eventId:m(),sessionId:e,timestamp:Date.now(),eventType:"console",level:"info",message:`${d}: ${g.toFixed(2)}ms`,args:[{label:d,duration:g}],source:"browser"})}o(d)});let u=console.count?.bind(console),p=console.countReset?.bind(console);u&&(console.count=(d="default")=>{let h=(c.get(d)??0)+1;c.set(d,h),t({eventId:m(),sessionId:e,timestamp:Date.now(),eventType:"console",level:"info",message:`${d}: ${h}`,args:[{label:d,count:h}],source:"browser"}),u(d)}),p&&(console.countReset=(d="default")=>{c.delete(d),p(d)});let l=console.table?.bind(console);return l&&(console.table=(d,h)=>{t({eventId:m(),sessionId:e,timestamp:Date.now(),eventType:"console",level:"info",message:`[table] ${Array.isArray(d)?`${d.length} rows`:typeof d}`,args:[y(d,3)],source:"browser"}),l(d,h)}),()=>{for(let d of V)console[d]=s[d];a&&(console.assert=a),i&&(console.time=i),o&&(console.timeEnd=o),u&&(console.count=u),p&&(console.countReset=p),l&&(console.table=l)}}function Q(t){try{return JSON.stringify(t)}catch{return String(t)}}function Y(t,e,r,s){let n=new Set(r.map(l=>l.toLowerCase())),c=s?.captureBody??!1,a=s?.maxBodySize??65536,i=new AbortController,o=XMLHttpRequest.prototype.open,u=XMLHttpRequest.prototype.setRequestHeader,p=XMLHttpRequest.prototype.send;return XMLHttpRequest.prototype.open=function(l,d){return this.__rs_method=l.toUpperCase(),this.__rs_url=typeof d=="string"?d:d.href,this.__rs_headers={},o.apply(this,arguments)},XMLHttpRequest.prototype.setRequestHeader=function(l,d){return this.__rs_headers&&(this.__rs_headers[l.toLowerCase()]=n.has(l.toLowerCase())?"[REDACTED]":d),u.call(this,l,d)},XMLHttpRequest.prototype.send=function(l){let d=this.__rs_method??"GET",h=this.__rs_url??"",g=`${d}:${h}`,b=!1;for(let w of L.keys())if(w.startsWith(g)){b=!0;break}if(b)return this.__rs_fetchIntercepted=!0,p.call(this,l);let E={...this.__rs_headers??{}},_=performance.now(),v,k=0;if(l){if(typeof l=="string")k=new Blob([l]).size,c&&(v=l.length>a?l.slice(0,a):l);else if(l instanceof Blob)k=l.size,c&&(v=`[Blob ${l.size} bytes]`);else if(l instanceof ArrayBuffer)k=l.byteLength,c&&(v=`[ArrayBuffer ${l.byteLength} bytes]`);else if(l instanceof FormData)c&&(v="[FormData]");else if(l instanceof URLSearchParams){let w=l.toString();k=new Blob([w]).size,c&&(v=w.length>a?w.slice(0,a):w)}}let x=Se(l),C=w=>{let R={eventId:m(),sessionId:e,timestamp:Date.now(),eventType:"network",url:h,method:d,status:0,requestHeaders:E,responseHeaders:{},requestBodySize:k,responseBodySize:0,duration:0,ttfb:0,graphqlOperation:x,requestBody:v,source:"xhr",...w};if(s?.beforeSend){let I=s.beforeSend(R);I&&t(I)}else t(R)};return this.addEventListener("loadend",()=>{let w=performance.now()-_;if(this.status>0){let R=Re(this.getAllResponseHeaders(),n),I=parseInt(this.getResponseHeader("content-length")||"0",10),O;if(c&&(this.responseType===""||this.responseType==="text"))try{let q=this.responseText;O=q.length>a?q.slice(0,a):q}catch{}C({status:this.status,responseHeaders:R,responseBodySize:I,responseBody:O,duration:w,ttfb:w})}else{let R="error",I="Network error";this.readyState===0||this.status,this.timeout>0&&w>=this.timeout&&(R="timeout",I=`Request timed out after ${this.timeout}ms`),C({duration:w,errorPhase:R,errorMessage:I})}},{once:!0,signal:i.signal}),p.call(this,l)},()=>{i.abort(),XMLHttpRequest.prototype.open=o,XMLHttpRequest.prototype.setRequestHeader=u,XMLHttpRequest.prototype.send=p}}function Re(t,e){let r={};if(!t)return r;for(let s of t.trim().split(/[\r\n]+/)){let n=s.indexOf(":");if(n===-1)continue;let c=s.slice(0,n).trim().toLowerCase(),a=s.slice(n+1).trim();r[c]=e.has(c)?"[REDACTED]":a}return r}function Se(t){if(!(!t||typeof t!="string"))try{let e=JSON.parse(t);if(typeof e.query=="string"){let r=e.query.trim(),s="query";r.startsWith("mutation")?s="mutation":r.startsWith("subscription")&&(s="subscription");let n=e.operationName||be(r)||"anonymous";return{type:s,name:n}}}catch{}}function be(t){return t.match(/^(?:query|mutation|subscription)\s+(\w+)/)?.[1]}function Z(t,e,r,s){let n=[],c=new Map;for(let[a,i]of Object.entries(r)){let o=_e(i);if(o==="zustand"){let u=i;B(t,e,s?.beforeSend,{storeId:a,library:o,phase:"init",state:y(u.getState(),4)});let p=u.subscribe((l,d)=>{let h=J(d,l);B(t,e,s?.beforeSend,{storeId:a,library:o,phase:"update",state:y(l,4),previousState:y(d,4),diff:h?y(h,3):void 0})});n.push(p)}else if(o==="redux"){let u=i;B(t,e,s?.beforeSend,{storeId:a,library:o,phase:"init",state:y(u.getState(),4)});let p,l=u.dispatch.bind(u);c.set(a,l),u.dispatch=g=>(g&&typeof g=="object"&&"type"in g&&(p={type:String(g.type),payload:g.payload}),l(g));let d=u.getState(),h=u.subscribe(()=>{let g=u.getState(),b=J(d,g);B(t,e,s?.beforeSend,{storeId:a,library:o,phase:"update",state:y(g,4),previousState:y(d,4),diff:b?y(b,3):void 0,action:p?y(p,3):void 0}),d=g,p=void 0});n.push(h)}}return()=>{for(let a of n)a();for(let[a,i]of c){let o=r[a];o&&(o.dispatch=i)}}}function _e(t){if(!t||typeof t!="object")return"unknown";let e=t;return typeof e.getState=="function"&&typeof e.setState=="function"&&typeof e.subscribe=="function"?"zustand":typeof e.dispatch=="function"&&typeof e.getState=="function"&&typeof e.subscribe=="function"?"redux":"unknown"}function J(t,e){if(!t||!e||typeof t!="object"||typeof e!="object")return null;let r={},s=t,n=e,c=new Set([...Object.keys(s),...Object.keys(n)]);for(let a of c)s[a]!==n[a]&&(r[a]={from:s[a],to:n[a]});return Object.keys(r).length>0?r:null}function B(t,e,r,s){let n={eventId:m(),sessionId:e,timestamp:Date.now(),eventType:"state",...s};if(r){let c=r(n);c&&t(c)}else t(n)}var Te={LCP:[2500,4e3],FCP:[1800,3e3],CLS:[.1,.25],TTFB:[800,1800],FID:[100,300],INP:[200,500]};function Ie(t,e){let[r,s]=Te[t]??[1/0,1/0];return e<=r?"good":e<=s?"needs-improvement":"poor"}var F=null;function ee(t,e,r){if(F)for(let i of F)try{i.disconnect()}catch{}let s=[];F=s;let n=(i,o,u)=>{let p={eventId:m(),sessionId:e,timestamp:Date.now(),eventType:"performance",metricName:i,value:Math.round(o*100)/100,rating:Ie(i,o),element:u};if(r?.beforeSend){let l=r.beforeSend(p);l&&t(l)}else t(p)};A(s,"largest-contentful-paint",i=>{let o=i[i.length-1];if(!o)return;let u=o.element;n("LCP",o.startTime,u?.tagName?.toLowerCase())}),A(s,"paint",i=>{for(let o of i)o.name==="first-contentful-paint"&&n("FCP",o.startTime)});let c=0;A(s,"layout-shift",i=>{for(let o of i){let u=o;!u.hadRecentInput&&u.value&&(c+=u.value,n("CLS",c))}}),A(s,"first-input",i=>{let o=i[0];if(!o)return;let u=o;u.processingStart&&n("FID",u.processingStart-o.startTime)}),A(s,"navigation",i=>{let o=i[0];o&&n("TTFB",o.responseStart-o.requestStart)});let a=0;return A(s,"event",i=>{for(let o of i)o.duration>a&&(a=o.duration,n("INP",a))},{durationThreshold:16}),()=>{for(let i of s)try{i.disconnect()}catch{}F===s&&(F=null)}}function A(t,e,r,s){try{let n=new PerformanceObserver(c=>{r(c.getEntries())});n.observe({type:e,buffered:!0,...s}),t.push(n)}catch{}}var ke=0,Ce=1,re=1e4,te=100,Le=6e4,ne=500;function se(t,e,r){let s=new Map,n=r?.snapshotIntervalMs??5e3,c=null,a=De();if(!a)return()=>{};let i=a.onCommitFiberRoot;return a._runtimescope_original=i,a.onCommitFiberRoot=(o,u)=>{if(i)try{i(o,u)}catch{}u.current&&z(u.current,s)},c=setInterval(()=>{He(s,t,e,r?.beforeSend)},n),()=>{c&&(clearInterval(c),c=null),a&&(a._runtimescope_original?a.onCommitFiberRoot=a._runtimescope_original:delete a.onCommitFiberRoot,delete a._runtimescope_original)}}function De(){if(typeof window>"u")return null;let t=window;return t.__REACT_DEVTOOLS_GLOBAL_HOOK__||(t.__REACT_DEVTOOLS_GLOBAL_HOOK__={}),t.__REACT_DEVTOOLS_GLOBAL_HOOK__}function z(t,e){Ne(t,e),t.child&&z(t.child,e),t.sibling&&z(t.sibling,e)}function Ne(t,e){if(t.tag!==ke&&t.tag!==Ce)return;let r=xe(t);if(!r)return;let s=Date.now(),n=t.alternate===null,c=t.actualDuration??0,a=Oe(t,n),i=e.get(r);i||(i={renderCount:0,totalDuration:0,lastRenderTime:0,lastRenderPhase:"mount",lastRenderCause:"unknown",renderTimestamps:[]},e.set(r,i)),i.renderCount++,i.totalDuration+=c,i.lastRenderTime=s,i.lastRenderPhase=n?"mount":"update",i.lastRenderCause=a??"unknown",i.renderTimestamps.push(s),i.renderTimestamps.length>te&&(i.renderTimestamps=i.renderTimestamps.slice(-te))}function xe(t){if(t.type&&typeof t.type!="string")return t.type.displayName||t.type.name||void 0}function Oe(t,e){return e?"props":t.alternate?t.memoizedProps!==t.alternate.memoizedProps?"props":t.memoizedState!==t.alternate.memoizedState?"state":"parent":"unknown"}function Ae(t){if(t.length<2)return 0;let e=Date.now(),r=e-re,s=t.filter(c=>c>=r);if(s.length<2)return 0;let n=e-s[0];return n===0?0:s.length/(n/1e3)}function He(t,e,r,s){if(t.size===0)return;let n=[],c=[],a=0;for(let[u,p]of t){let l=Ae(p.renderTimestamps),d=l>4||p.renderCount>20;n.push({componentName:u,renderCount:p.renderCount,totalDuration:Math.round(p.totalDuration*100)/100,avgDuration:p.renderCount>0?Math.round(p.totalDuration/p.renderCount*100)/100:0,lastRenderPhase:p.lastRenderPhase,lastRenderCause:p.lastRenderCause,renderVelocity:Math.round(l*100)/100,suspicious:d}),d&&c.push(u),a+=p.renderCount}n.sort((u,p)=>p.renderCount-u.renderCount);let i={eventId:m(),sessionId:r,timestamp:Date.now(),eventType:"render",profiles:n,snapshotWindowMs:re,totalRenders:a,suspiciousComponents:c};if(s){let u=s(i);u&&e(u)}else e(i);let o=Date.now();for(let[u,p]of t)o-p.lastRenderTime>Le?t.delete(u):(p.renderCount=0,p.totalDuration=0);if(t.size>ne){let u=[...t.entries()].sort((l,d)=>l[1].lastRenderTime-d[1].lastRenderTime),p=t.size-ne;for(let l=0;l<p;l++)t.delete(u[l][0])}}function oe(t,e,r){let s=c=>{let a,i,o;if(c instanceof ErrorEvent)a=c.message||"Uncaught error",i=c.error?.stack,o=c.filename?`${c.filename}:${c.lineno}:${c.colno}`:void 0;else{let p=c.target;if(p&&p!==window){let l=p.tagName?.toLowerCase()??"unknown",d=p.src??p.src??p.href??"unknown";a=`Failed to load resource: <${l}> ${d}`}else return}let u={eventId:m(),sessionId:e,timestamp:Date.now(),eventType:"console",level:"error",message:`[Uncaught] ${a}`,args:[y(a,3)],stackTrace:i,sourceFile:o};if(r){let p=r(u);p&&t(p)}else t(u)},n=c=>{let a=c.reason,i,o;if(a instanceof Error)i=a.message,o=a.stack;else if(typeof a=="string")i=a;else try{i=JSON.stringify(a)}catch{i=String(a)}let u={eventId:m(),sessionId:e,timestamp:Date.now(),eventType:"console",level:"error",message:`[Unhandled Rejection] ${i}`,args:[y(a,3)],stackTrace:o,sourceFile:void 0};if(r){let p=r(u);p&&t(p)}else t(u)};return window.addEventListener("error",s,!0),window.addEventListener("unhandledrejection",n),()=>{window.removeEventListener("error",s,!0),window.removeEventListener("unhandledrejection",n)}}function ie(t,e){let r=window.location.href;function s(o,u){let p=r;p!==o&&(r=o,t({eventId:m(),sessionId:e,timestamp:Date.now(),eventType:"navigation",from:p,to:o,trigger:u}))}let n=history.pushState.bind(history),c=history.replaceState.bind(history);history.pushState=function(...o){n(...o),s(window.location.href,"pushState")},history.replaceState=function(...o){c(...o),s(window.location.href,"replaceState")};let a=()=>s(window.location.href,"popstate");window.addEventListener("popstate",a);let i=()=>s(window.location.href,"hashchange");return window.addEventListener("hashchange",i),()=>{history.pushState=n,history.replaceState=c,window.removeEventListener("popstate",a),window.removeEventListener("hashchange",i)}}function ae(t,e){let r=s=>{let n=s.target;if(!(n instanceof Element)||n.closest("[data-runtimescope]"))return;let c=Fe(n),a=Me(n),i={eventId:m(),sessionId:e,timestamp:Date.now(),eventType:"ui",action:"click",target:c,...a&&{text:a}};t(i)};return document.addEventListener("click",r,!0),()=>{document.removeEventListener("click",r,!0)}}function Fe(t){let e=t.tagName.toLowerCase();if(t.id)return`${e}#${t.id}`;let r=t.getAttribute("data-testid")??t.getAttribute("data-test-id");if(r)return`${e}[data-testid="${r}"]`;let s=t.getAttribute("role"),n=t.getAttribute("aria-label");if(s&&n)return`${e}[role="${s}"][aria-label="${n}"]`;let c=t.className;if(typeof c=="string"&&c.trim()){let i=c.split(/\s+/).find(o=>o.length>2&&!o.startsWith("_")&&!o.includes("__"));if(i)return`${e}.${i}`}let a=t.parentElement;if(a){let i=a.children,o=Array.from(i).filter(u=>u.tagName===t.tagName);if(o.length>1){let u=o.indexOf(t)+1;return`${e}:nth-child(${u})`}}return e}function Me(t){let e=t.getAttribute("aria-label");if(e)return e.slice(0,80);let r=t.innerText??t.textContent;if(!r)return;let s=r.trim().replace(/\s+/g," ");if(s.length!==0)return s.length>80?s.slice(0,77)+"...":s}function U(t){let e=t.startsWith("runtimescopes://");if(!t.startsWith("runtimescope://")&&!e)throw new Error("Invalid RuntimeScope DSN: must start with runtimescope:// or runtimescopes://");let r=new URL(t.replace(/^runtimescopes?:\/\//,"http://")),s=r.username;if(!s||!s.startsWith("proj_"))throw new Error("Invalid RuntimeScope DSN: missing projectId (expected proj_xxx@host)");let n=r.hostname,c=r.port?parseInt(r.port):9091,a=c-1,i=r.pathname.replace(/^\//,"")||void 0,o=e?"wss":"ws",u=e?"https":"http";return{projectId:s,wsEndpoint:`${o}://${n}:${a}`,httpEndpoint:`${u}://${n}:${c}`,appName:i,tls:e}}function Pe(t){let e=t.tls?"runtimescopes":"runtimescope",r=t.host??"localhost",s=t.port??9091,n=t.appName?`/${t.appName}`:"";return`${e}://${t.projectId}@${r}:${s}${n}`}var j="0.9.3",N=console.debug.bind(console),$=Symbol.for("__runtimescope_originals__");function Be(){let t=globalThis;return t[$]||(t[$]={fetch:window.fetch,xhrOpen:XMLHttpRequest.prototype.open,xhrSend:XMLHttpRequest.prototype.send,xhrSetRequestHeader:XMLHttpRequest.prototype.setRequestHeader,consoleMethods:{log:console.log.bind(console),warn:console.warn.bind(console),error:console.error.bind(console),info:console.info.bind(console),debug:console.debug.bind(console),trace:console.trace.bind(console)}}),t[$]}var T=class{static get sessionId(){return this._sessionId}static get isConnected(){return this._state==="started"}static shouldSample(){if(this._sampleRate<1&&Math.random()>this._sampleRate)return!1;if(this._maxEventsPerSecond!==void 0){let e=Date.now();if(e-this._windowStart>=1e3&&(this._windowCount=0,this._windowStart=e),this._windowCount>=this._maxEventsPerSecond)return!1;this._windowCount++}return!0}static connect(e={}){if(e.enabled===!1)return;let r=!1;if(e.dsn)try{let o=U(e.dsn);e={...e,serverUrl:o.wsEndpoint,projectId:o.projectId,...o.appName&&!e.appName?{appName:o.appName}:{}},r=!0}catch(o){N("[RuntimeScope] Invalid DSN:",o.message)}if(!(!!(e.serverUrl||e.endpoint)||r)&&typeof window<"u"){let o=window.location?.hostname;if(o&&o!=="localhost"&&o!=="127.0.0.1"&&!o.startsWith("192.168.")&&!o.startsWith("10.")){N("[RuntimeScope] No endpoint configured and not on localhost \u2014 SDK disabled for production");return}}this._state==="started"&&(N("[RuntimeScope] Already connected \u2014 disconnecting before re-init"),this.disconnect());let n={serverUrl:e.serverUrl??e.endpoint??"ws://localhost:9090",appName:e.appName??"unknown",captureNetwork:e.captureNetwork??!0,captureConsole:e.captureConsole??!0,captureXhr:e.captureXhr??!0,captureBody:e.captureBody??!1,maxBodySize:e.maxBodySize??65536,capturePerformance:e.capturePerformance??!0,captureRenders:e.captureRenders??!0,captureNavigation:e.captureNavigation??!0,captureClicks:e.captureClicks??!0,stores:e.stores??{},beforeSend:e.beforeSend,redactHeaders:e.redactHeaders??["authorization","cookie"],batchSize:e.batchSize??50,flushIntervalMs:e.flushIntervalMs??100};Be(),this._sessionId=X(),this._state="started",this.transport=new M({serverUrl:n.serverUrl,appName:n.appName,sessionId:this._sessionId,sdkVersion:j,authToken:e.authToken,projectId:e.projectId,batchSize:n.batchSize,flushIntervalMs:n.flushIntervalMs}),this._sampleRate=e.sampleRate??1,this._maxEventsPerSecond=e.maxEventsPerSecond,this._windowCount=0,this._windowStart=Date.now(),this._user=e.user,this.transport.connect(),N(`[RuntimeScope] SDK v${j} initializing \u2014 app: ${n.appName}, server: ${n.serverUrl}`);let c=o=>{o.eventType!=="session"&&o.eventType!=="custom"&&o.eventType!=="ui"&&!this.shouldSample()||this.transport?.send(o)};c({eventId:m(),sessionId:this._sessionId,timestamp:Date.now(),eventType:"session",appName:n.appName,connectedAt:Date.now(),sdkVersion:j,buildMeta:e.buildMeta,user:this._user,projectId:e.projectId});let a=this._sessionId;this.transport.onCommand(o=>{this.handleCommand(o,c,a)}),n.captureNetwork&&this.restoreFns.push(W(c,this._sessionId,n.redactHeaders,{captureBody:n.captureBody,maxBodySize:n.maxBodySize,beforeSend:n.beforeSend})),n.captureXhr&&this.restoreFns.push(Y(c,this._sessionId,n.redactHeaders,{captureBody:n.captureBody,maxBodySize:n.maxBodySize,beforeSend:n.beforeSend})),n.captureConsole&&this.restoreFns.push(K(c,this._sessionId,n.beforeSend)),e.captureErrors!==!1&&this.restoreFns.push(oe(c,this._sessionId,n.beforeSend)),Object.keys(n.stores).length>0&&this.restoreFns.push(Z(c,this._sessionId,n.stores,{beforeSend:n.beforeSend})),n.capturePerformance&&this.restoreFns.push(ee(c,this._sessionId,{beforeSend:n.beforeSend})),n.captureRenders&&this.restoreFns.push(se(c,this._sessionId,{beforeSend:n.beforeSend})),n.captureNavigation&&this.restoreFns.push(ie(c,this._sessionId)),n.captureClicks&&this.restoreFns.push(ae(c,this._sessionId));let i=[n.captureNetwork&&"fetch",n.captureXhr&&"xhr",n.captureConsole&&"console, errors",Object.keys(n.stores).length>0&&"state",n.capturePerformance&&"performance",n.captureRenders&&"renders",n.captureNavigation&&"navigation",n.captureClicks&&"clicks"].filter(Boolean);N(`[RuntimeScope] Interceptors active \u2014 ${i.join(", ")}`),this._sampleRate<1&&N(`[RuntimeScope] Sampling at ${(this._sampleRate*100).toFixed(0)}%`),this._maxEventsPerSecond!==void 0&&N(`[RuntimeScope] Rate limited to ${this._maxEventsPerSecond} events/sec`)}static handleCommand(e,r,s){if(e.command==="capture_dom_snapshot"){let n=e.params?.maxSize??5e5,c=document.documentElement.outerHTML,a=c.length>n;a&&(c=c.slice(0,n));let i={eventId:m(),sessionId:s,timestamp:Date.now(),eventType:"dom_snapshot",html:c,url:window.location.href,viewport:{width:window.innerWidth,height:window.innerHeight},scrollPosition:{x:window.scrollX,y:window.scrollY},elementCount:document.querySelectorAll("*").length,truncated:a};r(i),this.transport?.sendCommandResponse(e.requestId,e.command,i)}else this.transport?.sendCommandResponse(e.requestId,e.command,{error:"Unknown command"})}static init(e={}){return this.connect(e)}static track(e,r){if(!this.transport||!this._sessionId)return;let s={eventId:m(),sessionId:this._sessionId,timestamp:Date.now(),eventType:"custom",name:e,properties:r};this.transport.send(s)}static setUser(e){this._user=e??void 0,this.transport&&this._sessionId&&this.transport.send({eventId:m(),sessionId:this._sessionId,timestamp:Date.now(),eventType:"session",appName:"user_update",connectedAt:Date.now(),sdkVersion:j,user:this._user})}static addBreadcrumb(e,r){if(!this.transport||!this._sessionId)return;let s={eventId:m(),sessionId:this._sessionId,timestamp:Date.now(),eventType:"ui",action:"breadcrumb",target:"manual",text:e,...r&&{data:r}};this.transport.send(s)}static disconnect(){for(let r of this.restoreFns)try{r()}catch{}this.restoreFns=[];let e=globalThis[$];if(e){window.fetch!==e.fetch&&(window.fetch=e.fetch);for(let[r,s]of Object.entries(e.consoleMethods)){let n=console;n[r]!==s&&(n[r]=s)}}this.transport?.disconnect(),this.transport=null,this._sessionId=null,this._state="stopped"}};f(T,"transport",null),f(T,"restoreFns",[]),f(T,"_sessionId",null),f(T,"_state","stopped"),f(T,"_sampleRate",1),f(T,"_maxEventsPerSecond"),f(T,"_windowCount",0),f(T,"_windowStart",0),f(T,"_user");var It=T;export{T as RuntimeScope,Pe as buildDsn,It as default,U as parseDsn};
4
7
  if(typeof RuntimeScope!=="undefined"&&RuntimeScope.RuntimeScope){RuntimeScope=RuntimeScope.RuntimeScope;}
5
8
  //# sourceMappingURL=index.js.map