@grafana/faro-web-sdk 1.8.0 → 1.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/dist/bundle/faro-web-sdk.iife.js +1 -1
  2. package/dist/bundle/types/instrumentations/console/instrumentation.d.ts +1 -1
  3. package/dist/bundle/types/instrumentations/errors/instrumentation.d.ts +1 -1
  4. package/dist/bundle/types/instrumentations/performance/instrumentation.d.ts +1 -1
  5. package/dist/bundle/types/instrumentations/session/instrumentation.d.ts +1 -1
  6. package/dist/bundle/types/instrumentations/session/sessionManager/getSessionManagerByConfig.d.ts +3 -0
  7. package/dist/bundle/types/instrumentations/session/sessionManager/index.d.ts +1 -0
  8. package/dist/bundle/types/instrumentations/session/sessionManager/sessionManagerUtils.d.ts +1 -3
  9. package/dist/bundle/types/instrumentations/view/instrumentation.d.ts +1 -1
  10. package/dist/bundle/types/instrumentations/webVitals/instrumentation.d.ts +1 -1
  11. package/dist/bundle/types/transports/console/transport.d.ts +1 -1
  12. package/dist/bundle/types/transports/fetch/transport.d.ts +1 -1
  13. package/dist/cjs/instrumentations/session/instrumentation.js +1 -1
  14. package/dist/cjs/instrumentations/session/instrumentation.js.map +1 -1
  15. package/dist/cjs/instrumentations/session/sessionManager/getSessionManagerByConfig.js +10 -0
  16. package/dist/cjs/instrumentations/session/sessionManager/getSessionManagerByConfig.js.map +1 -0
  17. package/dist/cjs/instrumentations/session/sessionManager/index.js +3 -1
  18. package/dist/cjs/instrumentations/session/sessionManager/index.js.map +1 -1
  19. package/dist/cjs/instrumentations/session/sessionManager/sessionManagerUtils.js +1 -6
  20. package/dist/cjs/instrumentations/session/sessionManager/sessionManagerUtils.js.map +1 -1
  21. package/dist/cjs/transports/fetch/transport.js +2 -1
  22. package/dist/cjs/transports/fetch/transport.js.map +1 -1
  23. package/dist/esm/instrumentations/session/instrumentation.js +2 -2
  24. package/dist/esm/instrumentations/session/instrumentation.js.map +1 -1
  25. package/dist/esm/instrumentations/session/sessionManager/getSessionManagerByConfig.js +6 -0
  26. package/dist/esm/instrumentations/session/sessionManager/getSessionManagerByConfig.js.map +1 -0
  27. package/dist/esm/instrumentations/session/sessionManager/index.js +1 -0
  28. package/dist/esm/instrumentations/session/sessionManager/index.js.map +1 -1
  29. package/dist/esm/instrumentations/session/sessionManager/sessionManagerUtils.js +0 -4
  30. package/dist/esm/instrumentations/session/sessionManager/sessionManagerUtils.js.map +1 -1
  31. package/dist/esm/transports/fetch/transport.js +2 -1
  32. package/dist/esm/transports/fetch/transport.js.map +1 -1
  33. package/dist/types/instrumentations/console/instrumentation.d.ts +1 -1
  34. package/dist/types/instrumentations/errors/instrumentation.d.ts +1 -1
  35. package/dist/types/instrumentations/performance/instrumentation.d.ts +1 -1
  36. package/dist/types/instrumentations/session/instrumentation.d.ts +1 -1
  37. package/dist/types/instrumentations/session/sessionManager/getSessionManagerByConfig.d.ts +3 -0
  38. package/dist/types/instrumentations/session/sessionManager/index.d.ts +1 -0
  39. package/dist/types/instrumentations/session/sessionManager/sessionManagerUtils.d.ts +1 -3
  40. package/dist/types/instrumentations/view/instrumentation.d.ts +1 -1
  41. package/dist/types/instrumentations/webVitals/instrumentation.d.ts +1 -1
  42. package/dist/types/transports/console/transport.d.ts +1 -1
  43. package/dist/types/transports/fetch/transport.d.ts +1 -1
  44. package/package.json +3 -3
@@ -1 +1 @@
1
- var GrafanaFaroWebSdk=function(e){"use strict";function t(e,t){return typeof e===t}function n(e,t){return Object.prototype.toString.call(e)===`[object ${t}]`}function i(e,t){try{return e instanceof t}catch(e){return!1}}const r=e=>t(e,"null"),o=e=>t(e,"string"),a=e=>t(e,"number")&&!isNaN(e)||t(e,"bigint"),s=e=>!r(e)&&t(e,"object"),u=e=>t(e,"function"),l=e=>n(e,"Array"),c=e=>!s(e)&&!u(e),d="undefined"!=typeof Event,f=e=>d&&i(e,Event),p="undefined"!=typeof Error,m=e=>p&&i(e,Error),g=e=>n(e,"ErrorEvent"),v=e=>n(e,"DOMError"),h=e=>n(e,"DOMException"),b="undefined"!=typeof Element,w="undefined"!=typeof Map;function y(e,n){if(e===n)return!0;if(t(e,"number")&&isNaN(e))return t(n,"number")&&isNaN(n);const i=l(e),r=l(n);if(i!==r)return!1;if(i&&r){const t=e.length;if(t!==n.length)return!1;for(let i=t;0!=i--;)if(!y(e[i],n[i]))return!1;return!0}const o=s(e),a=s(n);if(o!==a)return!1;if(e&&n&&o&&a){const t=Object.keys(e),i=Object.keys(n);if(t.length!==i.length)return!1;for(let e of t)if(!i.includes(e))return!1;for(let i of t)if(!y(e[i],n[i]))return!1;return!0}return!1}function S(){return(new Date).toISOString()}var T;e.LogLevel=void 0,(T=e.LogLevel||(e.LogLevel={})).TRACE="trace",T.DEBUG="debug",T.INFO="info",T.LOG="log",T.WARN="warn",T.ERROR="error";const E=e.LogLevel.LOG,I=[e.LogLevel.TRACE,e.LogLevel.DEBUG,e.LogLevel.INFO,e.LogLevel.LOG,e.LogLevel.WARN,e.LogLevel.ERROR];function k(){}function x(e){const{size:t,concurrency:n}=e,i=[];let r=0;const o=()=>{if(r<n&&i.length){const{producer:e,resolve:t,reject:n}=i.shift();r++,e().then((e=>{r--,o(),t(e)}),(e=>{r--,o(),n(e)}))}};return{add:e=>{if(i.length+r>=t)throw new Error("Task buffer full");return new Promise(((t,n)=>{i.push({producer:e,resolve:t,reject:n}),o()}))}}}const L="abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ0123456789";function O(e=10){return Array.from(Array(e)).map((()=>L[Math.floor(Math.random()*L.length)])).join("")}const C="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof global?global:"undefined"!=typeof self?self:void 0;function P(){return Date.now()}class _{constructor(e,t){var n,i;this.signalBuffer=[],this.itemLimit=null!==(n=null==t?void 0:t.itemLimit)&&void 0!==n?n:50,this.sendTimeout=null!==(i=null==t?void 0:t.sendTimeout)&&void 0!==i?i:250,this.paused=(null==t?void 0:t.paused)||!1,this.sendFn=e,this.flushInterval=-1,this.paused||this.start(),document.addEventListener("visibilitychange",(()=>{"hidden"===document.visibilityState&&this.flush()}))}addItem(e){this.paused||(this.signalBuffer.push(e),this.signalBuffer.length>=this.itemLimit&&this.flush())}start(){this.paused=!1,this.sendTimeout>0&&(this.flushInterval=window.setInterval((()=>this.flush()),this.sendTimeout))}pause(){this.paused=!0,clearInterval(this.flushInterval)}groupItems(e){const t=new Map;return e.forEach((e=>{const n=JSON.stringify(e.meta);let i=t.get(n);i=void 0===i?[e]:[...i,e],t.set(n,i)})),Array.from(t.values())}flush(){if(this.paused||0===this.signalBuffer.length)return;this.groupItems(this.signalBuffer).forEach(this.sendFn),this.signalBuffer=[]}}var N;e.TransportItemType=void 0,(N=e.TransportItemType||(e.TransportItemType={})).EXCEPTION="exception",N.LOG="log",N.MEASUREMENT="measurement",N.TRACE="trace",N.EVENT="event";const A={[e.TransportItemType.EXCEPTION]:"exceptions",[e.TransportItemType.LOG]:"logs",[e.TransportItemType.MEASUREMENT]:"measurements",[e.TransportItemType.TRACE]:"traces",[e.TransportItemType.EVENT]:"events"};function M(t){return n=>{if(n.type===e.TransportItemType.EXCEPTION&&n.payload){const e=n.payload,i=`${e.type}: ${e.value}`;if(function(e,t){return e.some((e=>o(e)?t.includes(e):!!t.match(e)))}(t,i))return null}return n}}function D(e,t,n,i){var r;t.debug("Initializing transports");const o=[];let a=n.paused,s=[];const u=e=>{let t=e;for(const e of s){const n=t.map(e).filter(Boolean);if(0===n.length)return[];t=n}return t},l=e=>{const n=u(e);if(0!==n.length)for(const e of o)t.debug(`Transporting item using ${e.name}\n`,n),e.isBatched()&&e.send(n)};let c;(null===(r=n.batching)||void 0===r?void 0:r.enabled)&&(c=new _(l,{sendTimeout:n.batching.sendTimeout,itemLimit:n.batching.itemLimit,paused:a}));return{add:(...r)=>{t.debug("Adding transports"),r.forEach((r=>{t.debug(`Adding "${r.name}" transport`);o.some((e=>e===r))?t.warn(`Transport ${r.name} is already added`):(r.unpatchedConsole=e,r.internalLogger=t,r.config=n,r.metas=i,o.push(r))}))},addBeforeSendHooks:(...e)=>{t.debug("Adding beforeSendHooks\n",s),e.forEach((e=>{e&&s.push(e)}))},addIgnoreErrorsPatterns:(...e)=>{t.debug("Adding ignoreErrorsPatterns\n",e),e.forEach((e=>{e&&s.push(M(e))}))},getBeforeSendHooks:()=>[...s],execute:e=>{var i;a||((null===(i=n.batching)||void 0===i?void 0:i.enabled)&&(null==c||c.addItem(e)),(e=>{var i,r;if((null===(i=n.batching)||void 0===i?void 0:i.enabled)&&o.every((e=>e.isBatched())))return;const[a]=u([e]);if(void 0!==a)for(const e of o)t.debug(`Transporting item using ${e.name}\n`,a),e.isBatched()?(null===(r=n.batching)||void 0===r?void 0:r.enabled)||e.send([a]):e.send(a)})(e))},isPaused:()=>a,pause:()=>{t.debug("Pausing transports"),null==c||c.pause(),a=!0},remove:(...e)=>{t.debug("Removing transports"),e.forEach((e=>{t.debug(`Removing "${e.name}" transport`);const n=o.indexOf(e);-1!==n?o.splice(n,1):t.warn(`Transport "${e.name}" is not added`)}))},removeBeforeSendHooks:(...e)=>{s.filter((t=>!e.includes(t)))},get transports(){return[...o]},unpause:()=>{t.debug("Unpausing transports"),null==c||c.start(),a=!1}}}var j;e.InternalLoggerLevel=void 0,(j=e.InternalLoggerLevel||(e.InternalLoggerLevel={}))[j.OFF=0]="OFF",j[j.ERROR=1]="ERROR",j[j.WARN=2]="WARN",j[j.INFO=3]="INFO",j[j.VERBOSE=4]="VERBOSE";const R={debug:k,error:k,info:k,prefix:"Faro",warn:k},B=e.InternalLoggerLevel.ERROR,U=Object.assign({},console);let F=U;function z(e){var t;return F=null!==(t=e.unpatchedConsole)&&void 0!==t?t:F,F}function V(t=U,n=B){const i=R;return n>e.InternalLoggerLevel.OFF&&(i.error=n>=e.InternalLoggerLevel.ERROR?function(...e){t.error(`${i.prefix}\n`,...e)}:k,i.warn=n>=e.InternalLoggerLevel.WARN?function(...e){t.warn(`${i.prefix}\n`,...e)}:k,i.info=n>=e.InternalLoggerLevel.INFO?function(...e){t.info(`${i.prefix}\n`,...e)}:k,i.debug=n>=e.InternalLoggerLevel.VERBOSE?function(...e){t.debug(`${i.prefix}\n`,...e)}:k),i}let $=R;function q(e,t){return $=V(e,t.internalLoggerLevel),$}class G{constructor(){this.unpatchedConsole=U,this.internalLogger=R,this.config={},this.metas={}}logDebug(...e){this.internalLogger.debug(`${this.name}\n`,...e)}logInfo(...e){this.internalLogger.info(`${this.name}\n`,...e)}logWarn(...e){this.internalLogger.warn(`${this.name}\n`,...e)}logError(...e){this.internalLogger.error(`${this.name}\n`,...e)}}class W extends G{isBatched(){return!1}getIgnoreUrls(){return[]}}function H(e,t){var n,i;if(void 0===t)return e;if(void 0===e)return{resourceSpans:t};const r=null===(n=e.resourceSpans)||void 0===n?void 0:n[0];if(void 0===r)return e;const o=(null==r?void 0:r.scopeSpans)||[],a=(null===(i=null==t?void 0:t[0])||void 0===i?void 0:i.scopeSpans)||[];return Object.assign(Object.assign({},e),{resourceSpans:[Object.assign(Object.assign({},r),{scopeSpans:[...o,...a]})]})}function K(t){let n={meta:{}};return void 0!==t[0]&&(n.meta=t[0].meta),t.forEach((t=>{switch(t.type){case e.TransportItemType.LOG:case e.TransportItemType.EVENT:case e.TransportItemType.EXCEPTION:case e.TransportItemType.MEASUREMENT:const i=A[t.type],r=n[i];n=Object.assign(Object.assign({},n),{[i]:void 0===r?[t.payload]:[...r,t.payload]});break;case e.TransportItemType.TRACE:n=Object.assign(Object.assign({},n),{traces:H(n.traces,t.payload.resourceSpans)})}})),n}const X="Error";let J;const Z=e=>e.map((e=>{try{return String(e)}catch(e){return""}})).join(" ");function Y(t,n,i,o,a){n.debug("Initializing API");const s=function(t,n,i,r,o){let a;return n.debug("Initializing traces API"),{getOTEL:()=>a,getTraceContext:()=>{const e=null==a?void 0:a.trace.getSpanContext(a.context.active());return e?{trace_id:e.traceId,span_id:e.spanId}:void 0},initOTEL:(e,t)=>{n.debug("Initializing OpenTelemetry"),a={trace:e,context:t}},isOTELInitialized:()=>!!a,pushTraces:t=>{try{const i={type:e.TransportItemType.TRACE,payload:t,meta:r.value};n.debug("Pushing trace\n",i),o.execute(i)}catch(e){n.error("Error pushing trace\n",e)}}}}(0,n,0,o,a);return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},s),function(t,n,i,o,a,s){var u;n.debug("Initializing exceptions API");let l=null;J=null!==(u=i.parseStacktrace)&&void 0!==u?u:J;const c=e=>{n.debug("Changing stacktrace parser"),J=null!=e?e:J};return c(i.parseStacktrace),{changeStacktraceParser:c,getStacktraceParser:()=>J,pushError:(t,{skipDedupe:u,stackFrames:c,type:d,context:f,spanContext:p}={})=>{d=d||t.name||X;const m={meta:o.value,payload:{type:d,value:t.message,timestamp:S(),trace:p?{trace_id:p.traceId,span_id:p.spanId}:s.getTraceContext(),context:null!=f?f:{}},type:e.TransportItemType.EXCEPTION};(null==(c=null!=c?c:t.stack?null==J?void 0:J(t).frames:void 0)?void 0:c.length)&&(m.payload.stacktrace={frames:c});const g={type:m.payload.type,value:m.payload.value,stackTrace:m.payload.stacktrace,context:m.payload.context};u||!i.dedupe||r(l)||!y(g,l)?(l=g,n.debug("Pushing exception\n",m),a.execute(m)):n.debug("Skipping error push because it is the same as the last one\n",m.payload)}}}(0,n,i,o,a,s)),function(e,t,n,i,r){let o,a,s;t.debug("Initializing meta API");const u=e=>{a&&i.remove(a),a={user:e},i.add(a)},l=e=>{o&&i.remove(o),o={session:e},i.add(o)};return{setUser:u,resetUser:u,setSession:l,resetSession:l,getSession:()=>i.value.session,setView:e=>{var t;if((null===(t=null==s?void 0:s.view)||void 0===t?void 0:t.name)===(null==e?void 0:e.name))return;const n=s;s={view:e},i.add(s),n&&i.remove(n)},getView:()=>i.value.view}}(0,n,0,o)),function(t,n,i,o,a,s){var u;n.debug("Initializing logs API");let l=null;const c=null!==(u=i.logArgsSerializer)&&void 0!==u?u:Z;return{pushLog:(t,{context:u,level:d,skipDedupe:f,spanContext:p}={})=>{try{const m={type:e.TransportItemType.LOG,payload:{message:c(t),level:null!=d?d:E,context:null!=u?u:{},timestamp:S(),trace:p?{trace_id:p.traceId,span_id:p.spanId}:s.getTraceContext()},meta:o.value},g={message:m.payload.message,level:m.payload.level,context:m.payload.context};if(!f&&i.dedupe&&!r(l)&&y(g,l))return void n.debug("Skipping log push because it is the same as the last one\n",m.payload);l=g,n.debug("Pushing log\n",m),a.execute(m)}catch(e){n.error("Error pushing log\n",e)}}}}(0,n,i,o,a,s)),function(t,n,i,o,a,s){n.debug("Initializing measurements API");let u=null;return{pushMeasurement:(t,{skipDedupe:l,context:c,spanContext:d}={})=>{var f;try{const p={type:e.TransportItemType.MEASUREMENT,payload:Object.assign(Object.assign({},t),{trace:d?{trace_id:d.traceId,span_id:d.spanId}:s.getTraceContext(),timestamp:null!==(f=t.timestamp)&&void 0!==f?f:S(),context:null!=c?c:{}}),meta:o.value},m={type:p.payload.type,values:p.payload.values,context:p.payload.context};if(!l&&i.dedupe&&!r(u)&&y(m,u))return void n.debug("Skipping measurement push because it is the same as the last one\n",p.payload);u=m,n.debug("Pushing measurement\n",p),a.execute(p)}catch(e){n.error("Error pushing measurement\n",e)}}}}(0,n,i,o,a,s)),function(t,n,i,o,a,s){let u=null;return{pushEvent:(t,l,c,{skipDedupe:d,spanContext:f}={})=>{try{const p={meta:o.value,payload:{name:t,domain:null!=c?c:i.eventDomain,attributes:l,timestamp:S(),trace:f?{trace_id:f.traceId,span_id:f.spanId}:s.getTraceContext()},type:e.TransportItemType.EVENT},m={name:p.payload.name,attributes:p.payload.attributes,domain:p.payload.domain};if(!d&&i.dedupe&&!r(u)&&y(m,u))return void n.debug("Skipping event push because it is the same as the last one\n",p.payload);u=m,n.debug("Pushing event\n",p),a.execute(p)}catch(e){n.error("Error pushing event",e)}}}}(0,n,i,o,a,s))}class Q extends G{constructor(){super(...arguments),this.api={},this.transports={}}}const ee="1.8.0";const te="_faroInternal";function ne(e){e.config.isolate?e.internalLogger.debug("Skipping registering internal Faro instance on global object"):(e.internalLogger.debug("Registering internal Faro instance on global object"),Object.defineProperty(C,te,{configurable:!1,enumerable:!1,writable:!1,value:e}))}function ie(){return te in C}function re(t,n,i,r,o,a,s){return n.debug("Initializing Faro"),e.faro={api:a,config:i,instrumentations:s,internalLogger:n,metas:r,pause:o.pause,transports:o,unpatchedConsole:t,unpause:o.unpause},ne(e.faro),function(e){if(e.config.preventGlobalExposure)e.internalLogger.debug("Skipping registering public Faro instance in the global scope");else{if(e.internalLogger.debug(`Registering public faro reference in the global scope using "${e.config.globalObjectKey}" key`),e.config.globalObjectKey in C)return void e.internalLogger.warn(`Skipping global registration due to key "${e.config.globalObjectKey}" being used already. Please set "globalObjectKey" to something else or set "preventGlobalExposure" to "true"`);Object.defineProperty(C,e.config.globalObjectKey,{configurable:!1,writable:!1,value:e})}}(e.faro),e.faro}function oe(e){const t=z(e),n=q(t,e);if(ie()&&!e.isolate)return void n.error('Faro is already registered. Either add instrumentations, transports etc. to the global faro instance or use the "isolate" property');n.debug("Initializing");const i=function(e,t,n){let i=[],r=[];const o=()=>i.reduce(((e,t)=>Object.assign(e,u(t)?t():t)),{}),a=()=>{if(r.length){const e=o();r.forEach((t=>t(e)))}};return{add:(...e)=>{t.debug("Adding metas\n",e),i.push(...e),a()},remove:(...e)=>{t.debug("Removing metas\n",e),i=i.filter((t=>!e.includes(t))),a()},addListener:e=>{t.debug("Adding metas listener\n",e),r.push(e)},removeListener:e=>{t.debug("Removing metas listener\n",e),r=r.filter((t=>t!==e))},get value(){return o()}}}(0,n),r=D(t,n,e,i),o=Y(0,n,e,i,r),a=function(e,t,n,i,r,o){t.debug("Initializing instrumentations");const a=[];return{add:(...s)=>{t.debug("Adding instrumentations"),s.forEach((s=>{t.debug(`Adding "${s.name}" instrumentation`),a.some((e=>e.name===s.name))?t.warn(`Instrumentation ${s.name} is already added`):(s.unpatchedConsole=e,s.internalLogger=t,s.config=n,s.metas=i,s.transports=r,s.api=o,a.push(s),s.initialize())}))},get instrumentations(){return[...a]},remove:(...e)=>{t.debug("Removing instrumentations"),e.forEach((e=>{var n,i;t.debug(`Removing "${e.name}" instrumentation`);const r=a.reduce(((t,n,i)=>null===t&&n.name===e.name?i:null),null);r?(null===(i=(n=a[r]).destroy)||void 0===i||i.call(n),a.splice(r,1)):t.warn(`Instrumentation "${e.name}" is not added`)}))}}}(t,n,e,i,r,o),s=re(t,n,e,i,r,o,a);return function(e){var t,n;const i={sdk:{version:ee},app:{bundleId:e.config.app.name&&(r=e.config.app.name,null==C?void 0:C[`__faroBundleId_${r}`])}};var r;const o=null===(t=e.config.sessionTracking)||void 0===t?void 0:t.session;o&&e.api.setSession(o),e.config.app&&(i.app=Object.assign(Object.assign({},e.config.app),i.app)),e.config.user&&(i.user=e.config.user),e.config.view&&(i.view=e.config.view),e.metas.add(i,...null!==(n=e.config.metas)&&void 0!==n?n:[])}(s),function(e){e.transports.add(...e.config.transports),e.transports.addBeforeSendHooks(e.config.beforeSend),e.transports.addIgnoreErrorsPatterns(e.config.ignoreErrors)}(s),function(e){e.instrumentations.add(...e.config.instrumentations)}(s),s}e.faro={};const ae="faro",se={enabled:!0,sendTimeout:250,itemLimit:50},ue="view_changed",le="session_start",ce="session_resume",de="session_extend";var fe="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},pe={exports:{}};!function(e,t){!function(n,i){var r="function",o="undefined",a="object",s="string",u="major",l="model",c="name",d="type",f="vendor",p="version",m="architecture",g="console",v="mobile",h="tablet",b="smarttv",w="wearable",y="embedded",S="Amazon",T="Apple",E="ASUS",I="BlackBerry",k="Browser",x="Chrome",L="Firefox",O="Google",C="Huawei",P="LG",_="Microsoft",N="Motorola",A="Opera",M="Samsung",D="Sharp",j="Sony",R="Xiaomi",B="Zebra",U="Facebook",F="Chromium OS",z="Mac OS",V=function(e){for(var t={},n=0;n<e.length;n++)t[e[n].toUpperCase()]=e[n];return t},$=function(e,t){return typeof e===s&&-1!==q(t).indexOf(q(e))},q=function(e){return e.toLowerCase()},G=function(e,t){if(typeof e===s)return e=e.replace(/^\s\s*/,""),typeof t===o?e:e.substring(0,350)},W=function(e,t){for(var n,o,s,u,l,c,d=0;d<t.length&&!l;){var f=t[d],p=t[d+1];for(n=o=0;n<f.length&&!l&&f[n];)if(l=f[n++].exec(e))for(s=0;s<p.length;s++)c=l[++o],typeof(u=p[s])===a&&u.length>0?2===u.length?typeof u[1]==r?this[u[0]]=u[1].call(this,c):this[u[0]]=u[1]:3===u.length?typeof u[1]!==r||u[1].exec&&u[1].test?this[u[0]]=c?c.replace(u[1],u[2]):i:this[u[0]]=c?u[1].call(this,c,u[2]):i:4===u.length&&(this[u[0]]=c?u[3].call(this,c.replace(u[1],u[2])):i):this[u]=c||i;d+=2}},H=function(e,t){for(var n in t)if(typeof t[n]===a&&t[n].length>0){for(var r=0;r<t[n].length;r++)if($(t[n][r],e))return"?"===n?i:n}else if($(t[n],e))return"?"===n?i:n;return e},K={ME:"4.90","NT 3.11":"NT3.51","NT 4.0":"NT4.0",2e3:"NT 5.0",XP:["NT 5.1","NT 5.2"],Vista:"NT 6.0",7:"NT 6.1",8:"NT 6.2",8.1:"NT 6.3",10:["NT 6.4","NT 10.0"],RT:"ARM"},X={browser:[[/\b(?:crmo|crios)\/([\w\.]+)/i],[p,[c,"Chrome"]],[/edg(?:e|ios|a)?\/([\w\.]+)/i],[p,[c,"Edge"]],[/(opera mini)\/([-\w\.]+)/i,/(opera [mobiletab]{3,6})\b.+version\/([-\w\.]+)/i,/(opera)(?:.+version\/|[\/ ]+)([\w\.]+)/i],[c,p],[/opios[\/ ]+([\w\.]+)/i],[p,[c,A+" Mini"]],[/\bopr\/([\w\.]+)/i],[p,[c,A]],[/(kindle)\/([\w\.]+)/i,/(lunascape|maxthon|netfront|jasmine|blazer)[\/ ]?([\w\.]*)/i,/(avant |iemobile|slim)(?:browser)?[\/ ]?([\w\.]*)/i,/(ba?idubrowser)[\/ ]?([\w\.]+)/i,/(?:ms|\()(ie) ([\w\.]+)/i,/(flock|rockmelt|midori|epiphany|silk|skyfire|bolt|iron|vivaldi|iridium|phantomjs|bowser|quark|qupzilla|falkon|rekonq|puffin|brave|whale(?!.+naver)|qqbrowserlite|qq|duckduckgo)\/([-\w\.]+)/i,/(heytap|ovi)browser\/([\d\.]+)/i,/(weibo)__([\d\.]+)/i],[c,p],[/(?:\buc? ?browser|(?:juc.+)ucweb)[\/ ]?([\w\.]+)/i],[p,[c,"UC"+k]],[/microm.+\bqbcore\/([\w\.]+)/i,/\bqbcore\/([\w\.]+).+microm/i],[p,[c,"WeChat(Win) Desktop"]],[/micromessenger\/([\w\.]+)/i],[p,[c,"WeChat"]],[/konqueror\/([\w\.]+)/i],[p,[c,"Konqueror"]],[/trident.+rv[: ]([\w\.]{1,9})\b.+like gecko/i],[p,[c,"IE"]],[/ya(?:search)?browser\/([\w\.]+)/i],[p,[c,"Yandex"]],[/(avast|avg)\/([\w\.]+)/i],[[c,/(.+)/,"$1 Secure "+k],p],[/\bfocus\/([\w\.]+)/i],[p,[c,L+" Focus"]],[/\bopt\/([\w\.]+)/i],[p,[c,A+" Touch"]],[/coc_coc\w+\/([\w\.]+)/i],[p,[c,"Coc Coc"]],[/dolfin\/([\w\.]+)/i],[p,[c,"Dolphin"]],[/coast\/([\w\.]+)/i],[p,[c,A+" Coast"]],[/miuibrowser\/([\w\.]+)/i],[p,[c,"MIUI "+k]],[/fxios\/([-\w\.]+)/i],[p,[c,L]],[/\bqihu|(qi?ho?o?|360)browser/i],[[c,"360 "+k]],[/(oculus|samsung|sailfish|huawei)browser\/([\w\.]+)/i],[[c,/(.+)/,"$1 "+k],p],[/(comodo_dragon)\/([\w\.]+)/i],[[c,/_/g," "],p],[/(electron)\/([\w\.]+) safari/i,/(tesla)(?: qtcarbrowser|\/(20\d\d\.[-\w\.]+))/i,/m?(qqbrowser|baiduboxapp|2345Explorer)[\/ ]?([\w\.]+)/i],[c,p],[/(metasr)[\/ ]?([\w\.]+)/i,/(lbbrowser)/i,/\[(linkedin)app\]/i],[c],[/((?:fban\/fbios|fb_iab\/fb4a)(?!.+fbav)|;fbav\/([\w\.]+);)/i],[[c,U],p],[/(kakao(?:talk|story))[\/ ]([\w\.]+)/i,/(naver)\(.*?(\d+\.[\w\.]+).*\)/i,/safari (line)\/([\w\.]+)/i,/\b(line)\/([\w\.]+)\/iab/i,/(chromium|instagram|snapchat)[\/ ]([-\w\.]+)/i],[c,p],[/\bgsa\/([\w\.]+) .*safari\//i],[p,[c,"GSA"]],[/musical_ly(?:.+app_?version\/|_)([\w\.]+)/i],[p,[c,"TikTok"]],[/headlesschrome(?:\/([\w\.]+)| )/i],[p,[c,x+" Headless"]],[/ wv\).+(chrome)\/([\w\.]+)/i],[[c,x+" WebView"],p],[/droid.+ version\/([\w\.]+)\b.+(?:mobile safari|safari)/i],[p,[c,"Android "+k]],[/(chrome|omniweb|arora|[tizenoka]{5} ?browser)\/v?([\w\.]+)/i],[c,p],[/version\/([\w\.\,]+) .*mobile\/\w+ (safari)/i],[p,[c,"Mobile Safari"]],[/version\/([\w(\.|\,)]+) .*(mobile ?safari|safari)/i],[p,c],[/webkit.+?(mobile ?safari|safari)(\/[\w\.]+)/i],[c,[p,H,{"1.0":"/8",1.2:"/1",1.3:"/3","2.0":"/412","2.0.2":"/416","2.0.3":"/417","2.0.4":"/419","?":"/"}]],[/(webkit|khtml)\/([\w\.]+)/i],[c,p],[/(navigator|netscape\d?)\/([-\w\.]+)/i],[[c,"Netscape"],p],[/mobile vr; rv:([\w\.]+)\).+firefox/i],[p,[c,L+" Reality"]],[/ekiohf.+(flow)\/([\w\.]+)/i,/(swiftfox)/i,/(icedragon|iceweasel|camino|chimera|fennec|maemo browser|minimo|conkeror|klar)[\/ ]?([\w\.\+]+)/i,/(seamonkey|k-meleon|icecat|iceape|firebird|phoenix|palemoon|basilisk|waterfox)\/([-\w\.]+)$/i,/(firefox)\/([\w\.]+)/i,/(mozilla)\/([\w\.]+) .+rv\:.+gecko\/\d+/i,/(polaris|lynx|dillo|icab|doris|amaya|w3m|netsurf|sleipnir|obigo|mosaic|(?:go|ice|up)[\. ]?browser)[-\/ ]?v?([\w\.]+)/i,/(links) \(([\w\.]+)/i,/panasonic;(viera)/i],[c,p],[/(cobalt)\/([\w\.]+)/i],[c,[p,/master.|lts./,""]]],cpu:[[/(?:(amd|x(?:(?:86|64)[-_])?|wow|win)64)[;\)]/i],[[m,"amd64"]],[/(ia32(?=;))/i],[[m,q]],[/((?:i[346]|x)86)[;\)]/i],[[m,"ia32"]],[/\b(aarch64|arm(v?8e?l?|_?64))\b/i],[[m,"arm64"]],[/\b(arm(?:v[67])?ht?n?[fl]p?)\b/i],[[m,"armhf"]],[/windows (ce|mobile); ppc;/i],[[m,"arm"]],[/((?:ppc|powerpc)(?:64)?)(?: mac|;|\))/i],[[m,/ower/,"",q]],[/(sun4\w)[;\)]/i],[[m,"sparc"]],[/((?:avr32|ia64(?=;))|68k(?=\))|\barm(?=v(?:[1-7]|[5-7]1)l?|;|eabi)|(?=atmel )avr|(?:irix|mips|sparc)(?:64)?\b|pa-risc)/i],[[m,q]]],device:[[/\b(sch-i[89]0\d|shw-m380s|sm-[ptx]\w{2,4}|gt-[pn]\d{2,4}|sgh-t8[56]9|nexus 10)/i],[l,[f,M],[d,h]],[/\b((?:s[cgp]h|gt|sm)-\w+|sc[g-]?[\d]+a?|galaxy nexus)/i,/samsung[- ]([-\w]+)/i,/sec-(sgh\w+)/i],[l,[f,M],[d,v]],[/(?:\/|\()(ip(?:hone|od)[\w, ]*)(?:\/|;)/i],[l,[f,T],[d,v]],[/\((ipad);[-\w\),; ]+apple/i,/applecoremedia\/[\w\.]+ \((ipad)/i,/\b(ipad)\d\d?,\d\d?[;\]].+ios/i],[l,[f,T],[d,h]],[/(macintosh);/i],[l,[f,T]],[/\b(sh-?[altvz]?\d\d[a-ekm]?)/i],[l,[f,D],[d,v]],[/\b((?:ag[rs][23]?|bah2?|sht?|btv)-a?[lw]\d{2})\b(?!.+d\/s)/i],[l,[f,C],[d,h]],[/(?:huawei|honor)([-\w ]+)[;\)]/i,/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][012359c][adn]?)\b(?!.+d\/s)/i],[l,[f,C],[d,v]],[/\b(poco[\w ]+|m2\d{3}j\d\d[a-z]{2})(?: bui|\))/i,/\b; (\w+) build\/hm\1/i,/\b(hm[-_ ]?note?[_ ]?(?:\d\w)?) bui/i,/\b(redmi[\-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,/\b(mi[-_ ]?(?:a\d|one|one[_ ]plus|note lte|max|cc)?[_ ]?(?:\d?\w?)[_ ]?(?:plus|se|lite)?)(?: bui|\))/i],[[l,/_/g," "],[f,R],[d,v]],[/\b(mi[-_ ]?(?:pad)(?:[\w_ ]+))(?: bui|\))/i],[[l,/_/g," "],[f,R],[d,h]],[/; (\w+) bui.+ oppo/i,/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i],[l,[f,"OPPO"],[d,v]],[/vivo (\w+)(?: bui|\))/i,/\b(v[12]\d{3}\w?[at])(?: bui|;)/i],[l,[f,"Vivo"],[d,v]],[/\b(rmx[12]\d{3})(?: bui|;|\))/i],[l,[f,"Realme"],[d,v]],[/\b(milestone|droid(?:[2-4x]| (?:bionic|x2|pro|razr))?:?( 4g)?)\b[\w ]+build\//i,/\bmot(?:orola)?[- ](\w*)/i,/((?:moto[\w\(\) ]+|xt\d{3,4}|nexus 6)(?= bui|\)))/i],[l,[f,N],[d,v]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i],[l,[f,N],[d,h]],[/((?=lg)?[vl]k\-?\d{3}) bui| 3\.[-\w; ]{10}lg?-([06cv9]{3,4})/i],[l,[f,P],[d,h]],[/(lm(?:-?f100[nv]?|-[\w\.]+)(?= bui|\))|nexus [45])/i,/\blg[-e;\/ ]+((?!browser|netcast|android tv)\w+)/i,/\blg-?([\d\w]+) bui/i],[l,[f,P],[d,v]],[/(ideatab[-\w ]+)/i,/lenovo ?(s[56]000[-\w]+|tab(?:[\w ]+)|yt[-\d\w]{6}|tb[-\d\w]{6})/i],[l,[f,"Lenovo"],[d,h]],[/(?:maemo|nokia).*(n900|lumia \d+)/i,/nokia[-_ ]?([-\w\.]*)/i],[[l,/_/g," "],[f,"Nokia"],[d,v]],[/(pixel c)\b/i],[l,[f,O],[d,h]],[/droid.+; (pixel[\daxl ]{0,6})(?: bui|\))/i],[l,[f,O],[d,v]],[/droid.+ (a?\d[0-2]{2}so|[c-g]\d{4}|so[-gl]\w+|xq-a\w[4-7][12])(?= bui|\).+chrome\/(?![1-6]{0,1}\d\.))/i],[l,[f,j],[d,v]],[/sony tablet [ps]/i,/\b(?:sony)?sgp\w+(?: bui|\))/i],[[l,"Xperia Tablet"],[f,j],[d,h]],[/ (kb2005|in20[12]5|be20[12][59])\b/i,/(?:one)?(?:plus)? (a\d0\d\d)(?: b|\))/i],[l,[f,"OnePlus"],[d,v]],[/(alexa)webm/i,/(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\))/i,/(kf[a-z]+)( bui|\)).+silk\//i],[l,[f,S],[d,h]],[/((?:sd|kf)[0349hijorstuw]+)( bui|\)).+silk\//i],[[l,/(.+)/g,"Fire Phone $1"],[f,S],[d,v]],[/(playbook);[-\w\),; ]+(rim)/i],[l,f,[d,h]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,/\(bb10; (\w+)/i],[l,[f,I],[d,v]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i],[l,[f,E],[d,h]],[/ (z[bes]6[027][012][km][ls]|zenfone \d\w?)\b/i],[l,[f,E],[d,v]],[/(nexus 9)/i],[l,[f,"HTC"],[d,h]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,/(alcatel|geeksphone|nexian|panasonic(?!(?:;|\.))|sony(?!-bra))[-_ ]?([-\w]*)/i],[f,[l,/_/g," "],[d,v]],[/droid.+; ([ab][1-7]-?[0178a]\d\d?)/i],[l,[f,"Acer"],[d,h]],[/droid.+; (m[1-5] note) bui/i,/\bmz-([-\w]{2,})/i],[l,[f,"Meizu"],[d,v]],[/(blackberry|benq|palm(?=\-)|sonyericsson|acer|asus|dell|meizu|motorola|polytron|infinix|tecno)[-_ ]?([-\w]*)/i,/(hp) ([\w ]+\w)/i,/(asus)-?(\w+)/i,/(microsoft); (lumia[\w ]+)/i,/(lenovo)[-_ ]?([-\w]+)/i,/(jolla)/i,/(oppo) ?([\w ]+) bui/i],[f,l,[d,v]],[/(kobo)\s(ereader|touch)/i,/(archos) (gamepad2?)/i,/(hp).+(touchpad(?!.+tablet)|tablet)/i,/(kindle)\/([\w\.]+)/i,/(nook)[\w ]+build\/(\w+)/i,/(dell) (strea[kpr\d ]*[\dko])/i,/(le[- ]+pan)[- ]+(\w{1,9}) bui/i,/(trinity)[- ]*(t\d{3}) bui/i,/(gigaset)[- ]+(q\w{1,9}) bui/i,/(vodafone) ([\w ]+)(?:\)| bui)/i],[f,l,[d,h]],[/(surface duo)/i],[l,[f,_],[d,h]],[/droid [\d\.]+; (fp\du?)(?: b|\))/i],[l,[f,"Fairphone"],[d,v]],[/(u304aa)/i],[l,[f,"AT&T"],[d,v]],[/\bsie-(\w*)/i],[l,[f,"Siemens"],[d,v]],[/\b(rct\w+) b/i],[l,[f,"RCA"],[d,h]],[/\b(venue[\d ]{2,7}) b/i],[l,[f,"Dell"],[d,h]],[/\b(q(?:mv|ta)\w+) b/i],[l,[f,"Verizon"],[d,h]],[/\b(?:barnes[& ]+noble |bn[rt])([\w\+ ]*) b/i],[l,[f,"Barnes & Noble"],[d,h]],[/\b(tm\d{3}\w+) b/i],[l,[f,"NuVision"],[d,h]],[/\b(k88) b/i],[l,[f,"ZTE"],[d,h]],[/\b(nx\d{3}j) b/i],[l,[f,"ZTE"],[d,v]],[/\b(gen\d{3}) b.+49h/i],[l,[f,"Swiss"],[d,v]],[/\b(zur\d{3}) b/i],[l,[f,"Swiss"],[d,h]],[/\b((zeki)?tb.*\b) b/i],[l,[f,"Zeki"],[d,h]],[/\b([yr]\d{2}) b/i,/\b(dragon[- ]+touch |dt)(\w{5}) b/i],[[f,"Dragon Touch"],l,[d,h]],[/\b(ns-?\w{0,9}) b/i],[l,[f,"Insignia"],[d,h]],[/\b((nxa|next)-?\w{0,9}) b/i],[l,[f,"NextBook"],[d,h]],[/\b(xtreme\_)?(v(1[045]|2[015]|[3469]0|7[05])) b/i],[[f,"Voice"],l,[d,v]],[/\b(lvtel\-)?(v1[12]) b/i],[[f,"LvTel"],l,[d,v]],[/\b(ph-1) /i],[l,[f,"Essential"],[d,v]],[/\b(v(100md|700na|7011|917g).*\b) b/i],[l,[f,"Envizen"],[d,h]],[/\b(trio[-\w\. ]+) b/i],[l,[f,"MachSpeed"],[d,h]],[/\btu_(1491) b/i],[l,[f,"Rotor"],[d,h]],[/(shield[\w ]+) b/i],[l,[f,"Nvidia"],[d,h]],[/(sprint) (\w+)/i],[f,l,[d,v]],[/(kin\.[onetw]{3})/i],[[l,/\./g," "],[f,_],[d,v]],[/droid.+; (cc6666?|et5[16]|mc[239][23]x?|vc8[03]x?)\)/i],[l,[f,B],[d,h]],[/droid.+; (ec30|ps20|tc[2-8]\d[kx])\)/i],[l,[f,B],[d,v]],[/smart-tv.+(samsung)/i],[f,[d,b]],[/hbbtv.+maple;(\d+)/i],[[l,/^/,"SmartTV"],[f,M],[d,b]],[/(nux; netcast.+smarttv|lg (netcast\.tv-201\d|android tv))/i],[[f,P],[d,b]],[/(apple) ?tv/i],[f,[l,T+" TV"],[d,b]],[/crkey/i],[[l,x+"cast"],[f,O],[d,b]],[/droid.+aft(\w+)( bui|\))/i],[l,[f,S],[d,b]],[/\(dtv[\);].+(aquos)/i,/(aquos-tv[\w ]+)\)/i],[l,[f,D],[d,b]],[/(bravia[\w ]+)( bui|\))/i],[l,[f,j],[d,b]],[/(mitv-\w{5}) bui/i],[l,[f,R],[d,b]],[/Hbbtv.*(technisat) (.*);/i],[f,l,[d,b]],[/\b(roku)[\dx]*[\)\/]((?:dvp-)?[\d\.]*)/i,/hbbtv\/\d+\.\d+\.\d+ +\([\w\+ ]*; *([\w\d][^;]*);([^;]*)/i],[[f,G],[l,G],[d,b]],[/\b(android tv|smart[- ]?tv|opera tv|tv; rv:)\b/i],[[d,b]],[/(ouya)/i,/(nintendo) ([wids3utch]+)/i],[f,l,[d,g]],[/droid.+; (shield) bui/i],[l,[f,"Nvidia"],[d,g]],[/(playstation [345portablevi]+)/i],[l,[f,j],[d,g]],[/\b(xbox(?: one)?(?!; xbox))[\); ]/i],[l,[f,_],[d,g]],[/((pebble))app/i],[f,l,[d,w]],[/(watch)(?: ?os[,\/]|\d,\d\/)[\d\.]+/i],[l,[f,T],[d,w]],[/droid.+; (glass) \d/i],[l,[f,O],[d,w]],[/droid.+; (wt63?0{2,3})\)/i],[l,[f,B],[d,w]],[/(quest( 2| pro)?)/i],[l,[f,U],[d,w]],[/(tesla)(?: qtcarbrowser|\/[-\w\.]+)/i],[f,[d,y]],[/(aeobc)\b/i],[l,[f,S],[d,y]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+? mobile safari/i],[l,[d,v]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+?(?! mobile) safari/i],[l,[d,h]],[/\b((tablet|tab)[;\/]|focus\/\d(?!.+mobile))/i],[[d,h]],[/(phone|mobile(?:[;\/]| [ \w\/\.]*safari)|pda(?=.+windows ce))/i],[[d,v]],[/(android[-\w\. ]{0,9});.+buil/i],[l,[f,"Generic"]]],engine:[[/windows.+ edge\/([\w\.]+)/i],[p,[c,"EdgeHTML"]],[/webkit\/537\.36.+chrome\/(?!27)([\w\.]+)/i],[p,[c,"Blink"]],[/(presto)\/([\w\.]+)/i,/(webkit|trident|netfront|netsurf|amaya|lynx|w3m|goanna)\/([\w\.]+)/i,/ekioh(flow)\/([\w\.]+)/i,/(khtml|tasman|links)[\/ ]\(?([\w\.]+)/i,/(icab)[\/ ]([23]\.[\d\.]+)/i,/\b(libweb)/i],[c,p],[/rv\:([\w\.]{1,9})\b.+(gecko)/i],[p,c]],os:[[/microsoft (windows) (vista|xp)/i],[c,p],[/(windows) nt 6\.2; (arm)/i,/(windows (?:phone(?: os)?|mobile))[\/ ]?([\d\.\w ]*)/i,/(windows)[\/ ]?([ntce\d\. ]+\w)(?!.+xbox)/i],[c,[p,H,K]],[/(win(?=3|9|n)|win 9x )([nt\d\.]+)/i],[[c,"Windows"],[p,H,K]],[/ip[honead]{2,4}\b(?:.*os ([\w]+) like mac|; opera)/i,/(?:ios;fbsv\/|iphone.+ios[\/ ])([\d\.]+)/i,/cfnetwork\/.+darwin/i],[[p,/_/g,"."],[c,"iOS"]],[/(mac os x) ?([\w\. ]*)/i,/(macintosh|mac_powerpc\b)(?!.+haiku)/i],[[c,z],[p,/_/g,"."]],[/droid ([\w\.]+)\b.+(android[- ]x86|harmonyos)/i],[p,c],[/(android|webos|qnx|bada|rim tablet os|maemo|meego|sailfish)[-\/ ]?([\w\.]*)/i,/(blackberry)\w*\/([\w\.]*)/i,/(tizen|kaios)[\/ ]([\w\.]+)/i,/\((series40);/i],[c,p],[/\(bb(10);/i],[p,[c,I]],[/(?:symbian ?os|symbos|s60(?=;)|series60)[-\/ ]?([\w\.]*)/i],[p,[c,"Symbian"]],[/mozilla\/[\d\.]+ \((?:mobile|tablet|tv|mobile; [\w ]+); rv:.+ gecko\/([\w\.]+)/i],[p,[c,L+" OS"]],[/web0s;.+rt(tv)/i,/\b(?:hp)?wos(?:browser)?\/([\w\.]+)/i],[p,[c,"webOS"]],[/watch(?: ?os[,\/]|\d,\d\/)([\d\.]+)/i],[p,[c,"watchOS"]],[/crkey\/([\d\.]+)/i],[p,[c,x+"cast"]],[/(cros) [\w]+(?:\)| ([\w\.]+)\b)/i],[[c,F],p],[/panasonic;(viera)/i,/(netrange)mmh/i,/(nettv)\/(\d+\.[\w\.]+)/i,/(nintendo|playstation) ([wids345portablevuch]+)/i,/(xbox); +xbox ([^\);]+)/i,/\b(joli|palm)\b ?(?:os)?\/?([\w\.]*)/i,/(mint)[\/\(\) ]?(\w*)/i,/(mageia|vectorlinux)[; ]/i,/([kxln]?ubuntu|debian|suse|opensuse|gentoo|arch(?= linux)|slackware|fedora|mandriva|centos|pclinuxos|red ?hat|zenwalk|linpus|raspbian|plan 9|minix|risc os|contiki|deepin|manjaro|elementary os|sabayon|linspire)(?: gnu\/linux)?(?: enterprise)?(?:[- ]linux)?(?:-gnu)?[-\/ ]?(?!chrom|package)([-\w\.]*)/i,/(hurd|linux) ?([\w\.]*)/i,/(gnu) ?([\w\.]*)/i,/\b([-frentopcghs]{0,5}bsd|dragonfly)[\/ ]?(?!amd|[ix346]{1,2}86)([\w\.]*)/i,/(haiku) (\w+)/i],[c,p],[/(sunos) ?([\w\.\d]*)/i],[[c,"Solaris"],p],[/((?:open)?solaris)[-\/ ]?([\w\.]*)/i,/(aix) ((\d)(?=\.|\)| )[\w\.])*/i,/\b(beos|os\/2|amigaos|morphos|openvms|fuchsia|hp-ux|serenityos)/i,/(unix) ?([\w\.]*)/i],[c,p]]},J=function(e,t){if(typeof e===a&&(t=e,e=i),!(this instanceof J))return new J(e,t).getResult();var g=typeof n!==o&&n.navigator?n.navigator:i,b=e||(g&&g.userAgent?g.userAgent:""),w=g&&g.userAgentData?g.userAgentData:i,y=t?function(e,t){var n={};for(var i in e)t[i]&&t[i].length%2==0?n[i]=t[i].concat(e[i]):n[i]=e[i];return n}(X,t):X,S=g&&g.userAgent==b;return this.getBrowser=function(){var e,t={};return t[c]=i,t[p]=i,W.call(t,b,y.browser),t[u]=typeof(e=t[p])===s?e.replace(/[^\d\.]/g,"").split(".")[0]:i,S&&g&&g.brave&&typeof g.brave.isBrave==r&&(t[c]="Brave"),t},this.getCPU=function(){var e={};return e[m]=i,W.call(e,b,y.cpu),e},this.getDevice=function(){var e={};return e[f]=i,e[l]=i,e[d]=i,W.call(e,b,y.device),S&&!e[d]&&w&&w.mobile&&(e[d]=v),S&&"Macintosh"==e[l]&&g&&typeof g.standalone!==o&&g.maxTouchPoints&&g.maxTouchPoints>2&&(e[l]="iPad",e[d]=h),e},this.getEngine=function(){var e={};return e[c]=i,e[p]=i,W.call(e,b,y.engine),e},this.getOS=function(){var e={};return e[c]=i,e[p]=i,W.call(e,b,y.os),S&&!e[c]&&w&&"Unknown"!=w.platform&&(e[c]=w.platform.replace(/chrome os/i,F).replace(/macos/i,z)),e},this.getResult=function(){return{ua:this.getUA(),browser:this.getBrowser(),engine:this.getEngine(),os:this.getOS(),device:this.getDevice(),cpu:this.getCPU()}},this.getUA=function(){return b},this.setUA=function(e){return b=typeof e===s&&e.length>350?G(e,350):e,this},this.setUA(b),this};J.VERSION="1.0.36",J.BROWSER=V([c,p,u]),J.CPU=V([m]),J.DEVICE=V([l,f,d,g,v,b,h,w,y]),J.ENGINE=J.OS=V([c,p]),e.exports&&(t=e.exports=J),t.UAParser=J;var Z=typeof n!==o&&(n.jQuery||n.Zepto);if(Z&&!Z.ua){var Y=new J;Z.ua=Y.getResult(),Z.ua.get=function(){return Y.getUA()},Z.ua.set=function(e){Y.setUA(e);var t=Y.getResult();for(var n in t)Z.ua[n]=t[n]}}}("object"==typeof window?window:fe)}(pe,pe.exports);var me=pe.exports;const ge=()=>{const e=new me.UAParser,{name:t,version:n}=e.getBrowser(),{name:i,version:r}=e.getOS(),o=e.getUA(),a=navigator.language,s=navigator.userAgent.includes("Mobi"),u=function(){if(!t||!n)return;if("userAgentData"in navigator&&navigator.userAgentData)return navigator.userAgentData.brands;return}(),l="unknown";return{browser:{name:null!=t?t:l,version:null!=n?n:l,os:`${null!=i?i:l} ${null!=r?r:l}`,userAgent:null!=o?o:l,language:null!=a?a:l,mobile:s,brands:null!=u?u:l,viewportWidth:`${window.innerWidth}`,viewportHeight:`${window.innerHeight}`}}},ve=()=>({page:{url:location.href}}),he=[ge,ve];function be(t){var n,i,r,o;return{id:null!==(o=null===(r=null===(i=null===(n=e.faro.config)||void 0===n?void 0:n.sessionTracking)||void 0===i?void 0:i.generateSessionId)||void 0===r?void 0:r.call(i))&&void 0!==o?o:O(),attributes:t}}const we={name:"default"},ye="sessionStorage",Se="localStorage";function Te(t){var n;try{let e;e=window[t];const n="__faro_storage_test__";return e.setItem(n,n),e.removeItem(n),!0}catch(i){return null===(n=e.faro.internalLogger)||void 0===n||n.info(`Web storage of type ${t} is not available. Reason: ${i}`),!1}}function Ee(e,t){return Oe(t)?window[t].getItem(e):null}function Ie(e,t,n){if(Oe(n))try{window[n].setItem(e,t)}catch(e){}}function ke(e,t){Oe(t)&&window[t].removeItem(e)}const xe=Te(Se),Le=Te(ye);function Oe(e){return e===Se?xe:e===ye&&Le}function Ce(e,t){let n,i=!1;const r=()=>{null!=n?(e(...n),n=null,setTimeout(r,t)):i=!1};return(...o)=>{i?n=o:(e(...o),i=!0,setTimeout(r,t))}}function Pe(){var t,n,i;const r=e.faro.config.sessionTracking;let o=null!==(i=null!==(n=null===(t=null==r?void 0:r.sampler)||void 0===t?void 0:t.call(r,{metas:e.faro.metas.value}))&&void 0!==n?n:null==r?void 0:r.samplingRate)&&void 0!==i?i:1;if("number"!=typeof o){o=0}return Math.random()<o}const _e="com.grafana.faro.session",Ne=144e5,Ae=9e5,Me=Ae,De={enabled:!0,persistent:!1,maxSessionPersistenceTime:Me};function je({sessionId:t,started:n,lastActivity:i,isSampled:r=!0}={}){var o,a;const s=P(),u=null===(a=null===(o=e.faro.config)||void 0===o?void 0:o.sessionTracking)||void 0===a?void 0:a.generateSessionId;return null==t&&(t="function"==typeof u?u():O()),{sessionId:t,lastActivity:null!=i?i:s,started:null!=n?n:s,isSampled:r}}function Re(e){if(null==e)return!1;const t=P();if(!(t-e.started<Ne))return!1;return t-e.lastActivity<Ae}function Be({fetchUserSession:t,storeUserSession:n}){return function({forceSessionExtend:i}={forceSessionExtend:!1}){var r,o,a;if(!t||!n)return;const s=e.faro.config.sessionTracking,u=null==s?void 0:s.persistent;if(u&&!xe||!u&&!Le)return;const l=t();if(!1===i&&Re(l))n(Object.assign(Object.assign({},l),{lastActivity:P()}));else{let t=Ue(je({isSampled:Pe()}),l);n(t),null===(r=e.faro.api)||void 0===r||r.setSession(t.sessionMeta),null===(o=null==s?void 0:s.onSessionChange)||void 0===o||o.call(s,null!==(a=null==l?void 0:l.sessionMeta)&&void 0!==a?a:null,t.sessionMeta)}}}function Ue(t,n){var i,r,o,a;return Object.assign(Object.assign({},t),{sessionMeta:{id:t.sessionId,attributes:Object.assign(Object.assign(Object.assign(Object.assign({},null===(r=null===(i=e.faro.config.sessionTracking)||void 0===i?void 0:i.session)||void 0===r?void 0:r.attributes),null!==(a=null===(o=e.faro.metas.value.session)||void 0===o?void 0:o.attributes)&&void 0!==a?a:{}),null!=n?{previousSession:n.sessionId}:{}),{isSampled:t.isSampled.toString()})}})}function Fe(e){return(null==e?void 0:e.persistent)?ze:Ve}class ze{constructor(){this.updateSession=Ce((()=>this.updateUserSession()),1e3),this.updateUserSession=Be({fetchUserSession:ze.fetchUserSession,storeUserSession:ze.storeUserSession}),this.init()}static removeUserSession(){ke(_e,ze.storageTypeLocal)}static storeUserSession(e){Ie(_e,JSON.stringify(e),ze.storageTypeLocal)}static fetchUserSession(){const e=Ee(_e,ze.storageTypeLocal);return e?JSON.parse(e):null}init(){document.addEventListener("visibilitychange",(()=>{"visible"===document.visibilityState&&this.updateSession()})),e.faro.metas.addListener((function(t){const n=t.session,i=ze.fetchUserSession();if(n&&n.id!==(null==i?void 0:i.sessionId)){const t=Ue(je({sessionId:n.id,isSampled:Pe()}),i);ze.storeUserSession(t),e.faro.api.setSession(t.sessionMeta)}}))}}ze.storageTypeLocal=Se;class Ve{constructor(){this.updateSession=Ce((()=>this.updateUserSession()),1e3),this.updateUserSession=Be({fetchUserSession:Ve.fetchUserSession,storeUserSession:Ve.storeUserSession}),this.init()}static removeUserSession(){ke(_e,Ve.storageTypeSession)}static storeUserSession(e){Ie(_e,JSON.stringify(e),Ve.storageTypeSession)}static fetchUserSession(){const e=Ee(_e,Ve.storageTypeSession);return e?JSON.parse(e):null}init(){document.addEventListener("visibilitychange",(()=>{"visible"===document.visibilityState&&this.updateSession()})),e.faro.metas.addListener((function(t){const n=t.session,i=Ve.fetchUserSession();if(n&&n.id!==(null==i?void 0:i.sessionId)){const t=Ue(je({sessionId:n.id,isSampled:Pe()}),i);Ve.storeUserSession(t),e.faro.api.setSession(t.sessionMeta)}}))}}Ve.storageTypeSession=ye;class $e extends Q{constructor(){super(...arguments),this.name="@grafana/faro-web-sdk:instrumentation-session",this.version=ee}sendSessionStartEvent(e){var t,n;const i=e.session;if(i&&i.id!==(null===(t=this.notifiedSession)||void 0===t?void 0:t.id)){if(this.notifiedSession&&this.notifiedSession.id===(null===(n=i.attributes)||void 0===n?void 0:n.previousSession))return this.api.pushEvent(de,{},void 0,{skipDedupe:!0}),void(this.notifiedSession=i);this.notifiedSession=i,this.api.pushEvent(le,{},void 0,{skipDedupe:!0})}}createInitialSession(e,t){var n,i,r,o,a;let s,u,l=e.fetchUserSession();if(t.persistent&&t.maxSessionPersistenceTime&&l){const e=P();l.lastActivity<e-t.maxSessionPersistenceTime&&(ze.removeUserSession(),l=null)}if(Re(l)){const e=null==l?void 0:l.sessionId;u=je({sessionId:e,isSampled:l.isSampled||!1,started:null==l?void 0:l.started}),u.sessionMeta={id:e,attributes:Object.assign(Object.assign(Object.assign({},null===(n=t.session)||void 0===n?void 0:n.attributes),null===(i=null==l?void 0:l.sessionMeta)||void 0===i?void 0:i.attributes),{isSampled:u.isSampled.toString()})},s=ce}else{const e=null!==(o=null===(r=t.session)||void 0===r?void 0:r.id)&&void 0!==o?o:be().id;u=je({sessionId:e,isSampled:Pe()}),u.sessionMeta={id:e,attributes:Object.assign({isSampled:u.isSampled.toString()},null===(a=t.session)||void 0===a?void 0:a.attributes)},s=le}return{initialSession:u,lifecycleType:s}}registerBeforeSendHook(e){var t;const{updateSession:n}=new e;null===(t=this.transports)||void 0===t||t.addBeforeSendHooks((e=>{var t,i,r;n();const o=null===(t=e.meta.session)||void 0===t?void 0:t.attributes;if(o&&"true"===(null==o?void 0:o.isSampled)){let t=JSON.parse(JSON.stringify(e));const n=null===(i=t.meta.session)||void 0===i?void 0:i.attributes;return null==n||delete n.isSampled,0===Object.keys(null!=n?n:{}).length&&(null===(r=t.meta.session)||void 0===r||delete r.attributes),t}return null}))}initialize(){this.logDebug("init session instrumentation");const e=this.config.sessionTracking;if(null==e?void 0:e.enabled){const t=Fe(e);this.registerBeforeSendHook(t);const{initialSession:n,lifecycleType:i}=this.createInitialSession(t,e);t.storeUserSession(n);const r=n.sessionMeta;this.notifiedSession=r,this.api.setSession(r),i===le&&this.api.pushEvent(le,{},void 0,{skipDedupe:!0}),i===ce&&this.api.pushEvent(ce,{},void 0,{skipDedupe:!0})}this.metas.addListener(this.sendSessionStartEvent.bind(this))}}class qe extends Q{constructor(e={}){super(),this.options=e,this.name="@grafana/faro-web-sdk:instrumentation-console",this.version=ee}initialize(){this.logDebug("Initializing\n",this.options),I.filter((e=>{var t;return!(null!==(t=this.options.disabledLevels)&&void 0!==t?t:qe.defaultDisabledLevels).includes(e)})).forEach((e=>{console[e]=(...t)=>{try{this.api.pushLog(t,{level:e})}catch(e){this.logError(e)}finally{this.unpatchedConsole[e](...t)}}}))}}qe.defaultDisabledLevels=[e.LogLevel.DEBUG,e.LogLevel.TRACE,e.LogLevel.LOG];const Ge=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i,We=/^\s*at (?:(.*\).*?|.*?) ?\((?:address at )?)?((?:file|https?|blob|chrome-extension|address|native|eval|webpack|<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,He=/\((\S*)(?::(\d+))(?::(\d+))\)/,Ke="address at ",Xe=Ke.length,Je=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:file|https?|blob|chrome|webpack|resource|moz-extension|safari-extension|safari-web-extension|capacitor)?:\/.*?|\[native code]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,Ze=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,Ye="safari-extension",Qe="safari-web-extension",et=/Minified React error #\d+;/i;function tt(e,t,n,i){const r={filename:e||document.location.href,function:t||"?"};return void 0!==n&&(r.lineno=n),void 0!==i&&(r.colno=i),r}function nt(e,t){const n=null==e?void 0:e.includes(Ye),i=!n&&(null==e?void 0:e.includes(Qe));return n||i?[(null==e?void 0:e.includes("@"))?e.split("@")[0]:e,n?`${Ye}:${t}`:`${Qe}:${t}`]:[e,t]}function it(e){let t=[];e.stacktrace?t=e.stacktrace.split("\n").filter(((e,t)=>t%2==0)):e.stack&&(t=e.stack.split("\n"));const n=t.reduce(((t,n,i)=>{let r,o,s,u,l;if(r=We.exec(n)){if(o=r[1],s=r[2],u=r[3],l=r[4],null==s?void 0:s.startsWith("eval")){const e=He.exec(s);e&&(s=e[1],u=e[2],l=e[3])}s=(null==s?void 0:s.startsWith(Ke))?s.substring(Xe):s,[o,s]=nt(o,s)}else if(r=Je.exec(n)){if(o=r[1],s=r[3],u=r[4],l=r[5],s&&s.includes(" > eval")){const e=Ze.exec(s);e&&(o=o||"eval",s=e[1],u=e[2])}else 0===i&&!l&&a(e.columnNumber)&&(l=String(e.columnNumber+1));[o,s]=nt(o,s)}return(s||o)&&t.push(tt(s,o,u?Number(u):void 0,l?Number(l):void 0)),t}),[]);return et.test(e.message)?n.slice(1):n}function rt(e){return{frames:it(e)}}function ot(e){let t,n,i,r,o=[];if(g(e)&&e.error)t=e.error.message,n=e.error.name,o=it(e.error);else if((i=v(e))||h(e)){const{name:r,message:o}=e;n=null!=r?r:i?"DOMError":"DOMException",t=o?`${n}: ${o}`:n}else m(e)?(t=e.message,o=it(e)):(s(e)||(r=f(e)))&&(n=r?e.constructor.name:void 0,t=`Non-Error exception captured with keys: ${Object.keys(e)}`);return[t,n,o]}function at(e){const t=window.onerror;window.onerror=(...n)=>{try{const[i,r,a,s,u]=n;let l,c,d=[];const f=o(i),p=tt(r,"?",a,s);u||!f?([l,c,d]=ot(null!=u?u:i),0===d.length&&(d=[p])):f&&([l,c]=function(e){var t,n;const i=e.match(Ge),r=null!==(t=null==i?void 0:i[1])&&void 0!==t?t:X;return[null!==(n=null==i?void 0:i[2])&&void 0!==n?n:e,r]}(i),d=[p]),l&&e.pushError(new Error(l),{type:c,stackFrames:d})}finally{null==t||t.apply(window,n)}}}class st extends Q{constructor(){super(...arguments),this.name="@grafana/faro-web-sdk:instrumentation-errors",this.version=ee}initialize(){var e;this.logDebug("Initializing"),at(this.api),e=this.api,window.addEventListener("unhandledrejection",(t=>{var n,i;let r,o,a=t;a.reason?a=t.reason:(null===(n=t.detail)||void 0===n?void 0:n.reason)&&(a=null===(i=t.detail)||void 0===i?void 0:i.reason);let s=[];c(a)?(r=`Non-Error promise rejection captured with value: ${String(a)}`,o="UnhandledRejection"):[r,o,s]=ot(a),r&&e.pushError(new Error(r),{type:o,stackFrames:s})}))}}class ut extends Q{constructor(){super(...arguments),this.name="@grafana/faro-web-sdk:instrumentation-view",this.version=ee}sendViewChangedEvent(e){var t,n,i;const r=e.view;r&&r.name!==(null===(t=this.notifiedView)||void 0===t?void 0:t.name)&&(this.api.pushEvent(ue,{fromView:null!==(i=null===(n=this.notifiedView)||void 0===n?void 0:n.name)&&void 0!==i?i:"",toView:r.name},void 0,{skipDedupe:!0}),this.notifiedView=r)}initialize(){this.sendViewChangedEvent(this.metas.value),this.metas.addListener(this.sendViewChangedEvent.bind(this))}}var lt,ct,dt,ft,pt,mt=-1,gt=function(e){addEventListener("pageshow",(function(t){t.persisted&&(mt=t.timeStamp,e(t))}),!0)},vt=function(){var e=self.performance&&performance.getEntriesByType&&performance.getEntriesByType("navigation")[0];if(e&&e.responseStart>0&&e.responseStart<performance.now())return e},ht=function(){var e=vt();return e&&e.activationStart||0},bt=function(e,t){var n=vt(),i="navigate";return mt>=0?i="back-forward-cache":n&&(document.prerendering||ht()>0?i="prerender":document.wasDiscarded?i="restore":n.type&&(i=n.type.replace(/_/g,"-"))),{name:e,value:void 0===t?-1:t,rating:"good",delta:0,entries:[],id:"v4-".concat(Date.now(),"-").concat(Math.floor(8999999999999*Math.random())+1e12),navigationType:i}},wt=function(e,t,n){try{if(PerformanceObserver.supportedEntryTypes.includes(e)){var i=new PerformanceObserver((function(e){Promise.resolve().then((function(){t(e.getEntries())}))}));return i.observe(Object.assign({type:e,buffered:!0},n||{})),i}}catch(e){}},yt=function(e,t,n,i){var r,o;return function(a){t.value>=0&&(a||i)&&((o=t.value-(r||0))||void 0===r)&&(r=t.value,t.delta=o,t.rating=function(e,t){return e>t[1]?"poor":e>t[0]?"needs-improvement":"good"}(t.value,n),e(t))}},St=function(e){requestAnimationFrame((function(){return requestAnimationFrame((function(){return e()}))}))},Tt=function(e){document.addEventListener("visibilitychange",(function(){"hidden"===document.visibilityState&&e()}))},Et=function(e){var t=!1;return function(){t||(e(),t=!0)}},It=-1,kt=function(){return"hidden"!==document.visibilityState||document.prerendering?1/0:0},xt=function(e){"hidden"===document.visibilityState&&It>-1&&(It="visibilitychange"===e.type?e.timeStamp:0,Ot())},Lt=function(){addEventListener("visibilitychange",xt,!0),addEventListener("prerenderingchange",xt,!0)},Ot=function(){removeEventListener("visibilitychange",xt,!0),removeEventListener("prerenderingchange",xt,!0)},Ct=function(){return It<0&&(It=kt(),Lt(),gt((function(){setTimeout((function(){It=kt(),Lt()}),0)}))),{get firstHiddenTime(){return It}}},Pt=function(e){document.prerendering?addEventListener("prerenderingchange",(function(){return e()}),!0):e()},_t=[1800,3e3],Nt=function(e,t){t=t||{},Pt((function(){var n,i=Ct(),r=bt("FCP"),o=wt("paint",(function(e){e.forEach((function(e){"first-contentful-paint"===e.name&&(o.disconnect(),e.startTime<i.firstHiddenTime&&(r.value=Math.max(e.startTime-ht(),0),r.entries.push(e),n(!0)))}))}));o&&(n=yt(e,r,_t,t.reportAllChanges),gt((function(i){r=bt("FCP"),n=yt(e,r,_t,t.reportAllChanges),St((function(){r.value=performance.now()-i.timeStamp,n(!0)}))})))}))},At=[.1,.25],Mt=0,Dt=1/0,jt=0,Rt=function(e){e.forEach((function(e){e.interactionId&&(Dt=Math.min(Dt,e.interactionId),jt=Math.max(jt,e.interactionId),Mt=jt?(jt-Dt)/7+1:0)}))},Bt=[],Ut=new Map,Ft=0,zt=[],Vt=function(e){if(zt.forEach((function(t){return t(e)})),e.interactionId||"first-input"===e.entryType){var t=Bt[Bt.length-1],n=Ut.get(e.interactionId);if(n||Bt.length<10||e.duration>t.latency){if(n)e.duration>n.latency?(n.entries=[e],n.latency=e.duration):e.duration===n.latency&&e.startTime===n.entries[0].startTime&&n.entries.push(e);else{var i={id:e.interactionId,latency:e.duration,entries:[e]};Ut.set(i.id,i),Bt.push(i)}Bt.sort((function(e,t){return t.latency-e.latency})),Bt.length>10&&Bt.splice(10).forEach((function(e){return Ut.delete(e.id)}))}}},$t=[200,500],qt=[2500,4e3],Gt={},Wt=[800,1800],Ht=function e(t){document.prerendering?Pt((function(){return e(t)})):"complete"!==document.readyState?addEventListener("load",(function(){return e(t)}),!0):setTimeout(t,0)},Kt={passive:!0,capture:!0},Xt=new Date,Jt=function(e,t){ct||(ct=t,dt=e,ft=new Date,Qt(removeEventListener),Zt())},Zt=function(){if(dt>=0&&dt<ft-Xt){var e={entryType:"first-input",name:ct.type,target:ct.target,cancelable:ct.cancelable,startTime:ct.timeStamp,processingStart:ct.timeStamp+dt};pt.forEach((function(t){t(e)})),pt=[]}},Yt=function(e){if(e.cancelable){var t=(e.timeStamp>1e12?new Date:performance.now())-e.timeStamp;"pointerdown"==e.type?function(e,t){var n=function(){Jt(e,t),r()},i=function(){r()},r=function(){removeEventListener("pointerup",n,Kt),removeEventListener("pointercancel",i,Kt)};addEventListener("pointerup",n,Kt),addEventListener("pointercancel",i,Kt)}(t,e):Jt(t,e)}},Qt=function(e){["mousedown","keydown","touchstart","pointerdown"].forEach((function(t){return e(t,Yt,Kt)}))},en=[100,300];class tn{constructor(e){this.pushMeasurement=e}initialize(){Object.entries(tn.mapping).forEach((([e,t])=>{t((t=>{this.pushMeasurement({type:"web-vitals",values:{[e]:t.value}})}))}))}}tn.mapping={cls:function(e,t){t=t||{},Nt(Et((function(){var n,i=bt("CLS",0),r=0,o=[],a=function(e){e.forEach((function(e){if(!e.hadRecentInput){var t=o[0],n=o[o.length-1];r&&e.startTime-n.startTime<1e3&&e.startTime-t.startTime<5e3?(r+=e.value,o.push(e)):(r=e.value,o=[e])}})),r>i.value&&(i.value=r,i.entries=o,n())},s=wt("layout-shift",a);s&&(n=yt(e,i,At,t.reportAllChanges),Tt((function(){a(s.takeRecords()),n(!0)})),gt((function(){r=0,i=bt("CLS",0),n=yt(e,i,At,t.reportAllChanges),St((function(){return n()}))})),setTimeout(n,0))})))},fcp:Nt,fid:function(e,t){t=t||{},Pt((function(){var n,i=Ct(),r=bt("FID"),o=function(e){e.startTime<i.firstHiddenTime&&(r.value=e.processingStart-e.startTime,r.entries.push(e),n(!0))},a=function(e){e.forEach(o)},s=wt("first-input",a);n=yt(e,r,en,t.reportAllChanges),s&&(Tt(Et((function(){a(s.takeRecords()),s.disconnect()}))),gt((function(){var i;r=bt("FID"),n=yt(e,r,en,t.reportAllChanges),pt=[],dt=-1,ct=null,Qt(addEventListener),i=o,pt.push(i),Zt()})))}))},inp:function(e,t){t=t||{},Pt((function(){var n;"interactionCount"in performance||lt||(lt=wt("event",Rt,{type:"event",buffered:!0,durationThreshold:0}));var i,r=bt("INP"),o=function(e){e.forEach(Vt);var t,n=(t=Math.min(Bt.length-1,Math.floor(((lt?Mt:performance.interactionCount||0)-Ft)/50)),Bt[t]);n&&n.latency!==r.value&&(r.value=n.latency,r.entries=n.entries,i())},a=wt("event",o,{durationThreshold:null!==(n=t.durationThreshold)&&void 0!==n?n:40});i=yt(e,r,$t,t.reportAllChanges),a&&("PerformanceEventTiming"in self&&"interactionId"in PerformanceEventTiming.prototype&&a.observe({type:"first-input",buffered:!0}),Tt((function(){o(a.takeRecords()),i(!0)})),gt((function(){Ft=0,Bt.length=0,Ut.clear(),r=bt("INP"),i=yt(e,r,$t,t.reportAllChanges)})))}))},lcp:function(e,t){t=t||{},Pt((function(){var n,i=Ct(),r=bt("LCP"),o=function(e){t.reportAllChanges||(e=e.slice(-1)),e.forEach((function(e){e.startTime<i.firstHiddenTime&&(r.value=Math.max(e.startTime-ht(),0),r.entries=[e],n())}))},a=wt("largest-contentful-paint",o);if(a){n=yt(e,r,qt,t.reportAllChanges);var s=Et((function(){Gt[r.id]||(o(a.takeRecords()),a.disconnect(),Gt[r.id]=!0,n(!0))}));["keydown","click"].forEach((function(e){addEventListener(e,(function(){return e=s,t=self.requestIdleCallback||self.setTimeout,n=-1,e=Et(e),"hidden"===document.visibilityState?e():(n=t(e),Tt(e)),n;var e,t,n}),!0)})),Tt(s),gt((function(i){r=bt("LCP"),n=yt(e,r,qt,t.reportAllChanges),St((function(){r.value=performance.now()-i.timeStamp,Gt[r.id]=!0,n(!0)}))}))}}))},ttfb:function(e,t){t=t||{};var n=bt("TTFB"),i=yt(e,n,Wt,t.reportAllChanges);Ht((function(){var r=vt();r&&(n.value=Math.max(r.responseStart-ht(),0),n.entries=[r],i(!0),gt((function(){n=bt("TTFB",0),(i=yt(e,n,Wt,t.reportAllChanges))(!0)})))}))}};var nn,rn,on=function(){var e=self.performance&&performance.getEntriesByType&&performance.getEntriesByType("navigation")[0];if(e&&e.responseStart>0&&e.responseStart<performance.now())return e},an=function(e){if("loading"===document.readyState)return"loading";var t=on();if(t){if(e<t.domInteractive)return"loading";if(0===t.domContentLoadedEventStart||e<t.domContentLoadedEventStart)return"dom-interactive";if(0===t.domComplete||e<t.domComplete)return"dom-content-loaded"}return"complete"},sn=function(e){var t=e.nodeName;return 1===e.nodeType?t.toLowerCase():t.toUpperCase().replace(/^#/,"")},un=function(e,t){var n="";try{for(;e&&9!==e.nodeType;){var i=e,r=i.id?"#"+i.id:sn(i)+(i.classList&&i.classList.value&&i.classList.value.trim()&&i.classList.value.trim().length?"."+i.classList.value.trim().replace(/\s+/g,"."):"");if(n.length+r.length>(t||100)-1)return n||r;if(n=n?r+">"+n:r,i.id)break;e=i.parentNode}}catch(e){}return n},ln=-1,cn=function(){return ln},dn=function(e){addEventListener("pageshow",(function(t){t.persisted&&(ln=t.timeStamp,e(t))}),!0)},fn=function(){var e=on();return e&&e.activationStart||0},pn=function(e,t){var n=on(),i="navigate";return cn()>=0?i="back-forward-cache":n&&(document.prerendering||fn()>0?i="prerender":document.wasDiscarded?i="restore":n.type&&(i=n.type.replace(/_/g,"-"))),{name:e,value:void 0===t?-1:t,rating:"good",delta:0,entries:[],id:"v4-".concat(Date.now(),"-").concat(Math.floor(8999999999999*Math.random())+1e12),navigationType:i}},mn=function(e,t,n){try{if(PerformanceObserver.supportedEntryTypes.includes(e)){var i=new PerformanceObserver((function(e){Promise.resolve().then((function(){t(e.getEntries())}))}));return i.observe(Object.assign({type:e,buffered:!0},n||{})),i}}catch(e){}},gn=function(e,t,n,i){var r,o;return function(a){t.value>=0&&(a||i)&&((o=t.value-(r||0))||void 0===r)&&(r=t.value,t.delta=o,t.rating=function(e,t){return e>t[1]?"poor":e>t[0]?"needs-improvement":"good"}(t.value,n),e(t))}},vn=function(e){requestAnimationFrame((function(){return requestAnimationFrame((function(){return e()}))}))},hn=function(e){document.addEventListener("visibilitychange",(function(){"hidden"===document.visibilityState&&e()}))},bn=function(e){var t=!1;return function(){t||(e(),t=!0)}},wn=-1,yn=function(){return"hidden"!==document.visibilityState||document.prerendering?1/0:0},Sn=function(e){"hidden"===document.visibilityState&&wn>-1&&(wn="visibilitychange"===e.type?e.timeStamp:0,En())},Tn=function(){addEventListener("visibilitychange",Sn,!0),addEventListener("prerenderingchange",Sn,!0)},En=function(){removeEventListener("visibilitychange",Sn,!0),removeEventListener("prerenderingchange",Sn,!0)},In=function(){return wn<0&&(wn=yn(),Tn(),dn((function(){setTimeout((function(){wn=yn(),Tn()}),0)}))),{get firstHiddenTime(){return wn}}},kn=function(e){document.prerendering?addEventListener("prerenderingchange",(function(){return e()}),!0):e()},xn=[1800,3e3],Ln=function(e,t){t=t||{},kn((function(){var n,i=In(),r=pn("FCP"),o=mn("paint",(function(e){e.forEach((function(e){"first-contentful-paint"===e.name&&(o.disconnect(),e.startTime<i.firstHiddenTime&&(r.value=Math.max(e.startTime-fn(),0),r.entries.push(e),n(!0)))}))}));o&&(n=gn(e,r,xn,t.reportAllChanges),dn((function(i){r=pn("FCP"),n=gn(e,r,xn,t.reportAllChanges),vn((function(){r.value=performance.now()-i.timeStamp,n(!0)}))})))}))},On=[.1,.25],Cn=0,Pn=1/0,_n=0,Nn=function(e){e.forEach((function(e){e.interactionId&&(Pn=Math.min(Pn,e.interactionId),_n=Math.max(_n,e.interactionId),Cn=_n?(_n-Pn)/7+1:0)}))},An=function(){"interactionCount"in performance||nn||(nn=mn("event",Nn,{type:"event",buffered:!0,durationThreshold:0}))},Mn=[],Dn=new Map,jn=0,Rn=function(){return(nn?Cn:performance.interactionCount||0)-jn},Bn=[],Un=function(e){if(Bn.forEach((function(t){return t(e)})),e.interactionId||"first-input"===e.entryType){var t=Mn[Mn.length-1],n=Dn.get(e.interactionId);if(n||Mn.length<10||e.duration>t.latency){if(n)e.duration>n.latency?(n.entries=[e],n.latency=e.duration):e.duration===n.latency&&e.startTime===n.entries[0].startTime&&n.entries.push(e);else{var i={id:e.interactionId,latency:e.duration,entries:[e]};Dn.set(i.id,i),Mn.push(i)}Mn.sort((function(e,t){return t.latency-e.latency})),Mn.length>10&&Mn.splice(10).forEach((function(e){return Dn.delete(e.id)}))}}},Fn=function(e){var t=self.requestIdleCallback||self.setTimeout,n=-1;return e=bn(e),"hidden"===document.visibilityState?e():(n=t(e),hn(e)),n},zn=[200,500],Vn=[],$n=new Map,qn=[],Gn=new WeakMap,Wn=new Map,Hn=-1,Kn=function(e){e.forEach((function(e){return Vn.push(e)}))},Xn=function(){Wn.size>10&&Wn.forEach((function(e,t){Dn.has(t)||Wn.delete(t)})),qn=qn.slice(-50);var e=new Set(qn.concat(Mn.map((function(e){return Gn.get(e.entries[0])}))));$n.forEach((function(t,n){e.has(n)||$n.delete(n)}));var t=new Set;$n.forEach((function(e){ei(e.startTime,e.processingEnd).forEach((function(e){t.add(e)}))})),Vn=Array.from(t),Hn=-1};Bn.push((function(e){e.interactionId&&e.target&&!Wn.has(e.interactionId)&&Wn.set(e.interactionId,e.target)}),(function(e){for(var t,n=e.startTime+e.duration,i=qn.length-1;i>=0;i--)if(t=qn[i],Math.abs(n-t)<=8){var r=$n.get(t);r.startTime=Math.min(e.startTime,r.startTime),r.processingStart=Math.min(e.processingStart,r.processingStart),r.processingEnd=Math.max(e.processingEnd,r.processingEnd),r.entries.push(e),n=t;break}n!==t&&(qn.push(n),$n.set(n,{startTime:e.startTime,processingStart:e.processingStart,processingEnd:e.processingEnd,entries:[e]})),(e.interactionId||"first-input"===e.entryType)&&Gn.set(e,n)}),(function(){Hn<0&&(Hn=Fn(Xn))}));var Jn,Zn,Yn,Qn,ei=function(e,t){for(var n,i=[],r=0;n=Vn[r];r++)if(!(n.startTime+n.duration<e)){if(n.startTime>t)break;i.push(n)}return i},ti=function(e,t){rn||(rn=mn("long-animation-frame",Kn)),function(e,t){t=t||{},kn((function(){var n;An();var i,r=pn("INP"),o=function(e){e.forEach(Un);var t,n=(t=Math.min(Mn.length-1,Math.floor(Rn()/50)),Mn[t]);n&&n.latency!==r.value&&(r.value=n.latency,r.entries=n.entries,i())},a=mn("event",o,{durationThreshold:null!==(n=t.durationThreshold)&&void 0!==n?n:40});i=gn(e,r,zn,t.reportAllChanges),a&&("PerformanceEventTiming"in self&&"interactionId"in PerformanceEventTiming.prototype&&a.observe({type:"first-input",buffered:!0}),hn((function(){o(a.takeRecords()),i(!0)})),dn((function(){jn=0,Mn.length=0,Dn.clear(),r=pn("INP"),i=gn(e,r,zn,t.reportAllChanges)})))}))}((function(t){Fn((function(){var n=function(e){var t=e.entries[0],n=Gn.get(t),i=$n.get(n),r=t.processingStart,o=i.processingEnd,a=i.entries.sort((function(e,t){return e.processingStart-t.processingStart})),s=ei(t.startTime,o),u=e.entries.find((function(e){return e.target})),l=u&&u.target||Wn.get(t.interactionId),c=[t.startTime+t.duration,o].concat(s.map((function(e){return e.startTime+e.duration}))),d=Math.max.apply(Math,c),f={interactionTarget:un(l),interactionTargetElement:l,interactionType:t.name.startsWith("key")?"keyboard":"pointer",interactionTime:t.startTime,nextPaintTime:d,processedEventEntries:a,longAnimationFrameEntries:s,inputDelay:r-t.startTime,processingDuration:o-r,presentationDelay:Math.max(d-o,0),loadState:an(t.startTime)};return Object.assign(e,{attribution:f})}(t);e(n)}))}),t)},ni=[2500,4e3],ii={},ri=[800,1800],oi=function e(t){document.prerendering?kn((function(){return e(t)})):"complete"!==document.readyState?addEventListener("load",(function(){return e(t)}),!0):setTimeout(t,0)},ai=function(e,t){t=t||{};var n=pn("TTFB"),i=gn(e,n,ri,t.reportAllChanges);oi((function(){var r=on();r&&(n.value=Math.max(r.responseStart-fn(),0),n.entries=[r],i(!0),dn((function(){n=pn("TTFB",0),(i=gn(e,n,ri,t.reportAllChanges))(!0)})))}))},si={passive:!0,capture:!0},ui=new Date,li=function(e,t){Jn||(Jn=t,Zn=e,Yn=new Date,fi(removeEventListener),ci())},ci=function(){if(Zn>=0&&Zn<Yn-ui){var e={entryType:"first-input",name:Jn.type,target:Jn.target,cancelable:Jn.cancelable,startTime:Jn.timeStamp,processingStart:Jn.timeStamp+Zn};Qn.forEach((function(t){t(e)})),Qn=[]}},di=function(e){if(e.cancelable){var t=(e.timeStamp>1e12?new Date:performance.now())-e.timeStamp;"pointerdown"==e.type?function(e,t){var n=function(){li(e,t),r()},i=function(){r()},r=function(){removeEventListener("pointerup",n,si),removeEventListener("pointercancel",i,si)};addEventListener("pointerup",n,si),addEventListener("pointercancel",i,si)}(t,e):li(t,e)}},fi=function(e){["mousedown","keydown","touchstart","pointerdown"].forEach((function(t){return e(t,di,si)}))},pi=[100,300],mi=function(e,t){!function(e,t){t=t||{},kn((function(){var n,i=In(),r=pn("FID"),o=function(e){e.startTime<i.firstHiddenTime&&(r.value=e.processingStart-e.startTime,r.entries.push(e),n(!0))},a=function(e){e.forEach(o)},s=mn("first-input",a);n=gn(e,r,pi,t.reportAllChanges),s&&(hn(bn((function(){a(s.takeRecords()),s.disconnect()}))),dn((function(){var i;r=pn("FID"),n=gn(e,r,pi,t.reportAllChanges),Qn=[],Zn=-1,Jn=null,fi(addEventListener),i=o,Qn.push(i),ci()})))}))}((function(t){var n=function(e){var t=e.entries[0],n={eventTarget:un(t.target),eventType:t.name,eventTime:t.startTime,eventEntry:t,loadState:an(t.startTime)};return Object.assign(e,{attribution:n})}(t);e(n)}),t)};const gi="com.grafana.faro.lastNavigationId",vi="load_state",hi="time_to_first_byte";class bi{constructor(e){this.corePushMeasurement=e}initialize(){this.measureCLS(),this.measureFCP(),this.measureFID(),this.measureINP(),this.measureLCP(),this.measureTTFB()}measureCLS(){!function(e,t){!function(e,t){t=t||{},Ln(bn((function(){var n,i=pn("CLS",0),r=0,o=[],a=function(e){e.forEach((function(e){if(!e.hadRecentInput){var t=o[0],n=o[o.length-1];r&&e.startTime-n.startTime<1e3&&e.startTime-t.startTime<5e3?(r+=e.value,o.push(e)):(r=e.value,o=[e])}})),r>i.value&&(i.value=r,i.entries=o,n())},s=mn("layout-shift",a);s&&(n=gn(e,i,On,t.reportAllChanges),hn((function(){a(s.takeRecords()),n(!0)})),dn((function(){r=0,i=pn("CLS",0),n=gn(e,i,On,t.reportAllChanges),vn((function(){return n()}))})),setTimeout(n,0))})))}((function(t){var n=function(e){var t,n={};if(e.entries.length){var i=e.entries.reduce((function(e,t){return e&&e.value>t.value?e:t}));if(i&&i.sources&&i.sources.length){var r=(t=i.sources).find((function(e){return e.node&&1===e.node.nodeType}))||t[0];r&&(n={largestShiftTarget:un(r.node),largestShiftTime:i.startTime,largestShiftValue:i.value,largestShiftSource:r,largestShiftEntry:i,loadState:an(i.startTime)})}}return Object.assign(e,{attribution:n})}(t);e(n)}),t)}((e=>{const{loadState:t,largestShiftValue:n,largestShiftTime:i,largestShiftTarget:r}=e.attribution,o=this.buildInitialValues(e);this.addIfPresent(o,"largest_shift_value",n),this.addIfPresent(o,"largest_shift_time",i);const a=this.buildInitialContext(e);this.addIfPresent(a,vi,t),this.addIfPresent(a,"largest_shift_target",r),this.pushMeasurement(o,a)}))}measureFCP(){!function(e,t){Ln((function(t){var n=function(e){var t={timeToFirstByte:0,firstByteToFCP:e.value,loadState:an(cn())};if(e.entries.length){var n=on(),i=e.entries[e.entries.length-1];if(n){var r=n.activationStart||0,o=Math.max(0,n.responseStart-r);t={timeToFirstByte:o,firstByteToFCP:e.value-o,loadState:an(e.entries[0].startTime),navigationEntry:n,fcpEntry:i}}}return Object.assign(e,{attribution:t})}(t);e(n)}),t)}((e=>{const{firstByteToFCP:t,timeToFirstByte:n,loadState:i}=e.attribution,r=this.buildInitialValues(e);this.addIfPresent(r,"first_byte_to_fcp",t),this.addIfPresent(r,hi,n);const o=this.buildInitialContext(e);this.addIfPresent(o,vi,i),this.pushMeasurement(r,o)}))}measureFID(){mi((e=>{const{eventTime:t,eventTarget:n,eventType:i,loadState:r}=e.attribution,o=this.buildInitialValues(e);this.addIfPresent(o,"event_time",t);const a=this.buildInitialContext(e);this.addIfPresent(a,"event_target",n),this.addIfPresent(a,"event_type",i),this.addIfPresent(a,vi,r),this.pushMeasurement(o,a)}))}measureINP(){ti((e=>{const{interactionTime:t,presentationDelay:n,inputDelay:i,processingDuration:r,nextPaintTime:o,loadState:a,interactionTarget:s,interactionType:u}=e.attribution,l=this.buildInitialValues(e);this.addIfPresent(l,"interaction_time",t),this.addIfPresent(l,"presentation_delay",n),this.addIfPresent(l,"input_delay",i),this.addIfPresent(l,"processing_duration",r),this.addIfPresent(l,"next_paint_time",o);const c=this.buildInitialContext(e);this.addIfPresent(c,vi,a),this.addIfPresent(c,"interaction_target",s),this.addIfPresent(c,"interaction_type",u),this.pushMeasurement(l,c)}))}measureLCP(){!function(e,t){!function(e,t){t=t||{},kn((function(){var n,i=In(),r=pn("LCP"),o=function(e){t.reportAllChanges||(e=e.slice(-1)),e.forEach((function(e){e.startTime<i.firstHiddenTime&&(r.value=Math.max(e.startTime-fn(),0),r.entries=[e],n())}))},a=mn("largest-contentful-paint",o);if(a){n=gn(e,r,ni,t.reportAllChanges);var s=bn((function(){ii[r.id]||(o(a.takeRecords()),a.disconnect(),ii[r.id]=!0,n(!0))}));["keydown","click"].forEach((function(e){addEventListener(e,(function(){return Fn(s)}),!0)})),hn(s),dn((function(i){r=pn("LCP"),n=gn(e,r,ni,t.reportAllChanges),vn((function(){r.value=performance.now()-i.timeStamp,ii[r.id]=!0,n(!0)}))}))}}))}((function(t){var n=function(e){var t={timeToFirstByte:0,resourceLoadDelay:0,resourceLoadDuration:0,elementRenderDelay:e.value};if(e.entries.length){var n=on();if(n){var i=n.activationStart||0,r=e.entries[e.entries.length-1],o=r.url&&performance.getEntriesByType("resource").filter((function(e){return e.name===r.url}))[0],a=Math.max(0,n.responseStart-i),s=Math.max(a,o?(o.requestStart||o.startTime)-i:0),u=Math.max(s,o?o.responseEnd-i:0),l=Math.max(u,r.startTime-i);t={element:un(r.element),timeToFirstByte:a,resourceLoadDelay:s-a,resourceLoadDuration:u-s,elementRenderDelay:l-u,navigationEntry:n,lcpEntry:r},r.url&&(t.url=r.url),o&&(t.lcpResourceEntry=o)}}return Object.assign(e,{attribution:t})}(t);e(n)}),t)}((e=>{const{elementRenderDelay:t,resourceLoadDelay:n,resourceLoadDuration:i,timeToFirstByte:r,element:o}=e.attribution,a=this.buildInitialValues(e);this.addIfPresent(a,"element_render_delay",t),this.addIfPresent(a,"resource_load_delay",n),this.addIfPresent(a,"resource_load_duration",i),this.addIfPresent(a,hi,r);const s=this.buildInitialContext(e);this.addIfPresent(s,"element",o),this.pushMeasurement(a,s)}))}measureTTFB(){!function(e,t){ai((function(t){var n=function(e){var t={waitingDuration:0,cacheDuration:0,dnsDuration:0,connectionDuration:0,requestDuration:0};if(e.entries.length){var n=e.entries[0],i=n.activationStart||0,r=Math.max((n.workerStart||n.fetchStart)-i,0),o=Math.max(n.domainLookupStart-i,0),a=Math.max(n.connectStart-i,0),s=Math.max(n.connectEnd-i,0);t={waitingDuration:r,cacheDuration:o-r,dnsDuration:a-o,connectionDuration:s-a,requestDuration:e.value-s,navigationEntry:n}}return Object.assign(e,{attribution:t})}(t);e(n)}),t)}((e=>{const{dnsDuration:t,connectionDuration:n,requestDuration:i,waitingDuration:r,cacheDuration:o}=e.attribution,a=this.buildInitialValues(e);this.addIfPresent(a,"dns_duration",t),this.addIfPresent(a,"connection_duration",n),this.addIfPresent(a,"request_duration",i),this.addIfPresent(a,"waiting_duration",r),this.addIfPresent(a,"cache_duration",o);const s=this.buildInitialContext(e);this.pushMeasurement(a,s)}))}buildInitialValues(e){return{[e.name.toLowerCase()]:e.value,delta:e.delta}}buildInitialContext(e){var t;const n=null!==(t=Ee(gi,ye))&&void 0!==t?t:"unknown";return{id:e.id,rating:e.rating,navigation_type:e.navigationType,navigation_entry_id:n}}pushMeasurement(e,t){this.corePushMeasurement({type:"web-vitals",values:e},{context:t})}addIfPresent(e,t,n){n&&(e[t]=n)}}class wi extends Q{constructor(){super(...arguments),this.name="@grafana/faro-web-sdk:instrumentation-web-vitals",this.version=ee}initialize(){this.logDebug("Initializing");this.intializeWebVitalsInstrumentation().initialize()}intializeWebVitalsInstrumentation(){return this.config.trackWebVitalsAttribution?new bi(this.api.pushMeasurement):new tn(this.api.pushMeasurement)}}function yi(e,t,n,i){return new(n||(n=Promise))((function(r,o){function a(e){try{u(i.next(e))}catch(e){o(e)}}function s(e){try{u(i.throw(e))}catch(e){o(e)}}function u(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(a,s)}u((i=i.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;const Si=/^00-[a-f0-9]{32}-[a-f0-9]{16}-[0-9]{1,2}$/;function Ti(e=[]){for(const t of e)if("traceparent"===t.name){if(!Si.test(t.description))continue;const[,e,n]=t.description.split("-");if(null!=e&&null!=n)return{traceId:e,spanId:n};break}}function Ei(e=[],t){return e.some((e=>e&&null!=t.match(e)))}function Ii(e,t={}){for(const[n,i]of Object.entries(t)){const t=e[n];return null!=t&&(l(i)?i.includes(t):t===i)}return!0}function ki(e){const{connectEnd:t,connectStart:n,decodedBodySize:i,domainLookupEnd:r,domainLookupStart:o,duration:a,encodedBodySize:s,fetchStart:u,initiatorType:l,name:c,nextHopProtocol:d,redirectEnd:f,redirectStart:p,renderBlockingStatus:m,requestStart:g,responseEnd:v,responseStart:h,responseStatus:b,secureConnectionStart:w,transferSize:y,workerStart:S}=e;return{name:c,duration:Li(a),tcpHandshakeTime:Li(t-n),dnsLookupTime:Li(r-o),tlsNegotiationTime:Li(g-w),responseStatus:Li(b),redirectTime:Li(f-p),requestTime:Li(h-g),responseTime:Li(v-h),fetchTime:Li(v-u),serviceWorkerTime:Li(u-S),decodedBodySize:Li(i),encodedBodySize:Li(s),cacheHitStatus:function(){let e="fullLoad";0===y?i>0&&(e="cache"):null!=b?304===b&&(e="conditionalFetch"):s>0&&y<s&&(e="conditionalFetch");return e}(),renderBlockingStatus:Li(m),protocol:d,initiatorType:l}}function xi(e){const{activationStart:t,domComplete:n,domContentLoadedEventEnd:i,domContentLoadedEventStart:r,domInteractive:o,fetchStart:a,loadEventEnd:s,loadEventStart:u,responseStart:l,type:c}=e,d=function(){var e;if(null!=(null===(e=performance.timing)||void 0===e?void 0:e.domLoading))return performance.timing.domLoading-performance.timeOrigin;return null}();return Object.assign({visibilityState:document.visibilityState,pageLoadTime:Li(n-a),documentParsingTime:Li(d?o-d:null),domProcessingTime:Li(n-o),domContentLoadHandlerTime:Li(i-r),onLoadTime:Li(s-u),ttfb:Li(Math.max(l-(null!=t?t:0),0)),type:c},ki(e))}function Li(e){return null==e?"unknown":"number"==typeof e?Math.round(e).toString():e.toString()}const Oi={initiatorType:["xmlhttprequest","fetch"]};class Ci extends Q{constructor(){super(...arguments),this.name="@grafana/faro-web-sdk:instrumentation-performance",this.version=ee}initialize(){"PerformanceObserver"in window?function(e){if("complete"===document.readyState)e();else{const t=()=>{"complete"===document.readyState&&(e(),document.removeEventListener("readystatechange",t))};document.addEventListener("readystatechange",t)}}((()=>yi(this,void 0,void 0,(function*(){const t=this.api.pushEvent,n=this.getIgnoreUrls(),{faroNavigationId:i}=yield function(e,t){let n;const i=new Promise((e=>{n=e}));return new PerformanceObserver((i=>{var r;const[o]=i.getEntries();if(null==o||Ei(t,o.name))return;const a=o.toJSON();let s=Ti(null==a?void 0:a.serverTiming);const u=null!==(r=Ee(gi,ye))&&void 0!==r?r:"unknown",l=Object.assign(Object.assign({},xi(a)),{faroNavigationId:O(),faroPreviousNavigationId:u});Ie(gi,l.faroNavigationId,ye),e("faro.performance.navigation",l,void 0,{spanContext:s}),n(l)})).observe({type:"navigation",buffered:!0}),i}(t,n);null!=i&&function(t,n,i){const r=e.faro.config.trackResources;new PerformanceObserver((e=>{const o=e.getEntries();for(const e of o){if(Ei(i,e.name))return;const o=e.toJSON();let a=Ti(null==o?void 0:o.serverTiming);if(null==r&&Ii(o,Oi)||r){const e=Object.assign(Object.assign({},ki(o)),{faroNavigationId:t,faroResourceId:O()});n("faro.performance.resource",e,void 0,{spanContext:a})}}})).observe({type:"resource",buffered:!0})}(i,t,n)})))):this.logDebug("performance observer not supported. Disable performance instrumentation.")}getIgnoreUrls(){var e;return null===(e=this.transports.transports)||void 0===e?void 0:e.flatMap((e=>e.getIgnoreUrls()))}}function Pi(e={}){const t=[new st,new wi,new $e,new ut];return!1!==e.enablePerformanceInstrumentation&&t.unshift(new Ci),!1!==e.captureConsole&&t.push(new qe({disabledLevels:e.captureConsoleDisabledLevels})),t}const _i="browser",Ni=()=>{const e=window.k6;return{k6:Object.assign({isK6Browser:!0},(null==e?void 0:e.testRunId)&&{testRunId:null==e?void 0:e.testRunId})}};class Ai extends W{constructor(e){var t,n,i,r;super(),this.options=e,this.name="@grafana/faro-web-sdk:transport-fetch",this.version=ee,this.disabledUntil=new Date,this.rateLimitBackoffMs=null!==(t=e.defaultRateLimitBackoffMs)&&void 0!==t?t:5e3,this.getNow=null!==(n=e.getNow)&&void 0!==n?n:()=>Date.now(),this.promiseBuffer=x({size:null!==(i=e.bufferSize)&&void 0!==i?i:30,concurrency:null!==(r=e.concurrency)&&void 0!==r?r:5})}send(e){return yi(this,void 0,void 0,(function*(){try{if(this.disabledUntil>new Date(this.getNow()))return this.logWarn(`Dropping transport item due to too many requests. Backoff until ${this.disabledUntil}`),Promise.resolve();yield this.promiseBuffer.add((()=>{const t=JSON.stringify(K(e)),{url:n,requestOptions:i,apiKey:r}=this.options,o=null!=i?i:{},{headers:a}=o,s=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(o,["headers"]);let u;const l=this.metas.value.session;return null!=l&&(u=l.id),fetch(n,Object.assign({method:"POST",headers:Object.assign(Object.assign(Object.assign({"Content-Type":"application/json"},null!=a?a:{}),r?{"x-api-key":r}:{}),u?{"x-faro-session-id":u}:{}),body:t,keepalive:t.length<=6e4},null!=s?s:{})).then((e=>yi(this,void 0,void 0,(function*(){if(202===e.status){"invalid"===e.headers.get("X-Faro-Session-Status")&&this.extendFaroSession(this.config,this.logDebug)}return 429===e.status&&(this.disabledUntil=this.getRetryAfterDate(e),this.logWarn(`Too many requests, backing off until ${this.disabledUntil}`)),e.text().catch(k),e})))).catch((e=>{this.logError("Failed sending payload to the receiver\n",JSON.parse(t),e)}))}))}catch(e){this.logError(e)}}))}getIgnoreUrls(){var e;return[this.options.url].concat(null!==(e=this.config.ignoreUrls)&&void 0!==e?e:[])}isBatched(){return!0}getRetryAfterDate(e){const t=this.getNow(),n=e.headers.get("Retry-After");if(n){const e=Number(n);if(!isNaN(e))return new Date(1e3*e+t);const i=Date.parse(n);if(!isNaN(i))return new Date(i)}return new Date(t+this.rateLimitBackoffMs)}extendFaroSession(e,t){const n="Session expired",i=e.sessionTracking;if(null==i?void 0:i.enabled){const{fetchUserSession:e,storeUserSession:r}=Fe(i);Be({fetchUserSession:e,storeUserSession:r})({forceSessionExtend:!0}),t(`${n} created new session.`)}else t(`${n}.`)}}function Mi(e){var t,n,i,r,o,a,u,l,c,d;const f=[],p=V(e.unpatchedConsole,e.internalLoggerLevel);e.transports?((e.url||e.apiKey)&&p.error('if "transports" is defined, "url" and "apiKey" should not be defined'),f.push(...e.transports)):e.url?f.push(new Ai({url:e.url,apiKey:e.apiKey})):p.error('either "url" or "transports" must be defined');return{app:e.app,batching:Object.assign(Object.assign({},se),e.batching),dedupe:null===(t=e.dedupe)||void 0===t||t,globalObjectKey:e.globalObjectKey||ae,instrumentations:null!==(n=e.instrumentations)&&void 0!==n?n:Pi(),internalLoggerLevel:null!==(i=e.internalLoggerLevel)&&void 0!==i?i:B,isolate:null!==(r=e.isolate)&&void 0!==r&&r,logArgsSerializer:null!==(o=e.logArgsSerializer)&&void 0!==o?o:Z,metas:function(){const t=he;return e.metas&&t.push(...e.metas),s(window.k6)?[...t,Ni]:t}(),parseStacktrace:rt,paused:null!==(a=e.paused)&&void 0!==a&&a,preventGlobalExposure:null!==(u=e.preventGlobalExposure)&&void 0!==u&&u,transports:f,unpatchedConsole:null!==(l=e.unpatchedConsole)&&void 0!==l?l:U,beforeSend:e.beforeSend,eventDomain:null!==(c=e.eventDomain)&&void 0!==c?c:_i,ignoreErrors:e.ignoreErrors,ignoreUrls:e.ignoreUrls,sessionTracking:Object.assign(Object.assign({},De),e.sessionTracking),user:e.user,view:null!==(d=e.view)&&void 0!==d?d:we,trackResources:e.trackResources,trackWebVitalsAttribution:e.trackWebVitalsAttribution}}return e.BaseExtension=G,e.BaseInstrumentation=Q,e.BaseTransport=W,e.ConsoleInstrumentation=qe,e.ConsoleTransport=class extends W{constructor(e={}){super(),this.options=e,this.name="@grafana/faro-web-sdk:transport-console",this.version=ee}send(t){var n;return this.unpatchedConsole[null!==(n=this.options.level)&&void 0!==n?n:e.LogLevel.DEBUG]("New event",K([t]))}},e.Conventions={EventNames:{CLICK:"click",NAVIGATION:"navigation",SESSION_START:"session_start",VIEW_CHANGED:"view_changed"}},e.EVENT_CLICK="click",e.EVENT_NAVIGATION="navigation",e.EVENT_ROUTE_CHANGE="route_change",e.EVENT_SESSION_EXTEND=de,e.EVENT_SESSION_RESUME=ce,e.EVENT_SESSION_START=le,e.EVENT_VIEW_CHANGED=ue,e.ErrorsInstrumentation=st,e.FetchTransport=Ai,e.MAX_SESSION_PERSISTENCE_TIME=Me,e.MAX_SESSION_PERSISTENCE_TIME_BUFFER=6e4,e.PerformanceInstrumentation=Ci,e.PersistentSessionsManager=ze,e.SESSION_EXPIRATION_TIME=Ne,e.SESSION_INACTIVITY_TIME=Ae,e.STORAGE_KEY=_e,e.SessionInstrumentation=$e,e.VERSION=ee,e.ViewInstrumentation=ut,e.VolatileSessionsManager=Ve,e.WebVitalsInstrumentation=wi,e.allLogLevels=I,e.browserMeta=ge,e.buildStackFrame=tt,e.createInternalLogger=V,e.createPromiseBuffer=x,e.createSession=be,e.deepEqual=y,e.defaultEventDomain=_i,e.defaultExceptionType=X,e.defaultGlobalObjectKey=ae,e.defaultInternalLoggerLevel=B,e.defaultLogLevel=E,e.defaultMetas=he,e.defaultViewMeta=we,e.genShortID=O,e.getCurrentTimestamp=S,e.getDataFromSafariExtensions=nt,e.getInternalFaroFromGlobalObject=function(){return C[te]},e.getStackFramesFromError=it,e.getTransportBody=K,e.getWebInstrumentations=Pi,e.globalObject=C,e.initializeFaro=function(e){const t=Mi(e);if(t)return oe(t)},e.internalGlobalObjectKey=te,e.isArray=l,e.isBoolean=e=>t(e,"boolean"),e.isDomError=v,e.isDomException=h,e.isElement=e=>b&&i(e,Element),e.isElementDefined=b,e.isError=m,e.isErrorDefined=p,e.isErrorEvent=g,e.isEvent=f,e.isEventDefined=d,e.isFunction=u,e.isInstanceOf=i,e.isInt=e=>a(e)&&Number.isInteger(e),e.isInternalFaroOnGlobalObject=ie,e.isMap=e=>w&&i(e,Map),e.isMapDefined=w,e.isNull=r,e.isNumber=a,e.isObject=s,e.isPrimitive=c,e.isRegExp=e=>n(e,"RegExp"),e.isString=o,e.isSymbol=e=>t(e,"symbol"),e.isSyntheticEvent=e=>s(e)&&"nativeEvent"in e&&"preventDefault"in e&&"stopPropagation"in e,e.isThenable=e=>u(null==e?void 0:e.then),e.isToString=n,e.isTypeof=t,e.isUndefined=e=>t(e,"undefined"),e.makeCoreConfig=Mi,e.noop=k,e.pageMeta=ve,e.parseStacktrace=rt,e.sdkMeta=()=>({sdk:{name:"@grafana/faro-core",version:ee,integrations:e.faro.config.instrumentations.map((({name:e,version:t})=>({name:e,version:t})))}}),e.setInternalFaroOnGlobalObject=ne,e.transportItemTypeToBodyKey=A,e}({});
1
+ var GrafanaFaroWebSdk=function(e){"use strict";function t(e,t){return typeof e===t}function n(e,t){return Object.prototype.toString.call(e)===`[object ${t}]`}function i(e,t){try{return e instanceof t}catch(e){return!1}}const r=e=>t(e,"null"),o=e=>t(e,"string"),a=e=>t(e,"number")&&!isNaN(e)||t(e,"bigint"),s=e=>!r(e)&&t(e,"object"),u=e=>t(e,"function"),l=e=>n(e,"Array"),c=e=>!s(e)&&!u(e),d="undefined"!=typeof Event,f=e=>d&&i(e,Event),p="undefined"!=typeof Error,m=e=>p&&i(e,Error),g=e=>n(e,"ErrorEvent"),v=e=>n(e,"DOMError"),h=e=>n(e,"DOMException"),b="undefined"!=typeof Element,w="undefined"!=typeof Map;function y(e,n){if(e===n)return!0;if(t(e,"number")&&isNaN(e))return t(n,"number")&&isNaN(n);const i=l(e),r=l(n);if(i!==r)return!1;if(i&&r){const t=e.length;if(t!==n.length)return!1;for(let i=t;0!=i--;)if(!y(e[i],n[i]))return!1;return!0}const o=s(e),a=s(n);if(o!==a)return!1;if(e&&n&&o&&a){const t=Object.keys(e),i=Object.keys(n);if(t.length!==i.length)return!1;for(let e of t)if(!i.includes(e))return!1;for(let i of t)if(!y(e[i],n[i]))return!1;return!0}return!1}function S(){return(new Date).toISOString()}var T;e.LogLevel=void 0,(T=e.LogLevel||(e.LogLevel={})).TRACE="trace",T.DEBUG="debug",T.INFO="info",T.LOG="log",T.WARN="warn",T.ERROR="error";const E=e.LogLevel.LOG,I=[e.LogLevel.TRACE,e.LogLevel.DEBUG,e.LogLevel.INFO,e.LogLevel.LOG,e.LogLevel.WARN,e.LogLevel.ERROR];function k(){}function x(e){const{size:t,concurrency:n}=e,i=[];let r=0;const o=()=>{if(r<n&&i.length){const{producer:e,resolve:t,reject:n}=i.shift();r++,e().then((e=>{r--,o(),t(e)}),(e=>{r--,o(),n(e)}))}};return{add:e=>{if(i.length+r>=t)throw new Error("Task buffer full");return new Promise(((t,n)=>{i.push({producer:e,resolve:t,reject:n}),o()}))}}}const L="abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ0123456789";function O(e=10){return Array.from(Array(e)).map((()=>L[Math.floor(Math.random()*L.length)])).join("")}const C="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof global?global:"undefined"!=typeof self?self:void 0;function P(){return Date.now()}class _{constructor(e,t){var n,i;this.signalBuffer=[],this.itemLimit=null!==(n=null==t?void 0:t.itemLimit)&&void 0!==n?n:50,this.sendTimeout=null!==(i=null==t?void 0:t.sendTimeout)&&void 0!==i?i:250,this.paused=(null==t?void 0:t.paused)||!1,this.sendFn=e,this.flushInterval=-1,this.paused||this.start(),document.addEventListener("visibilitychange",(()=>{"hidden"===document.visibilityState&&this.flush()}))}addItem(e){this.paused||(this.signalBuffer.push(e),this.signalBuffer.length>=this.itemLimit&&this.flush())}start(){this.paused=!1,this.sendTimeout>0&&(this.flushInterval=window.setInterval((()=>this.flush()),this.sendTimeout))}pause(){this.paused=!0,clearInterval(this.flushInterval)}groupItems(e){const t=new Map;return e.forEach((e=>{const n=JSON.stringify(e.meta);let i=t.get(n);i=void 0===i?[e]:[...i,e],t.set(n,i)})),Array.from(t.values())}flush(){if(this.paused||0===this.signalBuffer.length)return;this.groupItems(this.signalBuffer).forEach(this.sendFn),this.signalBuffer=[]}}var N;e.TransportItemType=void 0,(N=e.TransportItemType||(e.TransportItemType={})).EXCEPTION="exception",N.LOG="log",N.MEASUREMENT="measurement",N.TRACE="trace",N.EVENT="event";const A={[e.TransportItemType.EXCEPTION]:"exceptions",[e.TransportItemType.LOG]:"logs",[e.TransportItemType.MEASUREMENT]:"measurements",[e.TransportItemType.TRACE]:"traces",[e.TransportItemType.EVENT]:"events"};function M(t){return n=>{if(n.type===e.TransportItemType.EXCEPTION&&n.payload){const e=n.payload,i=`${e.type}: ${e.value}`;if(function(e,t){return e.some((e=>o(e)?t.includes(e):!!t.match(e)))}(t,i))return null}return n}}function D(e,t,n,i){var r;t.debug("Initializing transports");const o=[];let a=n.paused,s=[];const u=e=>{let t=e;for(const e of s){const n=t.map(e).filter(Boolean);if(0===n.length)return[];t=n}return t},l=e=>{const n=u(e);if(0!==n.length)for(const e of o)t.debug(`Transporting item using ${e.name}\n`,n),e.isBatched()&&e.send(n)};let c;(null===(r=n.batching)||void 0===r?void 0:r.enabled)&&(c=new _(l,{sendTimeout:n.batching.sendTimeout,itemLimit:n.batching.itemLimit,paused:a}));return{add:(...r)=>{t.debug("Adding transports"),r.forEach((r=>{t.debug(`Adding "${r.name}" transport`);o.some((e=>e===r))?t.warn(`Transport ${r.name} is already added`):(r.unpatchedConsole=e,r.internalLogger=t,r.config=n,r.metas=i,o.push(r))}))},addBeforeSendHooks:(...e)=>{t.debug("Adding beforeSendHooks\n",s),e.forEach((e=>{e&&s.push(e)}))},addIgnoreErrorsPatterns:(...e)=>{t.debug("Adding ignoreErrorsPatterns\n",e),e.forEach((e=>{e&&s.push(M(e))}))},getBeforeSendHooks:()=>[...s],execute:e=>{var i;a||((null===(i=n.batching)||void 0===i?void 0:i.enabled)&&(null==c||c.addItem(e)),(e=>{var i,r;if((null===(i=n.batching)||void 0===i?void 0:i.enabled)&&o.every((e=>e.isBatched())))return;const[a]=u([e]);if(void 0!==a)for(const e of o)t.debug(`Transporting item using ${e.name}\n`,a),e.isBatched()?(null===(r=n.batching)||void 0===r?void 0:r.enabled)||e.send([a]):e.send(a)})(e))},isPaused:()=>a,pause:()=>{t.debug("Pausing transports"),null==c||c.pause(),a=!0},remove:(...e)=>{t.debug("Removing transports"),e.forEach((e=>{t.debug(`Removing "${e.name}" transport`);const n=o.indexOf(e);-1!==n?o.splice(n,1):t.warn(`Transport "${e.name}" is not added`)}))},removeBeforeSendHooks:(...e)=>{s.filter((t=>!e.includes(t)))},get transports(){return[...o]},unpause:()=>{t.debug("Unpausing transports"),null==c||c.start(),a=!1}}}var j;e.InternalLoggerLevel=void 0,(j=e.InternalLoggerLevel||(e.InternalLoggerLevel={}))[j.OFF=0]="OFF",j[j.ERROR=1]="ERROR",j[j.WARN=2]="WARN",j[j.INFO=3]="INFO",j[j.VERBOSE=4]="VERBOSE";const R={debug:k,error:k,info:k,prefix:"Faro",warn:k},B=e.InternalLoggerLevel.ERROR,U=Object.assign({},console);let F=U;function z(e){var t;return F=null!==(t=e.unpatchedConsole)&&void 0!==t?t:F,F}function V(t=U,n=B){const i=R;return n>e.InternalLoggerLevel.OFF&&(i.error=n>=e.InternalLoggerLevel.ERROR?function(...e){t.error(`${i.prefix}\n`,...e)}:k,i.warn=n>=e.InternalLoggerLevel.WARN?function(...e){t.warn(`${i.prefix}\n`,...e)}:k,i.info=n>=e.InternalLoggerLevel.INFO?function(...e){t.info(`${i.prefix}\n`,...e)}:k,i.debug=n>=e.InternalLoggerLevel.VERBOSE?function(...e){t.debug(`${i.prefix}\n`,...e)}:k),i}let $=R;function q(e,t){return $=V(e,t.internalLoggerLevel),$}class G{constructor(){this.unpatchedConsole=U,this.internalLogger=R,this.config={},this.metas={}}logDebug(...e){this.internalLogger.debug(`${this.name}\n`,...e)}logInfo(...e){this.internalLogger.info(`${this.name}\n`,...e)}logWarn(...e){this.internalLogger.warn(`${this.name}\n`,...e)}logError(...e){this.internalLogger.error(`${this.name}\n`,...e)}}class W extends G{isBatched(){return!1}getIgnoreUrls(){return[]}}function H(e,t){var n,i;if(void 0===t)return e;if(void 0===e)return{resourceSpans:t};const r=null===(n=e.resourceSpans)||void 0===n?void 0:n[0];if(void 0===r)return e;const o=(null==r?void 0:r.scopeSpans)||[],a=(null===(i=null==t?void 0:t[0])||void 0===i?void 0:i.scopeSpans)||[];return Object.assign(Object.assign({},e),{resourceSpans:[Object.assign(Object.assign({},r),{scopeSpans:[...o,...a]})]})}function K(t){let n={meta:{}};return void 0!==t[0]&&(n.meta=t[0].meta),t.forEach((t=>{switch(t.type){case e.TransportItemType.LOG:case e.TransportItemType.EVENT:case e.TransportItemType.EXCEPTION:case e.TransportItemType.MEASUREMENT:const i=A[t.type],r=n[i];n=Object.assign(Object.assign({},n),{[i]:void 0===r?[t.payload]:[...r,t.payload]});break;case e.TransportItemType.TRACE:n=Object.assign(Object.assign({},n),{traces:H(n.traces,t.payload.resourceSpans)})}})),n}const X="Error";let J;const Z=e=>e.map((e=>{try{return String(e)}catch(e){return""}})).join(" ");function Y(t,n,i,o,a){n.debug("Initializing API");const s=function(t,n,i,r,o){let a;return n.debug("Initializing traces API"),{getOTEL:()=>a,getTraceContext:()=>{const e=null==a?void 0:a.trace.getSpanContext(a.context.active());return e?{trace_id:e.traceId,span_id:e.spanId}:void 0},initOTEL:(e,t)=>{n.debug("Initializing OpenTelemetry"),a={trace:e,context:t}},isOTELInitialized:()=>!!a,pushTraces:t=>{try{const i={type:e.TransportItemType.TRACE,payload:t,meta:r.value};n.debug("Pushing trace\n",i),o.execute(i)}catch(e){n.error("Error pushing trace\n",e)}}}}(0,n,0,o,a);return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},s),function(t,n,i,o,a,s){var u;n.debug("Initializing exceptions API");let l=null;J=null!==(u=i.parseStacktrace)&&void 0!==u?u:J;const c=e=>{n.debug("Changing stacktrace parser"),J=null!=e?e:J};return c(i.parseStacktrace),{changeStacktraceParser:c,getStacktraceParser:()=>J,pushError:(t,{skipDedupe:u,stackFrames:c,type:d,context:f,spanContext:p}={})=>{d=d||t.name||X;const m={meta:o.value,payload:{type:d,value:t.message,timestamp:S(),trace:p?{trace_id:p.traceId,span_id:p.spanId}:s.getTraceContext(),context:null!=f?f:{}},type:e.TransportItemType.EXCEPTION};(null==(c=null!=c?c:t.stack?null==J?void 0:J(t).frames:void 0)?void 0:c.length)&&(m.payload.stacktrace={frames:c});const g={type:m.payload.type,value:m.payload.value,stackTrace:m.payload.stacktrace,context:m.payload.context};u||!i.dedupe||r(l)||!y(g,l)?(l=g,n.debug("Pushing exception\n",m),a.execute(m)):n.debug("Skipping error push because it is the same as the last one\n",m.payload)}}}(0,n,i,o,a,s)),function(e,t,n,i,r){let o,a,s;t.debug("Initializing meta API");const u=e=>{a&&i.remove(a),a={user:e},i.add(a)},l=e=>{o&&i.remove(o),o={session:e},i.add(o)};return{setUser:u,resetUser:u,setSession:l,resetSession:l,getSession:()=>i.value.session,setView:e=>{var t;if((null===(t=null==s?void 0:s.view)||void 0===t?void 0:t.name)===(null==e?void 0:e.name))return;const n=s;s={view:e},i.add(s),n&&i.remove(n)},getView:()=>i.value.view}}(0,n,0,o)),function(t,n,i,o,a,s){var u;n.debug("Initializing logs API");let l=null;const c=null!==(u=i.logArgsSerializer)&&void 0!==u?u:Z;return{pushLog:(t,{context:u,level:d,skipDedupe:f,spanContext:p}={})=>{try{const m={type:e.TransportItemType.LOG,payload:{message:c(t),level:null!=d?d:E,context:null!=u?u:{},timestamp:S(),trace:p?{trace_id:p.traceId,span_id:p.spanId}:s.getTraceContext()},meta:o.value},g={message:m.payload.message,level:m.payload.level,context:m.payload.context};if(!f&&i.dedupe&&!r(l)&&y(g,l))return void n.debug("Skipping log push because it is the same as the last one\n",m.payload);l=g,n.debug("Pushing log\n",m),a.execute(m)}catch(e){n.error("Error pushing log\n",e)}}}}(0,n,i,o,a,s)),function(t,n,i,o,a,s){n.debug("Initializing measurements API");let u=null;return{pushMeasurement:(t,{skipDedupe:l,context:c,spanContext:d}={})=>{var f;try{const p={type:e.TransportItemType.MEASUREMENT,payload:Object.assign(Object.assign({},t),{trace:d?{trace_id:d.traceId,span_id:d.spanId}:s.getTraceContext(),timestamp:null!==(f=t.timestamp)&&void 0!==f?f:S(),context:null!=c?c:{}}),meta:o.value},m={type:p.payload.type,values:p.payload.values,context:p.payload.context};if(!l&&i.dedupe&&!r(u)&&y(m,u))return void n.debug("Skipping measurement push because it is the same as the last one\n",p.payload);u=m,n.debug("Pushing measurement\n",p),a.execute(p)}catch(e){n.error("Error pushing measurement\n",e)}}}}(0,n,i,o,a,s)),function(t,n,i,o,a,s){let u=null;return{pushEvent:(t,l,c,{skipDedupe:d,spanContext:f}={})=>{try{const p={meta:o.value,payload:{name:t,domain:null!=c?c:i.eventDomain,attributes:l,timestamp:S(),trace:f?{trace_id:f.traceId,span_id:f.spanId}:s.getTraceContext()},type:e.TransportItemType.EVENT},m={name:p.payload.name,attributes:p.payload.attributes,domain:p.payload.domain};if(!d&&i.dedupe&&!r(u)&&y(m,u))return void n.debug("Skipping event push because it is the same as the last one\n",p.payload);u=m,n.debug("Pushing event\n",p),a.execute(p)}catch(e){n.error("Error pushing event",e)}}}}(0,n,i,o,a,s))}class Q extends G{constructor(){super(...arguments),this.api={},this.transports={}}}const ee="1.8.1";const te="_faroInternal";function ne(e){e.config.isolate?e.internalLogger.debug("Skipping registering internal Faro instance on global object"):(e.internalLogger.debug("Registering internal Faro instance on global object"),Object.defineProperty(C,te,{configurable:!1,enumerable:!1,writable:!1,value:e}))}function ie(){return te in C}function re(t,n,i,r,o,a,s){return n.debug("Initializing Faro"),e.faro={api:a,config:i,instrumentations:s,internalLogger:n,metas:r,pause:o.pause,transports:o,unpatchedConsole:t,unpause:o.unpause},ne(e.faro),function(e){if(e.config.preventGlobalExposure)e.internalLogger.debug("Skipping registering public Faro instance in the global scope");else{if(e.internalLogger.debug(`Registering public faro reference in the global scope using "${e.config.globalObjectKey}" key`),e.config.globalObjectKey in C)return void e.internalLogger.warn(`Skipping global registration due to key "${e.config.globalObjectKey}" being used already. Please set "globalObjectKey" to something else or set "preventGlobalExposure" to "true"`);Object.defineProperty(C,e.config.globalObjectKey,{configurable:!1,writable:!1,value:e})}}(e.faro),e.faro}function oe(e){const t=z(e),n=q(t,e);if(ie()&&!e.isolate)return void n.error('Faro is already registered. Either add instrumentations, transports etc. to the global faro instance or use the "isolate" property');n.debug("Initializing");const i=function(e,t,n){let i=[],r=[];const o=()=>i.reduce(((e,t)=>Object.assign(e,u(t)?t():t)),{}),a=()=>{if(r.length){const e=o();r.forEach((t=>t(e)))}};return{add:(...e)=>{t.debug("Adding metas\n",e),i.push(...e),a()},remove:(...e)=>{t.debug("Removing metas\n",e),i=i.filter((t=>!e.includes(t))),a()},addListener:e=>{t.debug("Adding metas listener\n",e),r.push(e)},removeListener:e=>{t.debug("Removing metas listener\n",e),r=r.filter((t=>t!==e))},get value(){return o()}}}(0,n),r=D(t,n,e,i),o=Y(0,n,e,i,r),a=function(e,t,n,i,r,o){t.debug("Initializing instrumentations");const a=[];return{add:(...s)=>{t.debug("Adding instrumentations"),s.forEach((s=>{t.debug(`Adding "${s.name}" instrumentation`),a.some((e=>e.name===s.name))?t.warn(`Instrumentation ${s.name} is already added`):(s.unpatchedConsole=e,s.internalLogger=t,s.config=n,s.metas=i,s.transports=r,s.api=o,a.push(s),s.initialize())}))},get instrumentations(){return[...a]},remove:(...e)=>{t.debug("Removing instrumentations"),e.forEach((e=>{var n,i;t.debug(`Removing "${e.name}" instrumentation`);const r=a.reduce(((t,n,i)=>null===t&&n.name===e.name?i:null),null);r?(null===(i=(n=a[r]).destroy)||void 0===i||i.call(n),a.splice(r,1)):t.warn(`Instrumentation "${e.name}" is not added`)}))}}}(t,n,e,i,r,o),s=re(t,n,e,i,r,o,a);return function(e){var t,n;const i={sdk:{version:ee},app:{bundleId:e.config.app.name&&(r=e.config.app.name,null==C?void 0:C[`__faroBundleId_${r}`])}};var r;const o=null===(t=e.config.sessionTracking)||void 0===t?void 0:t.session;o&&e.api.setSession(o),e.config.app&&(i.app=Object.assign(Object.assign({},e.config.app),i.app)),e.config.user&&(i.user=e.config.user),e.config.view&&(i.view=e.config.view),e.metas.add(i,...null!==(n=e.config.metas)&&void 0!==n?n:[])}(s),function(e){e.transports.add(...e.config.transports),e.transports.addBeforeSendHooks(e.config.beforeSend),e.transports.addIgnoreErrorsPatterns(e.config.ignoreErrors)}(s),function(e){e.instrumentations.add(...e.config.instrumentations)}(s),s}e.faro={};const ae="faro",se={enabled:!0,sendTimeout:250,itemLimit:50},ue="view_changed",le="session_start",ce="session_resume",de="session_extend";var fe="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},pe={exports:{}};!function(e,t){!function(n,i){var r="function",o="undefined",a="object",s="string",u="major",l="model",c="name",d="type",f="vendor",p="version",m="architecture",g="console",v="mobile",h="tablet",b="smarttv",w="wearable",y="embedded",S="Amazon",T="Apple",E="ASUS",I="BlackBerry",k="Browser",x="Chrome",L="Firefox",O="Google",C="Huawei",P="LG",_="Microsoft",N="Motorola",A="Opera",M="Samsung",D="Sharp",j="Sony",R="Xiaomi",B="Zebra",U="Facebook",F="Chromium OS",z="Mac OS",V=function(e){for(var t={},n=0;n<e.length;n++)t[e[n].toUpperCase()]=e[n];return t},$=function(e,t){return typeof e===s&&-1!==q(t).indexOf(q(e))},q=function(e){return e.toLowerCase()},G=function(e,t){if(typeof e===s)return e=e.replace(/^\s\s*/,""),typeof t===o?e:e.substring(0,350)},W=function(e,t){for(var n,o,s,u,l,c,d=0;d<t.length&&!l;){var f=t[d],p=t[d+1];for(n=o=0;n<f.length&&!l&&f[n];)if(l=f[n++].exec(e))for(s=0;s<p.length;s++)c=l[++o],typeof(u=p[s])===a&&u.length>0?2===u.length?typeof u[1]==r?this[u[0]]=u[1].call(this,c):this[u[0]]=u[1]:3===u.length?typeof u[1]!==r||u[1].exec&&u[1].test?this[u[0]]=c?c.replace(u[1],u[2]):i:this[u[0]]=c?u[1].call(this,c,u[2]):i:4===u.length&&(this[u[0]]=c?u[3].call(this,c.replace(u[1],u[2])):i):this[u]=c||i;d+=2}},H=function(e,t){for(var n in t)if(typeof t[n]===a&&t[n].length>0){for(var r=0;r<t[n].length;r++)if($(t[n][r],e))return"?"===n?i:n}else if($(t[n],e))return"?"===n?i:n;return e},K={ME:"4.90","NT 3.11":"NT3.51","NT 4.0":"NT4.0",2e3:"NT 5.0",XP:["NT 5.1","NT 5.2"],Vista:"NT 6.0",7:"NT 6.1",8:"NT 6.2",8.1:"NT 6.3",10:["NT 6.4","NT 10.0"],RT:"ARM"},X={browser:[[/\b(?:crmo|crios)\/([\w\.]+)/i],[p,[c,"Chrome"]],[/edg(?:e|ios|a)?\/([\w\.]+)/i],[p,[c,"Edge"]],[/(opera mini)\/([-\w\.]+)/i,/(opera [mobiletab]{3,6})\b.+version\/([-\w\.]+)/i,/(opera)(?:.+version\/|[\/ ]+)([\w\.]+)/i],[c,p],[/opios[\/ ]+([\w\.]+)/i],[p,[c,A+" Mini"]],[/\bopr\/([\w\.]+)/i],[p,[c,A]],[/(kindle)\/([\w\.]+)/i,/(lunascape|maxthon|netfront|jasmine|blazer)[\/ ]?([\w\.]*)/i,/(avant |iemobile|slim)(?:browser)?[\/ ]?([\w\.]*)/i,/(ba?idubrowser)[\/ ]?([\w\.]+)/i,/(?:ms|\()(ie) ([\w\.]+)/i,/(flock|rockmelt|midori|epiphany|silk|skyfire|bolt|iron|vivaldi|iridium|phantomjs|bowser|quark|qupzilla|falkon|rekonq|puffin|brave|whale(?!.+naver)|qqbrowserlite|qq|duckduckgo)\/([-\w\.]+)/i,/(heytap|ovi)browser\/([\d\.]+)/i,/(weibo)__([\d\.]+)/i],[c,p],[/(?:\buc? ?browser|(?:juc.+)ucweb)[\/ ]?([\w\.]+)/i],[p,[c,"UC"+k]],[/microm.+\bqbcore\/([\w\.]+)/i,/\bqbcore\/([\w\.]+).+microm/i],[p,[c,"WeChat(Win) Desktop"]],[/micromessenger\/([\w\.]+)/i],[p,[c,"WeChat"]],[/konqueror\/([\w\.]+)/i],[p,[c,"Konqueror"]],[/trident.+rv[: ]([\w\.]{1,9})\b.+like gecko/i],[p,[c,"IE"]],[/ya(?:search)?browser\/([\w\.]+)/i],[p,[c,"Yandex"]],[/(avast|avg)\/([\w\.]+)/i],[[c,/(.+)/,"$1 Secure "+k],p],[/\bfocus\/([\w\.]+)/i],[p,[c,L+" Focus"]],[/\bopt\/([\w\.]+)/i],[p,[c,A+" Touch"]],[/coc_coc\w+\/([\w\.]+)/i],[p,[c,"Coc Coc"]],[/dolfin\/([\w\.]+)/i],[p,[c,"Dolphin"]],[/coast\/([\w\.]+)/i],[p,[c,A+" Coast"]],[/miuibrowser\/([\w\.]+)/i],[p,[c,"MIUI "+k]],[/fxios\/([-\w\.]+)/i],[p,[c,L]],[/\bqihu|(qi?ho?o?|360)browser/i],[[c,"360 "+k]],[/(oculus|samsung|sailfish|huawei)browser\/([\w\.]+)/i],[[c,/(.+)/,"$1 "+k],p],[/(comodo_dragon)\/([\w\.]+)/i],[[c,/_/g," "],p],[/(electron)\/([\w\.]+) safari/i,/(tesla)(?: qtcarbrowser|\/(20\d\d\.[-\w\.]+))/i,/m?(qqbrowser|baiduboxapp|2345Explorer)[\/ ]?([\w\.]+)/i],[c,p],[/(metasr)[\/ ]?([\w\.]+)/i,/(lbbrowser)/i,/\[(linkedin)app\]/i],[c],[/((?:fban\/fbios|fb_iab\/fb4a)(?!.+fbav)|;fbav\/([\w\.]+);)/i],[[c,U],p],[/(kakao(?:talk|story))[\/ ]([\w\.]+)/i,/(naver)\(.*?(\d+\.[\w\.]+).*\)/i,/safari (line)\/([\w\.]+)/i,/\b(line)\/([\w\.]+)\/iab/i,/(chromium|instagram|snapchat)[\/ ]([-\w\.]+)/i],[c,p],[/\bgsa\/([\w\.]+) .*safari\//i],[p,[c,"GSA"]],[/musical_ly(?:.+app_?version\/|_)([\w\.]+)/i],[p,[c,"TikTok"]],[/headlesschrome(?:\/([\w\.]+)| )/i],[p,[c,x+" Headless"]],[/ wv\).+(chrome)\/([\w\.]+)/i],[[c,x+" WebView"],p],[/droid.+ version\/([\w\.]+)\b.+(?:mobile safari|safari)/i],[p,[c,"Android "+k]],[/(chrome|omniweb|arora|[tizenoka]{5} ?browser)\/v?([\w\.]+)/i],[c,p],[/version\/([\w\.\,]+) .*mobile\/\w+ (safari)/i],[p,[c,"Mobile Safari"]],[/version\/([\w(\.|\,)]+) .*(mobile ?safari|safari)/i],[p,c],[/webkit.+?(mobile ?safari|safari)(\/[\w\.]+)/i],[c,[p,H,{"1.0":"/8",1.2:"/1",1.3:"/3","2.0":"/412","2.0.2":"/416","2.0.3":"/417","2.0.4":"/419","?":"/"}]],[/(webkit|khtml)\/([\w\.]+)/i],[c,p],[/(navigator|netscape\d?)\/([-\w\.]+)/i],[[c,"Netscape"],p],[/mobile vr; rv:([\w\.]+)\).+firefox/i],[p,[c,L+" Reality"]],[/ekiohf.+(flow)\/([\w\.]+)/i,/(swiftfox)/i,/(icedragon|iceweasel|camino|chimera|fennec|maemo browser|minimo|conkeror|klar)[\/ ]?([\w\.\+]+)/i,/(seamonkey|k-meleon|icecat|iceape|firebird|phoenix|palemoon|basilisk|waterfox)\/([-\w\.]+)$/i,/(firefox)\/([\w\.]+)/i,/(mozilla)\/([\w\.]+) .+rv\:.+gecko\/\d+/i,/(polaris|lynx|dillo|icab|doris|amaya|w3m|netsurf|sleipnir|obigo|mosaic|(?:go|ice|up)[\. ]?browser)[-\/ ]?v?([\w\.]+)/i,/(links) \(([\w\.]+)/i,/panasonic;(viera)/i],[c,p],[/(cobalt)\/([\w\.]+)/i],[c,[p,/master.|lts./,""]]],cpu:[[/(?:(amd|x(?:(?:86|64)[-_])?|wow|win)64)[;\)]/i],[[m,"amd64"]],[/(ia32(?=;))/i],[[m,q]],[/((?:i[346]|x)86)[;\)]/i],[[m,"ia32"]],[/\b(aarch64|arm(v?8e?l?|_?64))\b/i],[[m,"arm64"]],[/\b(arm(?:v[67])?ht?n?[fl]p?)\b/i],[[m,"armhf"]],[/windows (ce|mobile); ppc;/i],[[m,"arm"]],[/((?:ppc|powerpc)(?:64)?)(?: mac|;|\))/i],[[m,/ower/,"",q]],[/(sun4\w)[;\)]/i],[[m,"sparc"]],[/((?:avr32|ia64(?=;))|68k(?=\))|\barm(?=v(?:[1-7]|[5-7]1)l?|;|eabi)|(?=atmel )avr|(?:irix|mips|sparc)(?:64)?\b|pa-risc)/i],[[m,q]]],device:[[/\b(sch-i[89]0\d|shw-m380s|sm-[ptx]\w{2,4}|gt-[pn]\d{2,4}|sgh-t8[56]9|nexus 10)/i],[l,[f,M],[d,h]],[/\b((?:s[cgp]h|gt|sm)-\w+|sc[g-]?[\d]+a?|galaxy nexus)/i,/samsung[- ]([-\w]+)/i,/sec-(sgh\w+)/i],[l,[f,M],[d,v]],[/(?:\/|\()(ip(?:hone|od)[\w, ]*)(?:\/|;)/i],[l,[f,T],[d,v]],[/\((ipad);[-\w\),; ]+apple/i,/applecoremedia\/[\w\.]+ \((ipad)/i,/\b(ipad)\d\d?,\d\d?[;\]].+ios/i],[l,[f,T],[d,h]],[/(macintosh);/i],[l,[f,T]],[/\b(sh-?[altvz]?\d\d[a-ekm]?)/i],[l,[f,D],[d,v]],[/\b((?:ag[rs][23]?|bah2?|sht?|btv)-a?[lw]\d{2})\b(?!.+d\/s)/i],[l,[f,C],[d,h]],[/(?:huawei|honor)([-\w ]+)[;\)]/i,/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][012359c][adn]?)\b(?!.+d\/s)/i],[l,[f,C],[d,v]],[/\b(poco[\w ]+|m2\d{3}j\d\d[a-z]{2})(?: bui|\))/i,/\b; (\w+) build\/hm\1/i,/\b(hm[-_ ]?note?[_ ]?(?:\d\w)?) bui/i,/\b(redmi[\-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,/\b(mi[-_ ]?(?:a\d|one|one[_ ]plus|note lte|max|cc)?[_ ]?(?:\d?\w?)[_ ]?(?:plus|se|lite)?)(?: bui|\))/i],[[l,/_/g," "],[f,R],[d,v]],[/\b(mi[-_ ]?(?:pad)(?:[\w_ ]+))(?: bui|\))/i],[[l,/_/g," "],[f,R],[d,h]],[/; (\w+) bui.+ oppo/i,/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i],[l,[f,"OPPO"],[d,v]],[/vivo (\w+)(?: bui|\))/i,/\b(v[12]\d{3}\w?[at])(?: bui|;)/i],[l,[f,"Vivo"],[d,v]],[/\b(rmx[12]\d{3})(?: bui|;|\))/i],[l,[f,"Realme"],[d,v]],[/\b(milestone|droid(?:[2-4x]| (?:bionic|x2|pro|razr))?:?( 4g)?)\b[\w ]+build\//i,/\bmot(?:orola)?[- ](\w*)/i,/((?:moto[\w\(\) ]+|xt\d{3,4}|nexus 6)(?= bui|\)))/i],[l,[f,N],[d,v]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i],[l,[f,N],[d,h]],[/((?=lg)?[vl]k\-?\d{3}) bui| 3\.[-\w; ]{10}lg?-([06cv9]{3,4})/i],[l,[f,P],[d,h]],[/(lm(?:-?f100[nv]?|-[\w\.]+)(?= bui|\))|nexus [45])/i,/\blg[-e;\/ ]+((?!browser|netcast|android tv)\w+)/i,/\blg-?([\d\w]+) bui/i],[l,[f,P],[d,v]],[/(ideatab[-\w ]+)/i,/lenovo ?(s[56]000[-\w]+|tab(?:[\w ]+)|yt[-\d\w]{6}|tb[-\d\w]{6})/i],[l,[f,"Lenovo"],[d,h]],[/(?:maemo|nokia).*(n900|lumia \d+)/i,/nokia[-_ ]?([-\w\.]*)/i],[[l,/_/g," "],[f,"Nokia"],[d,v]],[/(pixel c)\b/i],[l,[f,O],[d,h]],[/droid.+; (pixel[\daxl ]{0,6})(?: bui|\))/i],[l,[f,O],[d,v]],[/droid.+ (a?\d[0-2]{2}so|[c-g]\d{4}|so[-gl]\w+|xq-a\w[4-7][12])(?= bui|\).+chrome\/(?![1-6]{0,1}\d\.))/i],[l,[f,j],[d,v]],[/sony tablet [ps]/i,/\b(?:sony)?sgp\w+(?: bui|\))/i],[[l,"Xperia Tablet"],[f,j],[d,h]],[/ (kb2005|in20[12]5|be20[12][59])\b/i,/(?:one)?(?:plus)? (a\d0\d\d)(?: b|\))/i],[l,[f,"OnePlus"],[d,v]],[/(alexa)webm/i,/(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\))/i,/(kf[a-z]+)( bui|\)).+silk\//i],[l,[f,S],[d,h]],[/((?:sd|kf)[0349hijorstuw]+)( bui|\)).+silk\//i],[[l,/(.+)/g,"Fire Phone $1"],[f,S],[d,v]],[/(playbook);[-\w\),; ]+(rim)/i],[l,f,[d,h]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,/\(bb10; (\w+)/i],[l,[f,I],[d,v]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i],[l,[f,E],[d,h]],[/ (z[bes]6[027][012][km][ls]|zenfone \d\w?)\b/i],[l,[f,E],[d,v]],[/(nexus 9)/i],[l,[f,"HTC"],[d,h]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,/(alcatel|geeksphone|nexian|panasonic(?!(?:;|\.))|sony(?!-bra))[-_ ]?([-\w]*)/i],[f,[l,/_/g," "],[d,v]],[/droid.+; ([ab][1-7]-?[0178a]\d\d?)/i],[l,[f,"Acer"],[d,h]],[/droid.+; (m[1-5] note) bui/i,/\bmz-([-\w]{2,})/i],[l,[f,"Meizu"],[d,v]],[/(blackberry|benq|palm(?=\-)|sonyericsson|acer|asus|dell|meizu|motorola|polytron|infinix|tecno)[-_ ]?([-\w]*)/i,/(hp) ([\w ]+\w)/i,/(asus)-?(\w+)/i,/(microsoft); (lumia[\w ]+)/i,/(lenovo)[-_ ]?([-\w]+)/i,/(jolla)/i,/(oppo) ?([\w ]+) bui/i],[f,l,[d,v]],[/(kobo)\s(ereader|touch)/i,/(archos) (gamepad2?)/i,/(hp).+(touchpad(?!.+tablet)|tablet)/i,/(kindle)\/([\w\.]+)/i,/(nook)[\w ]+build\/(\w+)/i,/(dell) (strea[kpr\d ]*[\dko])/i,/(le[- ]+pan)[- ]+(\w{1,9}) bui/i,/(trinity)[- ]*(t\d{3}) bui/i,/(gigaset)[- ]+(q\w{1,9}) bui/i,/(vodafone) ([\w ]+)(?:\)| bui)/i],[f,l,[d,h]],[/(surface duo)/i],[l,[f,_],[d,h]],[/droid [\d\.]+; (fp\du?)(?: b|\))/i],[l,[f,"Fairphone"],[d,v]],[/(u304aa)/i],[l,[f,"AT&T"],[d,v]],[/\bsie-(\w*)/i],[l,[f,"Siemens"],[d,v]],[/\b(rct\w+) b/i],[l,[f,"RCA"],[d,h]],[/\b(venue[\d ]{2,7}) b/i],[l,[f,"Dell"],[d,h]],[/\b(q(?:mv|ta)\w+) b/i],[l,[f,"Verizon"],[d,h]],[/\b(?:barnes[& ]+noble |bn[rt])([\w\+ ]*) b/i],[l,[f,"Barnes & Noble"],[d,h]],[/\b(tm\d{3}\w+) b/i],[l,[f,"NuVision"],[d,h]],[/\b(k88) b/i],[l,[f,"ZTE"],[d,h]],[/\b(nx\d{3}j) b/i],[l,[f,"ZTE"],[d,v]],[/\b(gen\d{3}) b.+49h/i],[l,[f,"Swiss"],[d,v]],[/\b(zur\d{3}) b/i],[l,[f,"Swiss"],[d,h]],[/\b((zeki)?tb.*\b) b/i],[l,[f,"Zeki"],[d,h]],[/\b([yr]\d{2}) b/i,/\b(dragon[- ]+touch |dt)(\w{5}) b/i],[[f,"Dragon Touch"],l,[d,h]],[/\b(ns-?\w{0,9}) b/i],[l,[f,"Insignia"],[d,h]],[/\b((nxa|next)-?\w{0,9}) b/i],[l,[f,"NextBook"],[d,h]],[/\b(xtreme\_)?(v(1[045]|2[015]|[3469]0|7[05])) b/i],[[f,"Voice"],l,[d,v]],[/\b(lvtel\-)?(v1[12]) b/i],[[f,"LvTel"],l,[d,v]],[/\b(ph-1) /i],[l,[f,"Essential"],[d,v]],[/\b(v(100md|700na|7011|917g).*\b) b/i],[l,[f,"Envizen"],[d,h]],[/\b(trio[-\w\. ]+) b/i],[l,[f,"MachSpeed"],[d,h]],[/\btu_(1491) b/i],[l,[f,"Rotor"],[d,h]],[/(shield[\w ]+) b/i],[l,[f,"Nvidia"],[d,h]],[/(sprint) (\w+)/i],[f,l,[d,v]],[/(kin\.[onetw]{3})/i],[[l,/\./g," "],[f,_],[d,v]],[/droid.+; (cc6666?|et5[16]|mc[239][23]x?|vc8[03]x?)\)/i],[l,[f,B],[d,h]],[/droid.+; (ec30|ps20|tc[2-8]\d[kx])\)/i],[l,[f,B],[d,v]],[/smart-tv.+(samsung)/i],[f,[d,b]],[/hbbtv.+maple;(\d+)/i],[[l,/^/,"SmartTV"],[f,M],[d,b]],[/(nux; netcast.+smarttv|lg (netcast\.tv-201\d|android tv))/i],[[f,P],[d,b]],[/(apple) ?tv/i],[f,[l,T+" TV"],[d,b]],[/crkey/i],[[l,x+"cast"],[f,O],[d,b]],[/droid.+aft(\w+)( bui|\))/i],[l,[f,S],[d,b]],[/\(dtv[\);].+(aquos)/i,/(aquos-tv[\w ]+)\)/i],[l,[f,D],[d,b]],[/(bravia[\w ]+)( bui|\))/i],[l,[f,j],[d,b]],[/(mitv-\w{5}) bui/i],[l,[f,R],[d,b]],[/Hbbtv.*(technisat) (.*);/i],[f,l,[d,b]],[/\b(roku)[\dx]*[\)\/]((?:dvp-)?[\d\.]*)/i,/hbbtv\/\d+\.\d+\.\d+ +\([\w\+ ]*; *([\w\d][^;]*);([^;]*)/i],[[f,G],[l,G],[d,b]],[/\b(android tv|smart[- ]?tv|opera tv|tv; rv:)\b/i],[[d,b]],[/(ouya)/i,/(nintendo) ([wids3utch]+)/i],[f,l,[d,g]],[/droid.+; (shield) bui/i],[l,[f,"Nvidia"],[d,g]],[/(playstation [345portablevi]+)/i],[l,[f,j],[d,g]],[/\b(xbox(?: one)?(?!; xbox))[\); ]/i],[l,[f,_],[d,g]],[/((pebble))app/i],[f,l,[d,w]],[/(watch)(?: ?os[,\/]|\d,\d\/)[\d\.]+/i],[l,[f,T],[d,w]],[/droid.+; (glass) \d/i],[l,[f,O],[d,w]],[/droid.+; (wt63?0{2,3})\)/i],[l,[f,B],[d,w]],[/(quest( 2| pro)?)/i],[l,[f,U],[d,w]],[/(tesla)(?: qtcarbrowser|\/[-\w\.]+)/i],[f,[d,y]],[/(aeobc)\b/i],[l,[f,S],[d,y]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+? mobile safari/i],[l,[d,v]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+?(?! mobile) safari/i],[l,[d,h]],[/\b((tablet|tab)[;\/]|focus\/\d(?!.+mobile))/i],[[d,h]],[/(phone|mobile(?:[;\/]| [ \w\/\.]*safari)|pda(?=.+windows ce))/i],[[d,v]],[/(android[-\w\. ]{0,9});.+buil/i],[l,[f,"Generic"]]],engine:[[/windows.+ edge\/([\w\.]+)/i],[p,[c,"EdgeHTML"]],[/webkit\/537\.36.+chrome\/(?!27)([\w\.]+)/i],[p,[c,"Blink"]],[/(presto)\/([\w\.]+)/i,/(webkit|trident|netfront|netsurf|amaya|lynx|w3m|goanna)\/([\w\.]+)/i,/ekioh(flow)\/([\w\.]+)/i,/(khtml|tasman|links)[\/ ]\(?([\w\.]+)/i,/(icab)[\/ ]([23]\.[\d\.]+)/i,/\b(libweb)/i],[c,p],[/rv\:([\w\.]{1,9})\b.+(gecko)/i],[p,c]],os:[[/microsoft (windows) (vista|xp)/i],[c,p],[/(windows) nt 6\.2; (arm)/i,/(windows (?:phone(?: os)?|mobile))[\/ ]?([\d\.\w ]*)/i,/(windows)[\/ ]?([ntce\d\. ]+\w)(?!.+xbox)/i],[c,[p,H,K]],[/(win(?=3|9|n)|win 9x )([nt\d\.]+)/i],[[c,"Windows"],[p,H,K]],[/ip[honead]{2,4}\b(?:.*os ([\w]+) like mac|; opera)/i,/(?:ios;fbsv\/|iphone.+ios[\/ ])([\d\.]+)/i,/cfnetwork\/.+darwin/i],[[p,/_/g,"."],[c,"iOS"]],[/(mac os x) ?([\w\. ]*)/i,/(macintosh|mac_powerpc\b)(?!.+haiku)/i],[[c,z],[p,/_/g,"."]],[/droid ([\w\.]+)\b.+(android[- ]x86|harmonyos)/i],[p,c],[/(android|webos|qnx|bada|rim tablet os|maemo|meego|sailfish)[-\/ ]?([\w\.]*)/i,/(blackberry)\w*\/([\w\.]*)/i,/(tizen|kaios)[\/ ]([\w\.]+)/i,/\((series40);/i],[c,p],[/\(bb(10);/i],[p,[c,I]],[/(?:symbian ?os|symbos|s60(?=;)|series60)[-\/ ]?([\w\.]*)/i],[p,[c,"Symbian"]],[/mozilla\/[\d\.]+ \((?:mobile|tablet|tv|mobile; [\w ]+); rv:.+ gecko\/([\w\.]+)/i],[p,[c,L+" OS"]],[/web0s;.+rt(tv)/i,/\b(?:hp)?wos(?:browser)?\/([\w\.]+)/i],[p,[c,"webOS"]],[/watch(?: ?os[,\/]|\d,\d\/)([\d\.]+)/i],[p,[c,"watchOS"]],[/crkey\/([\d\.]+)/i],[p,[c,x+"cast"]],[/(cros) [\w]+(?:\)| ([\w\.]+)\b)/i],[[c,F],p],[/panasonic;(viera)/i,/(netrange)mmh/i,/(nettv)\/(\d+\.[\w\.]+)/i,/(nintendo|playstation) ([wids345portablevuch]+)/i,/(xbox); +xbox ([^\);]+)/i,/\b(joli|palm)\b ?(?:os)?\/?([\w\.]*)/i,/(mint)[\/\(\) ]?(\w*)/i,/(mageia|vectorlinux)[; ]/i,/([kxln]?ubuntu|debian|suse|opensuse|gentoo|arch(?= linux)|slackware|fedora|mandriva|centos|pclinuxos|red ?hat|zenwalk|linpus|raspbian|plan 9|minix|risc os|contiki|deepin|manjaro|elementary os|sabayon|linspire)(?: gnu\/linux)?(?: enterprise)?(?:[- ]linux)?(?:-gnu)?[-\/ ]?(?!chrom|package)([-\w\.]*)/i,/(hurd|linux) ?([\w\.]*)/i,/(gnu) ?([\w\.]*)/i,/\b([-frentopcghs]{0,5}bsd|dragonfly)[\/ ]?(?!amd|[ix346]{1,2}86)([\w\.]*)/i,/(haiku) (\w+)/i],[c,p],[/(sunos) ?([\w\.\d]*)/i],[[c,"Solaris"],p],[/((?:open)?solaris)[-\/ ]?([\w\.]*)/i,/(aix) ((\d)(?=\.|\)| )[\w\.])*/i,/\b(beos|os\/2|amigaos|morphos|openvms|fuchsia|hp-ux|serenityos)/i,/(unix) ?([\w\.]*)/i],[c,p]]},J=function(e,t){if(typeof e===a&&(t=e,e=i),!(this instanceof J))return new J(e,t).getResult();var g=typeof n!==o&&n.navigator?n.navigator:i,b=e||(g&&g.userAgent?g.userAgent:""),w=g&&g.userAgentData?g.userAgentData:i,y=t?function(e,t){var n={};for(var i in e)t[i]&&t[i].length%2==0?n[i]=t[i].concat(e[i]):n[i]=e[i];return n}(X,t):X,S=g&&g.userAgent==b;return this.getBrowser=function(){var e,t={};return t[c]=i,t[p]=i,W.call(t,b,y.browser),t[u]=typeof(e=t[p])===s?e.replace(/[^\d\.]/g,"").split(".")[0]:i,S&&g&&g.brave&&typeof g.brave.isBrave==r&&(t[c]="Brave"),t},this.getCPU=function(){var e={};return e[m]=i,W.call(e,b,y.cpu),e},this.getDevice=function(){var e={};return e[f]=i,e[l]=i,e[d]=i,W.call(e,b,y.device),S&&!e[d]&&w&&w.mobile&&(e[d]=v),S&&"Macintosh"==e[l]&&g&&typeof g.standalone!==o&&g.maxTouchPoints&&g.maxTouchPoints>2&&(e[l]="iPad",e[d]=h),e},this.getEngine=function(){var e={};return e[c]=i,e[p]=i,W.call(e,b,y.engine),e},this.getOS=function(){var e={};return e[c]=i,e[p]=i,W.call(e,b,y.os),S&&!e[c]&&w&&"Unknown"!=w.platform&&(e[c]=w.platform.replace(/chrome os/i,F).replace(/macos/i,z)),e},this.getResult=function(){return{ua:this.getUA(),browser:this.getBrowser(),engine:this.getEngine(),os:this.getOS(),device:this.getDevice(),cpu:this.getCPU()}},this.getUA=function(){return b},this.setUA=function(e){return b=typeof e===s&&e.length>350?G(e,350):e,this},this.setUA(b),this};J.VERSION="1.0.36",J.BROWSER=V([c,p,u]),J.CPU=V([m]),J.DEVICE=V([l,f,d,g,v,b,h,w,y]),J.ENGINE=J.OS=V([c,p]),e.exports&&(t=e.exports=J),t.UAParser=J;var Z=typeof n!==o&&(n.jQuery||n.Zepto);if(Z&&!Z.ua){var Y=new J;Z.ua=Y.getResult(),Z.ua.get=function(){return Y.getUA()},Z.ua.set=function(e){Y.setUA(e);var t=Y.getResult();for(var n in t)Z.ua[n]=t[n]}}}("object"==typeof window?window:fe)}(pe,pe.exports);var me=pe.exports;const ge=()=>{const e=new me.UAParser,{name:t,version:n}=e.getBrowser(),{name:i,version:r}=e.getOS(),o=e.getUA(),a=navigator.language,s=navigator.userAgent.includes("Mobi"),u=function(){if(!t||!n)return;if("userAgentData"in navigator&&navigator.userAgentData)return navigator.userAgentData.brands;return}(),l="unknown";return{browser:{name:null!=t?t:l,version:null!=n?n:l,os:`${null!=i?i:l} ${null!=r?r:l}`,userAgent:null!=o?o:l,language:null!=a?a:l,mobile:s,brands:null!=u?u:l,viewportWidth:`${window.innerWidth}`,viewportHeight:`${window.innerHeight}`}}},ve=()=>({page:{url:location.href}}),he=[ge,ve];function be(t){var n,i,r,o;return{id:null!==(o=null===(r=null===(i=null===(n=e.faro.config)||void 0===n?void 0:n.sessionTracking)||void 0===i?void 0:i.generateSessionId)||void 0===r?void 0:r.call(i))&&void 0!==o?o:O(),attributes:t}}const we={name:"default"},ye="sessionStorage",Se="localStorage";function Te(t){var n;try{let e;e=window[t];const n="__faro_storage_test__";return e.setItem(n,n),e.removeItem(n),!0}catch(i){return null===(n=e.faro.internalLogger)||void 0===n||n.info(`Web storage of type ${t} is not available. Reason: ${i}`),!1}}function Ee(e,t){return Oe(t)?window[t].getItem(e):null}function Ie(e,t,n){if(Oe(n))try{window[n].setItem(e,t)}catch(e){}}function ke(e,t){Oe(t)&&window[t].removeItem(e)}const xe=Te(Se),Le=Te(ye);function Oe(e){return e===Se?xe:e===ye&&Le}function Ce(e,t){let n,i=!1;const r=()=>{null!=n?(e(...n),n=null,setTimeout(r,t)):i=!1};return(...o)=>{i?n=o:(e(...o),i=!0,setTimeout(r,t))}}function Pe(){var t,n,i;const r=e.faro.config.sessionTracking;let o=null!==(i=null!==(n=null===(t=null==r?void 0:r.sampler)||void 0===t?void 0:t.call(r,{metas:e.faro.metas.value}))&&void 0!==n?n:null==r?void 0:r.samplingRate)&&void 0!==i?i:1;if("number"!=typeof o){o=0}return Math.random()<o}const _e="com.grafana.faro.session",Ne=144e5,Ae=9e5,Me=Ae,De={enabled:!0,persistent:!1,maxSessionPersistenceTime:Me};function je({sessionId:t,started:n,lastActivity:i,isSampled:r=!0}={}){var o,a;const s=P(),u=null===(a=null===(o=e.faro.config)||void 0===o?void 0:o.sessionTracking)||void 0===a?void 0:a.generateSessionId;return null==t&&(t="function"==typeof u?u():O()),{sessionId:t,lastActivity:null!=i?i:s,started:null!=n?n:s,isSampled:r}}function Re(e){if(null==e)return!1;const t=P();if(!(t-e.started<Ne))return!1;return t-e.lastActivity<Ae}function Be({fetchUserSession:t,storeUserSession:n}){return function({forceSessionExtend:i}={forceSessionExtend:!1}){var r,o,a;if(!t||!n)return;const s=e.faro.config.sessionTracking,u=null==s?void 0:s.persistent;if(u&&!xe||!u&&!Le)return;const l=t();if(!1===i&&Re(l))n(Object.assign(Object.assign({},l),{lastActivity:P()}));else{let t=Ue(je({isSampled:Pe()}),l);n(t),null===(r=e.faro.api)||void 0===r||r.setSession(t.sessionMeta),null===(o=null==s?void 0:s.onSessionChange)||void 0===o||o.call(s,null!==(a=null==l?void 0:l.sessionMeta)&&void 0!==a?a:null,t.sessionMeta)}}}function Ue(t,n){var i,r,o,a;return Object.assign(Object.assign({},t),{sessionMeta:{id:t.sessionId,attributes:Object.assign(Object.assign(Object.assign(Object.assign({},null===(r=null===(i=e.faro.config.sessionTracking)||void 0===i?void 0:i.session)||void 0===r?void 0:r.attributes),null!==(a=null===(o=e.faro.metas.value.session)||void 0===o?void 0:o.attributes)&&void 0!==a?a:{}),null!=n?{previousSession:n.sessionId}:{}),{isSampled:t.isSampled.toString()})}})}class Fe{constructor(){this.updateSession=Ce((()=>this.updateUserSession()),1e3),this.updateUserSession=Be({fetchUserSession:Fe.fetchUserSession,storeUserSession:Fe.storeUserSession}),this.init()}static removeUserSession(){ke(_e,Fe.storageTypeLocal)}static storeUserSession(e){Ie(_e,JSON.stringify(e),Fe.storageTypeLocal)}static fetchUserSession(){const e=Ee(_e,Fe.storageTypeLocal);return e?JSON.parse(e):null}init(){document.addEventListener("visibilitychange",(()=>{"visible"===document.visibilityState&&this.updateSession()})),e.faro.metas.addListener((function(t){const n=t.session,i=Fe.fetchUserSession();if(n&&n.id!==(null==i?void 0:i.sessionId)){const t=Ue(je({sessionId:n.id,isSampled:Pe()}),i);Fe.storeUserSession(t),e.faro.api.setSession(t.sessionMeta)}}))}}Fe.storageTypeLocal=Se;class ze{constructor(){this.updateSession=Ce((()=>this.updateUserSession()),1e3),this.updateUserSession=Be({fetchUserSession:ze.fetchUserSession,storeUserSession:ze.storeUserSession}),this.init()}static removeUserSession(){ke(_e,ze.storageTypeSession)}static storeUserSession(e){Ie(_e,JSON.stringify(e),ze.storageTypeSession)}static fetchUserSession(){const e=Ee(_e,ze.storageTypeSession);return e?JSON.parse(e):null}init(){document.addEventListener("visibilitychange",(()=>{"visible"===document.visibilityState&&this.updateSession()})),e.faro.metas.addListener((function(t){const n=t.session,i=ze.fetchUserSession();if(n&&n.id!==(null==i?void 0:i.sessionId)){const t=Ue(je({sessionId:n.id,isSampled:Pe()}),i);ze.storeUserSession(t),e.faro.api.setSession(t.sessionMeta)}}))}}function Ve(e){return(null==e?void 0:e.persistent)?Fe:ze}ze.storageTypeSession=ye;class $e extends Q{constructor(){super(...arguments),this.name="@grafana/faro-web-sdk:instrumentation-session",this.version=ee}sendSessionStartEvent(e){var t,n;const i=e.session;if(i&&i.id!==(null===(t=this.notifiedSession)||void 0===t?void 0:t.id)){if(this.notifiedSession&&this.notifiedSession.id===(null===(n=i.attributes)||void 0===n?void 0:n.previousSession))return this.api.pushEvent(de,{},void 0,{skipDedupe:!0}),void(this.notifiedSession=i);this.notifiedSession=i,this.api.pushEvent(le,{},void 0,{skipDedupe:!0})}}createInitialSession(e,t){var n,i,r,o,a;let s,u,l=e.fetchUserSession();if(t.persistent&&t.maxSessionPersistenceTime&&l){const e=P();l.lastActivity<e-t.maxSessionPersistenceTime&&(Fe.removeUserSession(),l=null)}if(Re(l)){const e=null==l?void 0:l.sessionId;u=je({sessionId:e,isSampled:l.isSampled||!1,started:null==l?void 0:l.started}),u.sessionMeta={id:e,attributes:Object.assign(Object.assign(Object.assign({},null===(n=t.session)||void 0===n?void 0:n.attributes),null===(i=null==l?void 0:l.sessionMeta)||void 0===i?void 0:i.attributes),{isSampled:u.isSampled.toString()})},s=ce}else{const e=null!==(o=null===(r=t.session)||void 0===r?void 0:r.id)&&void 0!==o?o:be().id;u=je({sessionId:e,isSampled:Pe()}),u.sessionMeta={id:e,attributes:Object.assign({isSampled:u.isSampled.toString()},null===(a=t.session)||void 0===a?void 0:a.attributes)},s=le}return{initialSession:u,lifecycleType:s}}registerBeforeSendHook(e){var t;const{updateSession:n}=new e;null===(t=this.transports)||void 0===t||t.addBeforeSendHooks((e=>{var t,i,r;n();const o=null===(t=e.meta.session)||void 0===t?void 0:t.attributes;if(o&&"true"===(null==o?void 0:o.isSampled)){let t=JSON.parse(JSON.stringify(e));const n=null===(i=t.meta.session)||void 0===i?void 0:i.attributes;return null==n||delete n.isSampled,0===Object.keys(null!=n?n:{}).length&&(null===(r=t.meta.session)||void 0===r||delete r.attributes),t}return null}))}initialize(){this.logDebug("init session instrumentation");const e=this.config.sessionTracking;if(null==e?void 0:e.enabled){const t=Ve(e);this.registerBeforeSendHook(t);const{initialSession:n,lifecycleType:i}=this.createInitialSession(t,e);t.storeUserSession(n);const r=n.sessionMeta;this.notifiedSession=r,this.api.setSession(r),i===le&&this.api.pushEvent(le,{},void 0,{skipDedupe:!0}),i===ce&&this.api.pushEvent(ce,{},void 0,{skipDedupe:!0})}this.metas.addListener(this.sendSessionStartEvent.bind(this))}}class qe extends Q{constructor(e={}){super(),this.options=e,this.name="@grafana/faro-web-sdk:instrumentation-console",this.version=ee}initialize(){this.logDebug("Initializing\n",this.options),I.filter((e=>{var t;return!(null!==(t=this.options.disabledLevels)&&void 0!==t?t:qe.defaultDisabledLevels).includes(e)})).forEach((e=>{console[e]=(...t)=>{try{this.api.pushLog(t,{level:e})}catch(e){this.logError(e)}finally{this.unpatchedConsole[e](...t)}}}))}}qe.defaultDisabledLevels=[e.LogLevel.DEBUG,e.LogLevel.TRACE,e.LogLevel.LOG];const Ge=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i,We=/^\s*at (?:(.*\).*?|.*?) ?\((?:address at )?)?((?:file|https?|blob|chrome-extension|address|native|eval|webpack|<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,He=/\((\S*)(?::(\d+))(?::(\d+))\)/,Ke="address at ",Xe=Ke.length,Je=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:file|https?|blob|chrome|webpack|resource|moz-extension|safari-extension|safari-web-extension|capacitor)?:\/.*?|\[native code]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,Ze=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,Ye="safari-extension",Qe="safari-web-extension",et=/Minified React error #\d+;/i;function tt(e,t,n,i){const r={filename:e||document.location.href,function:t||"?"};return void 0!==n&&(r.lineno=n),void 0!==i&&(r.colno=i),r}function nt(e,t){const n=null==e?void 0:e.includes(Ye),i=!n&&(null==e?void 0:e.includes(Qe));return n||i?[(null==e?void 0:e.includes("@"))?e.split("@")[0]:e,n?`${Ye}:${t}`:`${Qe}:${t}`]:[e,t]}function it(e){let t=[];e.stacktrace?t=e.stacktrace.split("\n").filter(((e,t)=>t%2==0)):e.stack&&(t=e.stack.split("\n"));const n=t.reduce(((t,n,i)=>{let r,o,s,u,l;if(r=We.exec(n)){if(o=r[1],s=r[2],u=r[3],l=r[4],null==s?void 0:s.startsWith("eval")){const e=He.exec(s);e&&(s=e[1],u=e[2],l=e[3])}s=(null==s?void 0:s.startsWith(Ke))?s.substring(Xe):s,[o,s]=nt(o,s)}else if(r=Je.exec(n)){if(o=r[1],s=r[3],u=r[4],l=r[5],s&&s.includes(" > eval")){const e=Ze.exec(s);e&&(o=o||"eval",s=e[1],u=e[2])}else 0===i&&!l&&a(e.columnNumber)&&(l=String(e.columnNumber+1));[o,s]=nt(o,s)}return(s||o)&&t.push(tt(s,o,u?Number(u):void 0,l?Number(l):void 0)),t}),[]);return et.test(e.message)?n.slice(1):n}function rt(e){return{frames:it(e)}}function ot(e){let t,n,i,r,o=[];if(g(e)&&e.error)t=e.error.message,n=e.error.name,o=it(e.error);else if((i=v(e))||h(e)){const{name:r,message:o}=e;n=null!=r?r:i?"DOMError":"DOMException",t=o?`${n}: ${o}`:n}else m(e)?(t=e.message,o=it(e)):(s(e)||(r=f(e)))&&(n=r?e.constructor.name:void 0,t=`Non-Error exception captured with keys: ${Object.keys(e)}`);return[t,n,o]}function at(e){const t=window.onerror;window.onerror=(...n)=>{try{const[i,r,a,s,u]=n;let l,c,d=[];const f=o(i),p=tt(r,"?",a,s);u||!f?([l,c,d]=ot(null!=u?u:i),0===d.length&&(d=[p])):f&&([l,c]=function(e){var t,n;const i=e.match(Ge),r=null!==(t=null==i?void 0:i[1])&&void 0!==t?t:X;return[null!==(n=null==i?void 0:i[2])&&void 0!==n?n:e,r]}(i),d=[p]),l&&e.pushError(new Error(l),{type:c,stackFrames:d})}finally{null==t||t.apply(window,n)}}}class st extends Q{constructor(){super(...arguments),this.name="@grafana/faro-web-sdk:instrumentation-errors",this.version=ee}initialize(){var e;this.logDebug("Initializing"),at(this.api),e=this.api,window.addEventListener("unhandledrejection",(t=>{var n,i;let r,o,a=t;a.reason?a=t.reason:(null===(n=t.detail)||void 0===n?void 0:n.reason)&&(a=null===(i=t.detail)||void 0===i?void 0:i.reason);let s=[];c(a)?(r=`Non-Error promise rejection captured with value: ${String(a)}`,o="UnhandledRejection"):[r,o,s]=ot(a),r&&e.pushError(new Error(r),{type:o,stackFrames:s})}))}}class ut extends Q{constructor(){super(...arguments),this.name="@grafana/faro-web-sdk:instrumentation-view",this.version=ee}sendViewChangedEvent(e){var t,n,i;const r=e.view;r&&r.name!==(null===(t=this.notifiedView)||void 0===t?void 0:t.name)&&(this.api.pushEvent(ue,{fromView:null!==(i=null===(n=this.notifiedView)||void 0===n?void 0:n.name)&&void 0!==i?i:"",toView:r.name},void 0,{skipDedupe:!0}),this.notifiedView=r)}initialize(){this.sendViewChangedEvent(this.metas.value),this.metas.addListener(this.sendViewChangedEvent.bind(this))}}var lt,ct,dt,ft,pt,mt=-1,gt=function(e){addEventListener("pageshow",(function(t){t.persisted&&(mt=t.timeStamp,e(t))}),!0)},vt=function(){var e=self.performance&&performance.getEntriesByType&&performance.getEntriesByType("navigation")[0];if(e&&e.responseStart>0&&e.responseStart<performance.now())return e},ht=function(){var e=vt();return e&&e.activationStart||0},bt=function(e,t){var n=vt(),i="navigate";return mt>=0?i="back-forward-cache":n&&(document.prerendering||ht()>0?i="prerender":document.wasDiscarded?i="restore":n.type&&(i=n.type.replace(/_/g,"-"))),{name:e,value:void 0===t?-1:t,rating:"good",delta:0,entries:[],id:"v4-".concat(Date.now(),"-").concat(Math.floor(8999999999999*Math.random())+1e12),navigationType:i}},wt=function(e,t,n){try{if(PerformanceObserver.supportedEntryTypes.includes(e)){var i=new PerformanceObserver((function(e){Promise.resolve().then((function(){t(e.getEntries())}))}));return i.observe(Object.assign({type:e,buffered:!0},n||{})),i}}catch(e){}},yt=function(e,t,n,i){var r,o;return function(a){t.value>=0&&(a||i)&&((o=t.value-(r||0))||void 0===r)&&(r=t.value,t.delta=o,t.rating=function(e,t){return e>t[1]?"poor":e>t[0]?"needs-improvement":"good"}(t.value,n),e(t))}},St=function(e){requestAnimationFrame((function(){return requestAnimationFrame((function(){return e()}))}))},Tt=function(e){document.addEventListener("visibilitychange",(function(){"hidden"===document.visibilityState&&e()}))},Et=function(e){var t=!1;return function(){t||(e(),t=!0)}},It=-1,kt=function(){return"hidden"!==document.visibilityState||document.prerendering?1/0:0},xt=function(e){"hidden"===document.visibilityState&&It>-1&&(It="visibilitychange"===e.type?e.timeStamp:0,Ot())},Lt=function(){addEventListener("visibilitychange",xt,!0),addEventListener("prerenderingchange",xt,!0)},Ot=function(){removeEventListener("visibilitychange",xt,!0),removeEventListener("prerenderingchange",xt,!0)},Ct=function(){return It<0&&(It=kt(),Lt(),gt((function(){setTimeout((function(){It=kt(),Lt()}),0)}))),{get firstHiddenTime(){return It}}},Pt=function(e){document.prerendering?addEventListener("prerenderingchange",(function(){return e()}),!0):e()},_t=[1800,3e3],Nt=function(e,t){t=t||{},Pt((function(){var n,i=Ct(),r=bt("FCP"),o=wt("paint",(function(e){e.forEach((function(e){"first-contentful-paint"===e.name&&(o.disconnect(),e.startTime<i.firstHiddenTime&&(r.value=Math.max(e.startTime-ht(),0),r.entries.push(e),n(!0)))}))}));o&&(n=yt(e,r,_t,t.reportAllChanges),gt((function(i){r=bt("FCP"),n=yt(e,r,_t,t.reportAllChanges),St((function(){r.value=performance.now()-i.timeStamp,n(!0)}))})))}))},At=[.1,.25],Mt=0,Dt=1/0,jt=0,Rt=function(e){e.forEach((function(e){e.interactionId&&(Dt=Math.min(Dt,e.interactionId),jt=Math.max(jt,e.interactionId),Mt=jt?(jt-Dt)/7+1:0)}))},Bt=[],Ut=new Map,Ft=0,zt=[],Vt=function(e){if(zt.forEach((function(t){return t(e)})),e.interactionId||"first-input"===e.entryType){var t=Bt[Bt.length-1],n=Ut.get(e.interactionId);if(n||Bt.length<10||e.duration>t.latency){if(n)e.duration>n.latency?(n.entries=[e],n.latency=e.duration):e.duration===n.latency&&e.startTime===n.entries[0].startTime&&n.entries.push(e);else{var i={id:e.interactionId,latency:e.duration,entries:[e]};Ut.set(i.id,i),Bt.push(i)}Bt.sort((function(e,t){return t.latency-e.latency})),Bt.length>10&&Bt.splice(10).forEach((function(e){return Ut.delete(e.id)}))}}},$t=[200,500],qt=[2500,4e3],Gt={},Wt=[800,1800],Ht=function e(t){document.prerendering?Pt((function(){return e(t)})):"complete"!==document.readyState?addEventListener("load",(function(){return e(t)}),!0):setTimeout(t,0)},Kt={passive:!0,capture:!0},Xt=new Date,Jt=function(e,t){ct||(ct=t,dt=e,ft=new Date,Qt(removeEventListener),Zt())},Zt=function(){if(dt>=0&&dt<ft-Xt){var e={entryType:"first-input",name:ct.type,target:ct.target,cancelable:ct.cancelable,startTime:ct.timeStamp,processingStart:ct.timeStamp+dt};pt.forEach((function(t){t(e)})),pt=[]}},Yt=function(e){if(e.cancelable){var t=(e.timeStamp>1e12?new Date:performance.now())-e.timeStamp;"pointerdown"==e.type?function(e,t){var n=function(){Jt(e,t),r()},i=function(){r()},r=function(){removeEventListener("pointerup",n,Kt),removeEventListener("pointercancel",i,Kt)};addEventListener("pointerup",n,Kt),addEventListener("pointercancel",i,Kt)}(t,e):Jt(t,e)}},Qt=function(e){["mousedown","keydown","touchstart","pointerdown"].forEach((function(t){return e(t,Yt,Kt)}))},en=[100,300];class tn{constructor(e){this.pushMeasurement=e}initialize(){Object.entries(tn.mapping).forEach((([e,t])=>{t((t=>{this.pushMeasurement({type:"web-vitals",values:{[e]:t.value}})}))}))}}tn.mapping={cls:function(e,t){t=t||{},Nt(Et((function(){var n,i=bt("CLS",0),r=0,o=[],a=function(e){e.forEach((function(e){if(!e.hadRecentInput){var t=o[0],n=o[o.length-1];r&&e.startTime-n.startTime<1e3&&e.startTime-t.startTime<5e3?(r+=e.value,o.push(e)):(r=e.value,o=[e])}})),r>i.value&&(i.value=r,i.entries=o,n())},s=wt("layout-shift",a);s&&(n=yt(e,i,At,t.reportAllChanges),Tt((function(){a(s.takeRecords()),n(!0)})),gt((function(){r=0,i=bt("CLS",0),n=yt(e,i,At,t.reportAllChanges),St((function(){return n()}))})),setTimeout(n,0))})))},fcp:Nt,fid:function(e,t){t=t||{},Pt((function(){var n,i=Ct(),r=bt("FID"),o=function(e){e.startTime<i.firstHiddenTime&&(r.value=e.processingStart-e.startTime,r.entries.push(e),n(!0))},a=function(e){e.forEach(o)},s=wt("first-input",a);n=yt(e,r,en,t.reportAllChanges),s&&(Tt(Et((function(){a(s.takeRecords()),s.disconnect()}))),gt((function(){var i;r=bt("FID"),n=yt(e,r,en,t.reportAllChanges),pt=[],dt=-1,ct=null,Qt(addEventListener),i=o,pt.push(i),Zt()})))}))},inp:function(e,t){t=t||{},Pt((function(){var n;"interactionCount"in performance||lt||(lt=wt("event",Rt,{type:"event",buffered:!0,durationThreshold:0}));var i,r=bt("INP"),o=function(e){e.forEach(Vt);var t,n=(t=Math.min(Bt.length-1,Math.floor(((lt?Mt:performance.interactionCount||0)-Ft)/50)),Bt[t]);n&&n.latency!==r.value&&(r.value=n.latency,r.entries=n.entries,i())},a=wt("event",o,{durationThreshold:null!==(n=t.durationThreshold)&&void 0!==n?n:40});i=yt(e,r,$t,t.reportAllChanges),a&&("PerformanceEventTiming"in self&&"interactionId"in PerformanceEventTiming.prototype&&a.observe({type:"first-input",buffered:!0}),Tt((function(){o(a.takeRecords()),i(!0)})),gt((function(){Ft=0,Bt.length=0,Ut.clear(),r=bt("INP"),i=yt(e,r,$t,t.reportAllChanges)})))}))},lcp:function(e,t){t=t||{},Pt((function(){var n,i=Ct(),r=bt("LCP"),o=function(e){t.reportAllChanges||(e=e.slice(-1)),e.forEach((function(e){e.startTime<i.firstHiddenTime&&(r.value=Math.max(e.startTime-ht(),0),r.entries=[e],n())}))},a=wt("largest-contentful-paint",o);if(a){n=yt(e,r,qt,t.reportAllChanges);var s=Et((function(){Gt[r.id]||(o(a.takeRecords()),a.disconnect(),Gt[r.id]=!0,n(!0))}));["keydown","click"].forEach((function(e){addEventListener(e,(function(){return e=s,t=self.requestIdleCallback||self.setTimeout,n=-1,e=Et(e),"hidden"===document.visibilityState?e():(n=t(e),Tt(e)),n;var e,t,n}),!0)})),Tt(s),gt((function(i){r=bt("LCP"),n=yt(e,r,qt,t.reportAllChanges),St((function(){r.value=performance.now()-i.timeStamp,Gt[r.id]=!0,n(!0)}))}))}}))},ttfb:function(e,t){t=t||{};var n=bt("TTFB"),i=yt(e,n,Wt,t.reportAllChanges);Ht((function(){var r=vt();r&&(n.value=Math.max(r.responseStart-ht(),0),n.entries=[r],i(!0),gt((function(){n=bt("TTFB",0),(i=yt(e,n,Wt,t.reportAllChanges))(!0)})))}))}};var nn,rn,on=function(){var e=self.performance&&performance.getEntriesByType&&performance.getEntriesByType("navigation")[0];if(e&&e.responseStart>0&&e.responseStart<performance.now())return e},an=function(e){if("loading"===document.readyState)return"loading";var t=on();if(t){if(e<t.domInteractive)return"loading";if(0===t.domContentLoadedEventStart||e<t.domContentLoadedEventStart)return"dom-interactive";if(0===t.domComplete||e<t.domComplete)return"dom-content-loaded"}return"complete"},sn=function(e){var t=e.nodeName;return 1===e.nodeType?t.toLowerCase():t.toUpperCase().replace(/^#/,"")},un=function(e,t){var n="";try{for(;e&&9!==e.nodeType;){var i=e,r=i.id?"#"+i.id:sn(i)+(i.classList&&i.classList.value&&i.classList.value.trim()&&i.classList.value.trim().length?"."+i.classList.value.trim().replace(/\s+/g,"."):"");if(n.length+r.length>(t||100)-1)return n||r;if(n=n?r+">"+n:r,i.id)break;e=i.parentNode}}catch(e){}return n},ln=-1,cn=function(){return ln},dn=function(e){addEventListener("pageshow",(function(t){t.persisted&&(ln=t.timeStamp,e(t))}),!0)},fn=function(){var e=on();return e&&e.activationStart||0},pn=function(e,t){var n=on(),i="navigate";return cn()>=0?i="back-forward-cache":n&&(document.prerendering||fn()>0?i="prerender":document.wasDiscarded?i="restore":n.type&&(i=n.type.replace(/_/g,"-"))),{name:e,value:void 0===t?-1:t,rating:"good",delta:0,entries:[],id:"v4-".concat(Date.now(),"-").concat(Math.floor(8999999999999*Math.random())+1e12),navigationType:i}},mn=function(e,t,n){try{if(PerformanceObserver.supportedEntryTypes.includes(e)){var i=new PerformanceObserver((function(e){Promise.resolve().then((function(){t(e.getEntries())}))}));return i.observe(Object.assign({type:e,buffered:!0},n||{})),i}}catch(e){}},gn=function(e,t,n,i){var r,o;return function(a){t.value>=0&&(a||i)&&((o=t.value-(r||0))||void 0===r)&&(r=t.value,t.delta=o,t.rating=function(e,t){return e>t[1]?"poor":e>t[0]?"needs-improvement":"good"}(t.value,n),e(t))}},vn=function(e){requestAnimationFrame((function(){return requestAnimationFrame((function(){return e()}))}))},hn=function(e){document.addEventListener("visibilitychange",(function(){"hidden"===document.visibilityState&&e()}))},bn=function(e){var t=!1;return function(){t||(e(),t=!0)}},wn=-1,yn=function(){return"hidden"!==document.visibilityState||document.prerendering?1/0:0},Sn=function(e){"hidden"===document.visibilityState&&wn>-1&&(wn="visibilitychange"===e.type?e.timeStamp:0,En())},Tn=function(){addEventListener("visibilitychange",Sn,!0),addEventListener("prerenderingchange",Sn,!0)},En=function(){removeEventListener("visibilitychange",Sn,!0),removeEventListener("prerenderingchange",Sn,!0)},In=function(){return wn<0&&(wn=yn(),Tn(),dn((function(){setTimeout((function(){wn=yn(),Tn()}),0)}))),{get firstHiddenTime(){return wn}}},kn=function(e){document.prerendering?addEventListener("prerenderingchange",(function(){return e()}),!0):e()},xn=[1800,3e3],Ln=function(e,t){t=t||{},kn((function(){var n,i=In(),r=pn("FCP"),o=mn("paint",(function(e){e.forEach((function(e){"first-contentful-paint"===e.name&&(o.disconnect(),e.startTime<i.firstHiddenTime&&(r.value=Math.max(e.startTime-fn(),0),r.entries.push(e),n(!0)))}))}));o&&(n=gn(e,r,xn,t.reportAllChanges),dn((function(i){r=pn("FCP"),n=gn(e,r,xn,t.reportAllChanges),vn((function(){r.value=performance.now()-i.timeStamp,n(!0)}))})))}))},On=[.1,.25],Cn=0,Pn=1/0,_n=0,Nn=function(e){e.forEach((function(e){e.interactionId&&(Pn=Math.min(Pn,e.interactionId),_n=Math.max(_n,e.interactionId),Cn=_n?(_n-Pn)/7+1:0)}))},An=function(){"interactionCount"in performance||nn||(nn=mn("event",Nn,{type:"event",buffered:!0,durationThreshold:0}))},Mn=[],Dn=new Map,jn=0,Rn=function(){return(nn?Cn:performance.interactionCount||0)-jn},Bn=[],Un=function(e){if(Bn.forEach((function(t){return t(e)})),e.interactionId||"first-input"===e.entryType){var t=Mn[Mn.length-1],n=Dn.get(e.interactionId);if(n||Mn.length<10||e.duration>t.latency){if(n)e.duration>n.latency?(n.entries=[e],n.latency=e.duration):e.duration===n.latency&&e.startTime===n.entries[0].startTime&&n.entries.push(e);else{var i={id:e.interactionId,latency:e.duration,entries:[e]};Dn.set(i.id,i),Mn.push(i)}Mn.sort((function(e,t){return t.latency-e.latency})),Mn.length>10&&Mn.splice(10).forEach((function(e){return Dn.delete(e.id)}))}}},Fn=function(e){var t=self.requestIdleCallback||self.setTimeout,n=-1;return e=bn(e),"hidden"===document.visibilityState?e():(n=t(e),hn(e)),n},zn=[200,500],Vn=[],$n=new Map,qn=[],Gn=new WeakMap,Wn=new Map,Hn=-1,Kn=function(e){e.forEach((function(e){return Vn.push(e)}))},Xn=function(){Wn.size>10&&Wn.forEach((function(e,t){Dn.has(t)||Wn.delete(t)})),qn=qn.slice(-50);var e=new Set(qn.concat(Mn.map((function(e){return Gn.get(e.entries[0])}))));$n.forEach((function(t,n){e.has(n)||$n.delete(n)}));var t=new Set;$n.forEach((function(e){ei(e.startTime,e.processingEnd).forEach((function(e){t.add(e)}))})),Vn=Array.from(t),Hn=-1};Bn.push((function(e){e.interactionId&&e.target&&!Wn.has(e.interactionId)&&Wn.set(e.interactionId,e.target)}),(function(e){for(var t,n=e.startTime+e.duration,i=qn.length-1;i>=0;i--)if(t=qn[i],Math.abs(n-t)<=8){var r=$n.get(t);r.startTime=Math.min(e.startTime,r.startTime),r.processingStart=Math.min(e.processingStart,r.processingStart),r.processingEnd=Math.max(e.processingEnd,r.processingEnd),r.entries.push(e),n=t;break}n!==t&&(qn.push(n),$n.set(n,{startTime:e.startTime,processingStart:e.processingStart,processingEnd:e.processingEnd,entries:[e]})),(e.interactionId||"first-input"===e.entryType)&&Gn.set(e,n)}),(function(){Hn<0&&(Hn=Fn(Xn))}));var Jn,Zn,Yn,Qn,ei=function(e,t){for(var n,i=[],r=0;n=Vn[r];r++)if(!(n.startTime+n.duration<e)){if(n.startTime>t)break;i.push(n)}return i},ti=function(e,t){rn||(rn=mn("long-animation-frame",Kn)),function(e,t){t=t||{},kn((function(){var n;An();var i,r=pn("INP"),o=function(e){e.forEach(Un);var t,n=(t=Math.min(Mn.length-1,Math.floor(Rn()/50)),Mn[t]);n&&n.latency!==r.value&&(r.value=n.latency,r.entries=n.entries,i())},a=mn("event",o,{durationThreshold:null!==(n=t.durationThreshold)&&void 0!==n?n:40});i=gn(e,r,zn,t.reportAllChanges),a&&("PerformanceEventTiming"in self&&"interactionId"in PerformanceEventTiming.prototype&&a.observe({type:"first-input",buffered:!0}),hn((function(){o(a.takeRecords()),i(!0)})),dn((function(){jn=0,Mn.length=0,Dn.clear(),r=pn("INP"),i=gn(e,r,zn,t.reportAllChanges)})))}))}((function(t){Fn((function(){var n=function(e){var t=e.entries[0],n=Gn.get(t),i=$n.get(n),r=t.processingStart,o=i.processingEnd,a=i.entries.sort((function(e,t){return e.processingStart-t.processingStart})),s=ei(t.startTime,o),u=e.entries.find((function(e){return e.target})),l=u&&u.target||Wn.get(t.interactionId),c=[t.startTime+t.duration,o].concat(s.map((function(e){return e.startTime+e.duration}))),d=Math.max.apply(Math,c),f={interactionTarget:un(l),interactionTargetElement:l,interactionType:t.name.startsWith("key")?"keyboard":"pointer",interactionTime:t.startTime,nextPaintTime:d,processedEventEntries:a,longAnimationFrameEntries:s,inputDelay:r-t.startTime,processingDuration:o-r,presentationDelay:Math.max(d-o,0),loadState:an(t.startTime)};return Object.assign(e,{attribution:f})}(t);e(n)}))}),t)},ni=[2500,4e3],ii={},ri=[800,1800],oi=function e(t){document.prerendering?kn((function(){return e(t)})):"complete"!==document.readyState?addEventListener("load",(function(){return e(t)}),!0):setTimeout(t,0)},ai=function(e,t){t=t||{};var n=pn("TTFB"),i=gn(e,n,ri,t.reportAllChanges);oi((function(){var r=on();r&&(n.value=Math.max(r.responseStart-fn(),0),n.entries=[r],i(!0),dn((function(){n=pn("TTFB",0),(i=gn(e,n,ri,t.reportAllChanges))(!0)})))}))},si={passive:!0,capture:!0},ui=new Date,li=function(e,t){Jn||(Jn=t,Zn=e,Yn=new Date,fi(removeEventListener),ci())},ci=function(){if(Zn>=0&&Zn<Yn-ui){var e={entryType:"first-input",name:Jn.type,target:Jn.target,cancelable:Jn.cancelable,startTime:Jn.timeStamp,processingStart:Jn.timeStamp+Zn};Qn.forEach((function(t){t(e)})),Qn=[]}},di=function(e){if(e.cancelable){var t=(e.timeStamp>1e12?new Date:performance.now())-e.timeStamp;"pointerdown"==e.type?function(e,t){var n=function(){li(e,t),r()},i=function(){r()},r=function(){removeEventListener("pointerup",n,si),removeEventListener("pointercancel",i,si)};addEventListener("pointerup",n,si),addEventListener("pointercancel",i,si)}(t,e):li(t,e)}},fi=function(e){["mousedown","keydown","touchstart","pointerdown"].forEach((function(t){return e(t,di,si)}))},pi=[100,300],mi=function(e,t){!function(e,t){t=t||{},kn((function(){var n,i=In(),r=pn("FID"),o=function(e){e.startTime<i.firstHiddenTime&&(r.value=e.processingStart-e.startTime,r.entries.push(e),n(!0))},a=function(e){e.forEach(o)},s=mn("first-input",a);n=gn(e,r,pi,t.reportAllChanges),s&&(hn(bn((function(){a(s.takeRecords()),s.disconnect()}))),dn((function(){var i;r=pn("FID"),n=gn(e,r,pi,t.reportAllChanges),Qn=[],Zn=-1,Jn=null,fi(addEventListener),i=o,Qn.push(i),ci()})))}))}((function(t){var n=function(e){var t=e.entries[0],n={eventTarget:un(t.target),eventType:t.name,eventTime:t.startTime,eventEntry:t,loadState:an(t.startTime)};return Object.assign(e,{attribution:n})}(t);e(n)}),t)};const gi="com.grafana.faro.lastNavigationId",vi="load_state",hi="time_to_first_byte";class bi{constructor(e){this.corePushMeasurement=e}initialize(){this.measureCLS(),this.measureFCP(),this.measureFID(),this.measureINP(),this.measureLCP(),this.measureTTFB()}measureCLS(){!function(e,t){!function(e,t){t=t||{},Ln(bn((function(){var n,i=pn("CLS",0),r=0,o=[],a=function(e){e.forEach((function(e){if(!e.hadRecentInput){var t=o[0],n=o[o.length-1];r&&e.startTime-n.startTime<1e3&&e.startTime-t.startTime<5e3?(r+=e.value,o.push(e)):(r=e.value,o=[e])}})),r>i.value&&(i.value=r,i.entries=o,n())},s=mn("layout-shift",a);s&&(n=gn(e,i,On,t.reportAllChanges),hn((function(){a(s.takeRecords()),n(!0)})),dn((function(){r=0,i=pn("CLS",0),n=gn(e,i,On,t.reportAllChanges),vn((function(){return n()}))})),setTimeout(n,0))})))}((function(t){var n=function(e){var t,n={};if(e.entries.length){var i=e.entries.reduce((function(e,t){return e&&e.value>t.value?e:t}));if(i&&i.sources&&i.sources.length){var r=(t=i.sources).find((function(e){return e.node&&1===e.node.nodeType}))||t[0];r&&(n={largestShiftTarget:un(r.node),largestShiftTime:i.startTime,largestShiftValue:i.value,largestShiftSource:r,largestShiftEntry:i,loadState:an(i.startTime)})}}return Object.assign(e,{attribution:n})}(t);e(n)}),t)}((e=>{const{loadState:t,largestShiftValue:n,largestShiftTime:i,largestShiftTarget:r}=e.attribution,o=this.buildInitialValues(e);this.addIfPresent(o,"largest_shift_value",n),this.addIfPresent(o,"largest_shift_time",i);const a=this.buildInitialContext(e);this.addIfPresent(a,vi,t),this.addIfPresent(a,"largest_shift_target",r),this.pushMeasurement(o,a)}))}measureFCP(){!function(e,t){Ln((function(t){var n=function(e){var t={timeToFirstByte:0,firstByteToFCP:e.value,loadState:an(cn())};if(e.entries.length){var n=on(),i=e.entries[e.entries.length-1];if(n){var r=n.activationStart||0,o=Math.max(0,n.responseStart-r);t={timeToFirstByte:o,firstByteToFCP:e.value-o,loadState:an(e.entries[0].startTime),navigationEntry:n,fcpEntry:i}}}return Object.assign(e,{attribution:t})}(t);e(n)}),t)}((e=>{const{firstByteToFCP:t,timeToFirstByte:n,loadState:i}=e.attribution,r=this.buildInitialValues(e);this.addIfPresent(r,"first_byte_to_fcp",t),this.addIfPresent(r,hi,n);const o=this.buildInitialContext(e);this.addIfPresent(o,vi,i),this.pushMeasurement(r,o)}))}measureFID(){mi((e=>{const{eventTime:t,eventTarget:n,eventType:i,loadState:r}=e.attribution,o=this.buildInitialValues(e);this.addIfPresent(o,"event_time",t);const a=this.buildInitialContext(e);this.addIfPresent(a,"event_target",n),this.addIfPresent(a,"event_type",i),this.addIfPresent(a,vi,r),this.pushMeasurement(o,a)}))}measureINP(){ti((e=>{const{interactionTime:t,presentationDelay:n,inputDelay:i,processingDuration:r,nextPaintTime:o,loadState:a,interactionTarget:s,interactionType:u}=e.attribution,l=this.buildInitialValues(e);this.addIfPresent(l,"interaction_time",t),this.addIfPresent(l,"presentation_delay",n),this.addIfPresent(l,"input_delay",i),this.addIfPresent(l,"processing_duration",r),this.addIfPresent(l,"next_paint_time",o);const c=this.buildInitialContext(e);this.addIfPresent(c,vi,a),this.addIfPresent(c,"interaction_target",s),this.addIfPresent(c,"interaction_type",u),this.pushMeasurement(l,c)}))}measureLCP(){!function(e,t){!function(e,t){t=t||{},kn((function(){var n,i=In(),r=pn("LCP"),o=function(e){t.reportAllChanges||(e=e.slice(-1)),e.forEach((function(e){e.startTime<i.firstHiddenTime&&(r.value=Math.max(e.startTime-fn(),0),r.entries=[e],n())}))},a=mn("largest-contentful-paint",o);if(a){n=gn(e,r,ni,t.reportAllChanges);var s=bn((function(){ii[r.id]||(o(a.takeRecords()),a.disconnect(),ii[r.id]=!0,n(!0))}));["keydown","click"].forEach((function(e){addEventListener(e,(function(){return Fn(s)}),!0)})),hn(s),dn((function(i){r=pn("LCP"),n=gn(e,r,ni,t.reportAllChanges),vn((function(){r.value=performance.now()-i.timeStamp,ii[r.id]=!0,n(!0)}))}))}}))}((function(t){var n=function(e){var t={timeToFirstByte:0,resourceLoadDelay:0,resourceLoadDuration:0,elementRenderDelay:e.value};if(e.entries.length){var n=on();if(n){var i=n.activationStart||0,r=e.entries[e.entries.length-1],o=r.url&&performance.getEntriesByType("resource").filter((function(e){return e.name===r.url}))[0],a=Math.max(0,n.responseStart-i),s=Math.max(a,o?(o.requestStart||o.startTime)-i:0),u=Math.max(s,o?o.responseEnd-i:0),l=Math.max(u,r.startTime-i);t={element:un(r.element),timeToFirstByte:a,resourceLoadDelay:s-a,resourceLoadDuration:u-s,elementRenderDelay:l-u,navigationEntry:n,lcpEntry:r},r.url&&(t.url=r.url),o&&(t.lcpResourceEntry=o)}}return Object.assign(e,{attribution:t})}(t);e(n)}),t)}((e=>{const{elementRenderDelay:t,resourceLoadDelay:n,resourceLoadDuration:i,timeToFirstByte:r,element:o}=e.attribution,a=this.buildInitialValues(e);this.addIfPresent(a,"element_render_delay",t),this.addIfPresent(a,"resource_load_delay",n),this.addIfPresent(a,"resource_load_duration",i),this.addIfPresent(a,hi,r);const s=this.buildInitialContext(e);this.addIfPresent(s,"element",o),this.pushMeasurement(a,s)}))}measureTTFB(){!function(e,t){ai((function(t){var n=function(e){var t={waitingDuration:0,cacheDuration:0,dnsDuration:0,connectionDuration:0,requestDuration:0};if(e.entries.length){var n=e.entries[0],i=n.activationStart||0,r=Math.max((n.workerStart||n.fetchStart)-i,0),o=Math.max(n.domainLookupStart-i,0),a=Math.max(n.connectStart-i,0),s=Math.max(n.connectEnd-i,0);t={waitingDuration:r,cacheDuration:o-r,dnsDuration:a-o,connectionDuration:s-a,requestDuration:e.value-s,navigationEntry:n}}return Object.assign(e,{attribution:t})}(t);e(n)}),t)}((e=>{const{dnsDuration:t,connectionDuration:n,requestDuration:i,waitingDuration:r,cacheDuration:o}=e.attribution,a=this.buildInitialValues(e);this.addIfPresent(a,"dns_duration",t),this.addIfPresent(a,"connection_duration",n),this.addIfPresent(a,"request_duration",i),this.addIfPresent(a,"waiting_duration",r),this.addIfPresent(a,"cache_duration",o);const s=this.buildInitialContext(e);this.pushMeasurement(a,s)}))}buildInitialValues(e){return{[e.name.toLowerCase()]:e.value,delta:e.delta}}buildInitialContext(e){var t;const n=null!==(t=Ee(gi,ye))&&void 0!==t?t:"unknown";return{id:e.id,rating:e.rating,navigation_type:e.navigationType,navigation_entry_id:n}}pushMeasurement(e,t){this.corePushMeasurement({type:"web-vitals",values:e},{context:t})}addIfPresent(e,t,n){n&&(e[t]=n)}}class wi extends Q{constructor(){super(...arguments),this.name="@grafana/faro-web-sdk:instrumentation-web-vitals",this.version=ee}initialize(){this.logDebug("Initializing");this.intializeWebVitalsInstrumentation().initialize()}intializeWebVitalsInstrumentation(){return this.config.trackWebVitalsAttribution?new bi(this.api.pushMeasurement):new tn(this.api.pushMeasurement)}}function yi(e,t,n,i){return new(n||(n=Promise))((function(r,o){function a(e){try{u(i.next(e))}catch(e){o(e)}}function s(e){try{u(i.throw(e))}catch(e){o(e)}}function u(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(a,s)}u((i=i.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;const Si=/^00-[a-f0-9]{32}-[a-f0-9]{16}-[0-9]{1,2}$/;function Ti(e=[]){for(const t of e)if("traceparent"===t.name){if(!Si.test(t.description))continue;const[,e,n]=t.description.split("-");if(null!=e&&null!=n)return{traceId:e,spanId:n};break}}function Ei(e=[],t){return e.some((e=>e&&null!=t.match(e)))}function Ii(e,t={}){for(const[n,i]of Object.entries(t)){const t=e[n];return null!=t&&(l(i)?i.includes(t):t===i)}return!0}function ki(e){const{connectEnd:t,connectStart:n,decodedBodySize:i,domainLookupEnd:r,domainLookupStart:o,duration:a,encodedBodySize:s,fetchStart:u,initiatorType:l,name:c,nextHopProtocol:d,redirectEnd:f,redirectStart:p,renderBlockingStatus:m,requestStart:g,responseEnd:v,responseStart:h,responseStatus:b,secureConnectionStart:w,transferSize:y,workerStart:S}=e;return{name:c,duration:Li(a),tcpHandshakeTime:Li(t-n),dnsLookupTime:Li(r-o),tlsNegotiationTime:Li(g-w),responseStatus:Li(b),redirectTime:Li(f-p),requestTime:Li(h-g),responseTime:Li(v-h),fetchTime:Li(v-u),serviceWorkerTime:Li(u-S),decodedBodySize:Li(i),encodedBodySize:Li(s),cacheHitStatus:function(){let e="fullLoad";0===y?i>0&&(e="cache"):null!=b?304===b&&(e="conditionalFetch"):s>0&&y<s&&(e="conditionalFetch");return e}(),renderBlockingStatus:Li(m),protocol:d,initiatorType:l}}function xi(e){const{activationStart:t,domComplete:n,domContentLoadedEventEnd:i,domContentLoadedEventStart:r,domInteractive:o,fetchStart:a,loadEventEnd:s,loadEventStart:u,responseStart:l,type:c}=e,d=function(){var e;if(null!=(null===(e=performance.timing)||void 0===e?void 0:e.domLoading))return performance.timing.domLoading-performance.timeOrigin;return null}();return Object.assign({visibilityState:document.visibilityState,pageLoadTime:Li(n-a),documentParsingTime:Li(d?o-d:null),domProcessingTime:Li(n-o),domContentLoadHandlerTime:Li(i-r),onLoadTime:Li(s-u),ttfb:Li(Math.max(l-(null!=t?t:0),0)),type:c},ki(e))}function Li(e){return null==e?"unknown":"number"==typeof e?Math.round(e).toString():e.toString()}const Oi={initiatorType:["xmlhttprequest","fetch"]};class Ci extends Q{constructor(){super(...arguments),this.name="@grafana/faro-web-sdk:instrumentation-performance",this.version=ee}initialize(){"PerformanceObserver"in window?function(e){if("complete"===document.readyState)e();else{const t=()=>{"complete"===document.readyState&&(e(),document.removeEventListener("readystatechange",t))};document.addEventListener("readystatechange",t)}}((()=>yi(this,void 0,void 0,(function*(){const t=this.api.pushEvent,n=this.getIgnoreUrls(),{faroNavigationId:i}=yield function(e,t){let n;const i=new Promise((e=>{n=e}));return new PerformanceObserver((i=>{var r;const[o]=i.getEntries();if(null==o||Ei(t,o.name))return;const a=o.toJSON();let s=Ti(null==a?void 0:a.serverTiming);const u=null!==(r=Ee(gi,ye))&&void 0!==r?r:"unknown",l=Object.assign(Object.assign({},xi(a)),{faroNavigationId:O(),faroPreviousNavigationId:u});Ie(gi,l.faroNavigationId,ye),e("faro.performance.navigation",l,void 0,{spanContext:s}),n(l)})).observe({type:"navigation",buffered:!0}),i}(t,n);null!=i&&function(t,n,i){const r=e.faro.config.trackResources;new PerformanceObserver((e=>{const o=e.getEntries();for(const e of o){if(Ei(i,e.name))return;const o=e.toJSON();let a=Ti(null==o?void 0:o.serverTiming);if(null==r&&Ii(o,Oi)||r){const e=Object.assign(Object.assign({},ki(o)),{faroNavigationId:t,faroResourceId:O()});n("faro.performance.resource",e,void 0,{spanContext:a})}}})).observe({type:"resource",buffered:!0})}(i,t,n)})))):this.logDebug("performance observer not supported. Disable performance instrumentation.")}getIgnoreUrls(){var e;return null===(e=this.transports.transports)||void 0===e?void 0:e.flatMap((e=>e.getIgnoreUrls()))}}function Pi(e={}){const t=[new st,new wi,new $e,new ut];return!1!==e.enablePerformanceInstrumentation&&t.unshift(new Ci),!1!==e.captureConsole&&t.push(new qe({disabledLevels:e.captureConsoleDisabledLevels})),t}const _i="browser",Ni=()=>{const e=window.k6;return{k6:Object.assign({isK6Browser:!0},(null==e?void 0:e.testRunId)&&{testRunId:null==e?void 0:e.testRunId})}};class Ai extends W{constructor(e){var t,n,i,r;super(),this.options=e,this.name="@grafana/faro-web-sdk:transport-fetch",this.version=ee,this.disabledUntil=new Date,this.rateLimitBackoffMs=null!==(t=e.defaultRateLimitBackoffMs)&&void 0!==t?t:5e3,this.getNow=null!==(n=e.getNow)&&void 0!==n?n:()=>Date.now(),this.promiseBuffer=x({size:null!==(i=e.bufferSize)&&void 0!==i?i:30,concurrency:null!==(r=e.concurrency)&&void 0!==r?r:5})}send(e){return yi(this,void 0,void 0,(function*(){try{if(this.disabledUntil>new Date(this.getNow()))return this.logWarn(`Dropping transport item due to too many requests. Backoff until ${this.disabledUntil}`),Promise.resolve();yield this.promiseBuffer.add((()=>{const t=JSON.stringify(K(e)),{url:n,requestOptions:i,apiKey:r}=this.options,o=null!=i?i:{},{headers:a}=o,s=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(o,["headers"]);let u;const l=this.metas.value.session;return null!=l&&(u=l.id),fetch(n,Object.assign({method:"POST",headers:Object.assign(Object.assign(Object.assign({"Content-Type":"application/json"},null!=a?a:{}),r?{"x-api-key":r}:{}),u?{"x-faro-session-id":u}:{}),body:t,keepalive:t.length<=6e4},null!=s?s:{})).then((e=>yi(this,void 0,void 0,(function*(){if(202===e.status){"invalid"===e.headers.get("X-Faro-Session-Status")&&this.extendFaroSession(this.config,this.logDebug)}return 429===e.status&&(this.disabledUntil=this.getRetryAfterDate(e),this.logWarn(`Too many requests, backing off until ${this.disabledUntil}`)),e.text().catch(k),e})))).catch((e=>{this.logError("Failed sending payload to the receiver\n",JSON.parse(t),e)}))}))}catch(e){this.logError(e)}}))}getIgnoreUrls(){var e;return[this.options.url].concat(null!==(e=this.config.ignoreUrls)&&void 0!==e?e:[])}isBatched(){return!0}getRetryAfterDate(e){const t=this.getNow(),n=e.headers.get("Retry-After");if(n){const e=Number(n);if(!isNaN(e))return new Date(1e3*e+t);const i=Date.parse(n);if(!isNaN(i))return new Date(i)}return new Date(t+this.rateLimitBackoffMs)}extendFaroSession(e,t){const n="Session expired",i=e.sessionTracking;if(null==i?void 0:i.enabled){const{fetchUserSession:e,storeUserSession:r}=Ve(i);Be({fetchUserSession:e,storeUserSession:r})({forceSessionExtend:!0}),t(`${n} created new session.`)}else t(`${n}.`)}}function Mi(e){var t,n,i,r,o,a,u,l,c,d;const f=[],p=V(e.unpatchedConsole,e.internalLoggerLevel);e.transports?((e.url||e.apiKey)&&p.error('if "transports" is defined, "url" and "apiKey" should not be defined'),f.push(...e.transports)):e.url?f.push(new Ai({url:e.url,apiKey:e.apiKey})):p.error('either "url" or "transports" must be defined');return{app:e.app,batching:Object.assign(Object.assign({},se),e.batching),dedupe:null===(t=e.dedupe)||void 0===t||t,globalObjectKey:e.globalObjectKey||ae,instrumentations:null!==(n=e.instrumentations)&&void 0!==n?n:Pi(),internalLoggerLevel:null!==(i=e.internalLoggerLevel)&&void 0!==i?i:B,isolate:null!==(r=e.isolate)&&void 0!==r&&r,logArgsSerializer:null!==(o=e.logArgsSerializer)&&void 0!==o?o:Z,metas:function(){const t=he;return e.metas&&t.push(...e.metas),s(window.k6)?[...t,Ni]:t}(),parseStacktrace:rt,paused:null!==(a=e.paused)&&void 0!==a&&a,preventGlobalExposure:null!==(u=e.preventGlobalExposure)&&void 0!==u&&u,transports:f,unpatchedConsole:null!==(l=e.unpatchedConsole)&&void 0!==l?l:U,beforeSend:e.beforeSend,eventDomain:null!==(c=e.eventDomain)&&void 0!==c?c:_i,ignoreErrors:e.ignoreErrors,ignoreUrls:e.ignoreUrls,sessionTracking:Object.assign(Object.assign({},De),e.sessionTracking),user:e.user,view:null!==(d=e.view)&&void 0!==d?d:we,trackResources:e.trackResources,trackWebVitalsAttribution:e.trackWebVitalsAttribution}}return e.BaseExtension=G,e.BaseInstrumentation=Q,e.BaseTransport=W,e.ConsoleInstrumentation=qe,e.ConsoleTransport=class extends W{constructor(e={}){super(),this.options=e,this.name="@grafana/faro-web-sdk:transport-console",this.version=ee}send(t){var n;return this.unpatchedConsole[null!==(n=this.options.level)&&void 0!==n?n:e.LogLevel.DEBUG]("New event",K([t]))}},e.Conventions={EventNames:{CLICK:"click",NAVIGATION:"navigation",SESSION_START:"session_start",VIEW_CHANGED:"view_changed"}},e.EVENT_CLICK="click",e.EVENT_NAVIGATION="navigation",e.EVENT_ROUTE_CHANGE="route_change",e.EVENT_SESSION_EXTEND=de,e.EVENT_SESSION_RESUME=ce,e.EVENT_SESSION_START=le,e.EVENT_VIEW_CHANGED=ue,e.ErrorsInstrumentation=st,e.FetchTransport=Ai,e.MAX_SESSION_PERSISTENCE_TIME=Me,e.MAX_SESSION_PERSISTENCE_TIME_BUFFER=6e4,e.PerformanceInstrumentation=Ci,e.PersistentSessionsManager=Fe,e.SESSION_EXPIRATION_TIME=Ne,e.SESSION_INACTIVITY_TIME=Ae,e.STORAGE_KEY=_e,e.SessionInstrumentation=$e,e.VERSION=ee,e.ViewInstrumentation=ut,e.VolatileSessionsManager=ze,e.WebVitalsInstrumentation=wi,e.allLogLevels=I,e.browserMeta=ge,e.buildStackFrame=tt,e.createInternalLogger=V,e.createPromiseBuffer=x,e.createSession=be,e.deepEqual=y,e.defaultEventDomain=_i,e.defaultExceptionType=X,e.defaultGlobalObjectKey=ae,e.defaultInternalLoggerLevel=B,e.defaultLogLevel=E,e.defaultMetas=he,e.defaultViewMeta=we,e.genShortID=O,e.getCurrentTimestamp=S,e.getDataFromSafariExtensions=nt,e.getInternalFaroFromGlobalObject=function(){return C[te]},e.getStackFramesFromError=it,e.getTransportBody=K,e.getWebInstrumentations=Pi,e.globalObject=C,e.initializeFaro=function(e){const t=Mi(e);if(t)return oe(t)},e.internalGlobalObjectKey=te,e.isArray=l,e.isBoolean=e=>t(e,"boolean"),e.isDomError=v,e.isDomException=h,e.isElement=e=>b&&i(e,Element),e.isElementDefined=b,e.isError=m,e.isErrorDefined=p,e.isErrorEvent=g,e.isEvent=f,e.isEventDefined=d,e.isFunction=u,e.isInstanceOf=i,e.isInt=e=>a(e)&&Number.isInteger(e),e.isInternalFaroOnGlobalObject=ie,e.isMap=e=>w&&i(e,Map),e.isMapDefined=w,e.isNull=r,e.isNumber=a,e.isObject=s,e.isPrimitive=c,e.isRegExp=e=>n(e,"RegExp"),e.isString=o,e.isSymbol=e=>t(e,"symbol"),e.isSyntheticEvent=e=>s(e)&&"nativeEvent"in e&&"preventDefault"in e&&"stopPropagation"in e,e.isThenable=e=>u(null==e?void 0:e.then),e.isToString=n,e.isTypeof=t,e.isUndefined=e=>t(e,"undefined"),e.makeCoreConfig=Mi,e.noop=k,e.pageMeta=ve,e.parseStacktrace=rt,e.sdkMeta=()=>({sdk:{name:"@grafana/faro-core",version:ee,integrations:e.faro.config.instrumentations.map((({name:e,version:t})=>({name:e,version:t})))}}),e.setInternalFaroOnGlobalObject=ne,e.transportItemTypeToBodyKey=A,e}({});
@@ -3,7 +3,7 @@ import type { ConsoleInstrumentationOptions } from './types';
3
3
  export declare class ConsoleInstrumentation extends BaseInstrumentation {
4
4
  private options;
5
5
  readonly name = "@grafana/faro-web-sdk:instrumentation-console";
6
- readonly version = "1.8.0";
6
+ readonly version = "1.8.1";
7
7
  static defaultDisabledLevels: LogLevel[];
8
8
  constructor(options?: ConsoleInstrumentationOptions);
9
9
  initialize(): void;
@@ -1,6 +1,6 @@
1
1
  import { BaseInstrumentation } from '@grafana/faro-core';
2
2
  export declare class ErrorsInstrumentation extends BaseInstrumentation {
3
3
  readonly name = "@grafana/faro-web-sdk:instrumentation-errors";
4
- readonly version = "1.8.0";
4
+ readonly version = "1.8.1";
5
5
  initialize(): void;
6
6
  }
@@ -1,7 +1,7 @@
1
1
  import { BaseInstrumentation } from '@grafana/faro-core';
2
2
  export declare class PerformanceInstrumentation extends BaseInstrumentation {
3
3
  readonly name = "@grafana/faro-web-sdk:instrumentation-performance";
4
- readonly version = "1.8.0";
4
+ readonly version = "1.8.1";
5
5
  initialize(): void;
6
6
  private getIgnoreUrls;
7
7
  }
@@ -1,7 +1,7 @@
1
1
  import { BaseInstrumentation } from '@grafana/faro-core';
2
2
  export declare class SessionInstrumentation extends BaseInstrumentation {
3
3
  readonly name = "@grafana/faro-web-sdk:instrumentation-session";
4
- readonly version = "1.8.0";
4
+ readonly version = "1.8.1";
5
5
  private notifiedSession;
6
6
  private sendSessionStartEvent;
7
7
  private createInitialSession;
@@ -0,0 +1,3 @@
1
+ import type { Config } from '@grafana/faro-core';
2
+ import type { SessionManager } from './types';
3
+ export declare function getSessionManagerByConfig(sessionTrackingConfig: Config['sessionTracking']): SessionManager;
@@ -3,3 +3,4 @@ export { VolatileSessionsManager } from './VolatileSessionManager';
3
3
  export { MAX_SESSION_PERSISTENCE_TIME, MAX_SESSION_PERSISTENCE_TIME_BUFFER, SESSION_EXPIRATION_TIME, SESSION_INACTIVITY_TIME, STORAGE_KEY, STORAGE_UPDATE_DELAY, defaultSessionTrackingConfig, } from './sessionConstants';
4
4
  export { isSampled } from './sampling';
5
5
  export type { FaroUserSession } from './types';
6
+ export { getSessionManagerByConfig } from './getSessionManagerByConfig';
@@ -1,5 +1,4 @@
1
- import type { Config } from '@grafana/faro-core';
2
- import type { FaroUserSession, SessionManager } from './types';
1
+ import type { FaroUserSession } from './types';
3
2
  type CreateUserSessionObjectParams = {
4
3
  sessionId?: string;
5
4
  started?: number;
@@ -17,5 +16,4 @@ type UpdateSessionParams = {
17
16
  };
18
17
  export declare function getUserSessionUpdater({ fetchUserSession, storeUserSession, }: GetUserSessionUpdaterParams): (options?: UpdateSessionParams) => void;
19
18
  export declare function addSessionMetadataToNextSession(newSession: FaroUserSession, previousSession: FaroUserSession | null): Required<FaroUserSession>;
20
- export declare function getSessionManagerByConfig(sessionTrackingConfig: Config['sessionTracking']): SessionManager;
21
19
  export {};
@@ -1,7 +1,7 @@
1
1
  import { BaseInstrumentation } from '@grafana/faro-core';
2
2
  export declare class ViewInstrumentation extends BaseInstrumentation {
3
3
  readonly name = "@grafana/faro-web-sdk:instrumentation-view";
4
- readonly version = "1.8.0";
4
+ readonly version = "1.8.1";
5
5
  private notifiedView;
6
6
  private sendViewChangedEvent;
7
7
  initialize(): void;
@@ -1,7 +1,7 @@
1
1
  import { BaseInstrumentation } from '@grafana/faro-core';
2
2
  export declare class WebVitalsInstrumentation extends BaseInstrumentation {
3
3
  readonly name = "@grafana/faro-web-sdk:instrumentation-web-vitals";
4
- readonly version = "1.8.0";
4
+ readonly version = "1.8.1";
5
5
  initialize(): void;
6
6
  private intializeWebVitalsInstrumentation;
7
7
  }
@@ -4,7 +4,7 @@ import type { ConsoleTransportOptions } from './types';
4
4
  export declare class ConsoleTransport extends BaseTransport {
5
5
  private options;
6
6
  readonly name = "@grafana/faro-web-sdk:transport-console";
7
- readonly version = "1.8.0";
7
+ readonly version = "1.8.1";
8
8
  constructor(options?: ConsoleTransportOptions);
9
9
  send(item: TransportItem): void;
10
10
  }
@@ -4,7 +4,7 @@ import type { FetchTransportOptions } from './types';
4
4
  export declare class FetchTransport extends BaseTransport {
5
5
  private options;
6
6
  readonly name = "@grafana/faro-web-sdk:transport-fetch";
7
- readonly version = "1.8.0";
7
+ readonly version = "1.8.1";
8
8
  promiseBuffer: PromiseBuffer<Response | void>;
9
9
  private readonly rateLimitBackoffMs;
10
10
  private readonly getNow;
@@ -120,7 +120,7 @@ var SessionInstrumentation = /** @class */ (function (_super) {
120
120
  this.logDebug('init session instrumentation');
121
121
  var sessionTrackingConfig = this.config.sessionTracking;
122
122
  if (sessionTrackingConfig === null || sessionTrackingConfig === void 0 ? void 0 : sessionTrackingConfig.enabled) {
123
- var SessionManager = (0, sessionManagerUtils_1.getSessionManagerByConfig)(sessionTrackingConfig);
123
+ var SessionManager = (0, sessionManager_1.getSessionManagerByConfig)(sessionTrackingConfig);
124
124
  this.registerBeforeSendHook(SessionManager);
125
125
  var _a = this.createInitialSession(SessionManager, sessionTrackingConfig), initialSession = _a.initialSession, lifecycleType = _a.lifecycleType;
126
126
  SessionManager.storeUserSession(initialSession);
@@ -1 +1 @@
1
- {"version":3,"file":"instrumentation.js","sourceRoot":"","sources":["../../../../src/instrumentations/session/instrumentation.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,gDAS4B;AAI5B,qCAA4C;AAE5C,mDAAmE;AACnE,wFAAuF;AACvF,4EAI8C;AAK9C;IAA4C,0CAAmB;IAA/D;QAAA,qEAgJC;QA/IU,UAAI,GAAG,+CAA+C,CAAC;QACvD,aAAO,GAAG,mBAAO,CAAC;;IA8I7B,CAAC;IAxIS,sDAAqB,GAA7B,UAA8B,IAAU;;QACtC,IAAM,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC;QAE7B,IAAI,OAAO,IAAI,OAAO,CAAC,EAAE,MAAK,MAAA,IAAI,CAAC,eAAe,0CAAE,EAAE,CAAA,EAAE;YACtD,IAAI,IAAI,CAAC,eAAe,IAAI,IAAI,CAAC,eAAe,CAAC,EAAE,MAAK,MAAA,OAAO,CAAC,UAAU,0CAAG,iBAAiB,CAAC,CAAA,EAAE;gBAC/F,IAAI,CAAC,GAAG,CAAC,SAAS,CAAC,gCAAoB,EAAE,EAAE,EAAE,SAAS,EAAE,EAAE,UAAU,EAAE,IAAI,EAAE,CAAC,CAAC;gBAC9E,IAAI,CAAC,eAAe,GAAG,OAAO,CAAC;gBAC/B,OAAO;aACR;YAED,IAAI,CAAC,eAAe,GAAG,OAAO,CAAC;YAC/B,8EAA8E;YAC9E,gBAAgB;YAChB,IAAI,CAAC,GAAG,CAAC,SAAS,CAAC,+BAAmB,EAAE,EAAE,EAAE,SAAS,EAAE,EAAE,UAAU,EAAE,IAAI,EAAE,CAAC,CAAC;SAC9E;IACH,CAAC;IAEO,qDAAoB,GAA5B,UACE,cAA8B,EAC9B,cAAm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_SESSION_EXTEND,\n EVENT_SESSION_RESUME,\n EVENT_SESSION_START,\n Meta,\n MetaSession,\n VERSION,\n} from '@grafana/faro-core';\nimport type { Config } from '@grafana/faro-core';\n\nimport type { TransportItem } from '../..';\nimport { createSession } from '../../metas';\n\nimport { type FaroUserSession, isSampled } from './sessionManager';\nimport { PersistentSessionsManager } from './sessionManager/PersistentSessionsManager';\nimport {\n createUserSessionObject,\n getSessionManagerByConfig,\n isUserSessionValid,\n} from './sessionManager/sessionManagerUtils';\nimport type { SessionManager } from './sessionManager/types';\n\ntype LifecycleType = typeof EVENT_SESSION_RESUME | typeof EVENT_SESSION_START;\n\nexport class SessionInstrumentation extends BaseInstrumentation {\n readonly name = '@grafana/faro-web-sdk:instrumentation-session';\n readonly version = VERSION;\n\n // previously notified session, to ensure we don't send session start\n // event twice for the same session\n private notifiedSession: MetaSession | undefined;\n\n private sendSessionStartEvent(meta: Meta): void {\n const session = meta.session;\n\n if (session && session.id !== this.notifiedSession?.id) {\n if (this.notifiedSession && this.notifiedSession.id === session.attributes?.['previousSession']) {\n this.api.pushEvent(EVENT_SESSION_EXTEND, {}, undefined, { skipDedupe: true });\n this.notifiedSession = session;\n return;\n }\n\n this.notifiedSession = session;\n // no need to add attributes and session id, they are included as part of meta\n // automatically\n this.api.pushEvent(EVENT_SESSION_START, {}, undefined, { skipDedupe: true });\n }\n }\n\n private createInitialSession(\n SessionManager: SessionManager,\n sessionsConfig: Required<Config>['sessionTracking']\n ): {\n initialSession: FaroUserSession;\n lifecycleType: LifecycleType;\n } {\n let userSession: FaroUserSession | null = SessionManager.fetchUserSession();\n\n if (sessionsConfig.persistent && sessionsConfig.maxSessionPersistenceTime && userSession) {\n const now = dateNow();\n const shouldClearPersistentSession = userSession.lastActivity < now - sessionsConfig.maxSessionPersistenceTime;\n\n if (shouldClearPersistentSession) {\n PersistentSessionsManager.removeUserSession();\n userSession = null;\n }\n }\n\n let lifecycleType: LifecycleType;\n let initialSession: FaroUserSession;\n\n if (isUserSessionValid(userSession)) {\n const sessionId = userSession?.sessionId;\n\n initialSession = createUserSessionObject({\n sessionId,\n isSampled: userSession!.isSampled || false,\n started: userSession?.started,\n });\n\n initialSession.sessionMeta = {\n id: sessionId,\n attributes: {\n ...sessionsConfig.session?.attributes,\n ...userSession?.sessionMeta?.attributes,\n // For valid resumed sessions we do not want to recalculate the sampling decision on each init phase.\n isSampled: initialSession.isSampled.toString(),\n },\n };\n\n lifecycleType = EVENT_SESSION_RESUME;\n } else {\n const sessionId = sessionsConfig.session?.id ?? createSession().id;\n\n initialSession = createUserSessionObject({\n sessionId,\n isSampled: isSampled(),\n });\n\n initialSession.sessionMeta = {\n id: sessionId,\n attributes: {\n isSampled: initialSession.isSampled.toString(),\n ...sessionsConfig.session?.attributes,\n },\n };\n\n lifecycleType = EVENT_SESSION_START;\n }\n\n return { initialSession, lifecycleType };\n }\n\n private registerBeforeSendHook(SessionManager: SessionManager) {\n const { updateSession } = new SessionManager();\n\n this.transports?.addBeforeSendHooks((item) => {\n updateSession();\n\n const attributes = item.meta.session?.attributes;\n\n if (attributes && attributes?.['isSampled'] === 'true') {\n let newItem: TransportItem = JSON.parse(JSON.stringify(item));\n\n const newAttributes = newItem.meta.session?.attributes;\n delete newAttributes?.['isSampled'];\n\n if (Object.keys(newAttributes ?? {}).length === 0) {\n delete newItem.meta.session?.attributes;\n }\n\n return newItem;\n }\n\n return null;\n });\n }\n\n initialize() {\n this.logDebug('init session instrumentation');\n\n const sessionTrackingConfig = this.config.sessionTracking;\n\n if (sessionTrackingConfig?.enabled) {\n const SessionManager = getSessionManagerByConfig(sessionTrackingConfig);\n\n this.registerBeforeSendHook(SessionManager);\n\n const { initialSession, lifecycleType } = this.createInitialSession(SessionManager, sessionTrackingConfig);\n\n SessionManager.storeUserSession(initialSession);\n\n const initialSessionMeta = initialSession.sessionMeta;\n\n this.notifiedSession = initialSessionMeta;\n this.api.setSession(initialSessionMeta);\n\n if (lifecycleType === EVENT_SESSION_START) {\n this.api.pushEvent(EVENT_SESSION_START, {}, undefined, { skipDedupe: true });\n }\n\n if (lifecycleType === EVENT_SESSION_RESUME) {\n this.api.pushEvent(EVENT_SESSION_RESUME, {}, undefined, { skipDedupe: true });\n }\n }\n\n this.metas.addListener(this.sendSessionStartEvent.bind(this));\n }\n}\n"]}
1
+ {"version":3,"file":"instrumentation.js","sourceRoot":"","sources":["../../../../src/instrumentations/session/instrumentation.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,gDAS4B;AAI5B,qCAA4C;AAE5C,mDAA8F;AAC9F,wFAAuF;AACvF,4EAAmG;AAKnG;IAA4C,0CAAmB;IAA/D;QAAA,qEAgJC;QA/IU,UAAI,GAAG,+CAA+C,CAAC;QACvD,aAAO,GAAG,mBAAO,CAAC;;IA8I7B,CAAC;IAxIS,sDAAqB,GAA7B,UAA8B,IAAU;;QACtC,IAAM,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC;QAE7B,IAAI,OAAO,IAAI,OAAO,CAAC,EAAE,MAAK,MAAA,IAAI,CAAC,eAAe,0CAAE,EAAE,CAAA,EAAE;YACtD,IAAI,IAAI,CAAC,eAAe,IAAI,IAAI,CAAC,eAAe,CAAC,EAAE,MAAK,MAAA,OAAO,CAAC,UAAU,0CAAG,iBAAiB,CAAC,CAAA,EAAE;gBAC/F,IAAI,CAAC,GAAG,CAAC,SAAS,CAAC,gCAAoB,EAAE,EAAE,EAAE,SAAS,EAAE,EAAE,UAAU,EAAE,IAAI,EAAE,CAAC,CAAC;gBAC9E,IAAI,CAAC,eAAe,GAAG,OAAO,CAAC;gBAC/B,OAAO;aACR;YAED,IAAI,CAAC,eAAe,GAAG,OAAO,CAAC;YAC/B,8EAA8E;YAC9E,gBAAgB;YAChB,IAAI,CAAC,GAAG,CAAC,SAAS,CAAC,+BAAmB,EAAE,EAAE,EAAE,SAAS,EAAE,EAAE,UAAU,EAAE,IAAI,EAAE,CAAC,CAAC;SAC9E;IACH,CAAC;IAEO,qD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Content":["import {\n BaseInstrumentation,\n dateNow,\n EVENT_SESSION_EXTEND,\n EVENT_SESSION_RESUME,\n EVENT_SESSION_START,\n Meta,\n MetaSession,\n VERSION,\n} from '@grafana/faro-core';\nimport type { Config } from '@grafana/faro-core';\n\nimport type { TransportItem } from '../..';\nimport { createSession } from '../../metas';\n\nimport { type FaroUserSession, getSessionManagerByConfig, isSampled } from './sessionManager';\nimport { PersistentSessionsManager } from './sessionManager/PersistentSessionsManager';\nimport { createUserSessionObject, isUserSessionValid } from './sessionManager/sessionManagerUtils';\nimport type { SessionManager } from './sessionManager/types';\n\ntype LifecycleType = typeof EVENT_SESSION_RESUME | typeof EVENT_SESSION_START;\n\nexport class SessionInstrumentation extends BaseInstrumentation {\n readonly name = '@grafana/faro-web-sdk:instrumentation-session';\n readonly version = VERSION;\n\n // previously notified session, to ensure we don't send session start\n // event twice for the same session\n private notifiedSession: MetaSession | undefined;\n\n private sendSessionStartEvent(meta: Meta): void {\n const session = meta.session;\n\n if (session && session.id !== this.notifiedSession?.id) {\n if (this.notifiedSession && this.notifiedSession.id === session.attributes?.['previousSession']) {\n this.api.pushEvent(EVENT_SESSION_EXTEND, {}, undefined, { skipDedupe: true });\n this.notifiedSession = session;\n return;\n }\n\n this.notifiedSession = session;\n // no need to add attributes and session id, they are included as part of meta\n // automatically\n this.api.pushEvent(EVENT_SESSION_START, {}, undefined, { skipDedupe: true });\n }\n }\n\n private createInitialSession(\n SessionManager: SessionManager,\n sessionsConfig: Required<Config>['sessionTracking']\n ): {\n initialSession: FaroUserSession;\n lifecycleType: LifecycleType;\n } {\n let userSession: FaroUserSession | null = SessionManager.fetchUserSession();\n\n if (sessionsConfig.persistent && sessionsConfig.maxSessionPersistenceTime && userSession) {\n const now = dateNow();\n const shouldClearPersistentSession = userSession.lastActivity < now - sessionsConfig.maxSessionPersistenceTime;\n\n if (shouldClearPersistentSession) {\n PersistentSessionsManager.removeUserSession();\n userSession = null;\n }\n }\n\n let lifecycleType: LifecycleType;\n let initialSession: FaroUserSession;\n\n if (isUserSessionValid(userSession)) {\n const sessionId = userSession?.sessionId;\n\n initialSession = createUserSessionObject({\n sessionId,\n isSampled: userSession!.isSampled || false,\n started: userSession?.started,\n });\n\n initialSession.sessionMeta = {\n id: sessionId,\n attributes: {\n ...sessionsConfig.session?.attributes,\n ...userSession?.sessionMeta?.attributes,\n // For valid resumed sessions we do not want to recalculate the sampling decision on each init phase.\n isSampled: initialSession.isSampled.toString(),\n },\n };\n\n lifecycleType = EVENT_SESSION_RESUME;\n } else {\n const sessionId = sessionsConfig.session?.id ?? createSession().id;\n\n initialSession = createUserSessionObject({\n sessionId,\n isSampled: isSampled(),\n });\n\n initialSession.sessionMeta = {\n id: sessionId,\n attributes: {\n isSampled: initialSession.isSampled.toString(),\n ...sessionsConfig.session?.attributes,\n },\n };\n\n lifecycleType = EVENT_SESSION_START;\n }\n\n return { initialSession, lifecycleType };\n }\n\n private registerBeforeSendHook(SessionManager: SessionManager) {\n const { updateSession } = new SessionManager();\n\n this.transports?.addBeforeSendHooks((item) => {\n updateSession();\n\n const attributes = item.meta.session?.attributes;\n\n if (attributes && attributes?.['isSampled'] === 'true') {\n let newItem: TransportItem = JSON.parse(JSON.stringify(item));\n\n const newAttributes = newItem.meta.session?.attributes;\n delete newAttributes?.['isSampled'];\n\n if (Object.keys(newAttributes ?? {}).length === 0) {\n delete newItem.meta.session?.attributes;\n }\n\n return newItem;\n }\n\n return null;\n });\n }\n\n initialize() {\n this.logDebug('init session instrumentation');\n\n const sessionTrackingConfig = this.config.sessionTracking;\n\n if (sessionTrackingConfig?.enabled) {\n const SessionManager = getSessionManagerByConfig(sessionTrackingConfig);\n\n this.registerBeforeSendHook(SessionManager);\n\n const { initialSession, lifecycleType } = this.createInitialSession(SessionManager, sessionTrackingConfig);\n\n SessionManager.storeUserSession(initialSession);\n\n const initialSessionMeta = initialSession.sessionMeta;\n\n this.notifiedSession = initialSessionMeta;\n this.api.setSession(initialSessionMeta);\n\n if (lifecycleType === EVENT_SESSION_START) {\n this.api.pushEvent(EVENT_SESSION_START, {}, undefined, { skipDedupe: true });\n }\n\n if (lifecycleType === EVENT_SESSION_RESUME) {\n this.api.pushEvent(EVENT_SESSION_RESUME, {}, undefined, { skipDedupe: true });\n }\n }\n\n this.metas.addListener(this.sendSessionStartEvent.bind(this));\n }\n}\n"]}
@@ -0,0 +1,10 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getSessionManagerByConfig = void 0;
4
+ var PersistentSessionsManager_1 = require("./PersistentSessionsManager");
5
+ var VolatileSessionManager_1 = require("./VolatileSessionManager");
6
+ function getSessionManagerByConfig(sessionTrackingConfig) {
7
+ return (sessionTrackingConfig === null || sessionTrackingConfig === void 0 ? void 0 : sessionTrackingConfig.persistent) ? PersistentSessionsManager_1.PersistentSessionsManager : VolatileSessionManager_1.VolatileSessionsManager;
8
+ }
9
+ exports.getSessionManagerByConfig = getSessionManagerByConfig;
10
+ //# sourceMappingURL=getSessionManagerByConfig.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"getSessionManagerByConfig.js","sourceRoot":"","sources":["../../../../../src/instrumentations/session/sessionManager/getSessionManagerByConfig.ts"],"names":[],"mappings":";;;AAEA,yEAAwE;AAExE,mEAAmE;AAEnE,SAAgB,yBAAyB,CAAC,qBAAgD;IACxF,OAAO,CAAA,qBAAqB,aAArB,qBAAqB,uBAArB,qBAAqB,CAAE,UAAU,EAAC,CAAC,CAAC,qDAAyB,CAAC,CAAC,CAAC,gDAAuB,CAAC;AACjG,CAAC;AAFD,8DAEC","sourcesContent":["import type { Config } from '@grafana/faro-core';\n\nimport { PersistentSessionsManager } from './PersistentSessionsManager';\nimport type { SessionManager } from './types';\nimport { VolatileSessionsManager } from './VolatileSessionManager';\n\nexport function getSessionManagerByConfig(sessionTrackingConfig: Config['sessionTracking']): SessionManager {\n return sessionTrackingConfig?.persistent ? PersistentSessionsManager : VolatileSessionsManager;\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.isSampled = exports.defaultSessionTrackingConfig = exports.STORAGE_UPDATE_DELAY = exports.STORAGE_KEY = exports.SESSION_INACTIVITY_TIME = exports.SESSION_EXPIRATION_TIME = exports.MAX_SESSION_PERSISTENCE_TIME_BUFFER = exports.MAX_SESSION_PERSISTENCE_TIME = exports.VolatileSessionsManager = exports.PersistentSessionsManager = void 0;
3
+ exports.getSessionManagerByConfig = exports.isSampled = exports.defaultSessionTrackingConfig = exports.STORAGE_UPDATE_DELAY = exports.STORAGE_KEY = exports.SESSION_INACTIVITY_TIME = exports.SESSION_EXPIRATION_TIME = exports.MAX_SESSION_PERSISTENCE_TIME_BUFFER = exports.MAX_SESSION_PERSISTENCE_TIME = exports.VolatileSessionsManager = exports.PersistentSessionsManager = void 0;
4
4
  var PersistentSessionsManager_1 = require("./PersistentSessionsManager");
5
5
  Object.defineProperty(exports, "PersistentSessionsManager", { enumerable: true, get: function () { return PersistentSessionsManager_1.PersistentSessionsManager; } });
6
6
  var VolatileSessionManager_1 = require("./VolatileSessionManager");
@@ -15,4 +15,6 @@ Object.defineProperty(exports, "STORAGE_UPDATE_DELAY", { enumerable: true, get:
15
15
  Object.defineProperty(exports, "defaultSessionTrackingConfig", { enumerable: true, get: function () { return sessionConstants_1.defaultSessionTrackingConfig; } });
16
16
  var sampling_1 = require("./sampling");
17
17
  Object.defineProperty(exports, "isSampled", { enumerable: true, get: function () { return sampling_1.isSampled; } });
18
+ var getSessionManagerByConfig_1 = require("./getSessionManagerByConfig");
19
+ Object.defineProperty(exports, "getSessionManagerByConfig", { enumerable: true, get: function () { return getSessionManagerByConfig_1.getSessionManagerByConfig; } });
18
20
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../src/instrumentations/session/sessionManager/index.ts"],"names":[],"mappings":";;;AAAA,yEAAwE;AAA/D,sIAAA,yBAAyB,OAAA;AAClC,mEAAmE;AAA1D,iIAAA,uBAAuB,OAAA;AAEhC,uDAQ4B;AAP1B,gIAAA,4BAA4B,OAAA;AAC5B,uIAAA,mCAAmC,OAAA;AACnC,2HAAA,uBAAuB,OAAA;AACvB,2HAAA,uBAAuB,OAAA;AACvB,+GAAA,WAAW,OAAA;AACX,wHAAA,oBAAoB,OAAA;AACpB,gIAAA,4BAA4B,OAAA;AAG9B,uCAAuC;AAA9B,qGAAA,SAAS,OAAA","sourcesContent":["export { PersistentSessionsManager } from './PersistentSessionsManager';\nexport { VolatileSessionsManager } from './VolatileSessionManager';\n\nexport {\n MAX_SESSION_PERSISTENCE_TIME,\n MAX_SESSION_PERSISTENCE_TIME_BUFFER,\n SESSION_EXPIRATION_TIME,\n SESSION_INACTIVITY_TIME,\n STORAGE_KEY,\n STORAGE_UPDATE_DELAY,\n defaultSessionTrackingConfig,\n} from './sessionConstants';\n\nexport { isSampled } from './sampling';\n\nexport type { FaroUserSession } from './types';\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../src/instrumentations/session/sessionManager/index.ts"],"names":[],"mappings":";;;AAAA,yEAAwE;AAA/D,sIAAA,yBAAyB,OAAA;AAClC,mEAAmE;AAA1D,iIAAA,uBAAuB,OAAA;AAEhC,uDAQ4B;AAP1B,gIAAA,4BAA4B,OAAA;AAC5B,uIAAA,mCAAmC,OAAA;AACnC,2HAAA,uBAAuB,OAAA;AACvB,2HAAA,uBAAuB,OAAA;AACvB,+GAAA,WAAW,OAAA;AACX,wHAAA,oBAAoB,OAAA;AACpB,gIAAA,4BAA4B,OAAA;AAG9B,uCAAuC;AAA9B,qGAAA,SAAS,OAAA;AAIlB,yEAAwE;AAA/D,sIAAA,yBAAyB,OAAA","sourcesContent":["export { PersistentSessionsManager } from './PersistentSessionsManager';\nexport { VolatileSessionsManager } from './VolatileSessionManager';\n\nexport {\n MAX_SESSION_PERSISTENCE_TIME,\n MAX_SESSION_PERSISTENCE_TIME_BUFFER,\n SESSION_EXPIRATION_TIME,\n SESSION_INACTIVITY_TIME,\n STORAGE_KEY,\n STORAGE_UPDATE_DELAY,\n defaultSessionTrackingConfig,\n} from './sessionConstants';\n\nexport { isSampled } from './sampling';\n\nexport type { FaroUserSession } from './types';\n\nexport { getSessionManagerByConfig } from './getSessionManagerByConfig';\n"]}
@@ -11,10 +11,9 @@ var __assign = (this && this.__assign) || function () {
11
11
  return __assign.apply(this, arguments);
12
12
  };
13
13
  Object.defineProperty(exports, "__esModule", { value: true });
14
- exports.getSessionManagerByConfig = exports.addSessionMetadataToNextSession = exports.getUserSessionUpdater = exports.isUserSessionValid = exports.createUserSessionObject = void 0;
14
+ exports.addSessionMetadataToNextSession = exports.getUserSessionUpdater = exports.isUserSessionValid = exports.createUserSessionObject = void 0;
15
15
  var faro_core_1 = require("@grafana/faro-core");
16
16
  var utils_1 = require("../../../utils");
17
- var _1 = require(".");
18
17
  var sampling_1 = require("./sampling");
19
18
  var sessionConstants_1 = require("./sessionConstants");
20
19
  function createUserSessionObject(_a) {
@@ -81,8 +80,4 @@ function addSessionMetadataToNextSession(newSession, previousSession) {
81
80
  return sessionWithMeta;
82
81
  }
83
82
  exports.addSessionMetadataToNextSession = addSessionMetadataToNextSession;
84
- function getSessionManagerByConfig(sessionTrackingConfig) {
85
- return (sessionTrackingConfig === null || sessionTrackingConfig === void 0 ? void 0 : sessionTrackingConfig.persistent) ? _1.PersistentSessionsManager : _1.VolatileSessionsManager;
86
- }
87
- exports.getSessionManagerByConfig = getSessionManagerByConfig;
88
83
  //# sourceMappingURL=sessionManagerUtils.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"sessionManagerUtils.js","sourceRoot":"","sources":["../../../../../src/instrumentations/session/sessionManager/sessionManagerUtils.ts"],"names":[],"mappings":";;;;;;;;;;;;;;AAAA,gDAA+D;AAG/D,wCAAoF;AAEpF,sBAAuE;AACvE,uCAAuC;AACvC,uDAAsF;AAUtF,SAAgB,uBAAuB,CAAC,EAKH;;QAL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AAM,CAAC,eAAe,0CAAE,OAAO,0CAAE,UAAU,GAChD,CAAC,MAAA,MAAA,gBAAI,CAAC,KAAK,CAAC,KAAK,CAAC,OAAO,0CAAE,UAAU,mCAAI,EAAE,CAAC,GAC5C,CAAC,eAAe,IAAI,IAAI,CAAC,CAAC,CAAC,EAAE,eAAe,EAAE,eAAe,CAAC,SAAS,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,KAClF,SAAS,EAAE,UAAU,CAAC,SAAS,CAAC,QAAQ,EAAE,GAC3C;SACF,GACF,CAAC;IAEF,OAAO,eAAe,CAAC;AACzB,CAAC;AAfD,0EAeC;AAED,SAAgB,yBAAyB,CAAC,qBAAgD;IACxF,OAAO,CAAA,qBAAqB,aAArB,qBAAqB,uBAArB,qBAAqB,CAAE,UAAU,EAAC,CAAC,CAAC,4BAAyB,CAAC,CAAC,CAAC,0BAAuB,CAAC;AACjG,CAAC;AAFD,8DAEC","sourcesContent":["import { dateNow, faro, genShortID } from '@grafana/faro-core';\nimport type { Config } from '@grafana/faro-core';\n\nimport { isLocalStorageAvailable, isSessionStorageAvailable } from '../../../utils';\n\nimport { PersistentSessionsManager, VolatileSessionsManager } from '.';\nimport { isSampled } from './sampling';\nimport { SESSION_EXPIRATION_TIME, SESSION_INACTIVITY_TIME } from './sessionConstants';\nimport type { FaroUserSession, SessionManager } from './types';\n\ntype CreateUserSessionObjectParams = {\n sessionId?: string;\n started?: number;\n lastActivity?: number;\n isSampled?: boolean;\n};\n\nexport function createUserSessionObject({\n sessionId,\n started,\n lastActivity,\n isSampled = true,\n}: CreateUserSessionObjectParams = {}): FaroUserSession {\n const now = dateNow();\n\n const generateSessionId = faro.config?.sessionTracking?.generateSessionId;\n\n if (sessionId == null) {\n sessionId = typeof generateSessionId === 'function' ? generateSessionId() : genShortID();\n }\n\n return {\n sessionId,\n lastActivity: lastActivity ?? now,\n started: started ?? now,\n isSampled: isSampled,\n };\n}\n\nexport function isUserSessionValid(session: FaroUserSession | null): boolean {\n if (session == null) {\n return false;\n }\n\n const now = dateNow();\n const lifetimeValid = now - session.started < SESSION_EXPIRATION_TIME;\n\n if (!lifetimeValid) {\n return false;\n }\n\n const inactivityPeriodValid = now - session.lastActivity < SESSION_INACTIVITY_TIME;\n return inactivityPeriodValid;\n}\n\ntype GetUserSessionUpdaterParams = {\n storeUserSession: (session: FaroUserSession) => void;\n fetchUserSession: () => FaroUserSession | null;\n};\n\ntype UpdateSessionParams = { forceSessionExtend: boolean };\n\nexport function getUserSessionUpdater({\n fetchUserSession,\n storeUserSession,\n}: GetUserSessionUpdaterParams): (options?: UpdateSessionParams) => void {\n return function updateSession({ forceSessionExtend } = { forceSessionExtend: false }): void {\n if (!fetchUserSession || !storeUserSession) {\n return;\n }\n\n const sessionTrackingConfig = faro.config.sessionTracking;\n const isPersistentSessions = sessionTrackingConfig?.persistent;\n\n if ((isPersistentSessions && !isLocalStorageAvailable) || (!isPersistentSessions && !isSessionStorageAvailable)) {\n return;\n }\n\n const sessionFromStorage = fetchUserSession();\n\n if (forceSessionExtend === false && isUserSessionValid(sessionFromStorage)) {\n storeUserSession({ ...sessionFromStorage!, lastActivity: dateNow() });\n } else {\n let newSession = addSessionMetadataToNextSession(\n createUserSessionObject({ isSampled: isSampled() }),\n sessionFromStorage\n );\n\n storeUserSession(newSession);\n\n faro.api?.setSession(newSession.sessionMeta);\n sessionTrackingConfig?.onSessionChange?.(sessionFromStorage?.sessionMeta ?? null, newSession.sessionMeta!);\n }\n };\n}\n\nexport function addSessionMetadataToNextSession(newSession: FaroUserSession, previousSession: FaroUserSession | null) {\n const sessionWithMeta: Required<FaroUserSession> = {\n ...newSession,\n sessionMeta: {\n id: newSession.sessionId,\n attributes: {\n ...faro.config.sessionTracking?.session?.attributes,\n ...(faro.metas.value.session?.attributes ?? {}),\n ...(previousSession != null ? { previousSession: previousSession.sessionId } : {}),\n isSampled: newSession.isSampled.toString(),\n },\n },\n };\n\n return sessionWithMeta;\n}\n\nexport function getSessionManagerByConfig(sessionTrackingConfig: Config['sessionTracking']): SessionManager {\n return sessionTrackingConfig?.persistent ? PersistentSessionsManager : VolatileSessionsManager;\n}\n"]}
1
+ {"version":3,"file":"sessionManagerUtils.js","sourceRoot":"","sources":["../../../../../src/instrumentations/session/sessionManager/sessionManagerUtils.ts"],"names":[],"mappings":";;;;;;;;;;;;;;AAAA,gDAA+D;AAE/D,wCAAoF;AAEpF,uCAAuC;AACvC,uDAAsF;AAUtF,SAAgB,uBAAuB,CAAC,EAKH;;QALG,qBAKL,EAAE,KAAA,EAJnC,SAAS,eAAA,EACT,OAAO,aAAA,EACP,YAAY,kBAAA,EACZ,iBAAgB,EAAhB,SAAS,mBAAG,IAAI,KAAA;IAEhB,IAAM,GAAG,GAAG,IAAA,mBAAO,GAAE,CAAC;IAEtB,IAAM,iBAAiB,GAAG,MAAA,MAAA,gBAAI,CAAC,MAAM,0CAAE,eAAe,0CAAE,iBAAiB,CAAC;IAE1E,IAAI,SAAS,IAAI,IAAI,EAAE;QACrB,SAAS,GAAG,OAAO,iBAAiB,KAAK,UAAU,CAAC,CAAC,CAAC,iBAAiB,EAAE,CAAC,CAAC,CAAC,IAAA,sBAAU,GAAE,CAAC;KAC1F;IAED,OAAO;QACL,SAAS,WAAA;QACT,YAAY,EAAE,YAAY,aAAZ,YAAY,cAAZ,YAAY,GAAI,GAAG;QACjC,OAAO,EAAE,OAAO,aAAP,OAAO,cAAP,OAAO,GAAI,GAAG;QACvB,SAAS,EAAE,SAAS;KACrB,CAAC;AACJ,CAAC;AApBD,0DAoBC;AAED,SAAgB,kBAAkB,CAAC,OAA+B;IAChE,IAAI,OAAO,IAAI,IAAI,EAAE;QACnB,OAAO,KAAK,CAAC;KACd;IAED,IAAM,GAAG,GAAG,IAAA,mBAAO,GAAE,CAAC;IACtB,IAAM,aAAa,GAAG,GAAG,GAAG,OAAO,CAAC,OAAO,GAAG,0CAAuB,CAAC;IAEtE,IAAI,CAAC,aAAa,EAAE;QAClB,OAAO,KAAK,CAAC;KACd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B,uBAAlB,kBAAkB,CAAE,WAAW,mCAAI,IAAI,EAAE,UAAU,CAAC,WAAY,CAAC,CAAC;SAC5G;IACH,CAAC,CAAC;AACJ,CAAC;AAhCD,sDAgCC;AAED,SAAgB,+BAA+B,CAAC,UAA2B,EAAE,eAAuC;;IAClH,IAAM,eAAe,yBAChB,UAAU,KACb,WAAW,EAAE;YACX,EAAE,EAAE,UAAU,CAAC,SAAS;YACxB,UAAU,0CACL,MAAA,MAAA,gBAAI,CAAC,MAAM,CAAC,eAAe,0CAAE,OAAO,0CAAE,UAAU,GAChD,CAAC,MAAA,MAAA,gBAAI,CAAC,KAAK,CAAC,KAAK,CAAC,OAAO,0CAAE,UAAU,mCAAI,EAAE,CAAC,GAC5C,CAAC,eAAe,IAAI,IAAI,CAAC,CAAC,CAAC,EAAE,eAAe,EAAE,eAAe,CAAC,SAAS,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,KAClF,SAAS,EAAE,UAAU,CAAC,SAAS,CAAC,QAAQ,EAAE,GAC3C;SACF,GACF,CAAC;IAEF,OAAO,eAAe,CAAC;AACzB,CAAC;AAfD,0EAeC","sourcesContent":["import { dateNow, faro, genShortID } from '@grafana/faro-core';\n\nimport { isLocalStorageAvailable, isSessionStorageAvailable } from '../../../utils';\n\nimport { isSampled } from './sampling';\nimport { SESSION_EXPIRATION_TIME, SESSION_INACTIVITY_TIME } from './sessionConstants';\nimport type { FaroUserSession } from './types';\n\ntype CreateUserSessionObjectParams = {\n sessionId?: string;\n started?: number;\n lastActivity?: number;\n isSampled?: boolean;\n};\n\nexport function createUserSessionObject({\n sessionId,\n started,\n lastActivity,\n isSampled = true,\n}: CreateUserSessionObjectParams = {}): FaroUserSession {\n const now = dateNow();\n\n const generateSessionId = faro.config?.sessionTracking?.generateSessionId;\n\n if (sessionId == null) {\n sessionId = typeof generateSessionId === 'function' ? generateSessionId() : genShortID();\n }\n\n return {\n sessionId,\n lastActivity: lastActivity ?? now,\n started: started ?? now,\n isSampled: isSampled,\n };\n}\n\nexport function isUserSessionValid(session: FaroUserSession | null): boolean {\n if (session == null) {\n return false;\n }\n\n const now = dateNow();\n const lifetimeValid = now - session.started < SESSION_EXPIRATION_TIME;\n\n if (!lifetimeValid) {\n return false;\n }\n\n const inactivityPeriodValid = now - session.lastActivity < SESSION_INACTIVITY_TIME;\n return inactivityPeriodValid;\n}\n\ntype GetUserSessionUpdaterParams = {\n storeUserSession: (session: FaroUserSession) => void;\n fetchUserSession: () => FaroUserSession | null;\n};\n\ntype UpdateSessionParams = { forceSessionExtend: boolean };\n\nexport function getUserSessionUpdater({\n fetchUserSession,\n storeUserSession,\n}: GetUserSessionUpdaterParams): (options?: UpdateSessionParams) => void {\n return function updateSession({ forceSessionExtend } = { forceSessionExtend: false }): void {\n if (!fetchUserSession || !storeUserSession) {\n return;\n }\n\n const sessionTrackingConfig = faro.config.sessionTracking;\n const isPersistentSessions = sessionTrackingConfig?.persistent;\n\n if ((isPersistentSessions && !isLocalStorageAvailable) || (!isPersistentSessions && !isSessionStorageAvailable)) {\n return;\n }\n\n const sessionFromStorage = fetchUserSession();\n\n if (forceSessionExtend === false && isUserSessionValid(sessionFromStorage)) {\n storeUserSession({ ...sessionFromStorage!, lastActivity: dateNow() });\n } else {\n let newSession = addSessionMetadataToNextSession(\n createUserSessionObject({ isSampled: isSampled() }),\n sessionFromStorage\n );\n\n storeUserSession(newSession);\n\n faro.api?.setSession(newSession.sessionMeta);\n sessionTrackingConfig?.onSessionChange?.(sessionFromStorage?.sessionMeta ?? null, newSession.sessionMeta!);\n }\n };\n}\n\nexport function addSessionMetadataToNextSession(newSession: FaroUserSession, previousSession: FaroUserSession | null) {\n const sessionWithMeta: Required<FaroUserSession> = {\n ...newSession,\n sessionMeta: {\n id: newSession.sessionId,\n attributes: {\n ...faro.config.sessionTracking?.session?.attributes,\n ...(faro.metas.value.session?.attributes ?? {}),\n ...(previousSession != null ? { previousSession: previousSession.sessionId } : {}),\n isSampled: newSession.isSampled.toString(),\n },\n },\n };\n\n return sessionWithMeta;\n}\n"]}
@@ -75,6 +75,7 @@ var __rest = (this && this.__rest) || function (s, e) {
75
75
  Object.defineProperty(exports, "__esModule", { value: true });
76
76
  exports.FetchTransport = void 0;
77
77
  var faro_core_1 = require("@grafana/faro-core");
78
+ var sessionManager_1 = require("../../instrumentations/session/sessionManager");
78
79
  var sessionManagerUtils_1 = require("../../instrumentations/session/sessionManager/sessionManagerUtils");
79
80
  var DEFAULT_BUFFER_SIZE = 30;
80
81
  var DEFAULT_CONCURRENCY = 5; // chrome supports 10 total, firefox 17
@@ -182,7 +183,7 @@ var FetchTransport = /** @class */ (function (_super) {
182
183
  var SessionExpiredString = "Session expired";
183
184
  var sessionTrackingConfig = config.sessionTracking;
184
185
  if (sessionTrackingConfig === null || sessionTrackingConfig === void 0 ? void 0 : sessionTrackingConfig.enabled) {
185
- var _a = (0, sessionManagerUtils_1.getSessionManagerByConfig)(sessionTrackingConfig), fetchUserSession = _a.fetchUserSession, storeUserSession = _a.storeUserSession;
186
+ var _a = (0, sessionManager_1.getSessionManagerByConfig)(sessionTrackingConfig), fetchUserSession = _a.fetchUserSession, storeUserSession = _a.storeUserSession;
186
187
  (0, sessionManagerUtils_1.getUserSessionUpdater)({ fetchUserSession: fetchUserSession, storeUserSession: storeUserSession })({ forceSessionExtend: true });
187
188
  logDebug("".concat(SessionExpiredString, " created new session."));
188
189
  }
@@ -1 +1 @@
1
- {"version":3,"file":"transport.js","sourceRoot":"","sources":["../../../../src/transports/fetch/transport.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,gDAQ4B;AAG5B,yGAG2E;AAI3E,IAAM,mBAAmB,GAAG,EAAE,CAAC;AAC/B,IAAM,mBAAmB,GAAG,CAAC,CAAC,CAAC,uCAAuC;AACtE,IAAM,6BAA6B,GAAG,IAAI,CAAC;AAE3C,IAAM,sBAAsB,GAAG,K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,CAAC,IAAI,CAAC,CAAC;aACvB;SACF;QAED,OAAO,IAAI,IAAI,CAAC,GAAG,GAAG,IAAI,CAAC,kBAAkB,CAAC,CAAC;IACjD,CAAC;IAEO,0CAAiB,GAAzB,UAA0B,MAAc,EAAE,QAAmC;QAC3E,IAAM,oBAAoB,GAAG,iBAAiB,CAAC;QAE/C,IAAM,qBAAqB,GAAG,MAAM,CAAC,eAAe,CAAC;QAErD,IAAI,qBAAqB,aAArB,qBAAqB,uBAArB,qBAAqB,CAAE,OAAO,EAAE;YAC5B,IAAA,KAAyC,IAAA,+CAAyB,EAAC,qBAAqB,CAAC,EAAvF,gBAAgB,sBAAA,EAAE,gBAAgB,sBAAqD,CAAC;YAEhG,IAAA,2CAAqB,EAAC,EAAE,gBAAgB,kBAAA,EAAE,gBAAgB,kBAAA,EAAE,CAAC,CAAC,EAAE,kBAAkB,EAAE,IAAI,EAAE,CAAC,CAAC;YAE5F,QAAQ,CAAC,UAAG,oBAAoB,0BAAuB,CAAC,CAAC;SAC1D;aAAM;YACL,QAAQ,CAAC,UAAG,oBAAoB,MAAG,CAAC,CAAC;SACtC;IACH,CAAC;IACH,qBAAC;AAAD,CAAC,AA9HD,CAAoC,yBAAa,GA8HhD;AA9HY,wCAAc","sourcesContent":["import {\n BaseExtension,\n BaseTransport,\n createPromiseBuffer,\n getTransportBody,\n noop,\n PromiseBuffer,\n VERSION,\n} from '@grafana/faro-core';\nimport type { Config, Patterns, TransportItem } from '@grafana/faro-core';\n\nimport {\n getSessionManagerByConfig,\n getUserSessionUpdater,\n} from '../../instrumentations/session/sessionManager/sessionManagerUtils';\n\nimport type { FetchTransportOptions } from './types';\n\nconst DEFAULT_BUFFER_SIZE = 30;\nconst DEFAULT_CONCURRENCY = 5; // chrome supports 10 total, firefox 17\nconst DEFAULT_RATE_LIMIT_BACKOFF_MS = 5000;\n\nconst BEACON_BODY_SIZE_LIMIT = 60000;\nconst TOO_MANY_REQUESTS = 429;\nconst ACCEPTED = 202;\n\nexport class FetchTransport extends BaseTransport {\n readonly name = '@grafana/faro-web-sdk:transport-fetch';\n readonly version = VERSION;\n\n promiseBuffer: PromiseBuffer<Response | void>;\n\n private readonly rateLimitBackoffMs: number;\n private readonly getNow: () => number;\n private disabledUntil: Date = new Date();\n\n constructor(private options: FetchTransportOptions) {\n super();\n\n this.rateLimitBackoffMs = options.defaultRateLimitBackoffMs ?? DEFAULT_RATE_LIMIT_BACKOFF_MS;\n this.getNow = options.getNow ?? (() => Date.now());\n\n this.promiseBuffer = createPromiseBuffer({\n size: options.bufferSize ?? DEFAULT_BUFFER_SIZE,\n concurrency: options.concurrency ?? DEFAULT_CONCURRENCY,\n });\n }\n\n async send(items: TransportItem[]): Promise<void> {\n try {\n if (this.disabledUntil > new Date(this.getNow())) {\n this.logWarn(`Dropping transport item due to too many requests. Backoff until ${this.disabledUntil}`);\n\n return Promise.resolve();\n }\n\n await this.promiseBuffer.add(() => {\n const body = JSON.stringify(getTransportBody(items));\n\n const { url, requestOptions, apiKey } = this.options;\n\n const { headers, ...restOfRequestOptions } = requestOptions ?? {};\n\n let sessionId;\n const sessionMeta = this.metas.value.session;\n if (sessionMeta != null) {\n sessionId = sessionMeta.id;\n }\n\n return fetch(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...(headers ?? {}),\n ...(apiKey ? { 'x-api-key': apiKey } : {}),\n ...(sessionId ? { 'x-faro-session-id': sessionId } : {}),\n },\n body,\n keepalive: body.length <= BEACON_BODY_SIZE_LIMIT,\n ...(restOfRequestOptions ?? {}),\n })\n .then(async (response) => {\n if (response.status === ACCEPTED) {\n const sessionExpired = response.headers.get('X-Faro-Session-Status') === 'invalid';\n\n if (sessionExpired) {\n this.extendFaroSession(this.config, this.logDebug);\n }\n }\n\n if (response.status === TOO_MANY_REQUESTS) {\n this.disabledUntil = this.getRetryAfterDate(response);\n this.logWarn(`Too many requests, backing off until ${this.disabledUntil}`);\n }\n\n // read the body so the connection can be closed\n response.text().catch(noop);\n return response;\n })\n .catch((err) => {\n this.logError('Failed sending payload to the receiver\\n', JSON.parse(body), err);\n });\n });\n } catch (err) {\n this.logError(err);\n }\n }\n\n override getIgnoreUrls(): Patterns {\n return ([this.options.url] as Patterns).concat(this.config.ignoreUrls ?? []);\n }\n\n override isBatched(): boolean {\n return true;\n }\n\n private getRetryAfterDate(response: Response): Date {\n const now = this.getNow();\n const retryAfterHeader = response.headers.get('Retry-After');\n\n if (retryAfterHeader) {\n const delay = Number(retryAfterHeader);\n\n if (!isNaN(delay)) {\n return new Date(delay * 1000 + now);\n }\n\n const date = Date.parse(retryAfterHeader);\n\n if (!isNaN(date)) {\n return new Date(date);\n }\n }\n\n return new Date(now + this.rateLimitBackoffMs);\n }\n\n private extendFaroSession(config: Config, logDebug: BaseExtension['logDebug']) {\n const SessionExpiredString = `Session expired`;\n\n const sessionTrackingConfig = config.sessionTracking;\n\n if (sessionTrackingConfig?.enabled) {\n const { fetchUserSession, storeUserSession } = getSessionManagerByConfig(sessionTrackingConfig);\n\n getUserSessionUpdater({ fetchUserSession, storeUserSession })({ forceSessionExtend: true });\n\n logDebug(`${SessionExpiredString} created new session.`);\n } else {\n logDebug(`${SessionExpiredString}.`);\n }\n }\n}\n"]}
1
+ {"version":3,"file":"transport.js","sourceRoot":"","sources":["../../../../src/transports/fetch/transport.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,gDAQ4B;AAG5B,gFAA0F;AAC1F,yGAA0G;AAI1G,IAAM,mBAAmB,GAAG,EAAE,CAAC;AAC/B,IAAM,mBAAmB,GAAG,CAAC,CAAC,CAAC,uCAAuC;AACtE,IAAM,6BAA6B,GAAG,IAAI,CAAC;AAE3C,IAAM,sBAAsB,GAAG,KAAK,CAAC;AACrC,IAAM,iBAAiB,GAAG,GAAG,CAAC;AAC9B,IAAM,QAAQ,GAAG,GAAG,CAAC;AAErB;IAAoC,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C,CAAC;IACjD,CAAC;IAEO,0CAAiB,GAAzB,UAA0B,MAAc,EAAE,QAAmC;QAC3E,IAAM,oBAAoB,GAAG,iBAAiB,CAAC;QAE/C,IAAM,qBAAqB,GAAG,MAAM,CAAC,eAAe,CAAC;QAErD,IAAI,qBAAqB,aAArB,qBAAqB,uBAArB,qBAAqB,CAAE,OAAO,EAAE;YAC5B,IAAA,KAAyC,IAAA,0CAAyB,EAAC,qBAAqB,CAAC,EAAvF,gBAAgB,sBAAA,EAAE,gBAAgB,sBAAqD,CAAC;YAEhG,IAAA,2CAAqB,EAAC,EAAE,gBAAgB,kBAAA,EAAE,gBAAgB,kBAAA,EAAE,CAAC,CAAC,EAAE,kBAAkB,EAAE,IAAI,EAAE,CAAC,CAAC;YAE5F,QAAQ,CAAC,UAAG,oBAAoB,0BAAuB,CAAC,CAAC;SAC1D;aAAM;YACL,QAAQ,CAAC,UAAG,oBAAoB,MAAG,CAAC,CAAC;SACtC;IACH,CAAC;IACH,qBAAC;AAAD,CAAC,AA9HD,CAAoC,yBAAa,GA8HhD;AA9HY,wCAAc","sourcesContent":["import {\n BaseExtension,\n BaseTransport,\n createPromiseBuffer,\n getTransportBody,\n noop,\n PromiseBuffer,\n VERSION,\n} from '@grafana/faro-core';\nimport type { Config, Patterns, TransportItem } from '@grafana/faro-core';\n\nimport { getSessionManagerByConfig } from '../../instrumentations/session/sessionManager';\nimport { getUserSessionUpdater } from '../../instrumentations/session/sessionManager/sessionManagerUtils';\n\nimport type { FetchTransportOptions } from './types';\n\nconst DEFAULT_BUFFER_SIZE = 30;\nconst DEFAULT_CONCURRENCY = 5; // chrome supports 10 total, firefox 17\nconst DEFAULT_RATE_LIMIT_BACKOFF_MS = 5000;\n\nconst BEACON_BODY_SIZE_LIMIT = 60000;\nconst TOO_MANY_REQUESTS = 429;\nconst ACCEPTED = 202;\n\nexport class FetchTransport extends BaseTransport {\n readonly name = '@grafana/faro-web-sdk:transport-fetch';\n readonly version = VERSION;\n\n promiseBuffer: PromiseBuffer<Response | void>;\n\n private readonly rateLimitBackoffMs: number;\n private readonly getNow: () => number;\n private disabledUntil: Date = new Date();\n\n constructor(private options: FetchTransportOptions) {\n super();\n\n this.rateLimitBackoffMs = options.defaultRateLimitBackoffMs ?? DEFAULT_RATE_LIMIT_BACKOFF_MS;\n this.getNow = options.getNow ?? (() => Date.now());\n\n this.promiseBuffer = createPromiseBuffer({\n size: options.bufferSize ?? DEFAULT_BUFFER_SIZE,\n concurrency: options.concurrency ?? DEFAULT_CONCURRENCY,\n });\n }\n\n async send(items: TransportItem[]): Promise<void> {\n try {\n if (this.disabledUntil > new Date(this.getNow())) {\n this.logWarn(`Dropping transport item due to too many requests. Backoff until ${this.disabledUntil}`);\n\n return Promise.resolve();\n }\n\n await this.promiseBuffer.add(() => {\n const body = JSON.stringify(getTransportBody(items));\n\n const { url, requestOptions, apiKey } = this.options;\n\n const { headers, ...restOfRequestOptions } = requestOptions ?? {};\n\n let sessionId;\n const sessionMeta = this.metas.value.session;\n if (sessionMeta != null) {\n sessionId = sessionMeta.id;\n }\n\n return fetch(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...(headers ?? {}),\n ...(apiKey ? { 'x-api-key': apiKey } : {}),\n ...(sessionId ? { 'x-faro-session-id': sessionId } : {}),\n },\n body,\n keepalive: body.length <= BEACON_BODY_SIZE_LIMIT,\n ...(restOfRequestOptions ?? {}),\n })\n .then(async (response) => {\n if (response.status === ACCEPTED) {\n const sessionExpired = response.headers.get('X-Faro-Session-Status') === 'invalid';\n\n if (sessionExpired) {\n this.extendFaroSession(this.config, this.logDebug);\n }\n }\n\n if (response.status === TOO_MANY_REQUESTS) {\n this.disabledUntil = this.getRetryAfterDate(response);\n this.logWarn(`Too many requests, backing off until ${this.disabledUntil}`);\n }\n\n // read the body so the connection can be closed\n response.text().catch(noop);\n return response;\n })\n .catch((err) => {\n this.logError('Failed sending payload to the receiver\\n', JSON.parse(body), err);\n });\n });\n } catch (err) {\n this.logError(err);\n }\n }\n\n override getIgnoreUrls(): Patterns {\n return ([this.options.url] as Patterns).concat(this.config.ignoreUrls ?? []);\n }\n\n override isBatched(): boolean {\n return true;\n }\n\n private getRetryAfterDate(response: Response): Date {\n const now = this.getNow();\n const retryAfterHeader = response.headers.get('Retry-After');\n\n if (retryAfterHeader) {\n const delay = Number(retryAfterHeader);\n\n if (!isNaN(delay)) {\n return new Date(delay * 1000 + now);\n }\n\n const date = Date.parse(retryAfterHeader);\n\n if (!isNaN(date)) {\n return new Date(date);\n }\n }\n\n return new Date(now + this.rateLimitBackoffMs);\n }\n\n private extendFaroSession(config: Config, logDebug: BaseExtension['logDebug']) {\n const SessionExpiredString = `Session expired`;\n\n const sessionTrackingConfig = config.sessionTracking;\n\n if (sessionTrackingConfig?.enabled) {\n const { fetchUserSession, storeUserSession } = getSessionManagerByConfig(sessionTrackingConfig);\n\n getUserSessionUpdater({ fetchUserSession, storeUserSession })({ forceSessionExtend: true });\n\n logDebug(`${SessionExpiredString} created new session.`);\n } else {\n logDebug(`${SessionExpiredString}.`);\n }\n }\n}\n"]}
@@ -1,8 +1,8 @@
1
1
  import { BaseInstrumentation, dateNow, EVENT_SESSION_EXTEND, EVENT_SESSION_RESUME, EVENT_SESSION_START, VERSION, } from '@grafana/faro-core';
2
2
  import { createSession } from '../../metas';
3
- import { isSampled } from './sessionManager';
3
+ import { getSessionManagerByConfig, isSampled } from './sessionManager';
4
4
  import { PersistentSessionsManager } from './sessionManager/PersistentSessionsManager';
5
- import { createUserSessionObject, getSessionManagerByConfig, isUserSessionValid, } from './sessionManager/sessionManagerUtils';
5
+ import { createUserSessionObject, isUserSessionValid } from './sessionManager/sessionManagerUtils';
6
6
  export class SessionInstrumentation extends BaseInstrumentation {
7
7
  constructor() {
8
8
  super(...arguments);
@@ -1 +1 @@
1
- {"version":3,"file":"instrumentation.js","sourceRoot":"","sources":["../../../../src/instrumentations/session/instrumentation.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,mBAAmB,EAC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AAqB,GAAG,IAAI,CAAC,MAAM,CAAC,eAAe,CAAC;QAE1D,IAAI,qBAAqB,aAArB,qBAAqB,uBAArB,qBAAqB,CAAE,OAAO,EAAE;YAClC,MAAM,cAAc,GAAG,yBAAyB,CAAC,qBAAqB,CAAC,CAAC;YAExE,IAAI,CAAC,sBAAsB,CAAC,cAAc,CAAC,CAAC;YAE5C,MAAM,EAAE,cAAc,EAAE,aAAa,EAAE,GAAG,IAAI,CAAC,oBAAoB,CAAC,cAAc,EAAE,qBAAqB,CAAC,CAAC;YAE3G,cAAc,CAAC,gBAAgB,CAAC,cAAc,CAAC,CAAC;YAEhD,MAAM,kBAAkB,GAAG,cAAc,CAAC,WAAW,CAAC;YAEtD,IAAI,CAAC,eAAe,GAAG,kBAAkB,CAAC;YAC1C,IAAI,CAAC,GAAG,CAAC,UAAU,CAAC,kBAAkB,CAAC,CAAC;YAExC,IAAI,aAAa,KAAK,mBAAmB,EAAE;gBACzC,IAAI,CAAC,GAAG,CAAC,SAAS,CAAC,mBAAmB,EAAE,EAAE,EAAE,SAAS,EAAE,EAAE,UAAU,EAAE,IAAI,EAAE,CAAC,CAAC;aAC9E;YAED,IAAI,aAAa,KAAK,oBAAoB,EAAE;gBAC1C,IAAI,CAAC,GAAG,CAAC,SAAS,CAAC,oBAAoB,EAAE,EAAE,EAAE,SAAS,EAAE,EAAE,UAAU,EAAE,IAAI,EAAE,CAAC,CAAC;aAC/E;SACF;QAED,IAAI,CAAC,KAAK,CAAC,WAAW,CAAC,IAAI,CAAC,qBAAqB,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;IAChE,CAAC;CACF","sourcesContent":["import {\n BaseInstrumentation,\n dateNow,\n EVENT_SESSION_EXTEND,\n EVENT_SESSION_RESUME,\n EVENT_SESSION_START,\n Meta,\n MetaSession,\n VERSION,\n} from '@grafana/faro-core';\nimport type { Config } from '@grafana/faro-core';\n\nimport type { TransportItem } from '../..';\nimport { createSession } from '../../metas';\n\nimport { type FaroUserSession, isSampled } from './sessionManager';\nimport { PersistentSessionsManager } from './sessionManager/PersistentSessionsManager';\nimport {\n createUserSessionObject,\n getSessionManagerByConfig,\n isUserSessionValid,\n} from './sessionManager/sessionManagerUtils';\nimport type { SessionManager } from './sessionManager/types';\n\ntype LifecycleType = typeof EVENT_SESSION_RESUME | typeof EVENT_SESSION_START;\n\nexport class SessionInstrumentation extends BaseInstrumentation {\n readonly name = '@grafana/faro-web-sdk:instrumentation-session';\n readonly version = VERSION;\n\n // previously notified session, to ensure we don't send session start\n // event twice for the same session\n private notifiedSession: MetaSession | undefined;\n\n private sendSessionStartEvent(meta: Meta): void {\n const session = meta.session;\n\n if (session && session.id !== this.notifiedSession?.id) {\n if (this.notifiedSession && this.notifiedSession.id === session.attributes?.['previousSession']) {\n this.api.pushEvent(EVENT_SESSION_EXTEND, {}, undefined, { skipDedupe: true });\n this.notifiedSession = session;\n return;\n }\n\n this.notifiedSession = session;\n // no need to add attributes and session id, they are included as part of meta\n // automatically\n this.api.pushEvent(EVENT_SESSION_START, {}, undefined, { skipDedupe: true });\n }\n }\n\n private createInitialSession(\n SessionManager: SessionManager,\n sessionsConfig: Required<Config>['sessionTracking']\n ): {\n initialSession: FaroUserSession;\n lifecycleType: LifecycleType;\n } {\n let userSession: FaroUserSession | null = SessionManager.fetchUserSession();\n\n if (sessionsConfig.persistent && sessionsConfig.maxSessionPersistenceTime && userSession) {\n const now = dateNow();\n const shouldClearPersistentSession = userSession.lastActivity < now - sessionsConfig.maxSessionPersistenceTime;\n\n if (shouldClearPersistentSession) {\n PersistentSessionsManager.removeUserSession();\n userSession = null;\n }\n }\n\n let lifecycleType: LifecycleType;\n let initialSession: FaroUserSession;\n\n if (isUserSessionValid(userSession)) {\n const sessionId = userSession?.sessionId;\n\n initialSession = createUserSessionObject({\n sessionId,\n isSampled: userSession!.isSampled || false,\n started: userSession?.started,\n });\n\n initialSession.sessionMeta = {\n id: sessionId,\n attributes: {\n ...sessionsConfig.session?.attributes,\n ...userSession?.sessionMeta?.attributes,\n // For valid resumed sessions we do not want to recalculate the sampling decision on each init phase.\n isSampled: initialSession.isSampled.toString(),\n },\n };\n\n lifecycleType = EVENT_SESSION_RESUME;\n } else {\n const sessionId = sessionsConfig.session?.id ?? createSession().id;\n\n initialSession = createUserSessionObject({\n sessionId,\n isSampled: isSampled(),\n });\n\n initialSession.sessionMeta = {\n id: sessionId,\n attributes: {\n isSampled: initialSession.isSampled.toString(),\n ...sessionsConfig.session?.attributes,\n },\n };\n\n lifecycleType = EVENT_SESSION_START;\n }\n\n return { initialSession, lifecycleType };\n }\n\n private registerBeforeSendHook(SessionManager: SessionManager) {\n const { updateSession } = new SessionManager();\n\n this.transports?.addBeforeSendHooks((item) => {\n updateSession();\n\n const attributes = item.meta.session?.attributes;\n\n if (attributes && attributes?.['isSampled'] === 'true') {\n let newItem: TransportItem = JSON.parse(JSON.stringify(item));\n\n const newAttributes = newItem.meta.session?.attributes;\n delete newAttributes?.['isSampled'];\n\n if (Object.keys(newAttributes ?? {}).length === 0) {\n delete newItem.meta.session?.attributes;\n }\n\n return newItem;\n }\n\n return null;\n });\n }\n\n initialize() {\n this.logDebug('init session instrumentation');\n\n const sessionTrackingConfig = this.config.sessionTracking;\n\n if (sessionTrackingConfig?.enabled) {\n const SessionManager = getSessionManagerByConfig(sessionTrackingConfig);\n\n this.registerBeforeSendHook(SessionManager);\n\n const { initialSession, lifecycleType } = this.createInitialSession(SessionManager, sessionTrackingConfig);\n\n SessionManager.storeUserSession(initialSession);\n\n const initialSessionMeta = initialSession.sessionMeta;\n\n this.notifiedSession = initialSessionMeta;\n this.api.setSession(initialSessionMeta);\n\n if (lifecycleType === EVENT_SESSION_START) {\n this.api.pushEvent(EVENT_SESSION_START, {}, undefined, { skipDedupe: true });\n }\n\n if (lifecycleType === EVENT_SESSION_RESUME) {\n this.api.pushEvent(EVENT_SESSION_RESUME, {}, undefined, { skipDedupe: true });\n }\n }\n\n this.metas.addListener(this.sendSessionStartEvent.bind(this));\n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,\n Meta,\n MetaSession,\n VERSION,\n} from '@grafana/faro-core';\nimport type { Config } from '@grafana/faro-core';\n\nimport type { TransportItem } from '../..';\nimport { createSession } from '../../metas';\n\nimport { type FaroUserSession, getSessionManagerByConfig, isSampled } from './sessionManager';\nimport { PersistentSessionsManager } from './sessionManager/PersistentSessionsManager';\nimport { createUserSessionObject, isUserSessionValid } from './sessionManager/sessionManagerUtils';\nimport type { SessionManager } from './sessionManager/types';\n\ntype LifecycleType = typeof EVENT_SESSION_RESUME | typeof EVENT_SESSION_START;\n\nexport class SessionInstrumentation extends BaseInstrumentation {\n readonly name = '@grafana/faro-web-sdk:instrumentation-session';\n readonly version = VERSION;\n\n // previously notified session, to ensure we don't send session start\n // event twice for the same session\n private notifiedSession: MetaSession | undefined;\n\n private sendSessionStartEvent(meta: Meta): void {\n const session = meta.session;\n\n if (session && session.id !== this.notifiedSession?.id) {\n if (this.notifiedSession && this.notifiedSession.id === session.attributes?.['previousSession']) {\n this.api.pushEvent(EVENT_SESSION_EXTEND, {}, undefined, { skipDedupe: true });\n this.notifiedSession = session;\n return;\n }\n\n this.notifiedSession = session;\n // no need to add attributes and session id, they are included as part of meta\n // automatically\n this.api.pushEvent(EVENT_SESSION_START, {}, undefined, { skipDedupe: true });\n }\n }\n\n private createInitialSession(\n SessionManager: SessionManager,\n sessionsConfig: Required<Config>['sessionTracking']\n ): {\n initialSession: FaroUserSession;\n lifecycleType: LifecycleType;\n } {\n let userSession: FaroUserSession | null = SessionManager.fetchUserSession();\n\n if (sessionsConfig.persistent && sessionsConfig.maxSessionPersistenceTime && userSession) {\n const now = dateNow();\n const shouldClearPersistentSession = userSession.lastActivity < now - sessionsConfig.maxSessionPersistenceTime;\n\n if (shouldClearPersistentSession) {\n PersistentSessionsManager.removeUserSession();\n userSession = null;\n }\n }\n\n let lifecycleType: LifecycleType;\n let initialSession: FaroUserSession;\n\n if (isUserSessionValid(userSession)) {\n const sessionId = userSession?.sessionId;\n\n initialSession = createUserSessionObject({\n sessionId,\n isSampled: userSession!.isSampled || false,\n started: userSession?.started,\n });\n\n initialSession.sessionMeta = {\n id: sessionId,\n attributes: {\n ...sessionsConfig.session?.attributes,\n ...userSession?.sessionMeta?.attributes,\n // For valid resumed sessions we do not want to recalculate the sampling decision on each init phase.\n isSampled: initialSession.isSampled.toString(),\n },\n };\n\n lifecycleType = EVENT_SESSION_RESUME;\n } else {\n const sessionId = sessionsConfig.session?.id ?? createSession().id;\n\n initialSession = createUserSessionObject({\n sessionId,\n isSampled: isSampled(),\n });\n\n initialSession.sessionMeta = {\n id: sessionId,\n attributes: {\n isSampled: initialSession.isSampled.toString(),\n ...sessionsConfig.session?.attributes,\n },\n };\n\n lifecycleType = EVENT_SESSION_START;\n }\n\n return { initialSession, lifecycleType };\n }\n\n private registerBeforeSendHook(SessionManager: SessionManager) {\n const { updateSession } = new SessionManager();\n\n this.transports?.addBeforeSendHooks((item) => {\n updateSession();\n\n const attributes = item.meta.session?.attributes;\n\n if (attributes && attributes?.['isSampled'] === 'true') {\n let newItem: TransportItem = JSON.parse(JSON.stringify(item));\n\n const newAttributes = newItem.meta.session?.attributes;\n delete newAttributes?.['isSampled'];\n\n if (Object.keys(newAttributes ?? {}).length === 0) {\n delete newItem.meta.session?.attributes;\n }\n\n return newItem;\n }\n\n return null;\n });\n }\n\n initialize() {\n this.logDebug('init session instrumentation');\n\n const sessionTrackingConfig = this.config.sessionTracking;\n\n if (sessionTrackingConfig?.enabled) {\n const SessionManager = getSessionManagerByConfig(sessionTrackingConfig);\n\n this.registerBeforeSendHook(SessionManager);\n\n const { initialSession, lifecycleType } = this.createInitialSession(SessionManager, sessionTrackingConfig);\n\n SessionManager.storeUserSession(initialSession);\n\n const initialSessionMeta = initialSession.sessionMeta;\n\n this.notifiedSession = initialSessionMeta;\n this.api.setSession(initialSessionMeta);\n\n if (lifecycleType === EVENT_SESSION_START) {\n this.api.pushEvent(EVENT_SESSION_START, {}, undefined, { skipDedupe: true });\n }\n\n if (lifecycleType === EVENT_SESSION_RESUME) {\n this.api.pushEvent(EVENT_SESSION_RESUME, {}, undefined, { skipDedupe: true });\n }\n }\n\n this.metas.addListener(this.sendSessionStartEvent.bind(this));\n }\n}\n"]}
@@ -0,0 +1,6 @@
1
+ import { PersistentSessionsManager } from './PersistentSessionsManager';
2
+ import { VolatileSessionsManager } from './VolatileSessionManager';
3
+ export function getSessionManagerByConfig(sessionTrackingConfig) {
4
+ return (sessionTrackingConfig === null || sessionTrackingConfig === void 0 ? void 0 : sessionTrackingConfig.persistent) ? PersistentSessionsManager : VolatileSessionsManager;
5
+ }
6
+ //# sourceMappingURL=getSessionManagerByConfig.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"getSessionManagerByConfig.js","sourceRoot":"","sources":["../../../../../src/instrumentations/session/sessionManager/getSessionManagerByConfig.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,yBAAyB,EAAE,MAAM,6BAA6B,CAAC;AAExE,OAAO,EAAE,uBAAuB,EAAE,MAAM,0BAA0B,CAAC;AAEnE,MAAM,UAAU,yBAAyB,CAAC,qBAAgD;IACxF,OAAO,CAAA,qBAAqB,aAArB,qBAAqB,uBAArB,qBAAqB,CAAE,UAAU,EAAC,CAAC,CAAC,yBAAyB,CAAC,CAAC,CAAC,uBAAuB,CAAC;AACjG,CAAC","sourcesContent":["import type { Config } from '@grafana/faro-core';\n\nimport { PersistentSessionsManager } from './PersistentSessionsManager';\nimport type { SessionManager } from './types';\nimport { VolatileSessionsManager } from './VolatileSessionManager';\n\nexport function getSessionManagerByConfig(sessionTrackingConfig: Config['sessionTracking']): SessionManager {\n return sessionTrackingConfig?.persistent ? PersistentSessionsManager : VolatileSessionsManager;\n}\n"]}
@@ -2,4 +2,5 @@ export { PersistentSessionsManager } from './PersistentSessionsManager';
2
2
  export { VolatileSessionsManager } from './VolatileSessionManager';
3
3
  export { MAX_SESSION_PERSISTENCE_TIME, MAX_SESSION_PERSISTENCE_TIME_BUFFER, SESSION_EXPIRATION_TIME, SESSION_INACTIVITY_TIME, STORAGE_KEY, STORAGE_UPDATE_DELAY, defaultSessionTrackingConfig, } from './sessionConstants';
4
4
  export { isSampled } from './sampling';
5
+ export { getSessionManagerByConfig } from './getSessionManagerByConfig';
5
6
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../src/instrumentations/session/sessionManager/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,yBAAyB,EAAE,MAAM,6BAA6B,CAAC;AACxE,OAAO,EAAE,uBAAuB,EAAE,MAAM,0BAA0B,CAAC;AAEnE,OAAO,EACL,4BAA4B,EAC5B,mCAAmC,EACnC,uBAAuB,EACvB,uBAAuB,EACvB,WAAW,EACX,oBAAoB,EACpB,4BAA4B,GAC7B,MAAM,oBAAoB,CAAC;AAE5B,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC","sourcesContent":["export { PersistentSessionsManager } from './PersistentSessionsManager';\nexport { VolatileSessionsManager } from './VolatileSessionManager';\n\nexport {\n MAX_SESSION_PERSISTENCE_TIME,\n MAX_SESSION_PERSISTENCE_TIME_BUFFER,\n SESSION_EXPIRATION_TIME,\n SESSION_INACTIVITY_TIME,\n STORAGE_KEY,\n STORAGE_UPDATE_DELAY,\n defaultSessionTrackingConfig,\n} from './sessionConstants';\n\nexport { isSampled } from './sampling';\n\nexport type { FaroUserSession } from './types';\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../src/instrumentations/session/sessionManager/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,yBAAyB,EAAE,MAAM,6BAA6B,CAAC;AACxE,OAAO,EAAE,uBAAuB,EAAE,MAAM,0BAA0B,CAAC;AAEnE,OAAO,EACL,4BAA4B,EAC5B,mCAAmC,EACnC,uBAAuB,EACvB,uBAAuB,EACvB,WAAW,EACX,oBAAoB,EACpB,4BAA4B,GAC7B,MAAM,oBAAoB,CAAC;AAE5B,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAIvC,OAAO,EAAE,yBAAyB,EAAE,MAAM,6BAA6B,CAAC","sourcesContent":["export { PersistentSessionsManager } from './PersistentSessionsManager';\nexport { VolatileSessionsManager } from './VolatileSessionManager';\n\nexport {\n MAX_SESSION_PERSISTENCE_TIME,\n MAX_SESSION_PERSISTENCE_TIME_BUFFER,\n SESSION_EXPIRATION_TIME,\n SESSION_INACTIVITY_TIME,\n STORAGE_KEY,\n STORAGE_UPDATE_DELAY,\n defaultSessionTrackingConfig,\n} from './sessionConstants';\n\nexport { isSampled } from './sampling';\n\nexport type { FaroUserSession } from './types';\n\nexport { getSessionManagerByConfig } from './getSessionManagerByConfig';\n"]}
@@ -1,6 +1,5 @@
1
1
  import { dateNow, faro, genShortID } from '@grafana/faro-core';
2
2
  import { isLocalStorageAvailable, isSessionStorageAvailable } from '../../../utils';
3
- import { PersistentSessionsManager, VolatileSessionsManager } from '.';
4
3
  import { isSampled } from './sampling';
5
4
  import { SESSION_EXPIRATION_TIME, SESSION_INACTIVITY_TIME } from './sessionConstants';
6
5
  export function createUserSessionObject({ sessionId, started, lastActivity, isSampled = true, } = {}) {
@@ -60,7 +59,4 @@ export function addSessionMetadataToNextSession(newSession, previousSession) {
60
59
  } });
61
60
  return sessionWithMeta;
62
61
  }
63
- export function getSessionManagerByConfig(sessionTrackingConfig) {
64
- return (sessionTrackingConfig === null || sessionTrackingConfig === void 0 ? void 0 : sessionTrackingConfig.persistent) ? PersistentSessionsManager : VolatileSessionsManager;
65
- }
66
62
  //# sourceMappingURL=sessionManagerUtils.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"sessionManagerUtils.js","sourceRoot":"","sources":["../../../../../src/instrumentations/session/sessionManager/sessionManagerUtils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAG/D,OAAO,EAAE,uBAAuB,EAAE,yBAAyB,EAAE,MAAM,gBAAgB,C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,SAAS;YACxB,UAAU,8DACL,MAAA,MAAA,IAAI,CAAC,MAAM,CAAC,eAAe,0CAAE,OAAO,0CAAE,UAAU,GAChD,CAAC,MAAA,MAAA,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,OAAO,0CAAE,UAAU,mCAAI,EAAE,CAAC,GAC5C,CAAC,eAAe,IAAI,IAAI,CAAC,CAAC,CAAC,EAAE,eAAe,EAAE,eAAe,CAAC,SAAS,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,KAClF,SAAS,EAAE,UAAU,CAAC,SAAS,CAAC,QAAQ,EAAE,GAC3C;SACF,GACF,CAAC;IAEF,OAAO,eAAe,CAAC;AACzB,CAAC;AAED,MAAM,UAAU,yBAAyB,CAAC,qBAAgD;IACxF,OAAO,CAAA,qBAAqB,aAArB,qBAAqB,uBAArB,qBAAqB,CAAE,UAAU,EAAC,CAAC,CAAC,yBAAyB,CAAC,CAAC,CAAC,uBAAuB,CAAC;AACjG,CAAC","sourcesContent":["import { dateNow, faro, genShortID } from '@grafana/faro-core';\nimport type { Config } from '@grafana/faro-core';\n\nimport { isLocalStorageAvailable, isSessionStorageAvailable } from '../../../utils';\n\nimport { PersistentSessionsManager, VolatileSessionsManager } from '.';\nimport { isSampled } from './sampling';\nimport { SESSION_EXPIRATION_TIME, SESSION_INACTIVITY_TIME } from './sessionConstants';\nimport type { FaroUserSession, SessionManager } from './types';\n\ntype CreateUserSessionObjectParams = {\n sessionId?: string;\n started?: number;\n lastActivity?: number;\n isSampled?: boolean;\n};\n\nexport function createUserSessionObject({\n sessionId,\n started,\n lastActivity,\n isSampled = true,\n}: CreateUserSessionObjectParams = {}): FaroUserSession {\n const now = dateNow();\n\n const generateSessionId = faro.config?.sessionTracking?.generateSessionId;\n\n if (sessionId == null) {\n sessionId = typeof generateSessionId === 'function' ? generateSessionId() : genShortID();\n }\n\n return {\n sessionId,\n lastActivity: lastActivity ?? now,\n started: started ?? now,\n isSampled: isSampled,\n };\n}\n\nexport function isUserSessionValid(session: FaroUserSession | null): boolean {\n if (session == null) {\n return false;\n }\n\n const now = dateNow();\n const lifetimeValid = now - session.started < SESSION_EXPIRATION_TIME;\n\n if (!lifetimeValid) {\n return false;\n }\n\n const inactivityPeriodValid = now - session.lastActivity < SESSION_INACTIVITY_TIME;\n return inactivityPeriodValid;\n}\n\ntype GetUserSessionUpdaterParams = {\n storeUserSession: (session: FaroUserSession) => void;\n fetchUserSession: () => FaroUserSession | null;\n};\n\ntype UpdateSessionParams = { forceSessionExtend: boolean };\n\nexport function getUserSessionUpdater({\n fetchUserSession,\n storeUserSession,\n}: GetUserSessionUpdaterParams): (options?: UpdateSessionParams) => void {\n return function updateSession({ forceSessionExtend } = { forceSessionExtend: false }): void {\n if (!fetchUserSession || !storeUserSession) {\n return;\n }\n\n const sessionTrackingConfig = faro.config.sessionTracking;\n const isPersistentSessions = sessionTrackingConfig?.persistent;\n\n if ((isPersistentSessions && !isLocalStorageAvailable) || (!isPersistentSessions && !isSessionStorageAvailable)) {\n return;\n }\n\n const sessionFromStorage = fetchUserSession();\n\n if (forceSessionExtend === false && isUserSessionValid(sessionFromStorage)) {\n storeUserSession({ ...sessionFromStorage!, lastActivity: dateNow() });\n } else {\n let newSession = addSessionMetadataToNextSession(\n createUserSessionObject({ isSampled: isSampled() }),\n sessionFromStorage\n );\n\n storeUserSession(newSession);\n\n faro.api?.setSession(newSession.sessionMeta);\n sessionTrackingConfig?.onSessionChange?.(sessionFromStorage?.sessionMeta ?? null, newSession.sessionMeta!);\n }\n };\n}\n\nexport function addSessionMetadataToNextSession(newSession: FaroUserSession, previousSession: FaroUserSession | null) {\n const sessionWithMeta: Required<FaroUserSession> = {\n ...newSession,\n sessionMeta: {\n id: newSession.sessionId,\n attributes: {\n ...faro.config.sessionTracking?.session?.attributes,\n ...(faro.metas.value.session?.attributes ?? {}),\n ...(previousSession != null ? { previousSession: previousSession.sessionId } : {}),\n isSampled: newSession.isSampled.toString(),\n },\n },\n };\n\n return sessionWithMeta;\n}\n\nexport function getSessionManagerByConfig(sessionTrackingConfig: Config['sessionTracking']): SessionManager {\n return sessionTrackingConfig?.persistent ? PersistentSessionsManager : VolatileSessionsManager;\n}\n"]}
1
+ {"version":3,"file":"sessionManagerUtils.js","sourceRoot":"","sources":["../../../../../src/instrumentations/session/sessionManager/sessionManagerUtils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAE/D,OAAO,EAAE,uBAAuB,EAAE,yBAAyB,EAAE,MAAM,gBAAgB,CAAC;AAEpF,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AACvC,OAAO,EAAE,uBAAuB,EAAE,uBAAuB,EAAE,MAAM,oBAAoB,CAAC;AAUtF,MAAM,UAAU,uBAAuB,CAAC,EACtC,SAAS,EACT,OAAO,EACP,YAAY,EACZ,SAAS,GAAG,IAAI,MACiB,EAAE;;IACnC,MAAM,GAAG,GAAG,OAAO,EAAE,CAAC;IAEtB,MAAM,iBAAiB,GAAG,MAAA,MAAA,IAAI,CAAC,MAAM,0CAAE,eAAe,0CAAE,iBAAiB,CAAC;IAE1E,IAAI,SAAS,IAAI,IAAI,EAAE;QACrB,SAAS,GAAG,OAAO,iBAAiB,KAAK,UAAU,CAAC,CAAC,CAAC,iBAAiB,EAAE,CAAC,CAAC,CAAC,UAAU,EAAE,CAAC;KAC1F;IAED,OAAO;QACL,SAAS;QACT,YAAY,EAAE,YAAY,aAAZ,YAAY,cAAZ,YAAY,GAAI,GAAG;QACjC,OAAO,EAAE,OAAO,aAAP,OAAO,cAAP,OAAO,GAAI,GAAG;QACvB,SAAS,EAAE,SAAS;KACrB,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,kBAAkB,CAAC,OAA+B;IAChE,IAAI,OAAO,IAAI,IAAI,EAAE;QACnB,OAAO,KAAK,CAAC;KACd;IAED,MAAM,GAAG,GAAG,OAAO,EAAE,CAAC;IACtB,MAAM,aAAa,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B,CAAE,eAAe,sEAAG,MAAA,kBAAkB,aAAlB,kBAAkB,uBAAlB,kBAAkB,CAAE,WAAW,mCAAI,IAAI,EAAE,UAAU,CAAC,WAAY,CAAC,CAAC;SAC5G;IACH,CAAC,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,+BAA+B,CAAC,UAA2B,EAAE,eAAuC;;IAClH,MAAM,eAAe,mCAChB,UAAU,KACb,WAAW,EAAE;YACX,EAAE,EAAE,UAAU,CAAC,SAAS;YACxB,UAAU,8DACL,MAAA,MAAA,IAAI,CAAC,MAAM,CAAC,eAAe,0CAAE,OAAO,0CAAE,UAAU,GAChD,CAAC,MAAA,MAAA,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,OAAO,0CAAE,UAAU,mCAAI,EAAE,CAAC,GAC5C,CAAC,eAAe,IAAI,IAAI,CAAC,CAAC,CAAC,EAAE,eAAe,EAAE,eAAe,CAAC,SAAS,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,KAClF,SAAS,EAAE,UAAU,CAAC,SAAS,CAAC,QAAQ,EAAE,GAC3C;SACF,GACF,CAAC;IAEF,OAAO,eAAe,CAAC;AACzB,CAAC","sourcesContent":["import { dateNow, faro, genShortID } from '@grafana/faro-core';\n\nimport { isLocalStorageAvailable, isSessionStorageAvailable } from '../../../utils';\n\nimport { isSampled } from './sampling';\nimport { SESSION_EXPIRATION_TIME, SESSION_INACTIVITY_TIME } from './sessionConstants';\nimport type { FaroUserSession } from './types';\n\ntype CreateUserSessionObjectParams = {\n sessionId?: string;\n started?: number;\n lastActivity?: number;\n isSampled?: boolean;\n};\n\nexport function createUserSessionObject({\n sessionId,\n started,\n lastActivity,\n isSampled = true,\n}: CreateUserSessionObjectParams = {}): FaroUserSession {\n const now = dateNow();\n\n const generateSessionId = faro.config?.sessionTracking?.generateSessionId;\n\n if (sessionId == null) {\n sessionId = typeof generateSessionId === 'function' ? generateSessionId() : genShortID();\n }\n\n return {\n sessionId,\n lastActivity: lastActivity ?? now,\n started: started ?? now,\n isSampled: isSampled,\n };\n}\n\nexport function isUserSessionValid(session: FaroUserSession | null): boolean {\n if (session == null) {\n return false;\n }\n\n const now = dateNow();\n const lifetimeValid = now - session.started < SESSION_EXPIRATION_TIME;\n\n if (!lifetimeValid) {\n return false;\n }\n\n const inactivityPeriodValid = now - session.lastActivity < SESSION_INACTIVITY_TIME;\n return inactivityPeriodValid;\n}\n\ntype GetUserSessionUpdaterParams = {\n storeUserSession: (session: FaroUserSession) => void;\n fetchUserSession: () => FaroUserSession | null;\n};\n\ntype UpdateSessionParams = { forceSessionExtend: boolean };\n\nexport function getUserSessionUpdater({\n fetchUserSession,\n storeUserSession,\n}: GetUserSessionUpdaterParams): (options?: UpdateSessionParams) => void {\n return function updateSession({ forceSessionExtend } = { forceSessionExtend: false }): void {\n if (!fetchUserSession || !storeUserSession) {\n return;\n }\n\n const sessionTrackingConfig = faro.config.sessionTracking;\n const isPersistentSessions = sessionTrackingConfig?.persistent;\n\n if ((isPersistentSessions && !isLocalStorageAvailable) || (!isPersistentSessions && !isSessionStorageAvailable)) {\n return;\n }\n\n const sessionFromStorage = fetchUserSession();\n\n if (forceSessionExtend === false && isUserSessionValid(sessionFromStorage)) {\n storeUserSession({ ...sessionFromStorage!, lastActivity: dateNow() });\n } else {\n let newSession = addSessionMetadataToNextSession(\n createUserSessionObject({ isSampled: isSampled() }),\n sessionFromStorage\n );\n\n storeUserSession(newSession);\n\n faro.api?.setSession(newSession.sessionMeta);\n sessionTrackingConfig?.onSessionChange?.(sessionFromStorage?.sessionMeta ?? null, newSession.sessionMeta!);\n }\n };\n}\n\nexport function addSessionMetadataToNextSession(newSession: FaroUserSession, previousSession: FaroUserSession | null) {\n const sessionWithMeta: Required<FaroUserSession> = {\n ...newSession,\n sessionMeta: {\n id: newSession.sessionId,\n attributes: {\n ...faro.config.sessionTracking?.session?.attributes,\n ...(faro.metas.value.session?.attributes ?? {}),\n ...(previousSession != null ? { previousSession: previousSession.sessionId } : {}),\n isSampled: newSession.isSampled.toString(),\n },\n },\n };\n\n return sessionWithMeta;\n}\n"]}
@@ -19,7 +19,8 @@ var __rest = (this && this.__rest) || function (s, e) {
19
19
  return t;
20
20
  };
21
21
  import { BaseTransport, createPromiseBuffer, getTransportBody, noop, VERSION, } from '@grafana/faro-core';
22
- import { getSessionManagerByConfig, getUserSessionUpdater, } from '../../instrumentations/session/sessionManager/sessionManagerUtils';
22
+ import { getSessionManagerByConfig } from '../../instrumentations/session/sessionManager';
23
+ import { getUserSessionUpdater } from '../../instrumentations/session/sessionManager/sessionManagerUtils';
23
24
  const DEFAULT_BUFFER_SIZE = 30;
24
25
  const DEFAULT_CONCURRENCY = 5; // chrome supports 10 total, firefox 17
25
26
  const DEFAULT_RATE_LIMIT_BACKOFF_MS = 5000;
@@ -1 +1 @@
1
- {"version":3,"file":"transport.js","sourceRoot":"","sources":["../../../../src/transports/fetch/transport.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA,OAAO,EAEL,aAAa,EACb,mBAAmB,EACnB,gBAAgB,EAChB,IAAI,EAEJ,OAAO,GACR,MAAM,oBAAoB,CAAC;AAG5B,OAAO,EACL,yBAAyB,EACzB,qBAAqB,GACtB,MAAM,mEAAmE,CAAC;AAI3E,MAAM,mBAAmB,GAAG,EAAE,CAAC;AAC/B,MAAM,mBAAmB,GAAG,CAAC,CAAC,CAAC,uCAAuC;AACtE,MAAM,6BAA6B,GAAG,IAAI,CAAC;AAE3C,MAAM,sBAAsB,GAAG,KAAK,CAAC;AACrC,MAAM,iBAAiB,GAAG,GAAG,CAAC;AAC9B,MAAM,QAAQ,GAAG,GAAG,CAAC;AAErB,MAAM,OAAO,cAAe,SAAQ,aAAa;IAU/C,YAAoB,OAA8B;;QAChD,KAAK,EAAE,CAAC;QADU,YAAO,GAAP,OAAO,CAAuB;QATzC,SAAI,GAAG,uCAAuC,CAAC;QAC/C,YAAO,GAAG,OAAO,CAAC;QAMnB,kBAAa,GAAS,IAAI,IAAI,EAAE,C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BAAqB,CAAE,OAAO,EAAE;YAClC,MAAM,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,GAAG,yBAAyB,CAAC,qBAAqB,CAAC,CAAC;YAEhG,qBAAqB,CAAC,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,CAAC,CAAC,EAAE,kBAAkB,EAAE,IAAI,EAAE,CAAC,CAAC;YAE5F,QAAQ,CAAC,GAAG,oBAAoB,uBAAuB,CAAC,CAAC;SAC1D;aAAM;YACL,QAAQ,CAAC,GAAG,oBAAoB,GAAG,CAAC,CAAC;SACtC;IACH,CAAC;CACF","sourcesContent":["import {\n BaseExtension,\n BaseTransport,\n createPromiseBuffer,\n getTransportBody,\n noop,\n PromiseBuffer,\n VERSION,\n} from '@grafana/faro-core';\nimport type { Config, Patterns, TransportItem } from '@grafana/faro-core';\n\nimport {\n getSessionManagerByConfig,\n getUserSessionUpdater,\n} from '../../instrumentations/session/sessionManager/sessionManagerUtils';\n\nimport type { FetchTransportOptions } from './types';\n\nconst DEFAULT_BUFFER_SIZE = 30;\nconst DEFAULT_CONCURRENCY = 5; // chrome supports 10 total, firefox 17\nconst DEFAULT_RATE_LIMIT_BACKOFF_MS = 5000;\n\nconst BEACON_BODY_SIZE_LIMIT = 60000;\nconst TOO_MANY_REQUESTS = 429;\nconst ACCEPTED = 202;\n\nexport class FetchTransport extends BaseTransport {\n readonly name = '@grafana/faro-web-sdk:transport-fetch';\n readonly version = VERSION;\n\n promiseBuffer: PromiseBuffer<Response | void>;\n\n private readonly rateLimitBackoffMs: number;\n private readonly getNow: () => number;\n private disabledUntil: Date = new Date();\n\n constructor(private options: FetchTransportOptions) {\n super();\n\n this.rateLimitBackoffMs = options.defaultRateLimitBackoffMs ?? DEFAULT_RATE_LIMIT_BACKOFF_MS;\n this.getNow = options.getNow ?? (() => Date.now());\n\n this.promiseBuffer = createPromiseBuffer({\n size: options.bufferSize ?? DEFAULT_BUFFER_SIZE,\n concurrency: options.concurrency ?? DEFAULT_CONCURRENCY,\n });\n }\n\n async send(items: TransportItem[]): Promise<void> {\n try {\n if (this.disabledUntil > new Date(this.getNow())) {\n this.logWarn(`Dropping transport item due to too many requests. Backoff until ${this.disabledUntil}`);\n\n return Promise.resolve();\n }\n\n await this.promiseBuffer.add(() => {\n const body = JSON.stringify(getTransportBody(items));\n\n const { url, requestOptions, apiKey } = this.options;\n\n const { headers, ...restOfRequestOptions } = requestOptions ?? {};\n\n let sessionId;\n const sessionMeta = this.metas.value.session;\n if (sessionMeta != null) {\n sessionId = sessionMeta.id;\n }\n\n return fetch(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...(headers ?? {}),\n ...(apiKey ? { 'x-api-key': apiKey } : {}),\n ...(sessionId ? { 'x-faro-session-id': sessionId } : {}),\n },\n body,\n keepalive: body.length <= BEACON_BODY_SIZE_LIMIT,\n ...(restOfRequestOptions ?? {}),\n })\n .then(async (response) => {\n if (response.status === ACCEPTED) {\n const sessionExpired = response.headers.get('X-Faro-Session-Status') === 'invalid';\n\n if (sessionExpired) {\n this.extendFaroSession(this.config, this.logDebug);\n }\n }\n\n if (response.status === TOO_MANY_REQUESTS) {\n this.disabledUntil = this.getRetryAfterDate(response);\n this.logWarn(`Too many requests, backing off until ${this.disabledUntil}`);\n }\n\n // read the body so the connection can be closed\n response.text().catch(noop);\n return response;\n })\n .catch((err) => {\n this.logError('Failed sending payload to the receiver\\n', JSON.parse(body), err);\n });\n });\n } catch (err) {\n this.logError(err);\n }\n }\n\n override getIgnoreUrls(): Patterns {\n return ([this.options.url] as Patterns).concat(this.config.ignoreUrls ?? []);\n }\n\n override isBatched(): boolean {\n return true;\n }\n\n private getRetryAfterDate(response: Response): Date {\n const now = this.getNow();\n const retryAfterHeader = response.headers.get('Retry-After');\n\n if (retryAfterHeader) {\n const delay = Number(retryAfterHeader);\n\n if (!isNaN(delay)) {\n return new Date(delay * 1000 + now);\n }\n\n const date = Date.parse(retryAfterHeader);\n\n if (!isNaN(date)) {\n return new Date(date);\n }\n }\n\n return new Date(now + this.rateLimitBackoffMs);\n }\n\n private extendFaroSession(config: Config, logDebug: BaseExtension['logDebug']) {\n const SessionExpiredString = `Session expired`;\n\n const sessionTrackingConfig = config.sessionTracking;\n\n if (sessionTrackingConfig?.enabled) {\n const { fetchUserSession, storeUserSession } = getSessionManagerByConfig(sessionTrackingConfig);\n\n getUserSessionUpdater({ fetchUserSession, storeUserSession })({ forceSessionExtend: true });\n\n logDebug(`${SessionExpiredString} created new session.`);\n } else {\n logDebug(`${SessionExpiredString}.`);\n }\n }\n}\n"]}
1
+ {"version":3,"file":"transport.js","sourceRoot":"","sources":["../../../../src/transports/fetch/transport.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA,OAAO,EAEL,aAAa,EACb,mBAAmB,EACnB,gBAAgB,EAChB,IAAI,EAEJ,OAAO,GACR,MAAM,oBAAoB,CAAC;AAG5B,OAAO,EAAE,yBAAyB,EAAE,MAAM,+CAA+C,CAAC;AAC1F,OAAO,EAAE,qBAAqB,EAAE,MAAM,mEAAmE,CAAC;AAI1G,MAAM,mBAAmB,GAAG,EAAE,CAAC;AAC/B,MAAM,mBAAmB,GAAG,CAAC,CAAC,CAAC,uCAAuC;AACtE,MAAM,6BAA6B,GAAG,IAAI,CAAC;AAE3C,MAAM,sBAAsB,GAAG,KAAK,CAAC;AACrC,MAAM,iBAAiB,GAAG,GAAG,CAAC;AAC9B,MAAM,QAAQ,GAAG,GAAG,CAAC;AAErB,MAAM,OAAO,cAAe,SAAQ,aAAa;IAU/C,YAAoB,OAA8B;;QAChD,KAAK,EAAE,CAAC;QADU,YAAO,GAAP,OAAO,CAAuB;QATzC,SAAI,GAAG,uCAAuC,CAAC;QAC/C,YAAO,GAAG,OAAO,CAAC;QAMnB,kBAAa,GAAS,IAAI,IAAI,EAAE,CAAC;QAKvC,IAAI,CAAC,kBAAkB,GAAG,MAAA,OAAO,CAAC,yBAAyB,mCAAI,6BAA6B,CAAC;QAC7F,IAAI,CAAC,MAA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AC;YAEhG,qBAAqB,CAAC,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,CAAC,CAAC,EAAE,kBAAkB,EAAE,IAAI,EAAE,CAAC,CAAC;YAE5F,QAAQ,CAAC,GAAG,oBAAoB,uBAAuB,CAAC,CAAC;SAC1D;aAAM;YACL,QAAQ,CAAC,GAAG,oBAAoB,GAAG,CAAC,CAAC;SACtC;IACH,CAAC;CACF","sourcesContent":["import {\n BaseExtension,\n BaseTransport,\n createPromiseBuffer,\n getTransportBody,\n noop,\n PromiseBuffer,\n VERSION,\n} from '@grafana/faro-core';\nimport type { Config, Patterns, TransportItem } from '@grafana/faro-core';\n\nimport { getSessionManagerByConfig } from '../../instrumentations/session/sessionManager';\nimport { getUserSessionUpdater } from '../../instrumentations/session/sessionManager/sessionManagerUtils';\n\nimport type { FetchTransportOptions } from './types';\n\nconst DEFAULT_BUFFER_SIZE = 30;\nconst DEFAULT_CONCURRENCY = 5; // chrome supports 10 total, firefox 17\nconst DEFAULT_RATE_LIMIT_BACKOFF_MS = 5000;\n\nconst BEACON_BODY_SIZE_LIMIT = 60000;\nconst TOO_MANY_REQUESTS = 429;\nconst ACCEPTED = 202;\n\nexport class FetchTransport extends BaseTransport {\n readonly name = '@grafana/faro-web-sdk:transport-fetch';\n readonly version = VERSION;\n\n promiseBuffer: PromiseBuffer<Response | void>;\n\n private readonly rateLimitBackoffMs: number;\n private readonly getNow: () => number;\n private disabledUntil: Date = new Date();\n\n constructor(private options: FetchTransportOptions) {\n super();\n\n this.rateLimitBackoffMs = options.defaultRateLimitBackoffMs ?? DEFAULT_RATE_LIMIT_BACKOFF_MS;\n this.getNow = options.getNow ?? (() => Date.now());\n\n this.promiseBuffer = createPromiseBuffer({\n size: options.bufferSize ?? DEFAULT_BUFFER_SIZE,\n concurrency: options.concurrency ?? DEFAULT_CONCURRENCY,\n });\n }\n\n async send(items: TransportItem[]): Promise<void> {\n try {\n if (this.disabledUntil > new Date(this.getNow())) {\n this.logWarn(`Dropping transport item due to too many requests. Backoff until ${this.disabledUntil}`);\n\n return Promise.resolve();\n }\n\n await this.promiseBuffer.add(() => {\n const body = JSON.stringify(getTransportBody(items));\n\n const { url, requestOptions, apiKey } = this.options;\n\n const { headers, ...restOfRequestOptions } = requestOptions ?? {};\n\n let sessionId;\n const sessionMeta = this.metas.value.session;\n if (sessionMeta != null) {\n sessionId = sessionMeta.id;\n }\n\n return fetch(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...(headers ?? {}),\n ...(apiKey ? { 'x-api-key': apiKey } : {}),\n ...(sessionId ? { 'x-faro-session-id': sessionId } : {}),\n },\n body,\n keepalive: body.length <= BEACON_BODY_SIZE_LIMIT,\n ...(restOfRequestOptions ?? {}),\n })\n .then(async (response) => {\n if (response.status === ACCEPTED) {\n const sessionExpired = response.headers.get('X-Faro-Session-Status') === 'invalid';\n\n if (sessionExpired) {\n this.extendFaroSession(this.config, this.logDebug);\n }\n }\n\n if (response.status === TOO_MANY_REQUESTS) {\n this.disabledUntil = this.getRetryAfterDate(response);\n this.logWarn(`Too many requests, backing off until ${this.disabledUntil}`);\n }\n\n // read the body so the connection can be closed\n response.text().catch(noop);\n return response;\n })\n .catch((err) => {\n this.logError('Failed sending payload to the receiver\\n', JSON.parse(body), err);\n });\n });\n } catch (err) {\n this.logError(err);\n }\n }\n\n override getIgnoreUrls(): Patterns {\n return ([this.options.url] as Patterns).concat(this.config.ignoreUrls ?? []);\n }\n\n override isBatched(): boolean {\n return true;\n }\n\n private getRetryAfterDate(response: Response): Date {\n const now = this.getNow();\n const retryAfterHeader = response.headers.get('Retry-After');\n\n if (retryAfterHeader) {\n const delay = Number(retryAfterHeader);\n\n if (!isNaN(delay)) {\n return new Date(delay * 1000 + now);\n }\n\n const date = Date.parse(retryAfterHeader);\n\n if (!isNaN(date)) {\n return new Date(date);\n }\n }\n\n return new Date(now + this.rateLimitBackoffMs);\n }\n\n private extendFaroSession(config: Config, logDebug: BaseExtension['logDebug']) {\n const SessionExpiredString = `Session expired`;\n\n const sessionTrackingConfig = config.sessionTracking;\n\n if (sessionTrackingConfig?.enabled) {\n const { fetchUserSession, storeUserSession } = getSessionManagerByConfig(sessionTrackingConfig);\n\n getUserSessionUpdater({ fetchUserSession, storeUserSession })({ forceSessionExtend: true });\n\n logDebug(`${SessionExpiredString} created new session.`);\n } else {\n logDebug(`${SessionExpiredString}.`);\n }\n }\n}\n"]}
@@ -3,7 +3,7 @@ import type { ConsoleInstrumentationOptions } from './types';
3
3
  export declare class ConsoleInstrumentation extends BaseInstrumentation {
4
4
  private options;
5
5
  readonly name = "@grafana/faro-web-sdk:instrumentation-console";
6
- readonly version = "1.8.0";
6
+ readonly version = "1.8.1";
7
7
  static defaultDisabledLevels: LogLevel[];
8
8
  constructor(options?: ConsoleInstrumentationOptions);
9
9
  initialize(): void;
@@ -1,6 +1,6 @@
1
1
  import { BaseInstrumentation } from '@grafana/faro-core';
2
2
  export declare class ErrorsInstrumentation extends BaseInstrumentation {
3
3
  readonly name = "@grafana/faro-web-sdk:instrumentation-errors";
4
- readonly version = "1.8.0";
4
+ readonly version = "1.8.1";
5
5
  initialize(): void;
6
6
  }
@@ -1,7 +1,7 @@
1
1
  import { BaseInstrumentation } from '@grafana/faro-core';
2
2
  export declare class PerformanceInstrumentation extends BaseInstrumentation {
3
3
  readonly name = "@grafana/faro-web-sdk:instrumentation-performance";
4
- readonly version = "1.8.0";
4
+ readonly version = "1.8.1";
5
5
  initialize(): void;
6
6
  private getIgnoreUrls;
7
7
  }
@@ -1,7 +1,7 @@
1
1
  import { BaseInstrumentation } from '@grafana/faro-core';
2
2
  export declare class SessionInstrumentation extends BaseInstrumentation {
3
3
  readonly name = "@grafana/faro-web-sdk:instrumentation-session";
4
- readonly version = "1.8.0";
4
+ readonly version = "1.8.1";
5
5
  private notifiedSession;
6
6
  private sendSessionStartEvent;
7
7
  private createInitialSession;
@@ -0,0 +1,3 @@
1
+ import type { Config } from '@grafana/faro-core';
2
+ import type { SessionManager } from './types';
3
+ export declare function getSessionManagerByConfig(sessionTrackingConfig: Config['sessionTracking']): SessionManager;
@@ -3,3 +3,4 @@ export { VolatileSessionsManager } from './VolatileSessionManager';
3
3
  export { MAX_SESSION_PERSISTENCE_TIME, MAX_SESSION_PERSISTENCE_TIME_BUFFER, SESSION_EXPIRATION_TIME, SESSION_INACTIVITY_TIME, STORAGE_KEY, STORAGE_UPDATE_DELAY, defaultSessionTrackingConfig, } from './sessionConstants';
4
4
  export { isSampled } from './sampling';
5
5
  export type { FaroUserSession } from './types';
6
+ export { getSessionManagerByConfig } from './getSessionManagerByConfig';
@@ -1,5 +1,4 @@
1
- import type { Config } from '@grafana/faro-core';
2
- import type { FaroUserSession, SessionManager } from './types';
1
+ import type { FaroUserSession } from './types';
3
2
  type CreateUserSessionObjectParams = {
4
3
  sessionId?: string;
5
4
  started?: number;
@@ -17,5 +16,4 @@ type UpdateSessionParams = {
17
16
  };
18
17
  export declare function getUserSessionUpdater({ fetchUserSession, storeUserSession, }: GetUserSessionUpdaterParams): (options?: UpdateSessionParams) => void;
19
18
  export declare function addSessionMetadataToNextSession(newSession: FaroUserSession, previousSession: FaroUserSession | null): Required<FaroUserSession>;
20
- export declare function getSessionManagerByConfig(sessionTrackingConfig: Config['sessionTracking']): SessionManager;
21
19
  export {};
@@ -1,7 +1,7 @@
1
1
  import { BaseInstrumentation } from '@grafana/faro-core';
2
2
  export declare class ViewInstrumentation extends BaseInstrumentation {
3
3
  readonly name = "@grafana/faro-web-sdk:instrumentation-view";
4
- readonly version = "1.8.0";
4
+ readonly version = "1.8.1";
5
5
  private notifiedView;
6
6
  private sendViewChangedEvent;
7
7
  initialize(): void;
@@ -1,7 +1,7 @@
1
1
  import { BaseInstrumentation } from '@grafana/faro-core';
2
2
  export declare class WebVitalsInstrumentation extends BaseInstrumentation {
3
3
  readonly name = "@grafana/faro-web-sdk:instrumentation-web-vitals";
4
- readonly version = "1.8.0";
4
+ readonly version = "1.8.1";
5
5
  initialize(): void;
6
6
  private intializeWebVitalsInstrumentation;
7
7
  }
@@ -4,7 +4,7 @@ import type { ConsoleTransportOptions } from './types';
4
4
  export declare class ConsoleTransport extends BaseTransport {
5
5
  private options;
6
6
  readonly name = "@grafana/faro-web-sdk:transport-console";
7
- readonly version = "1.8.0";
7
+ readonly version = "1.8.1";
8
8
  constructor(options?: ConsoleTransportOptions);
9
9
  send(item: TransportItem): void;
10
10
  }
@@ -4,7 +4,7 @@ import type { FetchTransportOptions } from './types';
4
4
  export declare class FetchTransport extends BaseTransport {
5
5
  private options;
6
6
  readonly name = "@grafana/faro-web-sdk:transport-fetch";
7
- readonly version = "1.8.0";
7
+ readonly version = "1.8.1";
8
8
  promiseBuffer: PromiseBuffer<Response | void>;
9
9
  private readonly rateLimitBackoffMs;
10
10
  private readonly getNow;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@grafana/faro-web-sdk",
3
- "version": "1.8.0",
3
+ "version": "1.8.1",
4
4
  "description": "Faro instrumentations, metas, transports for web.",
5
5
  "keywords": [
6
6
  "observability",
@@ -52,7 +52,7 @@
52
52
  "quality:circular-deps": "madge --circular ."
53
53
  },
54
54
  "dependencies": {
55
- "@grafana/faro-core": "^1.8.0",
55
+ "@grafana/faro-core": "^1.8.1",
56
56
  "ua-parser-js": "^1.0.32",
57
57
  "web-vitals": "^4.0.1"
58
58
  },
@@ -63,5 +63,5 @@
63
63
  "publishConfig": {
64
64
  "access": "public"
65
65
  },
66
- "gitHead": "ec21b36031c20c859d64fbd75a77986397ebaf68"
66
+ "gitHead": "08d0f63dba5ff82c9b29b2f91df9d790514ea8d5"
67
67
  }