diff --git a/monteiro-cronosdown/.build-info b/monteiro-cronosdown/.build-info index fd56aee3..ef67851a 100644 --- a/monteiro-cronosdown/.build-info +++ b/monteiro-cronosdown/.build-info @@ -1,4 +1,4 @@ MODULE_NAME=monteiro-cronosdown -GIT_REF=v1.0.0 -RUN_URL=https://github.com/bitfocus/companion-bundled-modules/actions/runs/11154182869 -UPDATE_DATE=2024-10-03 +GIT_REF=v1.1.0 +RUN_URL=https://github.com/bitfocus/companion-bundled-modules/actions/runs/11394469917 +UPDATE_DATE=2024-10-17 diff --git a/monteiro-cronosdown/companion/manifest.json b/monteiro-cronosdown/companion/manifest.json index fe15a2ad..08671e87 100644 --- a/monteiro-cronosdown/companion/manifest.json +++ b/monteiro-cronosdown/companion/manifest.json @@ -1 +1 @@ -{"id":"monteiro-cronosdown","name":"monteiro-cronosdown","shortname":"cronosdown","description":"This software is for use as a stopwatch, making it easier to manipulate times through the companion.","version":"1.0.0","license":"MIT","repository":"git+https://github.com/bitfocus/companion-module-monteiro-cronosdown.git","bugs":"https://github.com/MonteiroVideo/cronosDown/issues","maintainers":[{"name":"Bruno Monteiro","email":"monteiro.audiovisual@gmail.com"}],"runtime":{"type":"node18","api":"nodejs-ipc","apiVersion":"1.1.1","entrypoint":"../main.js"},"legacyIds":[],"manufacturer":"JM","products":["CronosDown"],"keywords":["Software","Timer"]} \ No newline at end of file +{"id":"monteiro-cronosdown","name":"monteiro-cronosdown","shortname":"cronosdown","description":"This software is for use as a stopwatch, making it easier to manipulate times through the companion.","version":"1.1.0","license":"MIT","repository":"git+https://github.com/bitfocus/companion-module-monteiro-cronosdown.git","bugs":"https://github.com/bitfocus/companion-module-monteiro-cronosdown/issues","maintainers":[{"name":"Bruno Monteiro","email":"monteiro.audiovisual@gmail.com"}],"runtime":{"type":"node18","api":"nodejs-ipc","apiVersion":"1.11.0","entrypoint":"../main.js"},"legacyIds":[],"manufacturer":"Monteiro","products":["CronosDown"],"keywords":["Software","Timer"]} \ No newline at end of file diff --git a/monteiro-cronosdown/main.js b/monteiro-cronosdown/main.js index d10a8b13..118817c3 100644 --- a/monteiro-cronosdown/main.js +++ b/monteiro-cronosdown/main.js @@ -1 +1 @@ -(()=>{var t={7169:(t,e,n)=>{"use strict";const s=n(2017);s.code='require("ajv/dist/runtime/equal").default',e.A=s},2581:(t,e,n)=>{"use strict";n.d(e,{l:()=>r});var s=n(6588),i=n(1763),o=n(8560);function r(){(0,i.U)(),(0,o.wD)()&&function(){const e=(0,s.EU)();if(!e.__SENTRY__)return;const n={mongodb:()=>new((0,o.fj)(t,"./node/integrations/mongo").Mongo),mongoose:()=>new((0,o.fj)(t,"./node/integrations/mongo").Mongo),mysql:()=>new((0,o.fj)(t,"./node/integrations/mysql").Mysql),pg:()=>new((0,o.fj)(t,"./node/integrations/postgres").Postgres)},i=Object.keys(n).filter((t=>!!(0,o.Vw)(t))).map((t=>{try{return n[t]()}catch(t){return}})).filter((t=>t));i.length>0&&(e.__SENTRY__.integrations=[...e.__SENTRY__.integrations||[],...i])}()}t=n.hmd(t)},7765:(t,e,n)=>{"use strict";n.d(e,{U:()=>s});const s="production"},7022:(t,e,n)=>{"use strict";n.d(e,{T:()=>s});const s="undefined"==typeof __SENTRY_DEBUG__||__SENTRY_DEBUG__},9071:(t,e,n)=>{"use strict";n.d(e,{KU:()=>o,o5:()=>r,v4:()=>i});var s=n(6588);function i(...t){const e=(0,s.BF)();if(2===t.length){const[n,s]=t;return n?e.withScope((()=>(e.getStackTop().scope=n,s(n)))):e.withScope(s)}return e.withScope(t[0])}function o(){return(0,s.BF)().getClient()}function r(){return(0,s.BF)().getScope()}},6588:(t,e,n)=>{"use strict";n.d(e,{BF:()=>V,rm:()=>v,EU:()=>A,fx:()=>f});var s,i=n(138),o=n(4902),r=n(7567),c=n(6202),a=n(2231),g=n(7765),l=n(7022);!function(t){t[t.PENDING=0]="PENDING",t[t.RESOLVED=1]="RESOLVED",t[t.REJECTED=2]="REJECTED"}(s||(s={}));class d{constructor(t){d.prototype.__init.call(this),d.prototype.__init2.call(this),d.prototype.__init3.call(this),d.prototype.__init4.call(this),this._state=s.PENDING,this._handlers=[];try{t(this._resolve,this._reject)}catch(t){this._reject(t)}}then(t,e){return new d(((n,s)=>{this._handlers.push([!1,e=>{if(t)try{n(t(e))}catch(t){s(t)}else n(e)},t=>{if(e)try{n(e(t))}catch(t){s(t)}else s(t)}]),this._executeHandlers()}))}catch(t){return this.then((t=>t),t)}finally(t){return new d(((e,n)=>{let s,i;return this.then((e=>{i=!1,s=e,t&&t()}),(e=>{i=!0,s=e,t&&t()})).then((()=>{i?n(s):e(s)}))}))}__init(){this._resolve=t=>{this._setResult(s.RESOLVED,t)}}__init2(){this._reject=t=>{this._setResult(s.REJECTED,t)}}__init3(){this._setResult=(t,e)=>{this._state===s.PENDING&&((0,i.Qg)(e)?e.then(this._resolve,this._reject):(this._state=t,this._value=e,this._executeHandlers()))}}__init4(){this._executeHandlers=()=>{if(this._state===s.PENDING)return;const t=this._handlers.slice();this._handlers=[],t.forEach((t=>{t[0]||(this._state===s.RESOLVED&&t[1](this._value),this._state===s.REJECTED&&t[2](this._value),t[0]=!0)}))}}}function I(t,e,n,s=0){return new d(((o,r)=>{const a=t[s];if(null===e||"function"!=typeof a)o(e);else{const g=a({...e},n);l.T&&a.id&&null===g&&c.vF.log(`Event processor "${a.id}" dropped event`),(0,i.Qg)(g)?g.then((e=>I(t,e,n,s+1).then(o))).then(null,r):I(t,g,n,s+1).then(o).then(null,r)}}))}var u=n(1041);function C(t,e={}){if(e.user&&(!t.ipAddress&&e.user.ip_address&&(t.ipAddress=e.user.ip_address),t.did||e.did||(t.did=e.user.id||e.user.email||e.user.username)),t.timestamp=e.timestamp||(0,r.zf)(),e.abnormal_mechanism&&(t.abnormal_mechanism=e.abnormal_mechanism),e.ignoreDuration&&(t.ignoreDuration=e.ignoreDuration),e.sid&&(t.sid=32===e.sid.length?e.sid:(0,o.eJ)()),void 0!==e.init&&(t.init=e.init),!t.did&&e.did&&(t.did=`${e.did}`),"number"==typeof e.started&&(t.started=e.started),t.ignoreDuration)t.duration=void 0;else if("number"==typeof e.duration)t.duration=e.duration;else{const e=t.timestamp-t.started;t.duration=e>=0?e:0}e.release&&(t.release=e.release),e.environment&&(t.environment=e.environment),!t.ipAddress&&e.ipAddress&&(t.ipAddress=e.ipAddress),!t.userAgent&&e.userAgent&&(t.userAgent=e.userAgent),"number"==typeof e.errors&&(t.errors=e.errors),e.status&&(t.status=e.status)}var p=n(9738),b=n(9266),h=n(5895);class m{constructor(){this._notifyingListeners=!1,this._scopeListeners=[],this._eventProcessors=[],this._breadcrumbs=[],this._attachments=[],this._user={},this._tags={},this._extra={},this._contexts={},this._sdkProcessingMetadata={},this._propagationContext=Z()}static clone(t){return t?t.clone():new m}clone(){const t=new m;return t._breadcrumbs=[...this._breadcrumbs],t._tags={...this._tags},t._extra={...this._extra},t._contexts={...this._contexts},t._user=this._user,t._level=this._level,t._span=this._span,t._session=this._session,t._transactionName=this._transactionName,t._fingerprint=this._fingerprint,t._eventProcessors=[...this._eventProcessors],t._requestSession=this._requestSession,t._attachments=[...this._attachments],t._sdkProcessingMetadata={...this._sdkProcessingMetadata},t._propagationContext={...this._propagationContext},t._client=this._client,t}setClient(t){this._client=t}getClient(){return this._client}addScopeListener(t){this._scopeListeners.push(t)}addEventProcessor(t){return this._eventProcessors.push(t),this}setUser(t){return this._user=t||{email:void 0,id:void 0,ip_address:void 0,segment:void 0,username:void 0},this._session&&C(this._session,{user:t}),this._notifyScopeListeners(),this}getUser(){return this._user}getRequestSession(){return this._requestSession}setRequestSession(t){return this._requestSession=t,this}setTags(t){return this._tags={...this._tags,...t},this._notifyScopeListeners(),this}setTag(t,e){return this._tags={...this._tags,[t]:e},this._notifyScopeListeners(),this}setExtras(t){return this._extra={...this._extra,...t},this._notifyScopeListeners(),this}setExtra(t,e){return this._extra={...this._extra,[t]:e},this._notifyScopeListeners(),this}setFingerprint(t){return this._fingerprint=t,this._notifyScopeListeners(),this}setLevel(t){return this._level=t,this._notifyScopeListeners(),this}setTransactionName(t){return this._transactionName=t,this._notifyScopeListeners(),this}setContext(t,e){return null===e?delete this._contexts[t]:this._contexts[t]=e,this._notifyScopeListeners(),this}setSpan(t){return this._span=t,this._notifyScopeListeners(),this}getSpan(){return this._span}getTransaction(){const t=this._span;return t&&t.transaction}setSession(t){return t?this._session=t:delete this._session,this._notifyScopeListeners(),this}getSession(){return this._session}update(t){if(!t)return this;const e="function"==typeof t?t(this):t;if(e instanceof m){const t=e.getScopeData();this._tags={...this._tags,...t.tags},this._extra={...this._extra,...t.extra},this._contexts={...this._contexts,...t.contexts},t.user&&Object.keys(t.user).length&&(this._user=t.user),t.level&&(this._level=t.level),t.fingerprint.length&&(this._fingerprint=t.fingerprint),e.getRequestSession()&&(this._requestSession=e.getRequestSession()),t.propagationContext&&(this._propagationContext=t.propagationContext)}else if((0,i.Qd)(e)){const e=t;this._tags={...this._tags,...e.tags},this._extra={...this._extra,...e.extra},this._contexts={...this._contexts,...e.contexts},e.user&&(this._user=e.user),e.level&&(this._level=e.level),e.fingerprint&&(this._fingerprint=e.fingerprint),e.requestSession&&(this._requestSession=e.requestSession),e.propagationContext&&(this._propagationContext=e.propagationContext)}return this}clear(){return this._breadcrumbs=[],this._tags={},this._extra={},this._user={},this._contexts={},this._level=void 0,this._transactionName=void 0,this._fingerprint=void 0,this._requestSession=void 0,this._span=void 0,this._session=void 0,this._notifyScopeListeners(),this._attachments=[],this._propagationContext=Z(),this}addBreadcrumb(t,e){const n="number"==typeof e?e:100;if(n<=0)return this;const s={timestamp:(0,r.lu)(),...t},i=this._breadcrumbs;return i.push(s),this._breadcrumbs=i.length>n?i.slice(-n):i,this._notifyScopeListeners(),this}getLastBreadcrumb(){return this._breadcrumbs[this._breadcrumbs.length-1]}clearBreadcrumbs(){return this._breadcrumbs=[],this._notifyScopeListeners(),this}addAttachment(t){return this._attachments.push(t),this}getAttachments(){return this.getScopeData().attachments}clearAttachments(){return this._attachments=[],this}getScopeData(){const{_breadcrumbs:t,_attachments:e,_contexts:n,_tags:s,_extra:i,_user:o,_level:r,_fingerprint:c,_eventProcessors:a,_propagationContext:g,_sdkProcessingMetadata:l,_transactionName:d,_span:I}=this;return{breadcrumbs:t,attachments:e,contexts:n,tags:s,extra:i,user:o,level:r,fingerprint:c||[],eventProcessors:a,propagationContext:g,sdkProcessingMetadata:l,transactionName:d,span:I}}applyToEvent(t,e={},n=[]){return function(t,e){const{fingerprint:n,span:s,breadcrumbs:i,sdkProcessingMetadata:r}=e;!function(t,e){const{extra:n,tags:s,user:i,contexts:o,level:r,transactionName:c}=e,a=(0,u.Ce)(n);a&&Object.keys(a).length&&(t.extra={...a,...t.extra});const g=(0,u.Ce)(s);g&&Object.keys(g).length&&(t.tags={...g,...t.tags});const l=(0,u.Ce)(i);l&&Object.keys(l).length&&(t.user={...l,...t.user});const d=(0,u.Ce)(o);d&&Object.keys(d).length&&(t.contexts={...d,...t.contexts}),r&&(t.level=r),c&&(t.transaction=c)}(t,e),s&&function(t,e){t.contexts={trace:(0,h.kX)(e),...t.contexts};const n=(0,b.z)(e);if(n){t.sdkProcessingMetadata={dynamicSamplingContext:(0,p.k)(e),...t.sdkProcessingMetadata};const s=(0,h.et)(n).description;s&&(t.tags={transaction:s,...t.tags})}}(t,s),function(t,e){t.fingerprint=t.fingerprint?(0,o.k9)(t.fingerprint):[],e&&(t.fingerprint=t.fingerprint.concat(e)),t.fingerprint&&!t.fingerprint.length&&delete t.fingerprint}(t,n),function(t,e){const n=[...t.breadcrumbs||[],...e];t.breadcrumbs=n.length?n:void 0}(t,i),function(t,e){t.sdkProcessingMetadata={...t.sdkProcessingMetadata,...e}}(t,r)}(t,this.getScopeData()),I([...n,...(0,a.BY)("globalEventProcessors",(()=>[])),...this._eventProcessors],t,e)}setSDKProcessingMetadata(t){return this._sdkProcessingMetadata={...this._sdkProcessingMetadata,...t},this}setPropagationContext(t){return this._propagationContext=t,this}getPropagationContext(){return this._propagationContext}captureException(t,e){const n=e&&e.event_id?e.event_id:(0,o.eJ)();if(!this._client)return c.vF.warn("No client configured on scope - will not capture exception!"),n;const s=new Error("Sentry syntheticException");return this._client.captureException(t,{originalException:t,syntheticException:s,...e,event_id:n},this),n}captureMessage(t,e,n){const s=n&&n.event_id?n.event_id:(0,o.eJ)();if(!this._client)return c.vF.warn("No client configured on scope - will not capture message!"),s;const i=new Error(t);return this._client.captureMessage(t,e,{originalException:t,syntheticException:i,...n,event_id:s},this),s}captureEvent(t,e){const n=e&&e.event_id?e.event_id:(0,o.eJ)();return this._client?(this._client.captureEvent(t,{...e,event_id:n},this),n):(c.vF.warn("No client configured on scope - will not capture event!"),n)}_notifyScopeListeners(){this._notifyingListeners||(this._notifyingListeners=!0,this._scopeListeners.forEach((t=>{t(this)})),this._notifyingListeners=!1)}}function Z(){return{traceId:(0,o.eJ)(),spanId:(0,o.eJ)().substring(16)}}const G=parseFloat("7.114.0"),B=100;class y{constructor(t,e,n,s=G){let i,o;this._version=s,e?i=e:(i=new m,i.setClient(t)),n?o=n:(o=new m,o.setClient(t)),this._stack=[{scope:i}],t&&this.bindClient(t),this._isolationScope=o}isOlderThan(t){return this._version(this.popScope(),t)),(t=>{throw this.popScope(),t})):(this.popScope(),n)}getClient(){return this.getStackTop().client}getScope(){return this.getStackTop().scope}getIsolationScope(){return this._isolationScope}getStack(){return this._stack}getStackTop(){return this._stack[this._stack.length-1]}captureException(t,e){const n=this._lastEventId=e&&e.event_id?e.event_id:(0,o.eJ)(),s=new Error("Sentry syntheticException");return this.getScope().captureException(t,{originalException:t,syntheticException:s,...e,event_id:n}),n}captureMessage(t,e,n){const s=this._lastEventId=n&&n.event_id?n.event_id:(0,o.eJ)(),i=new Error(t);return this.getScope().captureMessage(t,e,{originalException:t,syntheticException:i,...n,event_id:s}),s}captureEvent(t,e){const n=e&&e.event_id?e.event_id:(0,o.eJ)();return t.type||(this._lastEventId=n),this.getScope().captureEvent(t,{...e,event_id:n}),n}lastEventId(){return this._lastEventId}addBreadcrumb(t,e){const{scope:n,client:s}=this.getStackTop();if(!s)return;const{beforeBreadcrumb:i=null,maxBreadcrumbs:o=B}=s.getOptions&&s.getOptions()||{};if(o<=0)return;const a={timestamp:(0,r.lu)(),...t},g=i?(0,c.pq)((()=>i(a,e))):a;null!==g&&(s.emit&&s.emit("beforeAddBreadcrumb",g,e),n.addBreadcrumb(g,o))}setUser(t){this.getScope().setUser(t),this.getIsolationScope().setUser(t)}setTags(t){this.getScope().setTags(t),this.getIsolationScope().setTags(t)}setExtras(t){this.getScope().setExtras(t),this.getIsolationScope().setExtras(t)}setTag(t,e){this.getScope().setTag(t,e),this.getIsolationScope().setTag(t,e)}setExtra(t,e){this.getScope().setExtra(t,e),this.getIsolationScope().setExtra(t,e)}setContext(t,e){this.getScope().setContext(t,e),this.getIsolationScope().setContext(t,e)}configureScope(t){const{scope:e,client:n}=this.getStackTop();n&&t(e)}run(t){const e=W(this);try{t(this)}finally{W(e)}}getIntegration(t){const e=this.getClient();if(!e)return null;try{return e.getIntegration(t)}catch(e){return l.T&&c.vF.warn(`Cannot retrieve integration ${t.id} from the current Hub`),null}}startTransaction(t,e){const n=this._callExtensionMethod("startTransaction",t,e);return l.T&&!n&&(this.getClient()?c.vF.warn("Tracing extension 'startTransaction' has not been added. Call 'addTracingExtensions' before calling 'init':\nSentry.addTracingExtensions();\nSentry.init({...});\n"):c.vF.warn("Tracing extension 'startTransaction' is missing. You should 'init' the SDK before calling 'startTransaction'")),n}traceHeaders(){return this._callExtensionMethod("traceHeaders")}captureSession(t=!1){if(t)return this.endSession();this._sendSessionUpdate()}endSession(){const t=this.getStackTop().scope,e=t.getSession();e&&function(t){let e={};"ok"===t.status&&(e={status:"exited"}),C(t,e)}(e),this._sendSessionUpdate(),t.setSession()}startSession(t){const{scope:e,client:n}=this.getStackTop(),{release:s,environment:i=g.U}=n&&n.getOptions()||{},{userAgent:c}=a.OW.navigator||{},l=function(t){const e=(0,r.zf)(),n={sid:(0,o.eJ)(),init:!0,timestamp:e,started:e,duration:0,status:"ok",errors:0,ignoreDuration:!1,toJSON:()=>function(t){return(0,u.Ce)({sid:`${t.sid}`,init:t.init,started:new Date(1e3*t.started).toISOString(),timestamp:new Date(1e3*t.timestamp).toISOString(),status:t.status,errors:t.errors,did:"number"==typeof t.did||"string"==typeof t.did?`${t.did}`:void 0,duration:t.duration,abnormal_mechanism:t.abnormal_mechanism,attrs:{release:t.release,environment:t.environment,ip_address:t.ipAddress,user_agent:t.userAgent}})}(n)};return t&&C(n,t),n}({release:s,environment:i,user:e.getUser(),...c&&{userAgent:c},...t}),d=e.getSession&&e.getSession();return d&&"ok"===d.status&&C(d,{status:"exited"}),this.endSession(),e.setSession(l),l}shouldSendDefaultPii(){const t=this.getClient(),e=t&&t.getOptions();return Boolean(e&&e.sendDefaultPii)}_sendSessionUpdate(){const{scope:t,client:e}=this.getStackTop(),n=t.getSession();n&&e&&e.captureSession&&e.captureSession(n)}_callExtensionMethod(t,...e){const n=A().__SENTRY__;if(n&&n.extensions&&"function"==typeof n.extensions[t])return n.extensions[t].apply(this,e);l.T&&c.vF.warn(`Extension method ${t} couldn't be found, doing nothing.`)}}function A(){return a.OW.__SENTRY__=a.OW.__SENTRY__||{extensions:{},hub:void 0},a.OW}function W(t){const e=A(),n=R(e);return Y(e,t),n}function V(){const t=A();if(t.__SENTRY__&&t.__SENTRY__.acs){const e=t.__SENTRY__.acs.getCurrentHub();if(e)return e}return function(t=A()){return e=t,!!(e&&e.__SENTRY__&&e.__SENTRY__.hub)&&!R(t).isOlderThan(G)||Y(t,new y),R(t);var e}(t)}function v(){return V().getIsolationScope()}function f(t,e={}){const n=A();return n.__SENTRY__&&n.__SENTRY__.acs?n.__SENTRY__.acs.runWithAsyncContext(t,e):t()}function R(t){return(0,a.BY)("hub",(()=>new y),t)}function Y(t,e){return!!t&&((t.__SENTRY__=t.__SENTRY__||{}).hub=e,!0)}},741:(t,e,n)=>{"use strict";n.d(e,{g:()=>o});var s=n(1041);let i;function o(t){const e=function(t){return i?i.get(t):void 0}(t);if(!e)return;const n={};for(const[,[t,i]]of e)n[t]||(n[t]=[]),n[t].push((0,s.Ce)(i));return n}},5071:(t,e,n)=>{"use strict";n.d(e,{E1:()=>c,JD:()=>r,i_:()=>s,sy:()=>i,uT:()=>o});const s="sentry.source",i="sentry.sample_rate",o="sentry.op",r="sentry.origin",c="profile_id"},9738:(t,e,n)=>{"use strict";n.d(e,{k:()=>g,l:()=>a});var s=n(1041),i=n(7765),o=n(9071),r=n(9266),c=n(5895);function a(t,e,n){const o=e.getOptions(),{publicKey:r}=e.getDsn()||{},{segment:c}=n&&n.getUser()||{},a=(0,s.Ce)({environment:o.environment||i.U,release:o.release,user_segment:c,public_key:r,trace_id:t});return e.emit&&e.emit("createDsc",a),a}function g(t){const e=(0,o.KU)();if(!e)return{};const n=a((0,c.et)(t).trace_id||"",e,(0,o.o5)()),s=(0,r.z)(t);if(!s)return n;const i=s&&s._frozenDynamicSamplingContext;if(i)return i;const{sampleRate:g,source:l}=s.metadata;null!=g&&(n.sample_rate=`${g}`);const d=(0,c.et)(s);return l&&"url"!==l&&(n.transaction=d.description),n.sampled=String((0,c.pK)(s)),e.emit&&e.emit("createDsc",n),n}},1763:(t,e,n)=>{"use strict";n.d(e,{U:()=>y,p:()=>B});var s=n(6202),i=n(7022),o=n(6588),r=n(5895),c=n(2231),a=n(6768);let g=null;function l(){g=c.OW.onerror,c.OW.onerror=function(t,e,n,s,i){const o={column:s,error:i,line:n,msg:t,url:e};return(0,a.aj)("error",o),!(!g||g.__SENTRY_LOADER__)&&g.apply(this,arguments)},c.OW.onerror.__SENTRY_INSTRUMENTED__=!0}let d=null;function I(){d=c.OW.onunhandledrejection,c.OW.onunhandledrejection=function(t){const e=t;return(0,a.aj)("unhandledrejection",e),!(d&&!d.__SENTRY_LOADER__)||d.apply(this,arguments)},c.OW.onunhandledrejection.__SENTRY_INSTRUMENTED__=!0}var u=n(1692);let C=!1;function p(){const t=(0,u.Z7)();if(t){const e="internal_error";i.T&&s.vF.log(`[Tracing] Transaction: ${e} -> Global error occured`),t.setStatus(e)}}p.tag="sentry_tracingErrorCallback";var b=n(683),h=n(6056),m=n(9049);function Z(){const t=this.getScope().getSpan();return t?{"sentry-trace":(0,r.Qh)(t)}:{}}function G(t,e){const n=this.getClient(),o=n&&n.getOptions()||{},r=o.instrumenter||"sentry",c=t.instrumenter||"sentry";r!==c&&(i.T&&s.vF.error(`A transaction was started with instrumenter=\`${c}\`, but the SDK is configured with the \`${r}\` instrumenter.\nThe transaction will not be sampled. Please use the ${r} instrumentation to start transactions.`),t.sampled=!1);let a=new m.Z(t,this);return a=(0,h.T)(a,o,{name:t.name,parentSampled:t.parentSampled,transactionContext:t,attributes:{...t.data,...t.attributes},...e}),a.isRecording()&&a.initSpanRecorder(o._experiments&&o._experiments.maxSpans),n&&n.emit&&n.emit("startTransaction",a),a}function B(t,e,n,s,i,o,r,c=!1){const a=t.getClient(),g=a&&a.getOptions()||{};let l=new b.zX(e,t,n,s,r,i,c);return l=(0,h.T)(l,g,{name:e.name,parentSampled:e.parentSampled,transactionContext:e,attributes:{...e.data,...e.attributes},...o}),l.isRecording()&&l.initSpanRecorder(g._experiments&&g._experiments.maxSpans),a&&a.emit&&a.emit("startTransaction",l),l}function y(){const t=(0,o.EU)();t.__SENTRY__&&(t.__SENTRY__.extensions=t.__SENTRY__.extensions||{},t.__SENTRY__.extensions.startTransaction||(t.__SENTRY__.extensions.startTransaction=G),t.__SENTRY__.extensions.traceHeaders||(t.__SENTRY__.extensions.traceHeaders=Z),C||(C=!0,function(t){const e="error";(0,a.s5)(e,t),(0,a.AS)(e,l)}(p),function(t){const e="unhandledrejection";(0,a.s5)(e,t),(0,a.AS)(e,I)}(p)))}},683:(t,e,n)=>{"use strict";n.d(e,{Cq:()=>g,zX:()=>I});var s=n(6202),i=n(7567),o=n(7022),r=n(5895),c=n(7037),a=n(9049);const g={idleTimeout:1e3,finalTimeout:3e4,heartbeatInterval:5e3},l=["heartbeatFailed","idleTimeout","documentHidden","finalTimeout","externalFinish","cancelled"];class d extends c.l{constructor(t,e,n,s){super(s),this._pushActivity=t,this._popActivity=e,this.transactionSpanId=n}add(t){if(t.spanContext().spanId!==this.transactionSpanId){const e=t.end;t.end=(...n)=>(this._popActivity(t.spanContext().spanId),e.apply(t,n)),void 0===(0,r.et)(t).timestamp&&this._pushActivity(t.spanContext().spanId)}super.add(t)}}class I extends a.Z{constructor(t,e,n=g.idleTimeout,i=g.finalTimeout,r=g.heartbeatInterval,c=!1,a=!1){super(t,e),this._idleHub=e,this._idleTimeout=n,this._finalTimeout=i,this._heartbeatInterval=r,this._onScope=c,this.activities={},this._heartbeatCounter=0,this._finished=!1,this._idleTimeoutCanceledPermanently=!1,this._beforeFinishCallbacks=[],this._finishReason=l[4],this._autoFinishAllowed=!a,c&&(o.T&&s.vF.log(`Setting idle transaction on scope. Span ID: ${this.spanContext().spanId}`),e.getScope().setSpan(this)),a||this._restartIdleTimeout(),setTimeout((()=>{this._finished||(this.setStatus("deadline_exceeded"),this._finishReason=l[3],this.end())}),this._finalTimeout)}end(t){const e=(0,r.cI)(t);if(this._finished=!0,this.activities={},"ui.action.click"===this.op&&this.setAttribute("finishReason",this._finishReason),this.spanRecorder){o.T&&s.vF.log("[Tracing] finishing IdleTransaction",new Date(1e3*e).toISOString(),this.op);for(const t of this._beforeFinishCallbacks)t(this,e);this.spanRecorder.spans=this.spanRecorder.spans.filter((t=>{if(t.spanContext().spanId===this.spanContext().spanId)return!0;(0,r.et)(t).timestamp||(t.setStatus("cancelled"),t.end(e),o.T&&s.vF.log("[Tracing] cancelling span since transaction ended early",JSON.stringify(t,void 0,2)));const{start_timestamp:n,timestamp:i}=(0,r.et)(t),c=n&&n{this._finished||this._pushActivity(t)},n=t=>{this._finished||this._popActivity(t)};this.spanRecorder=new d(e,n,this.spanContext().spanId,t),o.T&&s.vF.log("Starting heartbeat"),this._pingHeartbeat()}this.spanRecorder.add(this)}cancelIdleTimeout(t,{restartOnChildSpanChange:e}={restartOnChildSpanChange:!0}){this._idleTimeoutCanceledPermanently=!1===e,this._idleTimeoutID&&(clearTimeout(this._idleTimeoutID),this._idleTimeoutID=void 0,0===Object.keys(this.activities).length&&this._idleTimeoutCanceledPermanently&&(this._finishReason=l[5],this.end(t)))}setFinishReason(t){this._finishReason=t}sendAutoFinishSignal(){this._autoFinishAllowed||(o.T&&s.vF.log("[Tracing] Received finish signal for idle transaction."),this._restartIdleTimeout(),this._autoFinishAllowed=!0)}_restartIdleTimeout(t){this.cancelIdleTimeout(),this._idleTimeoutID=setTimeout((()=>{this._finished||0!==Object.keys(this.activities).length||(this._finishReason=l[1],this.end(t))}),this._idleTimeout)}_pushActivity(t){this.cancelIdleTimeout(void 0,{restartOnChildSpanChange:!this._idleTimeoutCanceledPermanently}),o.T&&s.vF.log(`[Tracing] pushActivity: ${t}`),this.activities[t]=!0,o.T&&s.vF.log("[Tracing] new activities count",Object.keys(this.activities).length)}_popActivity(t){if(this.activities[t]&&(o.T&&s.vF.log(`[Tracing] popActivity ${t}`),delete this.activities[t],o.T&&s.vF.log("[Tracing] new activities count",Object.keys(this.activities).length)),0===Object.keys(this.activities).length){const t=(0,i.zf)();this._idleTimeoutCanceledPermanently?this._autoFinishAllowed&&(this._finishReason=l[5],this.end(t)):this._restartIdleTimeout(t+this._idleTimeout/1e3)}}_beat(){if(this._finished)return;const t=Object.keys(this.activities).join("");t===this._prevHeartbeatString?this._heartbeatCounter++:this._heartbeatCounter=1,this._prevHeartbeatString=t,this._heartbeatCounter>=3?this._autoFinishAllowed&&(o.T&&s.vF.log("[Tracing] Transaction finished because of no change for 3 heart beats"),this.setStatus("deadline_exceeded"),this._finishReason=l[0],this.end()):this._pingHeartbeat()}_pingHeartbeat(){o.T&&s.vF.log(`pinging Heartbeat -> current counter: ${this._heartbeatCounter}`),setTimeout((()=>{this._beat()}),this._heartbeatInterval)}}},6056:(t,e,n)=>{"use strict";n.d(e,{T:()=>g,v:()=>l});var s=n(6202),i=n(138),o=n(7022),r=n(5071),c=n(5177),a=n(5895);function g(t,e,n){if(!(0,c.w)(e))return t.sampled=!1,t;if(void 0!==t.sampled)return t.setAttribute(r.sy,Number(t.sampled)),t;let i;return"function"==typeof e.tracesSampler?(i=e.tracesSampler(n),t.setAttribute(r.sy,Number(i))):void 0!==n.parentSampled?i=n.parentSampled:void 0!==e.tracesSampleRate?(i=e.tracesSampleRate,t.setAttribute(r.sy,Number(i))):(i=1,t.setAttribute(r.sy,i)),l(i)?i?(t.sampled=Math.random()1)||(o.T&&s.vF.warn(`[Tracing] Given sample rate is invalid. Sample rate must be between 0 and 1. Got ${t}.`),!1)}},7037:(t,e,n)=>{"use strict";n.d(e,{L:()=>C,l:()=>u});var s=n(4902),i=n(7567),o=n(6202),r=n(1041),c=n(7022),a=n(741),g=n(5071),l=n(9266),d=n(5895),I=n(4131);class u{constructor(t=1e3){this._maxlen=t,this.spans=[]}add(t){this.spans.length>this._maxlen?t.spanRecorder=void 0:this.spans.push(t)}}class C{constructor(t={}){this._traceId=t.traceId||(0,s.eJ)(),this._spanId=t.spanId||(0,s.eJ)().substring(16),this._startTime=t.startTimestamp||(0,i.zf)(),this.tags=t.tags?{...t.tags}:{},this.data=t.data?{...t.data}:{},this.instrumenter=t.instrumenter||"sentry",this._attributes={},this.setAttributes({[g.JD]:t.origin||"manual",[g.uT]:t.op,...t.attributes}),this._name=t.name||t.description,t.parentSpanId&&(this._parentSpanId=t.parentSpanId),"sampled"in t&&(this._sampled=t.sampled),t.status&&(this._status=t.status),t.endTimestamp&&(this._endTime=t.endTimestamp),void 0!==t.exclusiveTime&&(this._exclusiveTime=t.exclusiveTime),this._measurements=t.measurements?{...t.measurements}:{}}get name(){return this._name||""}set name(t){this.updateName(t)}get description(){return this._name}set description(t){this._name=t}get traceId(){return this._traceId}set traceId(t){this._traceId=t}get spanId(){return this._spanId}set spanId(t){this._spanId=t}set parentSpanId(t){this._parentSpanId=t}get parentSpanId(){return this._parentSpanId}get sampled(){return this._sampled}set sampled(t){this._sampled=t}get attributes(){return this._attributes}set attributes(t){this._attributes=t}get startTimestamp(){return this._startTime}set startTimestamp(t){this._startTime=t}get endTimestamp(){return this._endTime}set endTimestamp(t){this._endTime=t}get status(){return this._status}set status(t){this._status=t}get op(){return this._attributes[g.uT]}set op(t){this.setAttribute(g.uT,t)}get origin(){return this._attributes[g.JD]}set origin(t){this.setAttribute(g.JD,t)}spanContext(){const{_spanId:t,_traceId:e,_sampled:n}=this;return{spanId:t,traceId:e,traceFlags:n?d.aO:d.CC}}startChild(t){const e=new C({...t,parentSpanId:this._spanId,sampled:this._sampled,traceId:this._traceId});e.spanRecorder=this.spanRecorder,e.spanRecorder&&e.spanRecorder.add(e);const n=(0,l.z)(this);if(e.transaction=n,c.T&&n){const s=`[Tracing] Starting '${t&&t.op||"< unknown op >"}' span on transaction '${(0,d.et)(e).description||"< unknown name >"}' (${n.spanContext().spanId}).`;o.vF.log(s),this._logMessage=s}return e}setTag(t,e){return this.tags={...this.tags,[t]:e},this}setData(t,e){return this.data={...this.data,[t]:e},this}setAttribute(t,e){void 0===e?delete this._attributes[t]:this._attributes[t]=e}setAttributes(t){Object.keys(t).forEach((e=>this.setAttribute(e,t[e])))}setStatus(t){return this._status=t,this}setHttpStatus(t){return(0,I.N8)(this,t),this}setName(t){this.updateName(t)}updateName(t){return this._name=t,this}isSuccess(){return"ok"===this._status}finish(t){return this.end(t)}end(t){if(this._endTime)return;const e=(0,l.z)(this);if(c.T&&e&&e.spanContext().spanId!==this._spanId){const t=this._logMessage;t&&o.vF.log(t.replace("Starting","Finishing"))}this._endTime=(0,d.cI)(t)}toTraceparent(){return(0,d.Qh)(this)}toContext(){return(0,r.Ce)({data:this._getData(),description:this._name,endTimestamp:this._endTime,op:this.op,parentSpanId:this._parentSpanId,sampled:this._sampled,spanId:this._spanId,startTimestamp:this._startTime,status:this._status,tags:this.tags,traceId:this._traceId})}updateWithContext(t){return this.data=t.data||{},this._name=t.name||t.description,this._endTime=t.endTimestamp,this.op=t.op,this._parentSpanId=t.parentSpanId,this._sampled=t.sampled,this._spanId=t.spanId||this._spanId,this._startTime=t.startTimestamp||this._startTime,this._status=t.status,this.tags=t.tags||{},this._traceId=t.traceId||this._traceId,this}getTraceContext(){return(0,d.kX)(this)}getSpanJSON(){return(0,r.Ce)({data:this._getData(),description:this._name,op:this._attributes[g.uT],parent_span_id:this._parentSpanId,span_id:this._spanId,start_timestamp:this._startTime,status:this._status,tags:Object.keys(this.tags).length>0?this.tags:void 0,timestamp:this._endTime,trace_id:this._traceId,origin:this._attributes[g.JD],_metrics_summary:(0,a.g)(this),profile_id:this._attributes[g.E1],exclusive_time:this._exclusiveTime,measurements:Object.keys(this._measurements).length>0?this._measurements:void 0})}isRecording(){return!this._endTime&&!!this._sampled}toJSON(){return this.getSpanJSON()}_getData(){const{data:t,_attributes:e}=this,n=Object.keys(t).length>0,s=Object.keys(e).length>0;if(n||s)return n&&s?{...t,...e}:n?t:e}}},4131:(t,e,n)=>{"use strict";var s;function i(t){if(t<400&&t>=100)return"ok";if(t>=400&&t<500)switch(t){case 401:return"unauthenticated";case 403:return"permission_denied";case 404:return"not_found";case 409:return"already_exists";case 413:return"failed_precondition";case 429:return"resource_exhausted";default:return"invalid_argument"}if(t>=500&&t<600)switch(t){case 501:return"unimplemented";case 503:return"unavailable";case 504:return"deadline_exceeded";default:return"internal_error"}return"unknown_error"}n.d(e,{Fp:()=>s,N8:()=>r,o6:()=>o}),function(t){t.Ok="ok",t.DeadlineExceeded="deadline_exceeded",t.Unauthenticated="unauthenticated",t.PermissionDenied="permission_denied",t.NotFound="not_found",t.ResourceExhausted="resource_exhausted",t.InvalidArgument="invalid_argument",t.Unimplemented="unimplemented",t.Unavailable="unavailable",t.InternalError="internal_error",t.UnknownError="unknown_error",t.Cancelled="cancelled",t.AlreadyExists="already_exists",t.FailedPrecondition="failed_precondition",t.Aborted="aborted",t.OutOfRange="out_of_range",t.DataLoss="data_loss"}(s||(s={}));const o=i;function r(t,e){t.setTag("http.status_code",String(e)),t.setData("http.response.status_code",e);const n=i(e);"unknown_error"!==n&&t.setStatus(n)}},9589:(t,e,n)=>{"use strict";n.d(e,{Lb:()=>b,Uk:()=>d,Lk:()=>l});var s=n(1041),i=n(6588),o=n(5895),r=n(9738),c=n(9071),a=n(138);var g=n(5177);function l(t,e){const n=u(t);return(0,i.fx)((()=>(0,c.v4)(t.scope,(s=>{const r=(0,i.BF)(),c=s.getSpan(),g=t.onlyIfParent&&!c?void 0:I(r,{parentSpan:c,spanContext:n,forceTransaction:t.forceTransaction,scope:s});return function(t,e,n=()=>{}){let s;try{s=t()}catch(t){throw e(t),n(),t}return function(t,e,n){return(0,a.Qg)(t)?t.then((t=>(n(),t)),(t=>{throw e(t),n(),t})):(n(),t)}(s,e,n)}((()=>e(g)),(()=>{if(g){const{status:t}=(0,o.et)(g);t&&"ok"!==t||g.setStatus("internal_error")}}),(()=>g&&g.end()))}))))}function d(t){if(!(0,g.w)())return;const e=u(t),n=(0,i.BF)(),s=t.scope?t.scope.getSpan():(0,c.o5)().getSpan();if(t.onlyIfParent&&!s)return;const o=(t.scope||(0,c.o5)()).clone();return I(n,{parentSpan:s,spanContext:e,forceTransaction:t.forceTransaction,scope:o})}function I(t,{parentSpan:e,spanContext:n,forceTransaction:c,scope:a}){if(!(0,g.w)())return;const l=(0,i.rm)();let d;if(e&&!c)d=e.startChild(n);else if(e){const s=(0,r.k)(e),{traceId:i,spanId:c}=e.spanContext(),a=(0,o.pK)(e);d=t.startTransaction({traceId:i,parentSpanId:c,parentSampled:a,...n,metadata:{dynamicSamplingContext:s,...n.metadata}})}else{const{traceId:e,dsc:s,parentSpanId:i,sampled:o}={...l.getPropagationContext(),...a.getPropagationContext()};d=t.startTransaction({traceId:e,parentSpanId:i,parentSampled:o,...n,metadata:{dynamicSamplingContext:s,...n.metadata}})}return a.setSpan(d),function(t,e,n){t&&((0,s.my)(t,p,n),(0,s.my)(t,C,e))}(d,a,l),d}function u(t){if(t.startTime){const e={...t};return e.startTimestamp=(0,o.cI)(t.startTime),delete e.startTime,e}return t}const C="_sentryScope",p="_sentryIsolationScope";function b(t){return{scope:t[C],isolationScope:t[p]}}},9049:(t,e,n)=>{"use strict";n.d(e,{Z:()=>u});var s=n(1041),i=n(6202),o=n(7022),r=n(6588),c=n(741),a=n(5071),g=n(5895),l=n(9738),d=n(7037),I=n(9589);class u extends d.L{constructor(t,e){super(t),this._contexts={},this._hub=e||(0,r.BF)(),this._name=t.name||"",this._metadata={...t.metadata},this._trimEnd=t.trimEnd,this.transaction=this;const n=this._metadata.dynamicSamplingContext;n&&(this._frozenDynamicSamplingContext={...n})}get name(){return this._name}set name(t){this.setName(t)}get metadata(){return{source:"custom",spanMetadata:{},...this._metadata,...this._attributes[a.i_]&&{source:this._attributes[a.i_]},...this._attributes[a.sy]&&{sampleRate:this._attributes[a.sy]}}}set metadata(t){this._metadata=t}setName(t,e="custom"){this._name=t,this.setAttribute(a.i_,e)}updateName(t){return this._name=t,this}initSpanRecorder(t=1e3){this.spanRecorder||(this.spanRecorder=new d.l(t)),this.spanRecorder.add(this)}setContext(t,e){null===e?delete this._contexts[t]:this._contexts[t]=e}setMeasurement(t,e,n=""){this._measurements[t]={value:e,unit:n}}setMetadata(t){this._metadata={...this._metadata,...t}}end(t){const e=(0,g.cI)(t),n=this._finishTransaction(e);if(n)return this._hub.captureEvent(n)}toContext(){const t=super.toContext();return(0,s.Ce)({...t,name:this._name,trimEnd:this._trimEnd})}updateWithContext(t){return super.updateWithContext(t),this._name=t.name||"",this._trimEnd=t.trimEnd,this}getDynamicSamplingContext(){return(0,l.k)(this)}setHub(t){this._hub=t}getProfileId(){if(void 0!==this._contexts&&void 0!==this._contexts.profile)return this._contexts.profile.profile_id}_finishTransaction(t){if(void 0!==this._endTime)return;this._name||(o.T&&i.vF.warn("Transaction has no name, falling back to ``."),this._name=""),super.end(t);const e=this._hub.getClient();if(e&&e.emit&&e.emit("finishTransaction",this),!0!==this._sampled)return o.T&&i.vF.log("[Tracing] Discarding transaction because its trace was not chosen to be sampled."),void(e&&e.recordDroppedEvent("sample_rate","transaction"));const n=this.spanRecorder?this.spanRecorder.spans.filter((t=>t!==this&&(0,g.et)(t).timestamp)):[];if(this._trimEnd&&n.length>0){const t=n.map((t=>(0,g.et)(t).timestamp)).filter(Boolean);this._endTime=t.reduce(((t,e)=>t>e?t:e))}const{scope:r,isolationScope:a}=(0,I.Lb)(this),{metadata:d}=this,{source:u}=d,C={contexts:{...this._contexts,trace:(0,g.kX)(this)},spans:n,start_timestamp:this._startTime,tags:this.tags,timestamp:this._endTime,transaction:this._name,type:"transaction",sdkProcessingMetadata:{...d,capturedSpanScope:r,capturedSpanIsolationScope:a,...(0,s.Ce)({dynamicSamplingContext:(0,l.k)(this)})},_metrics_summary:(0,c.g)(this),...u&&{transaction_info:{source:u}}};return Object.keys(this._measurements).length>0&&(o.T&&i.vF.log("[Measurements] Adding measurements to transaction",JSON.stringify(this._measurements,void 0,2)),C.measurements=this._measurements),o.T&&i.vF.log(`[Tracing] Finishing ${this.op} transaction: ${this._name}.`),C}}},1692:(t,e,n)=>{"use strict";n.d(e,{Z7:()=>o,nc:()=>r});var s=n(1206),i=n(6588);function o(t){return(t||(0,i.BF)()).getScope().getTransaction()}const r=s.nc},9266:(t,e,n)=>{"use strict";function s(t){return t.transaction}n.d(e,{z:()=>s})},5177:(t,e,n)=>{"use strict";n.d(e,{w:()=>i});var s=n(9071);function i(t){if("boolean"==typeof __SENTRY_TRACING__&&!__SENTRY_TRACING__)return!1;const e=(0,s.KU)(),n=t||e&&e.getOptions();return!!n&&(n.enableTracing||"tracesSampleRate"in n||"tracesSampler"in n)}},5895:(t,e,n)=>{"use strict";n.d(e,{CC:()=>r,Qh:()=>g,aO:()=>c,cI:()=>l,et:()=>I,kX:()=>a,pK:()=>u});var s=n(1041),i=n(1206),o=n(7567);const r=0,c=1;function a(t){const{spanId:e,traceId:n}=t.spanContext(),{data:i,op:o,parent_span_id:r,status:c,tags:a,origin:g}=I(t);return(0,s.Ce)({data:i,op:o,parent_span_id:r,span_id:e,status:c,tags:a,trace_id:n,origin:g})}function g(t){const{traceId:e,spanId:n}=t.spanContext(),s=u(t);return(0,i.TC)(e,n,s)}function l(t){return"number"==typeof t?d(t):Array.isArray(t)?t[0]+t[1]/1e9:t instanceof Date?d(t.getTime()):(0,o.zf)()}function d(t){return t>9999999999?t/1e3:t}function I(t){return function(t){return"function"==typeof t.getSpanJSON}(t)?t.getSpanJSON():"function"==typeof t.toJSON?t.toJSON():{}}function u(t){const{traceFlags:e}=t.spanContext();return Boolean(e&c)}},8562:(t,e,n)=>{"use strict";n.d(e,{De:()=>d,hF:()=>r,yD:()=>l});var s=n(9610),i=n(138),o=n(6202);const r="baggage",c="sentry-",a=/^sentry-/,g=8192;function l(t){if(!(0,i.Kg)(t)&&!Array.isArray(t))return;let e={};if(Array.isArray(t))e=t.reduce(((t,e)=>{const n=I(e);for(const e of Object.keys(n))t[e]=n[e];return t}),{});else{if(!t)return;e=I(t)}const n=Object.entries(e).reduce(((t,[e,n])=>(e.match(a)&&(t[e.slice(c.length)]=n),t)),{});return Object.keys(n).length>0?n:void 0}function d(t){if(t)return function(t){if(0!==Object.keys(t).length)return Object.entries(t).reduce(((t,[e,n],i)=>{const r=`${encodeURIComponent(e)}=${encodeURIComponent(n)}`,c=0===i?r:`${t},${r}`;return c.length>g?(s.T&&o.vF.warn(`Not adding key: ${e} with val: ${n} to baggage header due to exceeding baggage size limits.`),t):c}),"")}(Object.entries(t).reduce(((t,[e,n])=>(n&&(t[`${c}${e}`]=n),t)),{}))}function I(t){return t.split(",").map((t=>t.split("=").map((t=>decodeURIComponent(t.trim()))))).reduce(((t,[e,n])=>(t[e]=n,t)),{})}},9610:(t,e,n)=>{"use strict";n.d(e,{T:()=>s});const s="undefined"==typeof __SENTRY_DEBUG__||__SENTRY_DEBUG__},6768:(t,e,n)=>{"use strict";n.d(e,{AS:()=>g,aj:()=>l,s5:()=>a});var s=n(9610),i=n(6202),o=n(8231);const r={},c={};function a(t,e){r[t]=r[t]||[],r[t].push(e)}function g(t,e){c[t]||(e(),c[t]=!0)}function l(t,e){const n=t&&r[t];if(n)for(const r of n)try{r(e)}catch(e){s.T&&i.vF.error(`Error while triggering instrumentation handler.\nType: ${t}\nName: ${(0,o.qQ)(r)}\nError:`,e)}}},138:(t,e,n)=>{"use strict";n.d(e,{Kg:()=>o,Qd:()=>r,Qg:()=>a,gd:()=>c,tH:()=>l,yr:()=>g});const s=Object.prototype.toString;function i(t,e){return s.call(t)===`[object ${e}]`}function o(t){return i(t,"String")}function r(t){return i(t,"Object")}function c(t){return i(t,"RegExp")}function a(t){return Boolean(t&&t.then&&"function"==typeof t.then)}function g(t){return"number"==typeof t&&t!=t}function l(t,e){try{return t instanceof e}catch(t){return!1}}},6202:(t,e,n)=>{"use strict";n.d(e,{pq:()=>c,vF:()=>a});var s=n(9610),i=n(2231);const o=["debug","info","warn","error","log","assert","trace"],r={};function c(t){if(!("console"in i.OW))return t();const e=i.OW.console,n={},s=Object.keys(r);s.forEach((t=>{const s=r[t];n[t]=e[t],e[t]=s}));try{return t()}finally{s.forEach((t=>{e[t]=n[t]}))}}const a=function(){let t=!1;const e={enable:()=>{t=!0},disable:()=>{t=!1},isEnabled:()=>t};return s.T?o.forEach((n=>{e[n]=(...e)=>{t&&c((()=>{i.OW.console[n](`Sentry Logger [${n}]:`,...e)}))}})):o.forEach((t=>{e[t]=()=>{}})),e}()},4902:(t,e,n)=>{"use strict";n.d(e,{eJ:()=>i,k9:()=>o});var s=n(2231);function i(){const t=s.OW,e=t.crypto||t.msCrypto;let n=()=>16*Math.random();try{if(e&&e.randomUUID)return e.randomUUID().replace(/-/g,"");e&&e.getRandomValues&&(n=()=>{const t=new Uint8Array(1);return e.getRandomValues(t),t[0]})}catch(t){}return([1e7]+1e3+4e3+8e3+1e11).replace(/[018]/g,(t=>(t^(15&n())>>t/4).toString(16)))}function o(t){return Array.isArray(t)?t:[t]}},8560:(t,e,n)=>{"use strict";function s(){return!("undefined"!=typeof __SENTRY_BROWSER_BUNDLE__&&__SENTRY_BROWSER_BUNDLE__)&&"[object process]"===Object.prototype.toString.call("undefined"!=typeof process?process:0)}function i(t,e){return t.require(e)}function o(e){let n;try{n=i(t,e)}catch(t){}try{const{cwd:s}=i(t,"process");n=i(t,`${s()}/node_modules/${e}`)}catch(t){}return n}n.d(e,{fj:()=>i,wD:()=>s,Vw:()=>o}),t=n.hmd(t)},1041:(t,e,n)=>{"use strict";n.d(e,{Ce:()=>a,GS:()=>r,my:()=>c});var s=n(9610),i=n(138),o=n(6202);function r(t,e,n){if(!(e in t))return;const s=t[e],i=n(s);"function"==typeof i&&function(t,e){try{const n=e.prototype||{};t.prototype=e.prototype=n,c(t,"__sentry_original__",e)}catch(t){}}(i,s),t[e]=i}function c(t,e,n){try{Object.defineProperty(t,e,{value:n,writable:!0,configurable:!0})}catch(n){s.T&&o.vF.log(`Failed to add non-enumerable property "${e}" to object`,t)}}function a(t){return g(t,new Map)}function g(t,e){if(function(t){if(!(0,i.Qd)(t))return!1;try{const e=Object.getPrototypeOf(t).constructor.name;return!e||"Object"===e}catch(t){return!0}}(t)){const n=e.get(t);if(void 0!==n)return n;const s={};e.set(t,s);for(const n of Object.keys(t))void 0!==t[n]&&(s[n]=g(t[n],e));return s}if(Array.isArray(t)){const n=e.get(t);if(void 0!==n)return n;const s=[];return e.set(t,s),t.forEach((t=>{s.push(g(t,e))})),s}return t}},8231:(t,e,n)=>{"use strict";n.d(e,{qQ:()=>i});const s="";function i(t){try{return t&&"function"==typeof t&&t.name||s}catch(t){return s}}},7567:(t,e,n)=>{"use strict";n.d(e,{k3:()=>a,lu:()=>o,zf:()=>r});var s=n(2231);const i=1e3;function o(){return Date.now()/i}const r=function(){const{performance:t}=s.OW;if(!t||!t.now)return o;const e=Date.now()-t.now(),n=null==t.timeOrigin?e:t.timeOrigin;return()=>(n+t.now())/i}();let c;const a=(()=>{const{performance:t}=s.OW;if(!t||!t.now)return void(c="none");const e=36e5,n=t.now(),i=Date.now(),o=t.timeOrigin?Math.abs(t.timeOrigin+n-i):e,r=o{"use strict";n.d(e,{MI:()=>o,TC:()=>a,kM:()=>c,nc:()=>r});var s=n(8562),i=n(4902);const o=new RegExp("^[ \\t]*([0-9a-f]{32})?-?([0-9a-f]{16})?-?([01])?[ \\t]*$");function r(t){if(!t)return;const e=t.match(o);if(!e)return;let n;return"1"===e[3]?n=!0:"0"===e[3]&&(n=!1),{traceId:e[1],parentSampled:n,parentSpanId:e[2]}}function c(t,e){const n=r(t),o=(0,s.yD)(e),{traceId:c,parentSpanId:a,parentSampled:g}=n||{};return n?{traceId:c||(0,i.eJ)(),parentSpanId:a||(0,i.eJ)().substring(16),spanId:(0,i.eJ)().substring(16),sampled:g,dsc:o||{}}:{traceId:c||(0,i.eJ)(),spanId:(0,i.eJ)().substring(16)}}function a(t=(0,i.eJ)(),e=(0,i.eJ)().substring(16),n){let s="";return void 0!==n&&(s=n?"-1":"-0"),`${t}-${e}${s}`}},2231:(t,e,n)=>{"use strict";function s(t){return t&&t.Math==Math?t:void 0}n.d(e,{BY:()=>r,OW:()=>i,VZ:()=>o});const i="object"==typeof globalThis&&s(globalThis)||"object"==typeof window&&s(window)||"object"==typeof self&&s(self)||"object"==typeof global&&s(global)||function(){return this}()||{};function o(){return i}function r(t,e,n){const s=n||i,o=s.__SENTRY__=s.__SENTRY__||{};return o[t]||(o[t]=e())}},2967:(t,e,n)=>{"use strict";n.d(e,{U:()=>s});const s="production"},2220:(t,e,n)=>{"use strict";n.d(e,{T:()=>s});const s="undefined"==typeof __SENTRY_DEBUG__||__SENTRY_DEBUG__},2531:(t,e,n)=>{"use strict";n.d(e,{jB:()=>l,lG:()=>a,lb:()=>g});var s=n(6341),i=n(690),o=n(7412),r=n(3816),c=n(2220);function a(){return(0,s.BY)("globalEventProcessors",(()=>[]))}function g(t){a().push(t)}function l(t,e,n,s=0){return new i.T2(((i,a)=>{const g=t[s];if(null===e||"function"!=typeof g)i(e);else{const d=g({...e},n);c.T&&g.id&&null===d&&o.vF.log(`Event processor "${g.id}" dropped event`),(0,r.Qg)(d)?d.then((e=>l(t,e,n,s+1).then(i))).then(null,a):l(t,d,n,s+1).then(i).then(null,a)}}))}},3741:(t,e,n)=>{"use strict";n.d(e,{Cp:()=>u,Dp:()=>K,J0:()=>F,J5:()=>_,KU:()=>N,NA:()=>y,PN:()=>b,Q:()=>S,SE:()=>R,T$:()=>Y,VN:()=>H,Wt:()=>B,ZQ:()=>h,bX:()=>X,cx:()=>Z,gV:()=>A,hb:()=>v,ky:()=>J,l7:()=>G,nb:()=>f,o:()=>m,o5:()=>w,r:()=>p,rB:()=>V,v4:()=>W,wd:()=>C});var s=n(7412),i=n(6936),o=n(9297),r=n(3816),c=n(6341),a=n(2967),g=n(2220),l=n(6641),d=n(7058),I=n(9475);function u(t,e){return(0,l.BF)().captureException(t,(0,I.li)(e))}function C(t,e){const n="string"==typeof e?e:void 0,s="string"!=typeof e?{captureContext:e}:void 0;return(0,l.BF)().captureMessage(t,n,s)}function p(t,e){return(0,l.BF)().captureEvent(t,e)}function b(t){(0,l.BF)().configureScope(t)}function h(t,e){(0,l.BF)().addBreadcrumb(t,e)}function m(t,e){(0,l.BF)().setContext(t,e)}function Z(t){(0,l.BF)().setExtras(t)}function G(t,e){(0,l.BF)().setExtra(t,e)}function B(t){(0,l.BF)().setTags(t)}function y(t,e){(0,l.BF)().setTag(t,e)}function A(t){(0,l.BF)().setUser(t)}function W(...t){const e=(0,l.BF)();if(2===t.length){const[n,s]=t;return n?e.withScope((()=>(e.getStackTop().scope=n,s(n)))):e.withScope(s)}return e.withScope(t[0])}function V(t){return(0,l.fx)((()=>t((0,l.rm)())))}function v(t,e){return W((n=>(n.setSpan(t),e(n))))}function f(t,e){return(0,l.BF)().startTransaction({...t},e)}function R(t,e){const n=w(),o=N();if(o){if(o.captureCheckIn)return o.captureCheckIn(t,e,n);g.T&&s.vF.warn("Cannot capture check-in. Client does not support sending check-ins.")}else g.T&&s.vF.warn("Cannot capture check-in. No client defined.");return(0,i.eJ)()}function Y(t,e,n){const s=R({monitorSlug:t,status:"in_progress"},n),i=(0,o.zf)();function c(e){R({monitorSlug:t,status:e,checkInId:s,duration:(0,o.zf)()-i})}let a;try{a=e()}catch(t){throw c("error"),t}return(0,r.Qg)(a)?Promise.resolve(a).then((()=>{c("ok")}),(()=>{c("error")})):c("ok"),a}async function X(t){const e=N();return e?e.flush(t):(g.T&&s.vF.warn("Cannot flush events. No client defined."),Promise.resolve(!1))}async function H(t){const e=N();return e?e.close(t):(g.T&&s.vF.warn("Cannot flush events and disable SDK. No client defined."),Promise.resolve(!1))}function S(){return(0,l.BF)().lastEventId()}function N(){return(0,l.BF)().getClient()}function K(){return!!N()}function w(){return(0,l.BF)().getScope()}function F(t){const e=N(),n=(0,l.rm)(),s=w(),{release:i,environment:o=a.U}=e&&e.getOptions()||{},{userAgent:r}=c.OW.navigator||{},g=(0,d.fj)({release:i,environment:o,user:s.getUser()||n.getUser(),...r&&{userAgent:r},...t}),I=n.getSession();return I&&"ok"===I.status&&(0,d.qO)(I,{status:"exited"}),J(),n.setSession(g),s.setSession(g),g}function J(){const t=(0,l.rm)(),e=w(),n=e.getSession()||t.getSession();n&&(0,d.Vu)(n),k(),t.setSession(),e.setSession()}function k(){const t=(0,l.rm)(),e=w(),n=N(),s=e.getSession()||t.getSession();s&&n&&n.captureSession&&n.captureSession(s)}function _(t=!1){t?J():k()}},6641:(t,e,n)=>{"use strict";n.d(e,{BF:()=>m,EU:()=>b,Me:()=>V,TF:()=>B,YZ:()=>p,fx:()=>A,gM:()=>h,lq:()=>v,nX:()=>y,rm:()=>Z});var s=n(3816),i=n(6936),o=n(9297),r=n(7412),c=n(6341),a=n(2967),g=n(2220),l=n(2486),d=n(7058),I=n(7986);const u=parseFloat(I.M),C=100;class p{constructor(t,e,n,s=u){let i,o;this._version=s,e?i=e:(i=new l.HG,i.setClient(t)),n?o=n:(o=new l.HG,o.setClient(t)),this._stack=[{scope:i}],t&&this.bindClient(t),this._isolationScope=o}isOlderThan(t){return this._version(this.popScope(),t)),(t=>{throw this.popScope(),t})):(this.popScope(),n)}getClient(){return this.getStackTop().client}getScope(){return this.getStackTop().scope}getIsolationScope(){return this._isolationScope}getStack(){return this._stack}getStackTop(){return this._stack[this._stack.length-1]}captureException(t,e){const n=this._lastEventId=e&&e.event_id?e.event_id:(0,i.eJ)(),s=new Error("Sentry syntheticException");return this.getScope().captureException(t,{originalException:t,syntheticException:s,...e,event_id:n}),n}captureMessage(t,e,n){const s=this._lastEventId=n&&n.event_id?n.event_id:(0,i.eJ)(),o=new Error(t);return this.getScope().captureMessage(t,e,{originalException:t,syntheticException:o,...n,event_id:s}),s}captureEvent(t,e){const n=e&&e.event_id?e.event_id:(0,i.eJ)();return t.type||(this._lastEventId=n),this.getScope().captureEvent(t,{...e,event_id:n}),n}lastEventId(){return this._lastEventId}addBreadcrumb(t,e){const{scope:n,client:s}=this.getStackTop();if(!s)return;const{beforeBreadcrumb:i=null,maxBreadcrumbs:c=C}=s.getOptions&&s.getOptions()||{};if(c<=0)return;const a={timestamp:(0,o.lu)(),...t},g=i?(0,r.pq)((()=>i(a,e))):a;null!==g&&(s.emit&&s.emit("beforeAddBreadcrumb",g,e),n.addBreadcrumb(g,c))}setUser(t){this.getScope().setUser(t),this.getIsolationScope().setUser(t)}setTags(t){this.getScope().setTags(t),this.getIsolationScope().setTags(t)}setExtras(t){this.getScope().setExtras(t),this.getIsolationScope().setExtras(t)}setTag(t,e){this.getScope().setTag(t,e),this.getIsolationScope().setTag(t,e)}setExtra(t,e){this.getScope().setExtra(t,e),this.getIsolationScope().setExtra(t,e)}setContext(t,e){this.getScope().setContext(t,e),this.getIsolationScope().setContext(t,e)}configureScope(t){const{scope:e,client:n}=this.getStackTop();n&&t(e)}run(t){const e=h(this);try{t(this)}finally{h(e)}}getIntegration(t){const e=this.getClient();if(!e)return null;try{return e.getIntegration(t)}catch(e){return g.T&&r.vF.warn(`Cannot retrieve integration ${t.id} from the current Hub`),null}}startTransaction(t,e){const n=this._callExtensionMethod("startTransaction",t,e);return g.T&&!n&&(this.getClient()?r.vF.warn("Tracing extension 'startTransaction' has not been added. Call 'addTracingExtensions' before calling 'init':\nSentry.addTracingExtensions();\nSentry.init({...});\n"):r.vF.warn("Tracing extension 'startTransaction' is missing. You should 'init' the SDK before calling 'startTransaction'")),n}traceHeaders(){return this._callExtensionMethod("traceHeaders")}captureSession(t=!1){if(t)return this.endSession();this._sendSessionUpdate()}endSession(){const t=this.getStackTop().scope,e=t.getSession();e&&(0,d.Vu)(e),this._sendSessionUpdate(),t.setSession()}startSession(t){const{scope:e,client:n}=this.getStackTop(),{release:s,environment:i=a.U}=n&&n.getOptions()||{},{userAgent:o}=c.OW.navigator||{},r=(0,d.fj)({release:s,environment:i,user:e.getUser(),...o&&{userAgent:o},...t}),g=e.getSession&&e.getSession();return g&&"ok"===g.status&&(0,d.qO)(g,{status:"exited"}),this.endSession(),e.setSession(r),r}shouldSendDefaultPii(){const t=this.getClient(),e=t&&t.getOptions();return Boolean(e&&e.sendDefaultPii)}_sendSessionUpdate(){const{scope:t,client:e}=this.getStackTop(),n=t.getSession();n&&e&&e.captureSession&&e.captureSession(n)}_callExtensionMethod(t,...e){const n=b().__SENTRY__;if(n&&n.extensions&&"function"==typeof n.extensions[t])return n.extensions[t].apply(this,e);g.T&&r.vF.warn(`Extension method ${t} couldn't be found, doing nothing.`)}}function b(){return c.OW.__SENTRY__=c.OW.__SENTRY__||{extensions:{},hub:void 0},c.OW}function h(t){const e=b(),n=V(e);return v(e,t),n}function m(){const t=b();if(t.__SENTRY__&&t.__SENTRY__.acs){const e=t.__SENTRY__.acs.getCurrentHub();if(e)return e}return G(t)}function Z(){return m().getIsolationScope()}function G(t=b()){return W(t)&&!V(t).isOlderThan(u)||v(t,new p),V(t)}function B(t,e=G()){if(!W(t)||V(t).isOlderThan(u)){const n=e.getClient(),s=e.getScope(),i=e.getIsolationScope();v(t,new p(n,s.clone(),i.clone()))}}function y(t){const e=b();e.__SENTRY__=e.__SENTRY__||{},e.__SENTRY__.acs=t}function A(t,e={}){const n=b();return n.__SENTRY__&&n.__SENTRY__.acs?n.__SENTRY__.acs.runWithAsyncContext(t,e):t()}function W(t){return!!(t&&t.__SENTRY__&&t.__SENTRY__.hub)}function V(t){return(0,c.BY)("hub",(()=>new p),t)}function v(t,e){return!!t&&((t.__SENTRY__=t.__SENTRY__||{}).hub=e,!0)}},5836:(t,e,n)=>{"use strict";n.d(e,{F:()=>p,P$:()=>d,Q8:()=>C,_C:()=>b,lc:()=>I,mH:()=>l,qm:()=>u});var s=n(6936),i=n(7412),o=n(2220),r=n(2531),c=n(3741),a=n(6641);const g=[];function l(t){const e=t.defaultIntegrations||[],n=t.integrations;let i;e.forEach((t=>{t.isDefaultInstance=!0})),i=Array.isArray(n)?[...e,...n]:"function"==typeof n?(0,s.k9)(n(e)):e;const o=function(t){const e={};return t.forEach((t=>{const{name:n}=t,s=e[n];s&&!s.isDefaultInstance&&t.isDefaultInstance||(e[n]=t)})),Object.keys(e).map((t=>e[t]))}(i),r=function(t){for(let e=0;e{e&&u(t,e,n)})),n}function I(t,e){for(const n of e)n&&n.afterAllSetup&&n.afterAllSetup(t)}function u(t,e,n){if(n[e.name])o.T&&i.vF.log(`Integration skipped because it was already installed: ${e.name}`);else{if(n[e.name]=e,-1===g.indexOf(e.name)&&(e.setupOnce(r.lb,a.BF),g.push(e.name)),e.setup&&"function"==typeof e.setup&&e.setup(t),t.on&&"function"==typeof e.preprocessEvent){const n=e.preprocessEvent.bind(e);t.on("preprocessEvent",((e,s)=>n(e,s,t)))}if(t.addEventProcessor&&"function"==typeof e.processEvent){const n=e.processEvent.bind(e),s=Object.assign(((e,s)=>n(e,s,t)),{id:e.name});t.addEventProcessor(s)}o.T&&i.vF.log(`Integration installed: ${e.name}`)}}function C(t){const e=(0,c.KU)();e&&e.addIntegration?e.addIntegration(t):o.T&&i.vF.warn(`Cannot add integration "${t.name}" because no SDK Client is available.`)}function p(t,e){return Object.assign((function(...t){return e(...t)}),{id:t})}function b(t){return t}},2486:(t,e,n)=>{"use strict";n.d(e,{HG:()=>d,m6:()=>I});var s=n(3816),i=n(9297),o=n(6936),r=n(7412),c=n(2531),a=n(7058),g=n(1535);let l;class d{constructor(){this._notifyingListeners=!1,this._scopeListeners=[],this._eventProcessors=[],this._breadcrumbs=[],this._attachments=[],this._user={},this._tags={},this._extra={},this._contexts={},this._sdkProcessingMetadata={},this._propagationContext=u()}static clone(t){return t?t.clone():new d}clone(){const t=new d;return t._breadcrumbs=[...this._breadcrumbs],t._tags={...this._tags},t._extra={...this._extra},t._contexts={...this._contexts},t._user=this._user,t._level=this._level,t._span=this._span,t._session=this._session,t._transactionName=this._transactionName,t._fingerprint=this._fingerprint,t._eventProcessors=[...this._eventProcessors],t._requestSession=this._requestSession,t._attachments=[...this._attachments],t._sdkProcessingMetadata={...this._sdkProcessingMetadata},t._propagationContext={...this._propagationContext},t._client=this._client,t}setClient(t){this._client=t}getClient(){return this._client}addScopeListener(t){this._scopeListeners.push(t)}addEventProcessor(t){return this._eventProcessors.push(t),this}setUser(t){return this._user=t||{email:void 0,id:void 0,ip_address:void 0,segment:void 0,username:void 0},this._session&&(0,a.qO)(this._session,{user:t}),this._notifyScopeListeners(),this}getUser(){return this._user}getRequestSession(){return this._requestSession}setRequestSession(t){return this._requestSession=t,this}setTags(t){return this._tags={...this._tags,...t},this._notifyScopeListeners(),this}setTag(t,e){return this._tags={...this._tags,[t]:e},this._notifyScopeListeners(),this}setExtras(t){return this._extra={...this._extra,...t},this._notifyScopeListeners(),this}setExtra(t,e){return this._extra={...this._extra,[t]:e},this._notifyScopeListeners(),this}setFingerprint(t){return this._fingerprint=t,this._notifyScopeListeners(),this}setLevel(t){return this._level=t,this._notifyScopeListeners(),this}setTransactionName(t){return this._transactionName=t,this._notifyScopeListeners(),this}setContext(t,e){return null===e?delete this._contexts[t]:this._contexts[t]=e,this._notifyScopeListeners(),this}setSpan(t){return this._span=t,this._notifyScopeListeners(),this}getSpan(){return this._span}getTransaction(){const t=this._span;return t&&t.transaction}setSession(t){return t?this._session=t:delete this._session,this._notifyScopeListeners(),this}getSession(){return this._session}update(t){if(!t)return this;const e="function"==typeof t?t(this):t;if(e instanceof d){const t=e.getScopeData();this._tags={...this._tags,...t.tags},this._extra={...this._extra,...t.extra},this._contexts={...this._contexts,...t.contexts},t.user&&Object.keys(t.user).length&&(this._user=t.user),t.level&&(this._level=t.level),t.fingerprint.length&&(this._fingerprint=t.fingerprint),e.getRequestSession()&&(this._requestSession=e.getRequestSession()),t.propagationContext&&(this._propagationContext=t.propagationContext)}else if((0,s.Qd)(e)){const e=t;this._tags={...this._tags,...e.tags},this._extra={...this._extra,...e.extra},this._contexts={...this._contexts,...e.contexts},e.user&&(this._user=e.user),e.level&&(this._level=e.level),e.fingerprint&&(this._fingerprint=e.fingerprint),e.requestSession&&(this._requestSession=e.requestSession),e.propagationContext&&(this._propagationContext=e.propagationContext)}return this}clear(){return this._breadcrumbs=[],this._tags={},this._extra={},this._user={},this._contexts={},this._level=void 0,this._transactionName=void 0,this._fingerprint=void 0,this._requestSession=void 0,this._span=void 0,this._session=void 0,this._notifyScopeListeners(),this._attachments=[],this._propagationContext=u(),this}addBreadcrumb(t,e){const n="number"==typeof e?e:100;if(n<=0)return this;const s={timestamp:(0,i.lu)(),...t},o=this._breadcrumbs;return o.push(s),this._breadcrumbs=o.length>n?o.slice(-n):o,this._notifyScopeListeners(),this}getLastBreadcrumb(){return this._breadcrumbs[this._breadcrumbs.length-1]}clearBreadcrumbs(){return this._breadcrumbs=[],this._notifyScopeListeners(),this}addAttachment(t){return this._attachments.push(t),this}getAttachments(){return this.getScopeData().attachments}clearAttachments(){return this._attachments=[],this}getScopeData(){const{_breadcrumbs:t,_attachments:e,_contexts:n,_tags:s,_extra:i,_user:o,_level:r,_fingerprint:c,_eventProcessors:a,_propagationContext:g,_sdkProcessingMetadata:l,_transactionName:d,_span:I}=this;return{breadcrumbs:t,attachments:e,contexts:n,tags:s,extra:i,user:o,level:r,fingerprint:c||[],eventProcessors:a,propagationContext:g,sdkProcessingMetadata:l,transactionName:d,span:I}}applyToEvent(t,e={},n=[]){(0,g.e2)(t,this.getScopeData());const s=[...n,...(0,c.lG)(),...this._eventProcessors];return(0,c.jB)(s,t,e)}setSDKProcessingMetadata(t){return this._sdkProcessingMetadata={...this._sdkProcessingMetadata,...t},this}setPropagationContext(t){return this._propagationContext=t,this}getPropagationContext(){return this._propagationContext}captureException(t,e){const n=e&&e.event_id?e.event_id:(0,o.eJ)();if(!this._client)return r.vF.warn("No client configured on scope - will not capture exception!"),n;const s=new Error("Sentry syntheticException");return this._client.captureException(t,{originalException:t,syntheticException:s,...e,event_id:n},this),n}captureMessage(t,e,n){const s=n&&n.event_id?n.event_id:(0,o.eJ)();if(!this._client)return r.vF.warn("No client configured on scope - will not capture message!"),s;const i=new Error(t);return this._client.captureMessage(t,e,{originalException:t,syntheticException:i,...n,event_id:s},this),s}captureEvent(t,e){const n=e&&e.event_id?e.event_id:(0,o.eJ)();return this._client?(this._client.captureEvent(t,{...e,event_id:n},this),n):(r.vF.warn("No client configured on scope - will not capture event!"),n)}_notifyScopeListeners(){this._notifyingListeners||(this._notifyingListeners=!0,this._scopeListeners.forEach((t=>{t(this)})),this._notifyingListeners=!1)}}function I(){return l||(l=new d),l}function u(){return{traceId:(0,o.eJ)(),spanId:(0,o.eJ)().substring(16)}}},7058:(t,e,n)=>{"use strict";n.d(e,{Vu:()=>a,fj:()=>r,qO:()=>c});var s=n(9297),i=n(6936),o=n(4022);function r(t){const e=(0,s.zf)(),n={sid:(0,i.eJ)(),init:!0,timestamp:e,started:e,duration:0,status:"ok",errors:0,ignoreDuration:!1,toJSON:()=>function(t){return(0,o.Ce)({sid:`${t.sid}`,init:t.init,started:new Date(1e3*t.started).toISOString(),timestamp:new Date(1e3*t.timestamp).toISOString(),status:t.status,errors:t.errors,did:"number"==typeof t.did||"string"==typeof t.did?`${t.did}`:void 0,duration:t.duration,abnormal_mechanism:t.abnormal_mechanism,attrs:{release:t.release,environment:t.environment,ip_address:t.ipAddress,user_agent:t.userAgent}})}(n)};return t&&c(n,t),n}function c(t,e={}){if(e.user&&(!t.ipAddress&&e.user.ip_address&&(t.ipAddress=e.user.ip_address),t.did||e.did||(t.did=e.user.id||e.user.email||e.user.username)),t.timestamp=e.timestamp||(0,s.zf)(),e.abnormal_mechanism&&(t.abnormal_mechanism=e.abnormal_mechanism),e.ignoreDuration&&(t.ignoreDuration=e.ignoreDuration),e.sid&&(t.sid=32===e.sid.length?e.sid:(0,i.eJ)()),void 0!==e.init&&(t.init=e.init),!t.did&&e.did&&(t.did=`${e.did}`),"number"==typeof e.started&&(t.started=e.started),t.ignoreDuration)t.duration=void 0;else if("number"==typeof e.duration)t.duration=e.duration;else{const e=t.timestamp-t.started;t.duration=e>=0?e:0}e.release&&(t.release=e.release),e.environment&&(t.environment=e.environment),!t.ipAddress&&e.ipAddress&&(t.ipAddress=e.ipAddress),!t.userAgent&&e.userAgent&&(t.userAgent=e.userAgent),"number"==typeof e.errors&&(t.errors=e.errors),e.status&&(t.status=e.status)}function a(t,e){let n={};e?n={status:e}:"ok"===t.status&&(n={status:"exited"}),c(t,n)}},5452:(t,e,n)=>{"use strict";n.d(e,{k:()=>g,l:()=>a});var s=n(4022),i=n(2967),o=n(3741),r=n(4636),c=n(3445);function a(t,e,n){const o=e.getOptions(),{publicKey:r}=e.getDsn()||{},{segment:c}=n&&n.getUser()||{},a=(0,s.Ce)({environment:o.environment||i.U,release:o.release,user_segment:c,public_key:r,trace_id:t});return e.emit&&e.emit("createDsc",a),a}function g(t){const e=(0,o.KU)();if(!e)return{};const n=a((0,c.et)(t).trace_id||"",e,(0,o.o5)()),s=(0,r.z)(t);if(!s)return n;const i=s&&s._frozenDynamicSamplingContext;if(i)return i;const{sampleRate:g,source:l}=s.metadata;null!=g&&(n.sample_rate=`${g}`);const d=(0,c.et)(s);return l&&"url"!==l&&(n.transaction=d.description),n.sampled=String((0,c.pK)(s)),e.emit&&e.emit("createDsc",n),n}},1535:(t,e,n)=>{"use strict";n.d(e,{Rg:()=>g,e2:()=>a});var s=n(4022),i=n(6936),o=n(5452),r=n(4636),c=n(3445);function a(t,e){const{fingerprint:n,span:a,breadcrumbs:g,sdkProcessingMetadata:l}=e;!function(t,e){const{extra:n,tags:i,user:o,contexts:r,level:c,transactionName:a}=e,g=(0,s.Ce)(n);g&&Object.keys(g).length&&(t.extra={...g,...t.extra});const l=(0,s.Ce)(i);l&&Object.keys(l).length&&(t.tags={...l,...t.tags});const d=(0,s.Ce)(o);d&&Object.keys(d).length&&(t.user={...d,...t.user});const I=(0,s.Ce)(r);I&&Object.keys(I).length&&(t.contexts={...I,...t.contexts}),c&&(t.level=c),a&&(t.transaction=a)}(t,e),a&&function(t,e){t.contexts={trace:(0,c.kX)(e),...t.contexts};const n=(0,r.z)(e);if(n){t.sdkProcessingMetadata={dynamicSamplingContext:(0,o.k)(e),...t.sdkProcessingMetadata};const s=(0,c.et)(n).description;s&&(t.tags={transaction:s,...t.tags})}}(t,a),function(t,e){t.fingerprint=t.fingerprint?(0,i.k9)(t.fingerprint):[],e&&(t.fingerprint=t.fingerprint.concat(e)),t.fingerprint&&!t.fingerprint.length&&delete t.fingerprint}(t,n),function(t,e){const n=[...t.breadcrumbs||[],...e];t.breadcrumbs=n.length?n:void 0}(t,g),function(t,e){t.sdkProcessingMetadata={...t.sdkProcessingMetadata,...e}}(t,l)}function g(t,e){const{extra:n,tags:s,user:i,contexts:o,level:r,sdkProcessingMetadata:c,breadcrumbs:a,fingerprint:g,eventProcessors:d,attachments:I,propagationContext:u,transactionName:C,span:p}=e;l(t,"extra",n),l(t,"tags",s),l(t,"user",i),l(t,"contexts",o),l(t,"sdkProcessingMetadata",c),r&&(t.level=r),C&&(t.transactionName=C),p&&(t.span=p),a.length&&(t.breadcrumbs=[...t.breadcrumbs,...a]),g.length&&(t.fingerprint=[...t.fingerprint,...g]),d.length&&(t.eventProcessors=[...t.eventProcessors,...d]),I.length&&(t.attachments=[...t.attachments,...I]),t.propagationContext={...t.propagationContext,...u}}function l(t,e,n){if(n&&Object.keys(n).length){t[e]={...t[e]};for(const s in n)Object.prototype.hasOwnProperty.call(n,s)&&(t[e][s]=n[s])}}},4636:(t,e,n)=>{"use strict";function s(t){return t.transaction}n.d(e,{z:()=>s})},9475:(t,e,n)=>{"use strict";n.d(e,{li:()=>p,mG:()=>u});var s=n(6936),i=n(9297),o=n(9653),r=n(6341),c=n(2181),a=n(2967),g=n(2531),l=n(2486),d=n(1535),I=n(3445);function u(t,e,n,u,p,b){const{normalizeDepth:h=3,normalizeMaxBreadth:m=1e3}=t,Z={...e,event_id:e.event_id||n.event_id||(0,s.eJ)(),timestamp:e.timestamp||(0,i.lu)()},G=n.integrations||t.integrations.map((t=>t.name));!function(t,e){const{environment:n,release:s,dist:i,maxValueLength:r=250}=e;"environment"in t||(t.environment="environment"in e?n:a.U),void 0===t.release&&void 0!==s&&(t.release=s),void 0===t.dist&&void 0!==i&&(t.dist=i),t.message&&(t.message=(0,o.xv)(t.message,r));const c=t.exception&&t.exception.values&&t.exception.values[0];c&&c.value&&(c.value=(0,o.xv)(c.value,r));const g=t.request;g&&g.url&&(g.url=(0,o.xv)(g.url,r))}(Z,t),function(t,e){e.length>0&&(t.sdk=t.sdk||{},t.sdk.integrations=[...t.sdk.integrations||[],...e])}(Z,G),void 0===e.type&&function(t,e){const n=r.OW._sentryDebugIds;if(!n)return;let s;const i=C.get(e);i?s=i:(s=new Map,C.set(e,s));const o=Object.keys(n).reduce(((t,i)=>{let o;const r=s.get(i);r?o=r:(o=e(i),s.set(i,o));for(let e=o.length-1;e>=0;e--){const s=o[e];if(s.filename){t[s.filename]=n[i];break}}return t}),{});try{t.exception.values.forEach((t=>{t.stacktrace.frames.forEach((t=>{t.filename&&(t.debug_id=o[t.filename])}))}))}catch(t){}}(Z,t.stackParser);const B=function(t,e){if(!e)return t;const n=t?t.clone():new l.HG;return n.update(e),n}(u,n.captureContext);n.mechanism&&(0,s.M6)(Z,n.mechanism);const y=p&&p.getEventProcessors?p.getEventProcessors():[],A=(0,l.m6)().getScopeData();if(b){const t=b.getScopeData();(0,d.Rg)(A,t)}if(B){const t=B.getScopeData();(0,d.Rg)(A,t)}const W=[...n.attachments||[],...A.attachments];W.length&&(n.attachments=W),(0,d.e2)(Z,A);const V=[...y,...(0,g.lG)(),...A.eventProcessors];return(0,g.jB)(V,Z,n).then((t=>(t&&function(t){const e={};try{t.exception.values.forEach((t=>{t.stacktrace.frames.forEach((t=>{t.debug_id&&(t.abs_path?e[t.abs_path]=t.debug_id:t.filename&&(e[t.filename]=t.debug_id),delete t.debug_id)}))}))}catch(t){}if(0===Object.keys(e).length)return;t.debug_meta=t.debug_meta||{},t.debug_meta.images=t.debug_meta.images||[];const n=t.debug_meta.images;Object.keys(e).forEach((t=>{n.push({type:"sourcemap",code_file:t,debug_id:e[t]})}))}(t),"number"==typeof h&&h>0?function(t,e,n){if(!t)return null;const s={...t,...t.breadcrumbs&&{breadcrumbs:t.breadcrumbs.map((t=>({...t,...t.data&&{data:(0,c.S8)(t.data,e,n)}})))},...t.user&&{user:(0,c.S8)(t.user,e,n)},...t.contexts&&{contexts:(0,c.S8)(t.contexts,e,n)},...t.extra&&{extra:(0,c.S8)(t.extra,e,n)}};return t.contexts&&t.contexts.trace&&s.contexts&&(s.contexts.trace=t.contexts.trace,t.contexts.trace.data&&(s.contexts.trace.data=(0,c.S8)(t.contexts.trace.data,e,n))),t.spans&&(s.spans=t.spans.map((t=>{const s=(0,I.et)(t).data;return s&&(t.data=(0,c.S8)(s,e,n)),t}))),s}(t,h,m):t)))}const C=new WeakMap;function p(t){if(t)return function(t){return t instanceof l.HG||"function"==typeof t}(t)||function(t){return Object.keys(t).some((t=>b.includes(t)))}(t)?{captureContext:t}:t}const b=["user","level","extra","contexts","tags","fingerprint","requestSession","propagationContext"]},3445:(t,e,n)=>{"use strict";n.d(e,{CC:()=>r,Qh:()=>g,aO:()=>c,cI:()=>l,et:()=>I,kX:()=>a,pK:()=>u});var s=n(4022),i=n(6524),o=n(9297);const r=0,c=1;function a(t){const{spanId:e,traceId:n}=t.spanContext(),{data:i,op:o,parent_span_id:r,status:c,tags:a,origin:g}=I(t);return(0,s.Ce)({data:i,op:o,parent_span_id:r,span_id:e,status:c,tags:a,trace_id:n,origin:g})}function g(t){const{traceId:e,spanId:n}=t.spanContext(),s=u(t);return(0,i.TC)(e,n,s)}function l(t){return"number"==typeof t?d(t):Array.isArray(t)?t[0]+t[1]/1e9:t instanceof Date?d(t.getTime()):(0,o.zf)()}function d(t){return t>9999999999?t/1e3:t}function I(t){return function(t){return"function"==typeof t.getSpanJSON}(t)?t.getSpanJSON():"function"==typeof t.toJSON?t.toJSON():{}}function u(t){const{traceFlags:e}=t.spanContext();return Boolean(e&c)}},7986:(t,e,n)=>{"use strict";n.d(e,{M:()=>s});const s="7.119.0"},6497:(t,e,n)=>{"use strict";n.r(e),n.d(e,{DEFAULT_USER_INCLUDES:()=>ge,Handlers:()=>i,Http:()=>os,Hub:()=>nt.YZ,Integrations:()=>Io,NodeClient:()=>Me,SDK_VERSION:()=>Ge.M,SEMANTIC_ATTRIBUTE_SENTRY_OP:()=>_,SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN:()=>z,SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE:()=>k,SEMANTIC_ATTRIBUTE_SENTRY_SOURCE:()=>J,Scope:()=>Be.HG,Undici:()=>Ns,addBreadcrumb:()=>a.ZQ,addEventProcessor:()=>bt,addGlobalEventProcessor:()=>ye.lb,addIntegration:()=>g.Q8,addRequestDataToEvent:()=>Ie,anrIntegration:()=>js.a,autoDiscoverNodePerformanceMonitoringIntegrations:()=>We,captureCheckIn:()=>a.SE,captureConsoleIntegration:()=>Vi,captureEvent:()=>a.r,captureException:()=>a.Cp,captureMessage:()=>a.wd,captureSession:()=>a.J5,close:()=>a.VN,configureScope:()=>a.PN,consoleIntegration:()=>Rn,contextLinesIntegration:()=>Qn,continueTrace:()=>ft,createGetModuleFromFilename:()=>_s,createTransport:()=>Kt,cron:()=>uo,debugIntegration:()=>fi,dedupeIntegration:()=>Xi,deepReadDirSync:()=>Qs,defaultIntegrations:()=>zs,defaultStackParser:()=>Ls,enableAnrDetection:()=>Os,endSession:()=>a.ky,extraErrorDataIntegration:()=>Fi,extractRequestData:()=>de,extractTraceparentData:()=>Jt,flush:()=>a.bX,functionToStringIntegration:()=>u,getActiveSpan:()=>vt,getActiveTransaction:()=>Ft,getClient:()=>a.KU,getCurrentHub:()=>nt.BF,getCurrentScope:()=>a.o5,getDefaultIntegrations:()=>Us,getGlobalScope:()=>Be.m6,getHubFromCarrier:()=>nt.Me,getIsolationScope:()=>nt.rm,getModuleFromFilename:()=>lo,getSentryRelease:()=>Es,getSpanStatusFromHttpCode:()=>_t,hapiErrorPlugin:()=>ii,hapiIntegration:()=>ci,httpClientIntegration:()=>ji,httpIntegration:()=>is,inboundFiltersIntegration:()=>y,init:()=>xs,isInitialized:()=>a.Dp,lastEventId:()=>a.Q,linkedErrorsIntegration:()=>K,localVariablesIntegration:()=>ps,makeMain:()=>nt.gM,makeNodeTransport:()=>Cn,metrics:()=>ne,modulesIntegration:()=>Zs,nativeNodeFetchintegration:()=>Ss,nodeContextIntegration:()=>Fn,onUncaughtExceptionIntegration:()=>As,onUnhandledRejectionIntegration:()=>vs,parameterize:()=>se,reportingObserverIntegration:()=>no,requestDataIntegration:()=>be,rewriteFramesIntegration:()=>io,runWithAsyncContext:()=>nt.fx,sessionTimingIntegration:()=>ro,setContext:()=>a.o,setCurrentClient:()=>me,setExtra:()=>a.l7,setExtras:()=>a.cx,setHttpStatus:()=>Ut,setMeasurement:()=>Ze,setTag:()=>a.NA,setTags:()=>a.Wt,setUser:()=>a.gV,spanStatusfromHttpCode:()=>zt,spotlightIntegration:()=>Ys,startActiveSpan:()=>At,startInactiveSpan:()=>Vt,startSession:()=>a.J0,startSpan:()=>yt,startSpanManual:()=>Wt,startTransaction:()=>a.nb,trace:()=>Bt,trpcMiddleware:()=>Ms,withActiveSpan:()=>a.hb,withIsolationScope:()=>a.rB,withMonitor:()=>a.T$,withScope:()=>a.v4});var s={};n.r(s),n.d(s,{FunctionToString:()=>C,InboundFilters:()=>A,LinkedErrors:()=>w});var i={};n.r(i),n.d(i,{errorHandler:()=>ei,extractRequestData:()=>Ps,parseRequest:()=>Ds,requestHandler:()=>$s,tracingHandler:()=>qs,trpcMiddleware:()=>ni});var o={};n.r(o),n.d(o,{Anr:()=>js.M,Console:()=>Yn,Context:()=>Jn,ContextLines:()=>jn,Hapi:()=>ai,Http:()=>os,LocalVariables:()=>Cs,Modules:()=>Gs,OnUncaughtException:()=>Ws,OnUnhandledRejection:()=>fs,RequestData:()=>he,Spotlight:()=>Xs,Undici:()=>Ns});var r={};n.r(r),n.d(r,{Apollo:()=>Ii,Express:()=>Ci,GraphQL:()=>hi,Mongo:()=>Gi,Mysql:()=>Bi,Postgres:()=>yi,Prisma:()=>Ai});var c=n(4022),a=n(3741),g=n(5836);let l;const d="FunctionToString",I=new WeakMap,u=(0,g._C)((()=>({name:d,setupOnce(){l=Function.prototype.toString;try{Function.prototype.toString=function(...t){const e=(0,c.sp)(this),n=I.has((0,a.KU)())&&void 0!==e?e:this;return l.apply(n,t)}}catch(t){}},setup(t){I.set(t,!0)}}))),C=(0,g.F)(d,u);var p=n(7412),b=n(6936),h=n(9653),m=n(2220);const Z=[/^Script error\.?$/,/^Javascript error: Script error\.? on line 0$/,/^ResizeObserver loop completed with undelivered notifications.$/,/^Cannot redefine property: googletag$/],G=[/^.*\/healthcheck$/,/^.*\/healthy$/,/^.*\/live$/,/^.*\/ready$/,/^.*\/heartbeat$/,/^.*\/health$/,/^.*\/healthz$/],B="InboundFilters",y=(0,g._C)(((t={})=>({name:B,setupOnce(){},processEvent(e,n,s){const i=s.getOptions(),o=function(t={},e={}){return{allowUrls:[...t.allowUrls||[],...e.allowUrls||[]],denyUrls:[...t.denyUrls||[],...e.denyUrls||[]],ignoreErrors:[...t.ignoreErrors||[],...e.ignoreErrors||[],...t.disableErrorDefaults?[]:Z],ignoreTransactions:[...t.ignoreTransactions||[],...e.ignoreTransactions||[],...t.disableTransactionDefaults?[]:G],ignoreInternal:void 0===t.ignoreInternal||t.ignoreInternal}}(t,i);return function(t,e){return e.ignoreInternal&&function(t){try{return"SentryError"===t.exception.values[0].type}catch(t){}return!1}(t)?(m.T&&p.vF.warn(`Event dropped due to being internal Sentry Error.\nEvent: ${(0,b.$X)(t)}`),!0):function(t,e){return!(t.type||!e||!e.length)&&function(t){const e=[];let n;t.message&&e.push(t.message);try{n=t.exception.values[t.exception.values.length-1]}catch(t){}return n&&n.value&&(e.push(n.value),n.type&&e.push(`${n.type}: ${n.value}`)),m.T&&0===e.length&&p.vF.error(`Could not extract message for event ${(0,b.$X)(t)}`),e}(t).some((t=>(0,h.Xr)(t,e)))}(t,e.ignoreErrors)?(m.T&&p.vF.warn(`Event dropped due to being matched by \`ignoreErrors\` option.\nEvent: ${(0,b.$X)(t)}`),!0):function(t,e){if("transaction"!==t.type||!e||!e.length)return!1;const n=t.transaction;return!!n&&(0,h.Xr)(n,e)}(t,e.ignoreTransactions)?(m.T&&p.vF.warn(`Event dropped due to being matched by \`ignoreTransactions\` option.\nEvent: ${(0,b.$X)(t)}`),!0):function(t,e){if(!e||!e.length)return!1;const n=W(t);return!!n&&(0,h.Xr)(n,e)}(t,e.denyUrls)?(m.T&&p.vF.warn(`Event dropped due to being matched by \`denyUrls\` option.\nEvent: ${(0,b.$X)(t)}.\nUrl: ${W(t)}`),!0):!function(t,e){if(!e||!e.length)return!0;const n=W(t);return!n||(0,h.Xr)(n,e)}(t,e.allowUrls)&&(m.T&&p.vF.warn(`Event dropped due to not being matched by \`allowUrls\` option.\nEvent: ${(0,b.$X)(t)}.\nUrl: ${W(t)}`),!0)}(e,o)?null:e}}))),A=(0,g.F)(B,y);function W(t){try{let e;try{e=t.exception.values[0].stacktrace.frames}catch(t){}return e?function(t=[]){for(let e=t.length-1;e>=0;e--){const n=t[e];if(n&&""!==n.filename&&"[native code]"!==n.filename)return n.filename||null}return null}(e):null}catch(e){return m.T&&p.vF.error(`Cannot extract url for event ${(0,b.$X)(t)}`),null}}var V=n(3816);function v(t,e,n=250,s,i,o,r){if(!(o.exception&&o.exception.values&&r&&(0,V.tH)(r.originalException,Error)))return;const c=o.exception.values.length>0?o.exception.values[o.exception.values.length-1]:void 0;var a,g;c&&(o.exception.values=(a=f(t,e,i,r.originalException,s,o.exception.values,c,0),g=n,a.map((t=>(t.value&&(t.value=(0,h.xv)(t.value,g)),t)))))}function f(t,e,n,s,i,o,r,c){if(o.length>=n+1)return o;let a=[...o];if((0,V.tH)(s[i],Error)){R(r,c);const o=t(e,s[i]),g=a.length;Y(o,i,g,c),a=f(t,e,n,s[i],i,[o,...a],o,g)}return Array.isArray(s.errors)&&s.errors.forEach(((s,o)=>{if((0,V.tH)(s,Error)){R(r,c);const g=t(e,s),l=a.length;Y(g,`errors[${o}]`,l,c),a=f(t,e,n,s,i,[g,...a],g,l)}})),a}function R(t,e){t.mechanism=t.mechanism||{type:"generic",handled:!0},t.mechanism={...t.mechanism,..."AggregateError"===t.type&&{is_exception_group:!0},exception_id:e}}function Y(t,e,n,s){t.mechanism=t.mechanism||{type:"generic",handled:!0},t.mechanism={...t.mechanism,type:"chained",source:e,exception_id:n,parent_id:s}}var X=n(2181);function H(t,e){return t(e.stack||"",1)}function S(t,e){const n={type:e.name||e.constructor.name,value:e.message},s=H(t,e);return s.length&&(n.stacktrace={frames:s}),n}const N="LinkedErrors",K=(0,g._C)(((t={})=>{const e=t.limit||5,n=t.key||"cause";return{name:N,setupOnce(){},preprocessEvent(t,s,i){const o=i.getOptions();v(S,o.stackParser,o.maxValueLength,n,e,t,s)}}})),w=(0,g.F)(N,K),F=s,J="sentry.source",k="sentry.sample_rate",_="sentry.op",z="sentry.origin";var U=n(5644);const x=/^(?:(\w+):)\/\/(?:(\w+)(?::(\w+)?)?@)([\w.-]+)(?::(\d+))?\/(.+)/;function T(t,e=!1){const{host:n,path:s,pass:i,port:o,projectId:r,protocol:c,publicKey:a}=t;return`${c}://${a}${e&&i?`:${i}`:""}@${n}${o?`:${o}`:""}/${s?`${s}/`:s}${r}`}function E(t){return{protocol:t.protocol,publicKey:t.publicKey||"",pass:t.pass||"",host:t.host,port:t.port||"",path:t.path||"",projectId:t.projectId}}var L=n(690);function Q(t,e=[]){return[t,e]}function j(t,e){const[n,s]=t;return[n,[...s,e]]}function O(t,e){const n=t[1];for(const t of n)if(e(t,t[0].type))return!0;return!1}function M(t,e){return(e||new TextEncoder).encode(t)}function P(t,e){const[n,s]=t;let i=JSON.stringify(n);function o(t){"string"==typeof i?i="string"==typeof t?i+t:[M(i,e),t]:i.push("string"==typeof t?M(t,e):t)}for(const t of s){const[e,n]=t;if(o(`\n${JSON.stringify(e)}\n`),"string"==typeof n||n instanceof Uint8Array)o(n);else{let t;try{t=JSON.stringify(n)}catch(e){t=JSON.stringify((0,X.S8)(n))}o(t)}}return"string"==typeof i?i:function(t){const e=t.reduce(((t,e)=>t+e.length),0),n=new Uint8Array(e);let s=0;for(const e of t)n.set(e,s),s+=e.length;return n}(i)}function D(t,e){const n="string"==typeof t.data?M(t.data,e):t.data;return[(0,c.Ce)({type:"attachment",length:n.length,filename:t.filename,content_type:t.contentType,attachment_type:t.attachmentType}),n]}const q={session:"session",sessions:"session",attachment:"attachment",transaction:"transaction",event:"error",client_report:"internal",user_report:"default",profile:"profile",replay_event:"replay",replay_recording:"replay",check_in:"monitor",feedback:"feedback",span:"span",statsd:"metric_bucket"};function $(t){return q[t]}function tt(t){if(!t||!t.sdk)return;const{name:e,version:n}=t.sdk;return{name:e,version:n}}class et extends Error{constructor(t,e="warn"){super(t),this.message=t,this.name=new.target.prototype.constructor.name,Object.setPrototypeOf(this,new.target.prototype),this.logLevel=e}}var nt=n(6641);function st(t,e,n,s){return`${t}${e}${n}${Object.entries((0,c.Ce)(s)).sort(((t,e)=>t[0].localeCompare(e[0])))}`}function it(t){return t.replace(/[^\w]+/gi,"_")}function ot(t){return t.replace(/[^\w\-.]+/gi,"_")}function rt(t){return t.replace(/[^\w\-./]+/gi,"")}const ct=[["\n","\\n"],["\r","\\r"],["\t","\\t"],["\\","\\\\"],["|","\\u{7c}"],[",","\\u{2c}"]];function at(t){const e={};for(const s in t)Object.prototype.hasOwnProperty.call(t,s)&&(e[rt(s)]=(n=String(t[s]),[...n].reduce(((t,e)=>t+function(t){for(const[e,n]of ct)if(t===e)return n;return t}(e)),"")));var n;return e}var gt=n(7058),lt=n(5452),dt=n(9475);const It="Not capturing exception because it's already been captured.";class ut{constructor(t){if(this._options=t,this._integrations={},this._integrationsInitialized=!1,this._numProcessing=0,this._outcomes={},this._hooks={},this._eventProcessors=[],t.dsn?this._dsn=function(t){const e="string"==typeof t?function(t){const e=x.exec(t);if(!e)return void(0,p.pq)((()=>{console.error(`Invalid Sentry Dsn: ${t}`)}));const[n,s,i="",o,r="",c]=e.slice(1);let a="",g=c;const l=g.split("/");if(l.length>1&&(a=l.slice(0,-1).join("/"),g=l.pop()),g){const t=g.match(/^\d+/);t&&(g=t[0])}return E({host:o,pass:i,path:a,projectId:g,port:r,protocol:n,publicKey:s})}(t):E(t);if(e&&function(t){if(!U.T)return!0;const{port:e,projectId:n,protocol:s}=t;return!(["protocol","publicKey","host","projectId"].find((e=>!t[e]&&(p.vF.error(`Invalid Sentry Dsn: ${e} missing`),!0)))||(n.match(/^\d+$/)?function(t){return"http"===t||"https"===t}(s)?e&&isNaN(parseInt(e,10))&&(p.vF.error(`Invalid Sentry Dsn: Invalid port ${e}`),1):(p.vF.error(`Invalid Sentry Dsn: Invalid protocol ${s}`),1):(p.vF.error(`Invalid Sentry Dsn: Invalid projectId ${n}`),1)))}(e))return e}(t.dsn):m.T&&p.vF.warn("No DSN provided, client will not send events."),this._dsn){const e=function(t,e={}){const n="string"==typeof e?e:e.tunnel,s="string"!=typeof e&&e._metadata?e._metadata.sdk:void 0;return n||`${function(t){return`${function(t){const e=t.protocol?`${t.protocol}:`:"",n=t.port?`:${t.port}`:"";return`${e}//${t.host}${n}${t.path?`/${t.path}`:""}/api/`}(t)}${t.projectId}/envelope/`}(t)}?${function(t,e){return(0,c.u4)({sentry_key:t.publicKey,sentry_version:"7",...e&&{sentry_client:`${e.name}/${e.version}`}})}(t,s)}`}(this._dsn,t);this._transport=t.transport({tunnel:this._options.tunnel,recordDroppedEvent:this.recordDroppedEvent.bind(this),...t.transportOptions,url:e})}}captureException(t,e,n){if((0,b.GR)(t))return void(m.T&&p.vF.log(It));let s=e&&e.event_id;return this._process(this.eventFromException(t,e).then((t=>this._captureEvent(t,e,n))).then((t=>{s=t}))),s}captureMessage(t,e,n,s){let i=n&&n.event_id;const o=(0,V.NF)(t)?t:String(t),r=(0,V.sO)(t)?this.eventFromMessage(o,e,n):this.eventFromException(t,n);return this._process(r.then((t=>this._captureEvent(t,n,s))).then((t=>{i=t}))),i}captureEvent(t,e,n){if(e&&e.originalException&&(0,b.GR)(e.originalException))return void(m.T&&p.vF.log(It));let s=e&&e.event_id;const i=(t.sdkProcessingMetadata||{}).capturedSpanScope;return this._process(this._captureEvent(t,e,i||n).then((t=>{s=t}))),s}captureSession(t){"string"!=typeof t.release?m.T&&p.vF.warn("Discarded session because of missing or non-string release"):(this.sendSession(t),(0,gt.qO)(t,{init:!1}))}getDsn(){return this._dsn}getOptions(){return this._options}getSdkMetadata(){return this._options._metadata}getTransport(){return this._transport}flush(t){const e=this._transport;return e?(this.metricsAggregator&&this.metricsAggregator.flush(),this._isClientDoneProcessing(t).then((n=>e.flush(t).then((t=>n&&t))))):(0,L.XW)(!0)}close(t){return this.flush(t).then((t=>(this.getOptions().enabled=!1,this.metricsAggregator&&this.metricsAggregator.close(),t)))}getEventProcessors(){return this._eventProcessors}addEventProcessor(t){this._eventProcessors.push(t)}setupIntegrations(t){(t&&!this._integrationsInitialized||this._isEnabled()&&!this._integrationsInitialized)&&this._setupIntegrations()}init(){this._isEnabled()&&this._setupIntegrations()}getIntegrationById(t){return this.getIntegrationByName(t)}getIntegrationByName(t){return this._integrations[t]}getIntegration(t){try{return this._integrations[t.id]||null}catch(e){return m.T&&p.vF.warn(`Cannot retrieve integration ${t.id} from the current Client`),null}}addIntegration(t){const e=this._integrations[t.name];(0,g.qm)(this,t,this._integrations),e||(0,g.lc)(this,[t])}sendEvent(t,e={}){this.emit("beforeSendEvent",t,e);let n=function(t,e,n,s){const i=tt(n),o=t.type&&"replay_event"!==t.type?t.type:"event";!function(t,e){e&&(t.sdk=t.sdk||{},t.sdk.name=t.sdk.name||e.name,t.sdk.version=t.sdk.version||e.version,t.sdk.integrations=[...t.sdk.integrations||[],...e.integrations||[]],t.sdk.packages=[...t.sdk.packages||[],...e.packages||[]])}(t,n&&n.sdk);const r=function(t,e,n,s){const i=t.sdkProcessingMetadata&&t.sdkProcessingMetadata.dynamicSamplingContext;return{event_id:t.event_id,sent_at:(new Date).toISOString(),...e&&{sdk:e},...!!n&&s&&{dsn:T(s)},...i&&{trace:(0,c.Ce)({...i})}}}(t,i,s,e);return delete t.sdkProcessingMetadata,Q(r,[[{type:o},t]])}(t,this._dsn,this._options._metadata,this._options.tunnel);for(const t of e.attachments||[])n=j(n,D(t,this._options.transportOptions&&this._options.transportOptions.textEncoder));const s=this._sendEnvelope(n);s&&s.then((e=>this.emit("afterSendEvent",t,e)),null)}sendSession(t){const e=function(t,e,n,s){const i=tt(n);return Q({sent_at:(new Date).toISOString(),...i&&{sdk:i},...!!s&&e&&{dsn:T(e)}},["aggregates"in t?[{type:"sessions"},t]:[{type:"session"},t.toJSON()]])}(t,this._dsn,this._options._metadata,this._options.tunnel);this._sendEnvelope(e)}recordDroppedEvent(t,e,n){if(this._options.sendClientReports){const s="number"==typeof n?n:1,i=`${t}:${e}`;m.T&&p.vF.log(`Recording outcome: "${i}"${s>1?` (${s} times)`:""}`),this._outcomes[i]=(this._outcomes[i]||0)+s}}captureAggregateMetrics(t){m.T&&p.vF.log(`Flushing aggregated metrics, number of metrics: ${t.length}`);const e=function(t,e,n,s){const i={sent_at:(new Date).toISOString()};n&&n.sdk&&(i.sdk={name:n.sdk.name,version:n.sdk.version}),s&&e&&(i.dsn=T(e));const o=function(t){const e=function(t){let e="";for(const n of t){const t=Object.entries(n.tags),s=t.length>0?`|#${t.map((([t,e])=>`${t}:${e}`)).join(",")}`:"";e+=`${n.name}@${n.unit}:${n.metric}|${n.metricType}${s}|T${n.timestamp}\n`}return e}(t);return[{type:"statsd",length:e.length},e]}(t);return Q(i,[o])}(t,this._dsn,this._options._metadata,this._options.tunnel);this._sendEnvelope(e)}on(t,e){this._hooks[t]||(this._hooks[t]=[]),this._hooks[t].push(e)}emit(t,...e){this._hooks[t]&&this._hooks[t].forEach((t=>t(...e)))}_setupIntegrations(){const{integrations:t}=this._options;this._integrations=(0,g.P$)(this,t),(0,g.lc)(this,t),this._integrationsInitialized=!0}_updateSessionFromEvent(t,e){let n=!1,s=!1;const i=e.exception&&e.exception.values;if(i){s=!0;for(const t of i){const e=t.mechanism;if(e&&!1===e.handled){n=!0;break}}}const o="ok"===t.status;(o&&0===t.errors||o&&n)&&((0,gt.qO)(t,{...n&&{status:"crashed"},errors:t.errors||Number(s||n)}),this.captureSession(t))}_isClientDoneProcessing(t){return new L.T2((e=>{let n=0;const s=setInterval((()=>{0==this._numProcessing?(clearInterval(s),e(!0)):(n+=1,t&&n>=t&&(clearInterval(s),e(!1)))}),1)}))}_isEnabled(){return!1!==this.getOptions().enabled&&void 0!==this._transport}_prepareEvent(t,e,n,s=(0,nt.rm)()){const i=this.getOptions(),o=Object.keys(this._integrations);return!e.integrations&&o.length>0&&(e.integrations=o),this.emit("preprocessEvent",t,e),(0,dt.mG)(i,t,e,n,this,s).then((t=>{if(null===t)return t;const e={...s.getPropagationContext(),...n?n.getPropagationContext():void 0};if((!t.contexts||!t.contexts.trace)&&e){const{traceId:s,spanId:i,parentSpanId:o,dsc:r}=e;t.contexts={trace:{trace_id:s,span_id:i,parent_span_id:o},...t.contexts};const c=r||(0,lt.l)(s,this,n);t.sdkProcessingMetadata={dynamicSamplingContext:c,...t.sdkProcessingMetadata}}return t}))}_captureEvent(t,e={},n){return this._processEvent(t,e,n).then((t=>t.event_id),(t=>{if(m.T){const e=t;"log"===e.logLevel?p.vF.log(e.message):p.vF.warn(e)}}))}_processEvent(t,e,n){const s=this.getOptions(),{sampleRate:i}=s,o=pt(t),r=Ct(t),c=t.type||"error",a=`before send for type \`${c}\``;if(r&&"number"==typeof i&&Math.random()>i)return this.recordDroppedEvent("sample_rate","error",t),(0,L.xg)(new et(`Discarding event because it's not included in the random sample (sampling rate = ${i})`,"log"));const g="replay_event"===c?"replay":c,l=(t.sdkProcessingMetadata||{}).capturedSpanIsolationScope;return this._prepareEvent(t,e,n,l).then((n=>{if(null===n)throw this.recordDroppedEvent("event_processor",g,t),new et("An event processor returned `null`, will not send event.","log");if(e.data&&!0===e.data.__sentry__)return n;const i=function(t,e,n){const{beforeSend:s,beforeSendTransaction:i}=t;if(Ct(e)&&s)return s(e,n);if(pt(e)&&i){if(e.spans){const t=e.spans.length;e.sdkProcessingMetadata={...e.sdkProcessingMetadata,spanCountBeforeProcessing:t}}return i(e,n)}return e}(s,n,e);return function(t,e){const n=`${e} must return \`null\` or a valid event.`;if((0,V.Qg)(t))return t.then((t=>{if(!(0,V.Qd)(t)&&null!==t)throw new et(n);return t}),(t=>{throw new et(`${e} rejected with ${t}`)}));if(!(0,V.Qd)(t)&&null!==t)throw new et(n);return t}(i,a)})).then((s=>{if(null===s){if(this.recordDroppedEvent("before_send",g,t),o){const e=1+(t.spans||[]).length;this.recordDroppedEvent("before_send","span",e)}throw new et(`${a} returned \`null\`, will not send event.`,"log")}const i=n&&n.getSession();if(!o&&i&&this._updateSessionFromEvent(i,s),o){const t=(s.sdkProcessingMetadata&&s.sdkProcessingMetadata.spanCountBeforeProcessing||0)-(s.spans?s.spans.length:0);t>0&&this.recordDroppedEvent("before_send","span",t)}const r=s.transaction_info;if(o&&r&&s.transaction!==t.transaction){const t="custom";s.transaction_info={...r,source:t}}return this.sendEvent(s,e),s})).then(null,(t=>{if(t instanceof et)throw t;throw this.captureException(t,{data:{__sentry__:!0},originalException:t}),new et(`Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event.\nReason: ${t}`)}))}_process(t){this._numProcessing++,t.then((t=>(this._numProcessing--,t)),(t=>(this._numProcessing--,t)))}_sendEnvelope(t){if(this.emit("beforeEnvelope",t),this._isEnabled()&&this._transport)return this._transport.send(t).then(null,(t=>{m.T&&p.vF.error("Error while sending event:",t)}));m.T&&p.vF.error("Transport disabled")}_clearOutcomes(){const t=this._outcomes;return this._outcomes={},Object.keys(t).map((e=>{const[n,s]=e.split(":");return{reason:n,category:s,quantity:t[e]}}))}}function Ct(t){return void 0===t.type}function pt(t){return"transaction"===t.type}function bt(t){const e=(0,a.KU)();e&&e.addEventProcessor&&e.addEventProcessor(t)}var ht=n(6524),mt=n(3445);function Zt(t,e,n=()=>{}){let s;try{s=t()}catch(t){throw e(t),n(),t}return function(t,e,n){return(0,V.Qg)(t)?t.then((t=>(n(),t)),(t=>{throw e(t),n(),t})):(n(),t)}(s,e,n)}function Gt(t){if("boolean"==typeof __SENTRY_TRACING__&&!__SENTRY_TRACING__)return!1;const e=(0,a.KU)(),n=t||e&&e.getOptions();return!!n&&(n.enableTracing||"tracesSampleRate"in n||"tracesSampler"in n)}function Bt(t,e,n=()=>{},s=()=>{}){const i=(0,nt.BF)(),o=(0,a.o5)(),r=o.getSpan(),c=Yt(t),g=Rt(i,{parentSpan:r,spanContext:c,forceTransaction:!1,scope:o});return o.setSpan(g),Zt((()=>e(g)),(t=>{g&&g.setStatus("internal_error"),n(t,g)}),(()=>{g&&g.end(),o.setSpan(r),s()}))}function yt(t,e){const n=Yt(t);return(0,nt.fx)((()=>(0,a.v4)(t.scope,(s=>{const i=(0,nt.BF)(),o=s.getSpan(),r=t.onlyIfParent&&!o?void 0:Rt(i,{parentSpan:o,spanContext:n,forceTransaction:t.forceTransaction,scope:s});return Zt((()=>e(r)),(()=>{if(r){const{status:t}=(0,mt.et)(r);t&&"ok"!==t||r.setStatus("internal_error")}}),(()=>r&&r.end()))}))))}const At=yt;function Wt(t,e){const n=Yt(t);return(0,nt.fx)((()=>(0,a.v4)(t.scope,(s=>{const i=(0,nt.BF)(),o=s.getSpan(),r=t.onlyIfParent&&!o?void 0:Rt(i,{parentSpan:o,spanContext:n,forceTransaction:t.forceTransaction,scope:s});function c(){r&&r.end()}return Zt((()=>e(r,c)),(()=>{if(r&&r.isRecording()){const{status:t}=(0,mt.et)(r);t&&"ok"!==t||r.setStatus("internal_error")}}))}))))}function Vt(t){if(!Gt())return;const e=Yt(t),n=(0,nt.BF)(),s=t.scope?t.scope.getSpan():vt();if(t.onlyIfParent&&!s)return;const i=(t.scope||(0,a.o5)()).clone();return Rt(n,{parentSpan:s,spanContext:e,forceTransaction:t.forceTransaction,scope:i})}function vt(){return(0,a.o5)().getSpan()}const ft=({sentryTrace:t,baggage:e},n)=>{const s=(0,a.o5)(),{traceparentData:i,dynamicSamplingContext:o,propagationContext:r}=(0,ht.E0)(t,e);s.setPropagationContext(r),m.T&&i&&p.vF.log(`[Tracing] Continuing trace ${i.traceId}.`);const g={...i,metadata:(0,c.Ce)({dynamicSamplingContext:o})};return n?(0,nt.fx)((()=>n(g))):g};function Rt(t,{parentSpan:e,spanContext:n,forceTransaction:s,scope:i}){if(!Gt())return;const o=(0,nt.rm)();let r;if(e&&!s)r=e.startChild(n);else if(e){const s=(0,lt.k)(e),{traceId:i,spanId:o}=e.spanContext(),c=(0,mt.pK)(e);r=t.startTransaction({traceId:i,parentSpanId:o,parentSampled:c,...n,metadata:{dynamicSamplingContext:s,...n.metadata}})}else{const{traceId:e,dsc:s,parentSpanId:c,sampled:a}={...o.getPropagationContext(),...i.getPropagationContext()};r=t.startTransaction({traceId:e,parentSpanId:c,parentSampled:a,...n,metadata:{dynamicSamplingContext:s,...n.metadata}})}return i.setSpan(r),function(t,e,n){t&&((0,c.my)(t,Ht,n),(0,c.my)(t,Xt,e))}(r,i,o),r}function Yt(t){if(t.startTime){const e={...t};return e.startTimestamp=(0,mt.cI)(t.startTime),delete e.startTime,e}return t}const Xt="_sentryScope",Ht="_sentryIsolationScope";const St=6e4;const Nt=30;function Kt(t,e,n=function(t){const e=[];function n(t){return e.splice(e.indexOf(t),1)[0]}return{$:e,add:function(s){if(!(void 0===t||e.lengthn(i))).then(null,(()=>n(i).then(null,(()=>{})))),i},drain:function(t){return new L.T2(((n,s)=>{let i=e.length;if(!i)return n(!0);const o=setTimeout((()=>{t&&t>0&&n(!1)}),t);e.forEach((t=>{(0,L.XW)(t).then((()=>{--i||(clearTimeout(o),n(!0))}),s)}))}))}}}(t.bufferSize||Nt)){let s={};function i(i){const o=[];if(O(i,((e,n)=>{const i=$(n);if(function(t,e,n=Date.now()){return function(t,e){return t[e]||t.all||0}(t,e)>n}(s,i)){const s=wt(e,n);t.recordDroppedEvent("ratelimit_backoff",i,s)}else o.push(e)})),0===o.length)return(0,L.XW)();const r=Q(i[0],o),c=e=>{O(r,((n,s)=>{const i=wt(n,s);t.recordDroppedEvent(e,$(s),i)}))};return n.add((()=>e({body:P(r,t.textEncoder)}).then((t=>(void 0!==t.statusCode&&(t.statusCode<200||t.statusCode>=300)&&m.T&&p.vF.warn(`Sentry responded with status code ${t.statusCode} to sent event.`),s=function(t,{statusCode:e,headers:n},s=Date.now()){const i={...t},o=n&&n["x-sentry-rate-limits"],r=n&&n["retry-after"];if(o)for(const t of o.trim().split(",")){const[e,n,,,o]=t.split(":",5),r=parseInt(e,10),c=1e3*(isNaN(r)?60:r);if(n)for(const t of n.split(";"))"metric_bucket"===t&&o&&!o.split(";").includes("custom")||(i[t]=s+c);else i.all=s+c}else r?i.all=s+function(t,e=Date.now()){const n=parseInt(`${t}`,10);if(!isNaN(n))return 1e3*n;const s=Date.parse(`${t}`);return isNaN(s)?St:s-e}(r,s):429===e&&(i.all=s+6e4);return i}(s,t),t)),(t=>{throw c("network_error"),t})))).then((t=>t),(t=>{if(t instanceof et)return m.T&&p.vF.error("Skipped sending event because buffer is full."),c("queue_overflow"),(0,L.XW)();throw t}))}return i.__sentry__baseTransport__=!0,{send:i,flush:t=>n.drain(t)}}function wt(t,e){if("event"===e||"transaction"===e)return Array.isArray(t)?t[1]:void 0}function Ft(t){return(t||(0,nt.BF)()).getScope().getTransaction()}const Jt=ht.nc;var kt;function _t(t){if(t<400&&t>=100)return"ok";if(t>=400&&t<500)switch(t){case 401:return"unauthenticated";case 403:return"permission_denied";case 404:return"not_found";case 409:return"already_exists";case 413:return"failed_precondition";case 429:return"resource_exhausted";default:return"invalid_argument"}if(t>=500&&t<600)switch(t){case 501:return"unimplemented";case 503:return"unavailable";case 504:return"deadline_exceeded";default:return"internal_error"}return"unknown_error"}!function(t){t.Ok="ok",t.DeadlineExceeded="deadline_exceeded",t.Unauthenticated="unauthenticated",t.PermissionDenied="permission_denied",t.NotFound="not_found",t.ResourceExhausted="resource_exhausted",t.InvalidArgument="invalid_argument",t.Unimplemented="unimplemented",t.Unavailable="unavailable",t.InternalError="internal_error",t.UnknownError="unknown_error",t.Cancelled="cancelled",t.AlreadyExists="already_exists",t.FailedPrecondition="failed_precondition",t.Aborted="aborted",t.OutOfRange="out_of_range",t.DataLoss="data_loss"}(kt||(kt={}));const zt=_t;function Ut(t,e){t.setTag("http.status_code",String(e)),t.setData("http.response.status_code",e);const n=_t(e);"unknown_error"!==n&&t.setStatus(n)}const xt="c",Tt="g",Et="s",Lt="d";var Qt=n(9297);const jt={[xt]:class{constructor(t){this._value=t}get weight(){return 1}add(t){this._value+=t}toString(){return`${this._value}`}},[Tt]:class{constructor(t){this._last=t,this._min=t,this._max=t,this._sum=t,this._count=1}get weight(){return 5}add(t){this._last=t,tthis._max&&(this._max=t),this._sum+=t,this._count++}toString(){return`${this._last}:${this._min}:${this._max}:${this._sum}:${this._count}`}},[Lt]:class{constructor(t){this._value=[t]}get weight(){return this._value.length}add(t){this._value.push(t)}toString(){return this._value.join(":")}},[Et]:class{constructor(t){this.first=t,this._value=new Set([t])}get weight(){return this._value.size}add(t){this._value.add(t)}toString(){return Array.from(this._value).map((t=>"string"==typeof t?function(t){let e=0;for(let n=0;n>>0}(t):t)).join(":")}}};let Ot;function Mt(t){return Ot?Ot.get(t):void 0}function Pt(t){const e=Mt(t);if(!e)return;const n={};for(const[,[t,s]]of e)n[t]||(n[t]=[]),n[t].push((0,c.Ce)(s));return n}function Dt(t,e,n,s,i,o){const r=vt();if(r){const c=Mt(r)||new Map,a=`${t}:${e}@${s}`,g=c.get(o);if(g){const[,t]=g;c.set(o,[a,{min:Math.min(t.min,n),max:Math.max(t.max,n),count:t.count+=1,sum:t.sum+=n,tags:t.tags}])}else c.set(o,[a,{min:n,max:n,count:1,sum:n,tags:i}]);Ot||(Ot=new WeakMap),Ot.set(r,c)}}class qt{constructor(t){this._client=t,this._buckets=new Map,this._interval=setInterval((()=>this.flush()),5e3)}add(t,e,n,s="none",i={},o=(0,Qt.zf)()){const r=Math.floor(o),c=ot(e),a=at(i),g=it(s),l=st(t,c,g,a);let d=this._buckets.get(l);const I=d&&t===Et?d.metric.weight:0;d?(d.metric.add(n),d.timestampt));this._client.captureAggregateMetrics(t)}this._buckets.clear()}}close(){clearInterval(this._interval),this.flush()}}const $t="MetricsAggregator",te=(0,g._C)((()=>({name:$t,setupOnce(){},setup(t){t.metricsAggregator=new qt(t)}})));function ee(t,e,n,s={}){const i=(0,a.KU)(),o=(0,a.o5)();if(i){if(!i.metricsAggregator)return void(m.T&&p.vF.warn("No metrics aggregator enabled. Please add the MetricsAggregator integration to use metrics APIs"));const{unit:r,tags:c,timestamp:a}=s,{release:g,environment:l}=i.getOptions(),d=o.getTransaction(),I={};g&&(I.release=g),l&&(I.environment=l),d&&(I.transaction=(0,mt.et)(d).description||""),m.T&&p.vF.log(`Adding value of ${n} to ${t} metric ${e}`),i.metricsAggregator.add(t,e,n,r,{...I,...c},a)}}const ne={increment:function(t,e=1,n){ee("c",t,e,n)},distribution:function(t,e,n){ee("d",t,e,n)},set:function(t,e,n){ee(Et,t,e,n)},gauge:function(t,e,n){ee("g",t,e,n)},MetricsAggregator:(0,g.F)($t,te),metricsAggregatorIntegration:te};function se(t,...e){const n=new String(String.raw(t,...e));return n.__sentry_template_string__=t.join("\0").replace(/%/g,"%%").replace(/\0/g,"%s"),n.__sentry_template_values__=e,n}function ie(t){return t.split(/[\?#]/,1)[0]}function oe(t){return t.split(/\\?\//).filter((t=>t.length>0&&","!==t)).length}function re(t){const{protocol:e,host:n,path:s}=t;return`${e?`${e}://`:""}${n&&n.replace(/^.*@/,"[filtered]:[filtered]@").replace(/(:80)$/,"").replace(/(:443)$/,"")||""}${s}`}const ce={ip:!1,request:!0,transaction:!0,user:!0},ae=["cookies","data","headers","method","query_string","url"],ge=["id","username","email"];function le(t,e={}){const n=t.method&&t.method.toUpperCase();let s="",i="url";e.customRoute||t.route?(s=e.customRoute||`${t.baseUrl||""}${t.route&&t.route.path}`,i="route"):(t.originalUrl||t.url)&&(s=ie(t.originalUrl||t.url||""));let o="";return e.method&&n&&(o+=n),e.method&&e.path&&(o+=" "),e.path&&s&&(o+=s),[o,i]}function de(t,e){const{include:n=ae,deps:s}=e||{},i={},o=t.headers||{},r=t.method,c=o.host||t.hostname||t.host||"",a="https"===t.protocol||t.socket&&t.socket.encrypted?"https":"http",g=t.originalUrl||t.url||"",l=g.startsWith(a)?g:`${a}://${c}${g}`;return n.forEach((e=>{switch(e){case"headers":i.headers=o,n.includes("cookies")||delete i.headers.cookie;break;case"method":i.method=r;break;case"url":i.url=l;break;case"cookies":i.cookies=t.cookies||o.cookie&&function(t){const e={};let n=0;for(;n{t&&e in t&&(n[e]=t[e])})),n}(e.user,s.user):{};Object.keys(n).length&&(t.user={...t.user,...n})}if(s.ip){const n=e.ip||e.socket&&e.socket.remoteAddress;n&&(t.user={...t.user,ip_address:n})}return s.transaction&&!t.transaction&&(t.transaction=function(t,e){switch(e){case"path":return le(t,{path:!0})[0];case"handler":return t.route&&t.route.stack&&t.route.stack[0]&&t.route.stack[0].name||"";default:return le(t,{path:!0,method:!0,customRoute:t._reconstructedRoute?t._reconstructedRoute:void 0})[0]}}(e,s.transaction)),t}function ue(t,e){let n=t.originalUrl||t.url||"";if(n){n.startsWith("/")&&(n=`http://dogs.are.great${n}`);try{return t.query||"undefined"!=typeof URL&&new URL(n).search.slice(1)||e&&e.url&&e.url.parse(n).query||void 0}catch(t){return}}}const Ce={include:{cookies:!0,data:!0,headers:!0,ip:!1,query_string:!0,url:!0,user:{id:!0,username:!0,email:!0}},transactionNamingScheme:"methodPath"},pe="RequestData",be=(0,g._C)(((t={})=>{const e=Ie,n={...Ce,...t,include:{method:!0,...Ce.include,...t.include,user:t.include&&"boolean"==typeof t.include.user?t.include.user:{...Ce.include.user,...(t.include||{}).user}}};return{name:pe,setupOnce(){},processEvent(t,s,i){const{transactionNamingScheme:o}=n,{sdkProcessingMetadata:r={}}=t,c=r.request;if(!c)return t;const a=r.requestDataOptionsFromExpressHandler||r.requestDataOptionsFromGCPWrapper||function(t){const{transactionNamingScheme:e,include:{ip:n,user:s,...i}}=t,o=[];for(const[t,e]of Object.entries(i))e&&o.push(t);let r;if(void 0===s)r=!0;else if("boolean"==typeof s)r=s;else{const t=[];for(const[e,n]of Object.entries(s))n&&t.push(e);r=t}return{include:{ip:n,user:r,request:0!==o.length?o:void 0,transaction:e}}}(n),g=e(t,c,a);if("transaction"===t.type||"handler"===o)return g;const l=c._sentryTransaction;if(l){const t=(0,mt.et)(l).description||"",e="sentry.javascript.nextjs"===function(t){try{return t.getOptions()._metadata.sdk.name}catch(t){return}}(i)?t.startsWith("/api"):"path"!==o,[n]=le(c,{path:!0,method:e,customRoute:t});g.transaction=n}return g}}})),he=(0,g.F)(pe,be);function me(t){const e=(0,nt.BF)().getStackTop();e.client=t,e.scope.setClient(t)}function Ze(t,e,n){const s=Ft();s&&s.setMeasurement(t,e,n)}var Ge=n(7986),Be=n(2486),ye=n(2531),Ae=n(2786);function We(){const t=Ae.j.map((t=>{try{return t()}catch(t){return}})).filter((t=>!!t));return 0===t.length&&p.vF.warn("Performance monitoring integrations could not be automatically loaded."),t.filter((t=>!!t.loadDependency()))}const Ve=require("os"),ve=require("util");class fe{constructor(t){this._client=t,this._buckets=new Map,this._bucketsTotalWeight=0,this._interval=setInterval((()=>this._flush()),1e4),this._interval.unref&&this._interval.unref(),this._flushShift=Math.floor(1e4*Math.random()/1e3),this._forceFlush=!1}add(t,e,n,s="none",i={},o=(0,Qt.zf)()){const r=Math.floor(o),c=ot(e),a=at(i),g=it(s),l=st(t,c,g,a);let d=this._buckets.get(l);const I=d&&t===Et?d.metric.weight:0;d?(d.metric.add(n),d.timestamp=1e4&&this.flush()}flush(){this._forceFlush=!0,this._flush()}close(){this._forceFlush=!0,clearInterval(this._interval),this._flush()}_flush(){if(this._forceFlush)return this._forceFlush=!1,this._bucketsTotalWeight=0,this._captureMetrics(this._buckets),void this._buckets.clear();const t=Math.floor((0,Qt.zf)())-10-this._flushShift,e=new Map;for(const[n,s]of this._buckets)s.timestamp<=t&&(e.set(n,s),this._bucketsTotalWeight-=s.metric.weight);for(const[t]of e)this._buckets.delete(t);this._captureMetrics(e)}_captureMetrics(t){if(t.size>0&&this._client.captureAggregateMetrics){const e=Array.from(t).map((([,t])=>t));this._client.captureAggregateMetrics(e)}}}class Re{constructor(t,e){this._client=t,this.flushTimeout=60,this._pendingAggregates={},this._isEnabled=!0,this._intervalId=setInterval((()=>this.flush()),1e3*this.flushTimeout),this._intervalId.unref&&this._intervalId.unref(),this._sessionAttrs=e}flush(){const t=this.getSessionAggregates();0!==t.aggregates.length&&(this._pendingAggregates={},this._client.sendSession(t))}getSessionAggregates(){const t=Object.keys(this._pendingAggregates).map((t=>this._pendingAggregates[parseInt(t)])),e={attrs:this._sessionAttrs,aggregates:t};return(0,c.Ce)(e)}close(){clearInterval(this._intervalId),this._isEnabled=!1,this.flush()}incrementSessionStatusCount(){if(!this._isEnabled)return;const t=(0,a.o5)(),e=t.getRequestSession();e&&e.status&&(this._incrementSessionStatusCount(e.status,new Date),t.setRequestSession(void 0))}_incrementSessionStatusCount(t,e){const n=new Date(e).setSeconds(0,0);this._pendingAggregates[n]=this._pendingAggregates[n]||{};const s=this._pendingAggregates[n];switch(s.started||(s.started=new Date(n).toISOString()),t){case"errored":return s.errored=(s.errored||0)+1,s.errored;case"ok":return s.exited=(s.exited||0)+1,s.exited;default:return s.crashed=(s.crashed||0)+1,s.crashed}}}var Ye=n(6341),Xe=n(7930);const He={},Se={};function Ne(t,e){He[t]=He[t]||[],He[t].push(e)}function Ke(t,e){Se[t]||(e(),Se[t]=!0)}function we(t,e){const n=t&&He[t];if(n)for(const s of n)try{s(e)}catch(e){U.T&&p.vF.error(`Error while triggering instrumentation handler.\nType: ${t}\nName: ${(0,Xe.qQ)(s)}\nError:`,e)}}let Fe=null;function Je(){Fe=Ye.OW.onerror,Ye.OW.onerror=function(t,e,n,s,i){return we("error",{column:s,error:i,line:n,msg:t,url:e}),!(!Fe||Fe.__SENTRY_LOADER__)&&Fe.apply(this,arguments)},Ye.OW.onerror.__SENTRY_INSTRUMENTED__=!0}let ke=null;function _e(){ke=Ye.OW.onunhandledrejection,Ye.OW.onunhandledrejection=function(t){return we("unhandledrejection",t),!(ke&&!ke.__SENTRY_LOADER__)||ke.apply(this,arguments)},Ye.OW.onunhandledrejection.__SENTRY_INSTRUMENTED__=!0}let ze=!1;function Ue(){const t=Ft();if(t){const e="internal_error";m.T&&p.vF.log(`[Tracing] Transaction: ${e} -> Global error occured`),t.setStatus(e)}}Ue.tag="sentry_tracingErrorCallback";var xe=n(4636);class Te{constructor(t=1e3){this._maxlen=t,this.spans=[]}add(t){this.spans.length>this._maxlen?t.spanRecorder=void 0:this.spans.push(t)}}class Ee{constructor(t={}){this._traceId=t.traceId||(0,b.eJ)(),this._spanId=t.spanId||(0,b.eJ)().substring(16),this._startTime=t.startTimestamp||(0,Qt.zf)(),this.tags=t.tags?{...t.tags}:{},this.data=t.data?{...t.data}:{},this.instrumenter=t.instrumenter||"sentry",this._attributes={},this.setAttributes({[z]:t.origin||"manual",[_]:t.op,...t.attributes}),this._name=t.name||t.description,t.parentSpanId&&(this._parentSpanId=t.parentSpanId),"sampled"in t&&(this._sampled=t.sampled),t.status&&(this._status=t.status),t.endTimestamp&&(this._endTime=t.endTimestamp),void 0!==t.exclusiveTime&&(this._exclusiveTime=t.exclusiveTime),this._measurements=t.measurements?{...t.measurements}:{}}get name(){return this._name||""}set name(t){this.updateName(t)}get description(){return this._name}set description(t){this._name=t}get traceId(){return this._traceId}set traceId(t){this._traceId=t}get spanId(){return this._spanId}set spanId(t){this._spanId=t}set parentSpanId(t){this._parentSpanId=t}get parentSpanId(){return this._parentSpanId}get sampled(){return this._sampled}set sampled(t){this._sampled=t}get attributes(){return this._attributes}set attributes(t){this._attributes=t}get startTimestamp(){return this._startTime}set startTimestamp(t){this._startTime=t}get endTimestamp(){return this._endTime}set endTimestamp(t){this._endTime=t}get status(){return this._status}set status(t){this._status=t}get op(){return this._attributes[_]}set op(t){this.setAttribute(_,t)}get origin(){return this._attributes[z]}set origin(t){this.setAttribute(z,t)}spanContext(){const{_spanId:t,_traceId:e,_sampled:n}=this;return{spanId:t,traceId:e,traceFlags:n?mt.aO:mt.CC}}startChild(t){const e=new Ee({...t,parentSpanId:this._spanId,sampled:this._sampled,traceId:this._traceId});e.spanRecorder=this.spanRecorder,e.spanRecorder&&e.spanRecorder.add(e);const n=(0,xe.z)(this);if(e.transaction=n,m.T&&n){const s=`[Tracing] Starting '${t&&t.op||"< unknown op >"}' span on transaction '${(0,mt.et)(e).description||"< unknown name >"}' (${n.spanContext().spanId}).`;p.vF.log(s),this._logMessage=s}return e}setTag(t,e){return this.tags={...this.tags,[t]:e},this}setData(t,e){return this.data={...this.data,[t]:e},this}setAttribute(t,e){void 0===e?delete this._attributes[t]:this._attributes[t]=e}setAttributes(t){Object.keys(t).forEach((e=>this.setAttribute(e,t[e])))}setStatus(t){return this._status=t,this}setHttpStatus(t){return Ut(this,t),this}setName(t){this.updateName(t)}updateName(t){return this._name=t,this}isSuccess(){return"ok"===this._status}finish(t){return this.end(t)}end(t){if(this._endTime)return;const e=(0,xe.z)(this);if(m.T&&e&&e.spanContext().spanId!==this._spanId){const t=this._logMessage;t&&p.vF.log(t.replace("Starting","Finishing"))}this._endTime=(0,mt.cI)(t)}toTraceparent(){return(0,mt.Qh)(this)}toContext(){return(0,c.Ce)({data:this._getData(),description:this._name,endTimestamp:this._endTime,op:this.op,parentSpanId:this._parentSpanId,sampled:this._sampled,spanId:this._spanId,startTimestamp:this._startTime,status:this._status,tags:this.tags,traceId:this._traceId})}updateWithContext(t){return this.data=t.data||{},this._name=t.name||t.description,this._endTime=t.endTimestamp,this.op=t.op,this._parentSpanId=t.parentSpanId,this._sampled=t.sampled,this._spanId=t.spanId||this._spanId,this._startTime=t.startTimestamp||this._startTime,this._status=t.status,this.tags=t.tags||{},this._traceId=t.traceId||this._traceId,this}getTraceContext(){return(0,mt.kX)(this)}getSpanJSON(){return(0,c.Ce)({data:this._getData(),description:this._name,op:this._attributes[_],parent_span_id:this._parentSpanId,span_id:this._spanId,start_timestamp:this._startTime,status:this._status,tags:Object.keys(this.tags).length>0?this.tags:void 0,timestamp:this._endTime,trace_id:this._traceId,origin:this._attributes[z],_metrics_summary:Pt(this),profile_id:this._attributes.profile_id,exclusive_time:this._exclusiveTime,measurements:Object.keys(this._measurements).length>0?this._measurements:void 0})}isRecording(){return!this._endTime&&!!this._sampled}toJSON(){return this.getSpanJSON()}_getData(){const{data:t,_attributes:e}=this,n=Object.keys(t).length>0,s=Object.keys(e).length>0;if(n||s)return n&&s?{...t,...e}:n?t:e}}class Le extends Ee{constructor(t,e){super(t),this._contexts={},this._hub=e||(0,nt.BF)(),this._name=t.name||"",this._metadata={...t.metadata},this._trimEnd=t.trimEnd,this.transaction=this;const n=this._metadata.dynamicSamplingContext;n&&(this._frozenDynamicSamplingContext={...n})}get name(){return this._name}set name(t){this.setName(t)}get metadata(){return{source:"custom",spanMetadata:{},...this._metadata,...this._attributes[J]&&{source:this._attributes[J]},...this._attributes[k]&&{sampleRate:this._attributes[k]}}}set metadata(t){this._metadata=t}setName(t,e="custom"){this._name=t,this.setAttribute(J,e)}updateName(t){return this._name=t,this}initSpanRecorder(t=1e3){this.spanRecorder||(this.spanRecorder=new Te(t)),this.spanRecorder.add(this)}setContext(t,e){null===e?delete this._contexts[t]:this._contexts[t]=e}setMeasurement(t,e,n=""){this._measurements[t]={value:e,unit:n}}setMetadata(t){this._metadata={...this._metadata,...t}}end(t){const e=(0,mt.cI)(t),n=this._finishTransaction(e);if(n)return this._hub.captureEvent(n)}toContext(){const t=super.toContext();return(0,c.Ce)({...t,name:this._name,trimEnd:this._trimEnd})}updateWithContext(t){return super.updateWithContext(t),this._name=t.name||"",this._trimEnd=t.trimEnd,this}getDynamicSamplingContext(){return(0,lt.k)(this)}setHub(t){this._hub=t}getProfileId(){if(void 0!==this._contexts&&void 0!==this._contexts.profile)return this._contexts.profile.profile_id}_finishTransaction(t){if(void 0!==this._endTime)return;this._name||(m.T&&p.vF.warn("Transaction has no name, falling back to ``."),this._name=""),super.end(t);const e=this._hub.getClient();if(e&&e.emit&&e.emit("finishTransaction",this),!0!==this._sampled)return m.T&&p.vF.log("[Tracing] Discarding transaction because its trace was not chosen to be sampled."),void(e&&e.recordDroppedEvent("sample_rate","transaction"));const n=this.spanRecorder?this.spanRecorder.spans.filter((t=>t!==this&&(0,mt.et)(t).timestamp)):[];if(this._trimEnd&&n.length>0){const t=n.map((t=>(0,mt.et)(t).timestamp)).filter(Boolean);this._endTime=t.reduce(((t,e)=>t>e?t:e))}const{scope:s,isolationScope:i}={scope:this[Xt],isolationScope:this[Ht]};const{metadata:o}=this,{source:r}=o,a={contexts:{...this._contexts,trace:(0,mt.kX)(this)},spans:n,start_timestamp:this._startTime,tags:this.tags,timestamp:this._endTime,transaction:this._name,type:"transaction",sdkProcessingMetadata:{...o,capturedSpanScope:s,capturedSpanIsolationScope:i,...(0,c.Ce)({dynamicSamplingContext:(0,lt.k)(this)})},_metrics_summary:Pt(this),...r&&{transaction_info:{source:r}}};return Object.keys(this._measurements).length>0&&(m.T&&p.vF.log("[Measurements] Adding measurements to transaction",JSON.stringify(this._measurements,void 0,2)),a.measurements=this._measurements),m.T&&p.vF.log(`[Tracing] Finishing ${this.op} transaction: ${this._name}.`),a}}function Qe(){const t=this.getScope().getSpan();return t?{"sentry-trace":(0,mt.Qh)(t)}:{}}function je(t,e){const n=this.getClient(),s=n&&n.getOptions()||{},i=s.instrumenter||"sentry",o=t.instrumenter||"sentry";i!==o&&(m.T&&p.vF.error(`A transaction was started with instrumenter=\`${o}\`, but the SDK is configured with the \`${i}\` instrumenter.\nThe transaction will not be sampled. Please use the ${i} instrumentation to start transactions.`),t.sampled=!1);let r=new Le(t,this);return r=function(t,e,n){if(!Gt(e))return t.sampled=!1,t;if(void 0!==t.sampled)return t.setAttribute(k,Number(t.sampled)),t;let s;return"function"==typeof e.tracesSampler?(s=e.tracesSampler(n),t.setAttribute(k,Number(s))):void 0!==n.parentSampled?s=n.parentSampled:void 0!==e.tracesSampleRate?(s=e.tracesSampleRate,t.setAttribute(k,Number(s))):(s=1,t.setAttribute(k,s)),i=s,((0,V.yr)(i)||"number"!=typeof i&&"boolean"!=typeof i?(m.T&&p.vF.warn(`[Tracing] Given sample rate is invalid. Sample rate must be a boolean or a number between 0 and 1. Got ${JSON.stringify(i)} of type ${JSON.stringify(typeof i)}.`),0):!(i<0||i>1)||(m.T&&p.vF.warn(`[Tracing] Given sample rate is invalid. Sample rate must be between 0 and 1. Got ${i}.`),0))?s?(t.sampled=Math.random()0){const t=n.getRequestSession();t&&"ok"===t.status&&(t.status="errored")}return super.captureEvent(t,e,n)}close(t){return this._sessionFlusher&&this._sessionFlusher.close(),super.close(t)}initSessionFlusher(){const{release:t,environment:e}=this._options;t?this._sessionFlusher=new Re(this,{release:t,environment:e}):m.T&&p.vF.warn("Cannot initialise an instance of SessionFlusher if no release is provided!")}captureCheckIn(t,e,n){const s="checkInId"in t&&t.checkInId?t.checkInId:(0,b.eJ)();if(!this._isEnabled())return m.T&&p.vF.warn("SDK not enabled, will not capture checkin."),s;const i=this.getOptions(),{release:o,environment:r,tunnel:a}=i,g={check_in_id:s,monitor_slug:t.monitorSlug,status:t.status,release:o,environment:r};"duration"in t&&(g.duration=t.duration),e&&(g.monitor_config={schedule:e.schedule,checkin_margin:e.checkinMargin,max_runtime:e.maxRuntime,timezone:e.timezone});const[l,d]=this._getTraceInfoFromScope(n);d&&(g.contexts={trace:d});const I=function(t,e,n,s,i){const o={sent_at:(new Date).toISOString()};n&&n.sdk&&(o.sdk={name:n.sdk.name,version:n.sdk.version}),s&&i&&(o.dsn=T(i)),e&&(o.trace=(0,c.Ce)(e));const r=function(t){return[{type:"check_in"},t]}(t);return Q(o,[r])}(g,l,this.getSdkMetadata(),a,this.getDsn());return m.T&&p.vF.info("Sending checkin:",t.monitorSlug,t.status),this._sendEnvelope(I),s}_captureRequestSession(){this._sessionFlusher?this._sessionFlusher.incrementSessionStatusCount():m.T&&p.vF.warn("Discarded request mode session because autoSessionTracking option was disabled")}_prepareEvent(t,e,n,s){return this._options.platform&&(t.platform=t.platform||this._options.platform),this._options.runtime&&(t.contexts={...t.contexts,runtime:(t.contexts||{}).runtime||this._options.runtime}),this._options.serverName&&(t.server_name=t.server_name||this._options.serverName),super._prepareEvent(t,e,n,s)}_getTraceInfoFromScope(t){if(!t)return[void 0,void 0];const e=t.getSpan();if(e)return[(0,xe.z)(e)?(0,lt.k)(e):void 0,(0,mt.kX)(e)];const{traceId:n,spanId:s,parentSpanId:i,dsc:o}=t.getPropagationContext(),r={trace_id:n,span_id:s,parent_span_id:i};return o?[o,r]:[(0,lt.l)(n,this,t),r]}}class Me extends Oe{constructor(t){!function(t,e,n=[e],s="npm"){const i=t._metadata||{};i.sdk||(i.sdk={name:`sentry.javascript.${e}`,packages:n.map((t=>({name:`${s}:@sentry/${t}`,version:Ge.M}))),version:Ge.M}),t._metadata=i}(t,"node"),t.transportOptions={textEncoder:new ve.TextEncoder,...t.transportOptions},super({...t,platform:"node",runtime:{name:"node",version:global.process.version},serverName:t.serverName||global.process.env.SENTRY_NAME||Ve.hostname()})}}function Pe(t,e){return null!=t?t:e()}var De=n(8611),qe=n(5692),$e=n(2203),tn=n(7016);const en=require("zlib");var nn=n(853),sn=n(9278);const on=require("tls"),rn=Symbol("AgentBaseInternalState");class cn extends De.Agent{constructor(t){super(t),this[rn]={}}isSecureEndpoint(t){if(t){if("boolean"==typeof t.secureEndpoint)return t.secureEndpoint;if("string"==typeof t.protocol)return"https:"===t.protocol}const{stack:e}=new Error;return"string"==typeof e&&e.split("\n").some((t=>-1!==t.indexOf("(https.js:")||-1!==t.indexOf("node:https:")))}createSocket(t,e,n){const s={...e,secureEndpoint:this.isSecureEndpoint(e)};Promise.resolve().then((()=>this.connect(t,s))).then((i=>{if(i instanceof De.Agent)return i.addRequest(t,s);this[rn].currentSocket=i,super.createSocket(t,e,n)}),n)}createConnection(){const t=this[rn].currentSocket;if(this[rn].currentSocket=void 0,!t)throw new Error("No socket was returned in the `connect()` function");return t}get defaultPort(){return Pe(this[rn].defaultPort,(()=>"https:"===this.protocol?443:80))}set defaultPort(t){this[rn]&&(this[rn].defaultPort=t)}get protocol(){return Pe(this[rn].protocol,(()=>this.isSecureEndpoint()?"https:":"http:"))}set protocol(t){this[rn]&&(this[rn].protocol=t)}}function an(...t){p.vF.log("[https-proxy-agent:parse-proxy-response]",...t)}function gn(...t){p.vF.log("[https-proxy-agent]",...t)}class ln extends cn{static __initStatic(){this.protocols=["http","https"]}constructor(t,e){super(e),this.options={},this.proxy="string"==typeof t?new tn.URL(t):t,this.proxyHeaders=Pe((0,nn.z)([e,"optionalAccess",t=>t.headers]),(()=>({}))),gn("Creating new HttpsProxyAgent instance: %o",this.proxy.href);const n=(this.proxy.hostname||this.proxy.host).replace(/^\[|\]$/g,""),s=this.proxy.port?parseInt(this.proxy.port,10):"https:"===this.proxy.protocol?443:80;this.connectOpts={ALPNProtocols:["http/1.1"],...e?In(e,"headers"):null,host:n,port:s}}async connect(t,e){const{proxy:n}=this;if(!e.host)throw new TypeError('No "host" provided');let s;if("https:"===n.protocol){gn("Creating `tls.Socket`: %o",this.connectOpts);const t=this.connectOpts.servername||this.connectOpts.host;s=on.connect({...this.connectOpts,servername:t&&sn.isIP(t)?void 0:t})}else gn("Creating `net.Socket`: %o",this.connectOpts),s=sn.connect(this.connectOpts);const i="function"==typeof this.proxyHeaders?this.proxyHeaders():{...this.proxyHeaders},o=sn.isIPv6(e.host)?`[${e.host}]`:e.host;let r=`CONNECT ${o}:${e.port} HTTP/1.1\r\n`;if(n.username||n.password){const t=`${decodeURIComponent(n.username)}:${decodeURIComponent(n.password)}`;i["Proxy-Authorization"]=`Basic ${Buffer.from(t).toString("base64")}`}i.Host=`${o}:${e.port}`,i["Proxy-Connection"]||(i["Proxy-Connection"]=this.keepAlive?"Keep-Alive":"close");for(const t of Object.keys(i))r+=`${t}: ${i[t]}\r\n`;const c=function(t){return new Promise(((e,n)=>{let s=0;const i=[];function o(){const c=t.read();c?function(c){i.push(c),s+=c.length;const a=Buffer.concat(i,s),g=a.indexOf("\r\n\r\n");if(-1===g)return an("have not received end of HTTP headers yet..."),void o();const l=a.slice(0,g).toString("ascii").split("\r\n"),d=l.shift();if(!d)return t.destroy(),n(new Error("No header received from proxy CONNECT response"));const I=d.split(" "),u=+I[1],C=I.slice(2).join(" "),p={};for(const e of l){if(!e)continue;const s=e.indexOf(":");if(-1===s)return t.destroy(),n(new Error(`Invalid header from proxy CONNECT response: "${e}"`));const i=e.slice(0,s).toLowerCase(),o=e.slice(s+1).trimStart(),r=p[i];"string"==typeof r?p[i]=[r,o]:Array.isArray(r)?r.push(o):p[i]=o}an("got proxy server response: %o %o",d,p),r(),e({connect:{statusCode:u,statusText:C,headers:p},buffered:a})}(c):t.once("readable",o)}function r(){t.removeListener("end",c),t.removeListener("error",a),t.removeListener("readable",o)}function c(){r(),an("onend"),n(new Error("Proxy connection ended before receiving CONNECT response"))}function a(t){r(),an("onerror %o",t),n(t)}t.on("error",a),t.on("end",c),o()}))}(s);s.write(`${r}\r\n`);const{connect:a,buffered:g}=await c;if(t.emit("proxyConnect",a),this.emit("proxyConnect",a,t),200===a.statusCode){if(t.once("socket",dn),e.secureEndpoint){gn("Upgrading socket connection to TLS");const t=e.servername||e.host;return on.connect({...In(e,"host","path","port"),socket:s,servername:sn.isIP(t)?void 0:t})}return s}s.destroy();const l=new sn.Socket({writable:!1});return l.readable=!0,t.once("socket",(t=>{gn("Replaying proxy buffer for failed request"),t.push(g),t.push(null)})),l}}function dn(t){t.resume()}function In(t,...e){const n={};let s;for(s in t)e.includes(s)||(n[s]=t[s]);return n}ln.__initStatic();const un=32768;function Cn(t){let e;try{e=new tn.URL(t.url)}catch(e){return(0,p.pq)((()=>{console.warn("[@sentry/node]: Invalid dsn or tunnel option, will not send any events. The tunnel option must be a full URL when used.")})),Kt(t,(()=>Promise.resolve({})))}const n="https:"===e.protocol,s=function(t,e){const{no_proxy:n}=process.env;return n&&n.split(",").some((e=>t.host.endsWith(e)||t.hostname.endsWith(e)))?void 0:e}(e,t.proxy||(n?process.env.https_proxy:void 0)||process.env.http_proxy),i=n?qe:De,o=void 0!==t.keepAlive&&t.keepAlive,r=s?new ln(s):new i.Agent({keepAlive:o,maxSockets:30,timeout:2e3}),c=function(t,e,n){const{hostname:s,pathname:i,port:o,protocol:r,search:c}=new tn.URL(t.url);return function(a){return new Promise(((g,l)=>{let d=function(t){return new $e.Readable({read(){this.push(t),this.push(null)}})}(a.body);const I={...t.headers};a.body.length>un&&(I["content-encoding"]="gzip",d=d.pipe((0,en.createGzip)()));const u=e.request({method:"POST",agent:n,headers:I,hostname:s,path:`${i}${c}`,port:o,protocol:r,ca:t.caCerts},(t=>{t.on("data",(()=>{})),t.on("end",(()=>{})),t.setEncoding("utf8");const e=Pe(t.headers["retry-after"],(()=>null)),n=Pe(t.headers["x-sentry-rate-limits"],(()=>null));g({statusCode:t.statusCode,headers:{"retry-after":e,"x-sentry-rate-limits":Array.isArray(n)?n[0]:n}})}));u.on("error",l),d.pipe(u)}))}}(t,Pe(t.httpModule,(()=>i)),r);return Kt(t,c)}var pn=n(3245);const bn=require("domain");function hn(){return bn.active}function mn(){const t=hn();if(t)return(0,nt.TF)(t),(0,nt.Me)(t)}function Zn(t,e){const n=hn();if(n&&(0,nn.z)([e,"optionalAccess",t=>t.reuseExisting]))return t();const s=bn.create(),i=function(t){const e={};return(0,nt.TF)(e,t),(0,nt.Me)(e)}(n?(0,nt.Me)(n):void 0);return(0,nt.lq)(s,i),s.bind((()=>t()))()}const Gn=require("async_hooks");let Bn;function yn(){pn.S.major>=14?function(){function t(){return Bn.getStore()}Bn||(Bn=new Gn.AsyncLocalStorage),(0,nt.nX)({getCurrentHub:t,runWithAsyncContext:function(e,n){const s=t();if(s&&(0,nn.z)([n,"optionalAccess",t=>t.reuseExisting]))return e();const i=function(t){const e={};return(0,nt.TF)(e,t),(0,nt.Me)(e)}(s);return Bn.run(i,(()=>e()))}})}():(0,nt.nX)({getCurrentHub:mn,runWithAsyncContext:Zn})}function An(t){const e="console";Ne(e,t),Ke(e,Wn)}function Wn(){"console"in Ye.OW&&p.Ow.forEach((function(t){t in Ye.OW.console&&(0,c.GS)(Ye.OW.console,t,(function(e){return p.Z9[t]=e,function(...e){we("console",{args:e,level:t});const n=p.Z9[t];n&&n.apply(Ye.OW.console,e)}}))}))}const Vn=["fatal","error","warning","log","info","debug"];function vn(t){return"warn"===t?"warning":Vn.includes(t)?t:"log"}const fn="Console",Rn=(0,g._C)((()=>({name:fn,setupOnce(){},setup(t){An((({args:e,level:n})=>{(0,a.KU)()===t&&(0,a.ZQ)({category:"console",level:vn(n),message:ve.format.apply(void 0,e)},{input:[...e],level:n})}))}}))),Yn=(0,g.F)(fn,Rn),Xn=require("child_process"),Hn=require("fs"),Sn=require("path"),Nn=(0,ve.promisify)(Hn.readFile),Kn=(0,ve.promisify)(Hn.readdir),wn="Context",Fn=(0,g._C)(((t={})=>{let e;const n={app:!0,os:!0,device:!0,culture:!0,cloudResource:!0,...t};return{name:wn,setupOnce(){},processEvent:t=>async function(t){void 0===e&&(e=async function(){const t={};if(n.os&&(t.os=await async function(){const t=Ve.platform();switch(t){case"darwin":return async function(){const t={kernel_version:Ve.release(),name:"Mac OS X",version:"10."+(Number(Ve.release().split(".")[0])-4)};try{const e=await new Promise(((t,e)=>{(0,Xn.execFile)("/usr/bin/sw_vers",((n,s)=>{n?e(n):t(s)}))}));t.name=Un(/^ProductName:\s+(.*)$/m,e),t.version=Un(/^ProductVersion:\s+(.*)$/m,e),t.build=Un(/^BuildVersion:\s+(.*)$/m,e)}catch(t){}return t}();case"linux":return async function(){const t={kernel_version:Ve.release(),name:"Linux"};try{const e=await Kn("/etc"),n=_n.find((t=>e.includes(t.name)));if(!n)return t;const s=(0,Sn.join)("/etc",n.name),i=(await Nn(s,{encoding:"utf-8"})).toLowerCase(),{distros:o}=n;t.name=o.find((t=>i.indexOf(xn(t))>=0))||o[0];const r=xn(t.name);t.version=zn[r](i)}catch(t){}return t}();default:return{name:kn[t]||t,version:Ve.release()}}}()),n.app&&(t.app=function(){const t=process.memoryUsage().rss;return{app_start_time:new Date(Date.now()-1e3*process.uptime()).toISOString(),app_memory:t}}()),n.device&&(t.device=function(t){const e={};let n;try{n=Ve.uptime&&Ve.uptime()}catch(t){}if("number"==typeof n&&(e.boot_time=new Date(Date.now()-1e3*n).toISOString()),e.arch=Ve.arch(),(!0===t||t.memory)&&(e.memory_size=Ve.totalmem(),e.free_memory=Ve.freemem()),!0===t||t.cpu){const t=Ve.cpus();if(t&&t.length){const n=t[0];e.processor_count=t.length,e.cpu_description=n.model,e.processor_frequency=n.speed}}return e}(n.device)),n.culture){const e=function(){try{if("string"!=typeof process.versions.icu)return;const t=new Date(9e8);if("enero"===new Intl.DateTimeFormat("es",{month:"long"}).format(t)){const t=Intl.DateTimeFormat().resolvedOptions();return{locale:t.locale,timezone:t.timeZone}}}catch(t){}}();e&&(t.culture=e)}return n.cloudResource&&(t.cloud_resource=process.env.VERCEL?{"cloud.provider":"vercel","cloud.region":process.env.VERCEL_REGION}:process.env.AWS_REGION?{"cloud.provider":"aws","cloud.region":process.env.AWS_REGION,"cloud.platform":process.env.AWS_EXECUTION_ENV}:process.env.GCP_PROJECT?{"cloud.provider":"gcp"}:process.env.ALIYUN_REGION_ID?{"cloud.provider":"alibaba_cloud","cloud.region":process.env.ALIYUN_REGION_ID}:process.env.WEBSITE_SITE_NAME&&process.env.REGION_NAME?{"cloud.provider":"azure","cloud.region":process.env.REGION_NAME}:process.env.IBM_CLOUD_REGION?{"cloud.provider":"ibm_cloud","cloud.region":process.env.IBM_CLOUD_REGION}:process.env.TENCENTCLOUD_REGION?{"cloud.provider":"tencent_cloud","cloud.region":process.env.TENCENTCLOUD_REGION,"cloud.account.id":process.env.TENCENTCLOUD_APPID,"cloud.availability_zone":process.env.TENCENTCLOUD_ZONE}:process.env.NETLIFY?{"cloud.provider":"netlify"}:process.env.FLY_REGION?{"cloud.provider":"fly.io","cloud.region":process.env.FLY_REGION}:process.env.DYNO?{"cloud.provider":"heroku"}:void 0),t}());const s=(i=await e,(0,nn.z)([i,"optionalAccess",t=>t.app,"optionalAccess",t=>t.app_memory])&&(i.app.app_memory=process.memoryUsage().rss),(0,nn.z)([i,"optionalAccess",t=>t.device,"optionalAccess",t=>t.free_memory])&&(i.device.free_memory=Ve.freemem()),i);var i;return t.contexts={...t.contexts,app:{...s.app,...(0,nn.z)([t,"access",t=>t.contexts,"optionalAccess",t=>t.app])},os:{...s.os,...(0,nn.z)([t,"access",t=>t.contexts,"optionalAccess",t=>t.os])},device:{...s.device,...(0,nn.z)([t,"access",t=>t.contexts,"optionalAccess",t=>t.device])},culture:{...s.culture,...(0,nn.z)([t,"access",t=>t.contexts,"optionalAccess",t=>t.culture])},cloud_resource:{...s.cloud_resource,...(0,nn.z)([t,"access",t=>t.contexts,"optionalAccess",t=>t.cloud_resource])}},t}(t)}})),Jn=(0,g.F)(wn,Fn),kn={aix:"IBM AIX",freebsd:"FreeBSD",openbsd:"OpenBSD",sunos:"SunOS",win32:"Windows"},_n=[{name:"fedora-release",distros:["Fedora"]},{name:"redhat-release",distros:["Red Hat Linux","Centos"]},{name:"redhat_version",distros:["Red Hat Linux"]},{name:"SuSE-release",distros:["SUSE Linux"]},{name:"lsb-release",distros:["Ubuntu Linux","Arch Linux"]},{name:"debian_version",distros:["Debian"]},{name:"debian_release",distros:["Debian"]},{name:"arch-release",distros:["Arch Linux"]},{name:"gentoo-release",distros:["Gentoo Linux"]},{name:"novell-release",distros:["SUSE Linux"]},{name:"alpine-release",distros:["Alpine Linux"]}],zn={alpine:t=>t,arch:t=>Un(/distrib_release=(.*)/,t),centos:t=>Un(/release ([^ ]+)/,t),debian:t=>t,fedora:t=>Un(/release (..)/,t),mint:t=>Un(/distrib_release=(.*)/,t),red:t=>Un(/release ([^ ]+)/,t),suse:t=>Un(/VERSION = (.*)\n/,t),ubuntu:t=>Un(/distrib_release=(.*)/,t)};function Un(t,e){const n=t.exec(e);return n?n[1]:void 0}function xn(t){return t.split(" ")[0].toLowerCase()}class Tn{constructor(t){this._maxSize=t,this._cache=new Map}get size(){return this._cache.size}get(t){const e=this._cache.get(t);if(void 0!==e)return this._cache.delete(t),this._cache.set(t,e),e}set(t,e){this._cache.size>=this._maxSize&&this._cache.delete(this._cache.keys().next().value),this._cache.set(t,e)}remove(t){const e=this._cache.get(t);return e&&this._cache.delete(t),e}clear(){this._cache.clear()}keys(){return Array.from(this._cache.keys())}values(){const t=[];return this._cache.forEach((e=>t.push(e))),t}}const En=new Tn(100),Ln="ContextLines",Qn=(0,g._C)(((t={})=>{const e=void 0!==t.frameContextLines?t.frameContextLines:7;return{name:Ln,setupOnce(){},processEvent:t=>async function(t,e){const n={},s=[];if(e>0&&(0,nn.z)([t,"access",t=>t.exception,"optionalAccess",t=>t.values]))for(const e of t.exception.values)if((0,nn.z)([e,"access",t=>t.stacktrace,"optionalAccess",t=>t.frames]))for(let t=e.stacktrace.frames.length-1;t>=0;t--){const i=e.stacktrace.frames[t];!i.filename||n[i.filename]||En.get(i.filename)||(s.push(Mn(i.filename)),n[i.filename]=1)}if(s.length>0&&await Promise.all(s),e>0&&(0,nn.z)([t,"access",t=>t.exception,"optionalAccess",t=>t.values]))for(const n of t.exception.values)n.stacktrace&&n.stacktrace.frames&&await On(n.stacktrace.frames,e);return t}(t,e)}})),jn=(0,g.F)(Ln,Qn);function On(t,e){for(const n of t)if(n.filename&&void 0===n.context_line){const t=En.get(n.filename);if(t)try{(0,b.db)(t,n,e)}catch(t){}}}async function Mn(t){const e=En.get(t);if(null===e)return null;if(void 0!==e)return e;let n=null;try{const e=await(s=t,new Promise(((t,e)=>{(0,Hn.readFile)(s,"utf8",((n,s)=>{n?e(n):t(s)}))})));n=e.split("\n")}catch(t){}var s;return En.set(t,n),n}function Pn(t,e){const n=e&&function(t){return void 0!==t.getClient}(e)?e.getClient():e,s=n&&n.getDsn(),i=n&&n.getOptions().tunnel;return function(t,e){return!!e&&t.includes(e.host)}(t,s)||function(t,e){return!!e&&Dn(t)===Dn(e)}(t,i)}function Dn(t){return"/"===t[t.length-1]?t.slice(0,-1):t}var qn=n(5584);const $n="undefined"==typeof __SENTRY_DEBUG__||__SENTRY_DEBUG__;function ts(t){const{protocol:e,hostname:n,port:s}=ss(t),i=t.pathname||"/";return`${e}//${t.auth?function(t){const[e,n]=t.split(":");return`${e?"[Filtered]":""}:${n?"[Filtered]":""}@`}(t.auth):""}${n}${s}${i}`}function es(t,e,n){if(!t)return t;let[s,i]=t.split(" ");return e.host&&!e.protocol&&(e.protocol=(0,nn.z)([n,"optionalAccess",t=>t.agent,"optionalAccess",t=>t.protocol]),i=ts(e)),(0,nn.z)([i,"optionalAccess",t=>t.startsWith,"call",t=>t("///")])&&(i=i.slice(2)),`${s} ${i}`}function ns(t){const e={protocol:t.protocol,hostname:"string"==typeof t.hostname&&t.hostname.startsWith("[")?t.hostname.slice(1,-1):t.hostname,hash:t.hash,search:t.search,pathname:t.pathname,path:`${t.pathname||""}${t.search||""}`,href:t.href};return""!==t.port&&(e.port=Number(t.port)),(t.username||t.password)&&(e.auth=`${t.username}:${t.password}`),e}function ss(t){const e=t.protocol||"",n=t.hostname||t.host||"";return{protocol:e,hostname:n,port:!t.port||80===t.port||443===t.port||/^(.*):(\d+)$/.test(n)?"":`:${t.port}`}}const is=(0,g._C)(((t={})=>{const{breadcrumbs:e,tracing:n,shouldCreateSpanForRequest:s}=t,i={breadcrumbs:e,tracing:!1!==n&&(0,c.Ce)({enableIfHasTracingEnabled:!0!==n||void 0,shouldCreateSpanForRequest:s})};return new os(i)}));class os{static __initStatic(){this.id="Http"}__init(){this.name=os.id}constructor(t={}){os.prototype.__init.call(this),this._breadcrumbs=void 0===t.breadcrumbs||t.breadcrumbs,this._tracing=t.tracing?!0===t.tracing?{}:t.tracing:void 0}setupOnce(t,e){const s=(0,nn.z)([e,"call",t=>t(),"access",t=>t.getClient,"call",t=>t(),"optionalAccess",t=>t.getOptions,"call",t=>t()]),i=function(t,e){return void 0!==t&&(!t.enableIfHasTracingEnabled||Gt(e))}(this._tracing,s);if(!this._breadcrumbs&&!i)return;if(s&&"sentry"!==s.instrumenter)return void($n&&p.vF.log("HTTP Integration is skipped because of instrumenter configuration."));const o=function(t,e,n){return t?(0,nn.z)([e,"optionalAccess",t=>t.shouldCreateSpanForRequest])||(0,nn.z)([n,"optionalAccess",t=>t.shouldCreateSpanForRequest]):()=>!1}(i,this._tracing,s),r=(0,nn.z)([s,"optionalAccess",t=>t.tracePropagationTargets])||(0,nn.z)([this,"access",t=>t._tracing,"optionalAccess",t=>t.tracePropagationTargets]),a=n(8611),g=rs(a,this._breadcrumbs,o,r);if((0,c.GS)(a,"get",g),(0,c.GS)(a,"request",g),pn.S.major>8){const t=n(5692),e=rs(t,this._breadcrumbs,o,r);(0,c.GS)(t,"get",e),(0,c.GS)(t,"request",e)}}}function rs(t,e,n,s){const i=new Tn(100),o=new Tn(100);function r(t,e,n,s){(0,nt.BF)().getIntegration(os)&&(0,a.ZQ)({category:"http",data:{status_code:s&&s.statusCode,...e},type:"http"},{event:t,request:n,response:s})}return function(c){return function(...g){const l=function(t,e){let n,s;if("function"==typeof e[e.length-1]&&(n=e.pop()),"string"==typeof e[0])s=ns(new tn.URL(e[0]));else if(e[0]instanceof tn.URL)s=ns(e[0]);else{s=e[0];try{const t=new tn.URL(s.path||"",`${s.protocol||"http:"}//${s.hostname}`);s={pathname:t.pathname,search:t.search,hash:t.hash,...s}}catch(t){}}return 2===e.length&&(s={...s,...e[1]}),void 0===s.protocol&&(pn.S.major>8?s.protocol=(0,nn.z)([(0,nn.z)([t,"optionalAccess",t=>t.globalAgent]),"optionalAccess",t=>t.protocol])||(0,nn.z)([s.agent,"optionalAccess",t=>t.protocol])||(0,nn.z)([s._defaultAgent,"optionalAccess",t=>t.protocol]):s.protocol=(0,nn.z)([s.agent,"optionalAccess",t=>t.protocol])||(0,nn.z)([s._defaultAgent,"optionalAccess",t=>t.protocol])||(0,nn.z)([(0,nn.z)([t,"optionalAccess",t=>t.globalAgent]),"optionalAccess",t=>t.protocol])),n?[s,n]:[s]}(t,g),d=l[0],I=function(t){const{protocol:e,hostname:n,port:s}=ss(t);return`${e}//${n}${s}${t.path?t.path:"/"}`}(d),u=ts(d),C=(0,a.KU)();if(Pn(u,C))return c.apply(t,l);const b=(0,a.o5)(),m=(0,nt.rm)(),Z=vt(),G=function(t,e){const n={url:t,"http.method":e.method||"GET"};return e.hash&&(n["http.fragment"]=e.hash.substring(1)),e.search&&(n["http.query"]=e.search.substring(1)),n}(u,d),B=(t=>{if(void 0===n)return!0;const e=i.get(t);if(void 0!==e)return e;const s=n(t);return i.set(t,s),s})(I)?(0,nn.z)([Z,"optionalAccess",t=>t.startChild,"call",t=>t({op:"http.client",origin:"auto.http.node.http",description:`${G["http.method"]} ${G.url}`,data:G})]):void 0;if(C&&(t=>{if(void 0===s)return!0;const e=o.get(t);if(void 0!==e)return e;const n=(0,h.Xr)(t,s);return o.set(t,n),n})(I)){const{traceId:t,spanId:e,sampled:n,dsc:s}={...m.getPropagationContext(),...b.getPropagationContext()},i=B?(0,mt.Qh)(B):(0,ht.TC)(t,e,n),o=(0,qn.De)(s||(B?(0,lt.k)(B):(0,lt.l)(t,C,b)));!function(t,e,n,s){(t.headers||{})["sentry-trace"]||($n&&p.vF.log(`[Tracing] Adding sentry-trace header ${n} to outgoing request to "${e}": `),t.headers={...t.headers,"sentry-trace":n,...s&&s.length>0&&{baggage:cs(t,s)}})}(d,u,i,o)}else $n&&p.vF.log(`[Tracing] Not adding sentry-trace header to outgoing request (${u}) due to mismatching tracePropagationTargets option.`);return c.apply(t,l).once("response",(function(t){e&&r("response",G,this,t),B&&(t.statusCode&&Ut(B,t.statusCode),B.updateName(es((0,mt.et)(B).description||"",d,this)||""),B.end())})).once("error",(function(){e&&r("error",G,this),B&&(Ut(B,500),B.updateName(es((0,mt.et)(B).description||"",d,this)||""),B.end())}))}}}function cs(t,e){return t.headers&&t.headers.baggage?e?Array.isArray(t.headers.baggage)?[...t.headers.baggage,e]:[t.headers.baggage,e]:t.headers.baggage:e}function as(t){return void 0!==t&&(0===t.length||"?"===t||""===t)}function gs(t){if(void 0!==t)return t.slice(-10).reduce(((t,e)=>`${t},${e.function},${e.lineno},${e.colno}`),"")}function ls(t){let e=[],n=!1;function s(s){e=[],n||(n=!0,t(s))}return e.push(s),{add:function(t){e.push(t)},next:function(t){const n=e.pop()||s;try{n(t)}catch(e){s(t)}}}}os.__initStatic();class ds{constructor(){const{Session:t}=n(264);this._session=new t}configureAndConnect(t,e){this._session.connect(),this._session.on("Debugger.paused",(e=>{t(e,(()=>{this._session.post("Debugger.resume")}))})),this._session.post("Debugger.enable"),this._session.post("Debugger.setPauseOnExceptions",{state:e?"all":"uncaught"})}setPauseOnExceptions(t){this._session.post("Debugger.setPauseOnExceptions",{state:t?"all":"uncaught"})}getLocalVariables(t,e){this._getProperties(t,(t=>{const{add:n,next:s}=ls(e);for(const e of t)if((0,nn.z)([e,"optionalAccess",t=>t.value,"optionalAccess",t=>t.objectId])&&"Array"===(0,nn.z)([e,"optionalAccess",t=>t.value,"access",t=>t.className])){const t=e.value.objectId;n((n=>this._unrollArray(t,e.name,n,s)))}else if((0,nn.z)([e,"optionalAccess",t=>t.value,"optionalAccess",t=>t.objectId])&&"Object"===(0,nn.z)([e,"optionalAccess",t=>t.value,"optionalAccess",t=>t.className])){const t=e.value.objectId;n((n=>this._unrollObject(t,e.name,n,s)))}else null==(0,nn.z)([e,"optionalAccess",t=>t.value,"optionalAccess",t=>t.value])&&null==(0,nn.z)([e,"optionalAccess",t=>t.value,"optionalAccess",t=>t.description])||n((t=>this._unrollOther(e,t,s)));s({})}))}_getProperties(t,e){this._session.post("Runtime.getProperties",{objectId:t,ownProperties:!0},((t,n)=>{e(t?[]:n.result)}))}_unrollArray(t,e,n,s){this._getProperties(t,(t=>{n[e]=t.filter((t=>"length"!==t.name&&!isNaN(parseInt(t.name,10)))).sort(((t,e)=>parseInt(t.name,10)-parseInt(e.name,10))).map((t=>(0,nn.z)([t,"optionalAccess",t=>t.value,"optionalAccess",t=>t.value]))),s(n)}))}_unrollObject(t,e,n,s){this._getProperties(t,(t=>{n[e]=t.map((t=>[t.name,(0,nn.z)([t,"optionalAccess",t=>t.value,"optionalAccess",t=>t.value])])).reduce(((t,[e,n])=>(t[e]=n,t)),{}),s(n)}))}_unrollOther(t,e,n){null!=(0,nn.z)([t,"optionalAccess",t=>t.value,"optionalAccess",t=>t.value])?e[t.name]=t.value.value:null!=(0,nn.z)([t,"optionalAccess",t=>t.value,"optionalAccess",t=>t.description])&&"function"!==(0,nn.z)([t,"optionalAccess",t=>t.value,"optionalAccess",t=>t.type])&&(e[t.name]=`<${t.value.description}>`),n(e)}}const Is="LocalVariables",us=(0,g._C)(((t={},e=function(){try{return new ds}catch(t){return}}())=>{const n=new Tn(20);let s,i=!1;function o(t){const e=gs((0,nn.z)([t,"optionalAccess",t=>t.stacktrace,"optionalAccess",t=>t.frames]));if(void 0===e)return;const s=n.remove(e);if(void 0===s)return;const i=((0,nn.z)([t,"access",t=>t.stacktrace,"optionalAccess",t=>t.frames])||[]).filter((t=>"new Promise"!==t.function));for(let t=0;tt.getOptions,"call",t=>t()]);if(e&&(0,nn.z)([r,"optionalAccess",t=>t.includeLocalVariables])){if(pn.S.major<18)return void p.vF.log("The `LocalVariables` integration is only supported on Node >= v18.");const o=!1!==t.captureAllExceptions;if(e.configureAndConnect(((t,i)=>function(t,{params:{reason:i,data:o,callFrames:r}},c){if("exception"!==i&&"promiseRejection"!==i)return void c();(0,nn.z)([s,"optionalCall",t=>t()]);const a=function(t,e){if(void 0!==e)return gs(t(e,1))}(t,(0,nn.z)([o,"optionalAccess",t=>t.description]));if(null==a)return void c();const{add:g,next:l}=ls((t=>{n.set(a,t),c()}));for(let t=0;t"local"===t.type)),c="global"!==i.className&&i.className?`${i.className}.${s}`:s;if(void 0===(0,nn.z)([o,"optionalAccess",t=>t.object,"access",t=>t.objectId]))g((e=>{e[t]={function:c},l(e)}));else{const n=o.object.objectId;g((s=>(0,nn.z)([e,"optionalAccess",t=>t.getLocalVariables,"call",e=>e(n,(e=>{s[t]={function:c,vars:e},l(s)}))])))}}l([])}(r.stackParser,t,i)),o),o){const n=t.maxExceptionsPerSecond||50;s=function(t){let n=0,s=5,i=0;return setInterval((()=>{var o;0===i?n>t&&(s*=2,o=s,p.vF.log(`Local variables rate-limit exceeded. Disabling capturing of caught exceptions for ${o} seconds.`),(0,nn.z)([e,"optionalAccess",t=>t.setPauseOnExceptions,"call",t=>t(!1)]),s>86400&&(s=86400),i=s):(i-=1,0===i&&(p.vF.log("Local variables rate-limit lifted."),(0,nn.z)([e,"optionalAccess",t=>t.setPauseOnExceptions,"call",t=>t(!0)]))),n=0}),1e3).unref(),()=>{n+=1}}(n)}i=!0}},processEvent:t=>i?function(t){for(const e of(0,nn.z)([t,"optionalAccess",t=>t.exception,"optionalAccess",t=>t.values])||[])o(e);return t}(t):t,_getCachedFramesCount:()=>n.size,_getFirstCachedFrame:()=>n.values()[0]}})),Cs=(0,g.F)(Is,us),ps=us;let bs;const hs="Modules";function ms(){const t=n.c[n.s]&&n.c[n.s].paths||[],e=function(){try{return n.c?Object.keys(n.c):[]}catch(t){return[]}}(),s={},i={};return e.forEach((e=>{let n=e;const o=()=>{const e=n;if(n=(0,Sn.dirname)(e),!n||e===n||i[e])return;if(t.indexOf(n)<0)return o();const r=(0,Sn.join)(e,"package.json");if(i[e]=!0,!(0,Hn.existsSync)(r))return o();try{const t=JSON.parse((0,Hn.readFileSync)(r,"utf8"));s[t.name]=t.version}catch(t){}};o()})),s}const Zs=(0,g._C)((()=>({name:hs,setupOnce(){},processEvent:t=>(t.modules={...t.modules,...(bs||(bs=ms()),bs)},t)}))),Gs=(0,g.F)(hs,Zs);function Bs(t){(0,p.pq)((()=>{console.error(t)}));const e=(0,a.KU)();void 0===e&&($n&&p.vF.warn("No NodeClient was defined, we are exiting the process now."),global.process.exit(1));const n=e.getOptions(),s=n&&n.shutdownTimeout&&n.shutdownTimeout>0&&n.shutdownTimeout||2e3;e.close(s).then((t=>{t||$n&&p.vF.warn("We reached the timeout for emptying the request buffer, still exiting now!"),global.process.exit(1)}),(t=>{$n&&p.vF.error(t)}))}const ys="OnUncaughtException",As=(0,g._C)(((t={})=>{const e={exitEvenIfOtherHandlersAreRegistered:!0,...t};return{name:ys,setupOnce(){},setup(t){global.process.on("uncaughtException",function(t,e){let n,s=!1,i=!1,o=!1;const r=t.getOptions();return Object.assign((c=>{let g=Bs;e.onFatalError?g=e.onFatalError:r.onFatalError&&(g=r.onFatalError);const l=0===global.process.listeners("uncaughtException").reduce(((t,e)=>"domainUncaughtExceptionClear"===e.name||e.tag&&"sentry_tracingErrorCallback"===e.tag||e._errorHandler?t:t+1),0),d=e.exitEvenIfOtherHandlersAreRegistered||l;s?d&&(o?($n&&p.vF.warn("uncaught exception after calling fatal error shutdown callback - this is bad! forcing shutdown"),Bs(c)):i||(i=!0,setTimeout((()=>{o||(o=!0,g(n,c))}),2e3))):(n=c,s=!0,(0,a.KU)()===t&&(0,a.Cp)(c,{originalException:c,captureContext:{level:"fatal"},mechanism:{handled:!1,type:"onuncaughtexception"}}),!o&&d&&(o=!0,g(c)))}),{_errorHandler:!0})}(t,e))}}})),Ws=(0,g.F)(ys,As),Vs="OnUnhandledRejection",vs=(0,g._C)(((t={})=>{const e=t.mode||"warn";return{name:Vs,setupOnce(){},setup(t){global.process.on("unhandledRejection",function(t,e){return function(n,s){(0,a.KU)()===t&&((0,a.Cp)(n,{originalException:s,captureContext:{extra:{unhandledPromiseRejection:!0}},mechanism:{handled:!1,type:"onunhandledrejection"}}),function(t,e){const n="This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason:";"warn"===e.mode?(0,p.pq)((()=>{console.warn(n),console.error(t&&t.stack?t.stack:t)})):"strict"===e.mode&&((0,p.pq)((()=>{console.warn(n)})),Bs(t))}(n,e))}}(t,{mode:e}))}}})),fs=(0,g.F)(Vs,vs),Rs="Spotlight",Ys=(0,g._C)(((t={})=>{const e={sidecarUrl:t.sidecarUrl||"http://localhost:8969/stream"};return{name:Rs,setupOnce(){},setup(t){"object"==typeof process&&process.env&&p.vF.warn("[Spotlight] It seems you're not in dev mode. Do you really want to have Spotlight enabled?"),function(t,e){const n=function(t){try{return new tn.URL(`${t}`)}catch(e){return void p.vF.warn(`[Spotlight] Invalid sidecar URL: ${t}`)}}(e.sidecarUrl);if(!n)return;let s=0;"function"==typeof t.on?t.on("beforeEnvelope",(t=>{if(s>3)return void p.vF.warn("[Spotlight] Disabled Sentry -> Spotlight integration due to too many failed requests");const e=P(t),i=function(){const{request:t}=De;return"__sentry_original__"in t?t.__sentry_original__:t}()({method:"POST",path:n.pathname,hostname:n.hostname,port:n.port,headers:{"Content-Type":"application/x-sentry-envelope"}},(t=>{t.on("data",(()=>{})),t.on("end",(()=>{})),t.setEncoding("utf8")}));i.on("error",(()=>{s++,p.vF.warn("[Spotlight] Failed to send envelope to Spotlight Sidecar")})),i.write(e),i.end()})):p.vF.warn("[Spotlight] Cannot connect to spotlight due to missing method on SDK client (`client.on`)")}(t,e)}}})),Xs=(0,g.F)(Rs,Ys);var Hs;!function(t){t.RequestCreate="undici:request:create",t.RequestEnd="undici:request:headers",t.RequestError="undici:request:error"}(Hs||(Hs={}));const Ss=(0,g._C)((t=>new Ns(t)));class Ns{static __initStatic(){this.id="Undici"}__init(){this.name=Ns.id}__init2(){this._createSpanUrlMap=new Tn(100)}__init3(){this._headersUrlMap=new Tn(100)}constructor(t={}){Ns.prototype.__init.call(this),Ns.prototype.__init2.call(this),Ns.prototype.__init3.call(this),Ns.prototype.__init4.call(this),Ns.prototype.__init5.call(this),Ns.prototype.__init6.call(this),this._options={breadcrumbs:void 0===t.breadcrumbs||t.breadcrumbs,tracing:t.tracing,shouldCreateSpanForRequest:t.shouldCreateSpanForRequest}}setupOnce(t){if(pn.S.major<16)return;let e;try{e=n(1637)}catch(t){}e&&e.subscribe&&(e.subscribe(Hs.RequestCreate,this._onRequestCreate),e.subscribe(Hs.RequestEnd,this._onRequestEnd),e.subscribe(Hs.RequestError,this._onRequestError))}_shouldCreateSpan(t){if(!1===this._options.tracing||void 0===this._options.tracing&&!Gt())return!1;if(void 0===this._options.shouldCreateSpanForRequest)return!0;const e=this._createSpanUrlMap.get(t);if(void 0!==e)return e;const n=this._options.shouldCreateSpanForRequest(t);return this._createSpanUrlMap.set(t,n),n}__init4(){this._onRequestCreate=t=>{if(!(0,nn.z)([a.KU,"call",t=>t(),"optionalAccess",t=>t.getIntegration,"call",t=>t(Ns)]))return;const{request:e}=t,n=e.origin?e.origin.toString()+e.path:e.path,s=(0,a.KU)();if(!s)return;if(Pn(n,s)||void 0!==e.__sentry_span__)return;const i=s.getOptions(),o=(0,a.o5)(),r=(0,nt.rm)(),c=vt(),g=this._shouldCreateSpan(n)?function(t,e,n){const s=function(t){if(!t)return{};const e=t.match(/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);if(!e)return{};const n=e[6]||"",s=e[8]||"";return{host:e[4],path:e[5],protocol:e[2],search:n,hash:s,relative:e[5]+n+s}}(n),i=e.method||"GET",o={"http.method":i};return s.search&&(o["http.query"]=s.search),s.hash&&(o["http.fragment"]=s.hash),(0,nn.z)([t,"optionalAccess",t=>t.startChild,"call",t=>t({op:"http.client",origin:"auto.http.node.undici",description:`${i} ${re(s)}`,data:o})])}(c,e,n):void 0;if(g&&(e.__sentry_span__=g),(t=>{if(void 0===i.tracePropagationTargets)return!0;const e=this._headersUrlMap.get(t);if(void 0!==e)return e;const n=(0,h.Xr)(t,i.tracePropagationTargets);return this._headersUrlMap.set(t,n),n})(n)){const{traceId:t,spanId:n,sampled:i,dsc:c}={...r.getPropagationContext(),...o.getPropagationContext()};!function(t,e,n){let s;s=Array.isArray(t.headers)?t.headers.some((t=>"sentry-trace"===t)):t.headers.split("\r\n").some((t=>t.startsWith("sentry-trace:"))),s||(t.addHeader("sentry-trace",e),n&&t.addHeader("baggage",n))}(e,g?(0,mt.Qh)(g):(0,ht.TC)(t,n,i),(0,qn.De)(c||(g?(0,lt.k)(g):(0,lt.l)(t,s,o))))}}}__init5(){this._onRequestEnd=t=>{if(!(0,nn.z)([a.KU,"call",t=>t(),"optionalAccess",t=>t.getIntegration,"call",t=>t(Ns)]))return;const{request:e,response:n}=t,s=e.origin?e.origin.toString()+e.path:e.path;if(Pn(s,(0,a.KU)()))return;const i=e.__sentry_span__;i&&(Ut(i,n.statusCode),i.end()),this._options.breadcrumbs&&(0,a.ZQ)({category:"http",data:{method:e.method,status_code:n.statusCode,url:s},type:"http"},{event:"response",request:e,response:n})}}__init6(){this._onRequestError=t=>{if(!(0,nn.z)([a.KU,"call",t=>t(),"optionalAccess",t=>t.getIntegration,"call",t=>t(Ns)]))return;const{request:e}=t,n=e.origin?e.origin.toString()+e.path:e.path;if(Pn(n,(0,a.KU)()))return;const s=e.__sentry_span__;s&&(s.setStatus("internal_error"),s.end()),this._options.breadcrumbs&&(0,a.ZQ)({category:"http",data:{method:e.method,url:n},level:"error",type:"http"},{event:"error",request:e})}}}Ns.__initStatic();const Ks=/^(\S+:\\|\/?)([\s\S]*?)((?:\.{1,2}|[^/\\]+?|)(\.[^./\\]*|))(?:[/\\]*)$/;function ws(t){const e=t.length>1024?`${t.slice(-1024)}`:t,n=Ks.exec(e);return n?n.slice(1):[]}function Fs(...t){let e="",n=!1;for(let s=t.length-1;s>=-1&&!n;s--){const i=s>=0?t[s]:"/";i&&(e=`${i}/${e}`,n="/"===i.charAt(0))}return e=function(t,e){let n=0;for(let e=t.length-1;e>=0;e--){const s=t[e];"."===s?t.splice(e,1):".."===s?(t.splice(e,1),n++):n&&(t.splice(e,1),n--)}if(e)for(;n--;n)t.unshift("..");return t}(e.split("/").filter((t=>!!t)),!n).join("/"),(n?"/":"")+e||"."}function Js(t){let e=0;for(;e=0&&""===t[n];n--);return e>n?[]:t.slice(e,n-e+1)}function ks(t){return t.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}function _s(t=(process.argv[1]?function(){const t=ws(process.argv[1]),e=t[0];let n=t[1];return e||n?(n&&(n=n.slice(0,n.length-1)),e+n):"."}():process.cwd()),e="\\"===Sn.sep){const n=e?ks(t):t;return t=>{if(!t)return;const s=e?ks(t):t;let{dir:i,base:o,ext:r}=Sn.posix.parse(s);".js"!==r&&".mjs"!==r&&".cjs"!==r||(o=o.slice(0,-1*r.length)),i||(i=".");const c=i.lastIndexOf("/node_modules");if(c>-1)return`${i.slice(c+14).replace(/\//g,".")}:${o}`;if(i.startsWith(n)){let t=i.slice(n.length+1).replace(/\//g,".");return t&&(t+=":"),t+=o,t}return o}}const zs=[y(),u(),K(),be(),Rn(),is(),Ss(),As(),vs(),Qn(),ps(),Fn(),Zs()];function Us(t){const e=(0,nt.EU)(),n=(0,nn.z)([e,"access",t=>t.__SENTRY__,"optionalAccess",t=>t.integrations])||[];return[...zs,...n]}function xs(t={}){yn(),void 0===t.defaultIntegrations&&(t.defaultIntegrations=Us()),void 0===t.dsn&&process.env.SENTRY_DSN&&(t.dsn=process.env.SENTRY_DSN);const e=process.env.SENTRY_TRACES_SAMPLE_RATE;if(void 0===t.tracesSampleRate&&e){const n=parseFloat(e);isFinite(n)&&(t.tracesSampleRate=n)}if(void 0===t.release){const e=Es();void 0!==e?t.release=e:t.autoSessionTracking=!1}void 0===t.environment&&process.env.SENTRY_ENVIRONMENT&&(t.environment=process.env.SENTRY_ENVIRONMENT),void 0===t.autoSessionTracking&&void 0!==t.dsn&&(t.autoSessionTracking=!0),void 0===t.instrumenter&&(t.instrumenter="sentry");const n={...t,stackParser:(0,Xe.vk)(t.stackParser||Ls),integrations:(0,g.mH)(t),transport:t.transport||Cn};if(function(t,e){!0===e.debug&&(m.T?p.vF.enable():(0,p.pq)((()=>{console.warn("[Sentry] Cannot initialize SDK with `debug` option using a non-debug bundle.")}))),(0,a.o5)().update(e.initialScope);const n=new t(e);me(n),function(t){t.init?t.init():t.setupIntegrations&&t.setupIntegrations()}(n)}(t.clientClass||Me,n),t.autoSessionTracking&&((0,a.J0)(),process.on("beforeExit",(()=>{const t=(0,nt.rm)().getSession();t&&!["exited","crashed"].includes(t.status)&&(0,a.ky)()}))),function(){const t=(process.env.SENTRY_USE_ENVIRONMENT||"").toLowerCase();if(!["false","n","no","off","0"].includes(t)){const t=process.env.SENTRY_TRACE,e=process.env.SENTRY_BAGGAGE,n=(0,ht.kM)(t,e);(0,a.o5)().setPropagationContext(n)}}(),t.spotlight){const e=(0,a.KU)();if(e&&e.addIntegration){const n=e.getOptions().integrations;for(const t of n)e.addIntegration(t);e.addIntegration(Ys({sidecarUrl:"string"==typeof t.spotlight?t.spotlight:void 0}))}}}function Ts(t){if(void 0===t)return!1;const e=t&&t.getOptions();return!(!e||void 0===e.autoSessionTracking)&&e.autoSessionTracking}function Es(t){return process.env.SENTRY_RELEASE?process.env.SENTRY_RELEASE:Ye.OW.SENTRY_RELEASE&&Ye.OW.SENTRY_RELEASE.id?Ye.OW.SENTRY_RELEASE.id:process.env.GITHUB_SHA||process.env.COMMIT_REF||process.env.VERCEL_GIT_COMMIT_SHA||process.env.VERCEL_GITHUB_COMMIT_SHA||process.env.VERCEL_GITLAB_COMMIT_SHA||process.env.VERCEL_BITBUCKET_COMMIT_SHA||process.env.ZEIT_GITHUB_COMMIT_SHA||process.env.ZEIT_GITLAB_COMMIT_SHA||process.env.ZEIT_BITBUCKET_COMMIT_SHA||process.env.CF_PAGES_COMMIT_SHA||t}const Ls=(0,Xe.gd)((0,Xe.o)(_s()));function Qs(t){const e=Sn.resolve(t);if(!Hn.existsSync(e))throw new Error(`Cannot read contents of ${e}. Directory does not exist.`);if(!Hn.statSync(e).isDirectory())throw new Error(`Cannot read contents of ${e}, because it is not a directory.`);const n=t=>Hn.readdirSync(t).reduce(((e,s)=>{const i=Sn.join(t,s);return Hn.statSync(i).isDirectory()?e.concat(n(i)):(e.push(i),e)}),[]);return n(e).map((t=>Sn.relative(e,t)))}var js=n(1615);function Os(t){const e=(0,a.KU)();return new js.M(t).setup(e),Promise.resolve()}function Ms(t={}){return function({path:e,type:n,next:s,rawInput:i}){const o=(0,nn.z)([a.KU,"call",t=>t(),"optionalAccess",t=>t.getOptions,"call",t=>t()]),r=(0,a.o5)().getTransaction();if(r){r.updateName(`trpc/${e}`),r.setAttribute(J,"route"),r.op="rpc.server";const s={procedure_type:n};(void 0!==t.attachRpcInput?t.attachRpcInput:(0,nn.z)([o,"optionalAccess",t=>t.sendDefaultPii]))&&(s.input=(0,X.S8)(i)),r.setContext("trpc",s)}function c(t){t.ok||(0,a.Cp)(t.error,{mechanism:{handled:!1,data:{function:"trpcMiddleware"}}})}let g;try{g=s()}catch(t){throw(0,a.Cp)(t,{mechanism:{handled:!1,data:{function:"trpcMiddleware"}}}),t}return(0,V.Qg)(g)?Promise.resolve(g).then((t=>{c(t)}),(t=>{(0,a.Cp)(t,{mechanism:{handled:!1,data:{function:"trpcMiddleware"}}})})):c(g),g}}function Ps(t,e){return de(t,{include:e})}function Ds(t,e,n={}){return Ie(t,e,{include:n})}function qs(){return function(t,e,n){const s=(0,nn.z)([a.KU,"call",t=>t(),"optionalAccess",t=>t.getOptions,"call",t=>t()]);if(!s||"sentry"!==s.instrumenter||"OPTIONS"===(0,nn.z)([t,"access",t=>t.method,"optionalAccess",t=>t.toUpperCase,"call",t=>t()])||"HEAD"===(0,nn.z)([t,"access",t=>t.method,"optionalAccess",t=>t.toUpperCase,"call",t=>t()]))return n();const i=t.headers&&(0,V.Kg)(t.headers["sentry-trace"])?t.headers["sentry-trace"]:void 0,o=(0,nn.z)([t,"access",t=>t.headers,"optionalAccess",t=>t.baggage]);if(!Gt(s))return n();const[r,c]=le(t,{path:!0,method:!0}),g=ft({sentryTrace:i,baggage:o},(e=>(0,a.nb)({name:r,op:"http.server",origin:"auto.http.node.tracingHandler",...e,data:{[J]:c},metadata:{...e.metadata,request:t}},{request:de(t)})));(0,a.o5)().setSpan(g),e.__sentry_transaction=g,e.once("finish",(()=>{setImmediate((()=>{!function(t,e){if(t){if(!t.metadata.source||"url"===t.metadata.source){const[n,s]=le(e,{path:!0,method:!0});t.updateName(n),t.setMetadata({source:s})}t.setAttribute("url",e.originalUrl||e.url),e.baseUrl&&t.setAttribute("baseUrl",e.baseUrl),t.setData("query",ue(e,void 0))}}(g,t),Ut(g,e.statusCode),g.end()}))})),n()}}function $s(t){const e=function(t={}){let e;if("include"in t)e={include:t.include};else{const{ip:n,request:s,transaction:i,user:o}=t;(n||s||i||o)&&(e={include:(0,c.Ce)({ip:n,request:s,transaction:i,user:o})})}return e}(t),n=(0,a.KU)();if(n&&Ts(n)){n.initSessionFlusher();const t=(0,a.o5)();t.getSession()&&t.setSession()}return function(n,s,i){if(t&&t.flushTimeout&&t.flushTimeout>0){const e=s.end;s.end=function(n,s,i){(0,a.bX)(t.flushTimeout).then((()=>{e.call(this,n,s,i)})).then(null,(t=>{$n&&p.vF.error(t),e.call(this,n,s,i)}))}}(0,nt.fx)((()=>{const t=(0,a.o5)();t.setSDKProcessingMetadata({request:n,requestDataOptionsFromExpressHandler:e}),Ts((0,a.KU)())&&t.setRequestSession({status:"ok"}),s.once("finish",(()=>{const t=(0,a.KU)();Ts(t)&&setImmediate((()=>{t&&t._captureRequestSession&&t._captureRequestSession()}))})),i()}))}}function ti(t){const e=function(t){const e=t.status||t.statusCode||t.status_code||t.output&&t.output.statusCode;return e?parseInt(e,10):500}(t);return e>=500}function ei(t){return function(e,n,s,i){(t&&t.shouldHandleError||ti)(e)?(0,a.v4)((t=>{t.setSDKProcessingMetadata({request:n});const o=s.__sentry_transaction;o&&!vt()&&t.setSpan(o);const r=(0,a.KU)();if(r&&Ts(r)&&void 0!==r._sessionFlusher){const e=t.getRequestSession();e&&void 0!==e.status&&(e.status="crashed")}const c=(0,a.Cp)(e,{mechanism:{type:"middleware",handled:!1}});s.sentry=c,i(e)})):i(e)}}const ni=Ms;function si(t){return t&&void 0!==t.statusCode}const ii={name:"SentryHapiErrorPlugin",version:Ge.M,register:async function(t){t.events.on("request",((t,e)=>{const n=Ft();var s;(function(t){return t&&void 0!==t.error})(e)&&(s=e.error,(0,a.Cp)(s,{mechanism:{type:"hapi",handled:!1,data:{function:"hapiErrorPlugin"}}})),n&&(n.setStatus("internal_error"),n.end())}))}},oi={name:"SentryHapiTracingPlugin",version:Ge.M,register:async function(t){const e=t;e.ext("onPreHandler",((t,e)=>{const n=ft({sentryTrace:t.headers["sentry-trace"]||void 0,baggage:t.headers.baggage||void 0},(e=>(0,a.nb)({...e,op:"hapi.request",name:t.route.path,description:`${t.route.method} ${t.path}`})));return(0,a.o5)().setSpan(n),e.continue})),e.ext("onPreResponse",((t,e)=>{const n=Ft();if(t.response&&si(t.response)&&n){const e=t.response;e.header("sentry-trace",(0,mt.Qh)(n));const s=(0,qn.De)((0,lt.k)(n));s&&e.header("baggage",s)}return e.continue})),e.ext("onPostHandler",((t,e)=>{const n=Ft();return n&&(t.response&&si(t.response)&&Ut(n,t.response.statusCode),n.end()),e.continue}))}},ri="Hapi",ci=(0,g._C)(((t={})=>{const e=t.server;return{name:ri,setupOnce(){e&&(0,c.GS)(e,"start",(t=>async function(){return await this.register(oi),await this.register(ii),t.apply(this)}))}}})),ai=(0,g.F)(ri,ci);var gi=n(6284);const li="undefined"==typeof __SENTRY_DEBUG__||__SENTRY_DEBUG__;function di(t){const e=(0,nn.z)([t,"call",t=>t(),"access",t=>t.getClient,"call",t=>t(),"optionalAccess",t=>t.getOptions,"call",t=>t()]);return"sentry"!==((0,nn.z)([e,"optionalAccess",t=>t.instrumenter])||"sentry")}class Ii{static __initStatic(){this.id="Apollo"}constructor(t={useNestjs:!1}){this.name=Ii.id,this._useNest=!!t.useNestjs}loadDependency(){return this._useNest?this._module=this._module||(0,gi.Vw)("@nestjs/graphql"):this._module=this._module||(0,gi.Vw)("apollo-server-core"),this._module}setupOnce(t,e){if(di(e))li&&p.vF.log("Apollo Integration is skipped because of instrumenter configuration.");else if(this._useNest){const t=this.loadDependency();if(!t)return void(li&&p.vF.error("Apollo-NestJS Integration was unable to require @nestjs/graphql package."));(0,c.GS)(t.GraphQLFactory.prototype,"mergeWithSchema",(function(t){return function(...n){return(0,c.GS)(this.resolversExplorerService,"explore",(function(t){return function(){return ui((0,b.k9)(t.call(this)),e)}})),t.call(this,...n)}}))}else{const t=this.loadDependency();if(!t)return void(li&&p.vF.error("Apollo Integration was unable to require apollo-server-core package."));(0,c.GS)(t.ApolloServerBase.prototype,"constructSchema",(function(t){return function(){if(!this.config.resolvers)return li&&(this.config.schema?(p.vF.warn("Apollo integration is not able to trace `ApolloServer` instances constructed via `schema` property.If you are using NestJS with Apollo, please use `Sentry.Integrations.Apollo({ useNestjs: true })` instead."),p.vF.warn()):this.config.modules&&p.vF.warn("Apollo integration is not able to trace `ApolloServer` instances constructed via `modules` property."),p.vF.error("Skipping tracing as no resolvers found on the `ApolloServer` instance.")),t.call(this);const n=(0,b.k9)(this.config.resolvers);return this.config.resolvers=ui(n,e),t.call(this)}}))}}}function ui(t,e){return t.map((t=>(Object.keys(t).forEach((n=>{Object.keys(t[n]).forEach((s=>{"function"==typeof t[n][s]&&function(t,e,n,s){(0,c.GS)(t[e],n,(function(t){return function(...i){const o=s().getScope().getSpan(),r=(0,nn.z)([o,"optionalAccess",t=>t.startChild,"call",t=>t({description:`${e}.${n}`,op:"graphql.resolve",origin:"auto.graphql.apollo"})]),c=t.call(this,...i);return(0,V.Qg)(c)?c.then((t=>((0,nn.z)([r,"optionalAccess",t=>t.end,"call",t=>t()]),t))):((0,nn.z)([r,"optionalAccess",t=>t.end,"call",t=>t()]),c)}}))}(t,n,s,e)}))})),t)))}Ii.__initStatic();class Ci{static __initStatic(){this.id="Express"}constructor(t={}){this.name=Ci.id,this._router=t.router||t.app,this._methods=(Array.isArray(t.methods)?t.methods:[]).concat("use")}setupOnce(t,e){this._router?di(e)?li&&p.vF.log("Express Integration is skipped because of instrumenter configuration."):(function(t,e=[]){e.forEach((e=>function(t,e){const n=t[e];return t[e]=function(...t){return n.call(this,...function(t,e){return t.map((t=>"function"==typeof t?pi(t,e):Array.isArray(t)?t.map((t=>"function"==typeof t?pi(t,e):t)):t))}(t,e))},t}(t,e)))}(this._router,this._methods),function(t){const e="settings"in t;e&&void 0===t._router&&t.lazyrouter&&t.lazyrouter();const n=e?t._router:t;if(!n)return li&&p.vF.debug("Cannot instrument router for URL Parameterization (did not find a valid router)."),void(li&&p.vF.debug("Routing instrumentation is currently only supported in Express 4."));const s=Object.getPrototypeOf(n),i=s.process_params;s.process_params=function(t,e,n,s,o){n._reconstructedRoute||(n._reconstructedRoute="");const{layerRoutePath:r,isRegex:c,isArray:a,numExtraSegments:g}=function(t){let e=(0,nn.z)([t,"access",t=>t.route,"optionalAccess",t=>t.path]);const n=(0,V.gd)(e),s=Array.isArray(e);if(!e){const[n]=Ye.OW.process.versions.node.split(".").map(Number);n>=16&&(e=bi(t.path,t.regexp,t.keys))}if(!e)return{isRegex:n,isArray:s,numExtraSegments:0};const i=s?Math.max(e.reduce(((t,e)=>t+oe(e.toString())),0)-oe(t.path||""),0):0,o=function(t,e){return t?e.map((t=>t.toString())).join(","):e&&e.toString()}(s,e);return{layerRoutePath:o,isRegex:n,isArray:s,numExtraSegments:i}}(t);let l;(r||c||a)&&(n._hasParameters=!0),l=r||function(t,e,n){const s=ie(t||""),i=(0,nn.z)([s,"optionalAccess",t=>t.split,"call",t=>t("/"),"access",t=>t.filter,"call",t=>t((t=>!!t))]);let o=0;const r=(0,nn.z)([e,"optionalAccess",t=>t.split,"call",t=>t("/"),"access",t=>t.filter,"call",t=>t((t=>!!t)),"access",t=>t.length])||0;return(0,nn.z)([n,"optionalAccess",t=>t.split,"call",t=>t("/"),"access",t=>t.filter,"call",t=>t((t=>(0,nn.z)([i,"optionalAccess",t=>t[r+o]])===t&&(o+=1,!0))),"access",t=>t.join,"call",t=>t("/")])}(n.originalUrl,n._reconstructedRoute,t.path)||"";const d=l.split("/").filter((t=>t.length>0&&(c||a||!t.includes("*")))).join("/");if(d&&d.length>0&&(n._reconstructedRoute+=`/${d}${c?"/":""}`),oe(ie(n.originalUrl||""))+g===oe(n._reconstructedRoute)){n._hasParameters||n._reconstructedRoute!==n.originalUrl&&(n._reconstructedRoute=n.originalUrl?ie(n.originalUrl):n.originalUrl);const t=s.__sentry_transaction,e=t&&(0,mt.et)(t).data||{};if(t&&"custom"!==e[J]){const e=n._reconstructedRoute||"/",[s,i]=le(n,{path:!0,method:!0,customRoute:e});t.updateName(s),t.setAttribute(J,i)}}return i.call(this,t,e,n,s,o)}}(this._router)):li&&p.vF.error("ExpressIntegration is missing an Express instance")}}function pi(t,e){const n=t.length;switch(n){case 2:return function(n,s){const i=s.__sentry_transaction;if(i){const n=i.startChild({description:t.name,op:`middleware.express.${e}`,origin:"auto.middleware.express"});s.once("finish",(()=>{n.end()}))}return t.call(this,n,s)};case 3:return function(n,s,i){const o=s.__sentry_transaction,r=(0,nn.z)([o,"optionalAccess",t=>t.startChild,"call",n=>n({description:t.name,op:`middleware.express.${e}`,origin:"auto.middleware.express"})]);t.call(this,n,s,(function(...t){(0,nn.z)([r,"optionalAccess",t=>t.end,"call",t=>t()]),i.call(this,...t)}))};case 4:return function(n,s,i,o){const r=i.__sentry_transaction,c=(0,nn.z)([r,"optionalAccess",t=>t.startChild,"call",n=>n({description:t.name,op:`middleware.express.${e}`,origin:"auto.middleware.express"})]);t.call(this,n,s,i,(function(...t){(0,nn.z)([c,"optionalAccess",t=>t.end,"call",t=>t()]),o.call(this,...t)}))};default:throw new Error(`Express middleware takes 2-4 arguments. Got: ${n}`)}}Ci.__initStatic();const bi=(t,e,n)=>{if(!(t&&e&&n&&0!==Object.keys(n).length&&(0,nn.z)([n,"access",t=>t[0],"optionalAccess",t=>t.offset])))return;const s=n.sort(((t,e)=>t.offset-e.offset)),i=new RegExp(e,`${e.flags}d`).exec(t);if(!i||!i.indices)return;const[,...o]=i.indices;if(o.length!==s.length)return;let r=t,c=0;return o.forEach(((t,e)=>{if(t){const[n,i]=t,o=r.substring(0,n-c),a=`:${s[e].name}`,g=r.substring(i-c);r=o+a+g,c+=i-n-a.length}})),r};class hi{static __initStatic(){this.id="GraphQL"}constructor(){this.name=hi.id}loadDependency(){return this._module=this._module||(0,gi.Vw)("graphql/execution/execute.js")}setupOnce(t,e){if(di(e))return void(li&&p.vF.log("GraphQL Integration is skipped because of instrumenter configuration."));const n=this.loadDependency();n?(0,c.GS)(n,"execute",(function(t){return function(...n){const s=e().getScope(),i=s.getSpan(),o=(0,nn.z)([i,"optionalAccess",t=>t.startChild,"call",t=>t({description:"execute",op:"graphql.execute",origin:"auto.graphql.graphql"})]);(0,nn.z)([s,"optionalAccess",t=>t.setSpan,"call",t=>t(o)]);const r=t.call(this,...n);return(0,V.Qg)(r)?r.then((t=>((0,nn.z)([o,"optionalAccess",t=>t.end,"call",t=>t()]),(0,nn.z)([s,"optionalAccess",t=>t.setSpan,"call",t=>t(i)]),t))):((0,nn.z)([o,"optionalAccess",t=>t.end,"call",t=>t()]),(0,nn.z)([s,"optionalAccess",t=>t.setSpan,"call",t=>t(i)]),r)}})):li&&p.vF.error("GraphQL Integration was unable to require graphql/execution package.")}}hi.__initStatic();const mi=["aggregate","bulkWrite","countDocuments","createIndex","createIndexes","deleteMany","deleteOne","distinct","drop","dropIndex","dropIndexes","estimatedDocumentCount","find","findOne","findOneAndDelete","findOneAndReplace","findOneAndUpdate","indexes","indexExists","indexInformation","initializeOrderedBulkOp","insertMany","insertOne","isCapped","mapReduce","options","parallelCollectionScan","rename","replaceOne","stats","updateMany","updateOne"],Zi={bulkWrite:["operations"],countDocuments:["query"],createIndex:["fieldOrSpec"],createIndexes:["indexSpecs"],deleteMany:["filter"],deleteOne:["filter"],distinct:["key","query"],dropIndex:["indexName"],find:["query"],findOne:["query"],findOneAndDelete:["filter"],findOneAndReplace:["filter","replacement"],findOneAndUpdate:["filter","update"],indexExists:["indexes"],insertMany:["docs"],insertOne:["doc"],mapReduce:["map","reduce"],rename:["newName"],replaceOne:["filter","doc"],updateMany:["filter","update"],updateOne:["filter","update"]};class Gi{static __initStatic(){this.id="Mongo"}constructor(t={}){this.name=Gi.id,this._operations=Array.isArray(t.operations)?t.operations:mi,this._describeOperations=!("describeOperations"in t)||t.describeOperations,this._useMongoose=!!t.useMongoose}loadDependency(){const t=this._useMongoose?"mongoose":"mongodb";return this._module=this._module||(0,gi.Vw)(t)}setupOnce(t,e){if(di(e))return void(li&&p.vF.log("Mongo Integration is skipped because of instrumenter configuration."));const n=this.loadDependency();if(n)this._instrumentOperations(n.Collection,this._operations,e);else{const t=this._useMongoose?"mongoose":"mongodb";li&&p.vF.error(`Mongo Integration was unable to require \`${t}\` package.`)}}_instrumentOperations(t,e,n){e.forEach((e=>this._patchOperation(t,e,n)))}_patchOperation(t,e,n){if(!(e in t.prototype))return;const s=this._getSpanContextFromOperationArguments.bind(this);(0,c.GS)(t.prototype,e,(function(t){return function(...i){const o=i[i.length-1],r=n(),c=r.getScope(),a=r.getClient(),g=c.getSpan(),l=(0,nn.z)([a,"optionalAccess",t=>t.getOptions,"call",t=>t(),"access",t=>t.sendDefaultPii]);if("function"!=typeof o||"mapReduce"===e&&2===i.length){const n=(0,nn.z)([g,"optionalAccess",t=>t.startChild,"call",t=>t(s(this,e,i,l))]),o=t.call(this,...i);if((0,V.Qg)(o))return o.then((t=>((0,nn.z)([n,"optionalAccess",t=>t.end,"call",t=>t()]),t)));if((d=o)&&"object"==typeof d&&d.once&&"function"==typeof d.once){const t=o;try{t.once("close",(()=>{(0,nn.z)([n,"optionalAccess",t=>t.end,"call",t=>t()])}))}catch(t){(0,nn.z)([n,"optionalAccess",t=>t.end,"call",t=>t()])}return t}return(0,nn.z)([n,"optionalAccess",t=>t.end,"call",t=>t()]),o}var d;const I=(0,nn.z)([g,"optionalAccess",t=>t.startChild,"call",t=>t(s(this,e,i.slice(0,-1)))]);return t.call(this,...i.slice(0,-1),(function(t,e){(0,nn.z)([I,"optionalAccess",t=>t.end,"call",t=>t()]),o(t,e)}))}}))}_getSpanContextFromOperationArguments(t,e,n,s=!1){const i={"db.system":"mongodb","db.name":t.dbName,"db.operation":e,"db.mongodb.collection":t.collectionName},o={op:"db",origin:"auto.db.mongo",description:e,data:i},r=Zi[e],c=Array.isArray(this._describeOperations)?this._describeOperations.includes(e):this._describeOperations;if(!r||!c||!s)return o;try{if("mapReduce"===e){const[t,e]=n;i[r[0]]="string"==typeof t?t:t.name||"",i[r[1]]="string"==typeof e?e:e.name||""}else for(let t=0;t(s||(s=e.config),t.apply(e,n))})}catch(t){li&&p.vF.error("Mysql Integration was unable to instrument `mysql` config.")}function i(t){if(!t)return;const e=s?{"server.address":s.host,"server.port":s.port,"db.user":s.user}:{};Object.keys(e).forEach((n=>{t.setAttribute(n,e[n])})),t.end()}(0,c.GS)(n,"createQuery",(function(t){return function(n,s,o){const r=e().getScope().getSpan(),c=(0,nn.z)([r,"optionalAccess",t=>t.startChild,"call",t=>t({description:"string"==typeof n?n:n.sql,op:"db",origin:"auto.db.mysql",data:{"db.system":"mysql"}})]);if("function"==typeof o)return t.call(this,n,s,(function(t,e,n){i(c),o(t,e,n)}));if("function"==typeof s)return t.call(this,n,(function(t,e,n){i(c),s(t,e,n)}));const a=t.call(this,n,s);return a.on("end",(()=>{i(c)})),a}}))}}Bi.__initStatic();class yi{static __initStatic(){this.id="Postgres"}constructor(t={}){this.name=yi.id,this._usePgNative=!!t.usePgNative,this._module=t.module}loadDependency(){return this._module=this._module||(0,gi.Vw)("pg")}setupOnce(t,e){if(di(e))return void(li&&p.vF.log("Postgres Integration is skipped because of instrumenter configuration."));const n=this.loadDependency();if(!n)return void(li&&p.vF.error("Postgres Integration was unable to require `pg` package."));const s=this._usePgNative?(0,nn.z)([n,"access",t=>t.native,"optionalAccess",t=>t.Client]):n.Client;s?(0,c.GS)(s.prototype,"query",(function(t){return function(n,s,i){const o=e().getScope().getSpan(),r={"db.system":"postgresql"};try{this.database&&(r["db.name"]=this.database),this.host&&(r["server.address"]=this.host),this.port&&(r["server.port"]=this.port),this.user&&(r["db.user"]=this.user)}catch(t){}const c=(0,nn.z)([o,"optionalAccess",t=>t.startChild,"call",t=>t({description:"string"==typeof n?n:n.text,op:"db",origin:"auto.db.postgres",data:r})]);if("function"==typeof i)return t.call(this,n,s,(function(t,e){(0,nn.z)([c,"optionalAccess",t=>t.end,"call",t=>t()]),i(t,e)}));if("function"==typeof s)return t.call(this,n,(function(t,e){(0,nn.z)([c,"optionalAccess",t=>t.end,"call",t=>t()]),s(t,e)}));const a=void 0!==s?t.call(this,n,s):t.call(this,n);return(0,V.Qg)(a)?a.then((t=>((0,nn.z)([c,"optionalAccess",t=>t.end,"call",t=>t()]),t))):((0,nn.z)([c,"optionalAccess",t=>t.end,"call",t=>t()]),a)}})):li&&p.vF.error("Postgres Integration was unable to access 'pg-native' bindings.")}}yi.__initStatic();class Ai{static __initStatic(){this.id="Prisma"}constructor(t={}){if(this.name=Ai.id,(e=t.client)&&e.$use&&!t.client._sentryInstrumented){(0,c.my)(t.client,"_sentryInstrumented",!0);const e={};try{const n=t.client._engineConfig;if(n){const{activeProvider:t,clientVersion:s}=n;t&&(e["db.system"]=t),s&&(e["db.prisma.version"]=s)}}catch(t){}t.client.$use(((t,n)=>{if(di(nt.BF))return n(t);const s=t.action,i=t.model;return yt({name:i?`${i} ${s}`:s,onlyIfParent:!0,op:"db.prisma",attributes:{[z]:"auto.db.prisma"},data:{...e,"db.operation":s}},(()=>n(t)))}))}else li&&p.vF.warn("Unsupported Prisma client provided to PrismaIntegration. Provided client:",t.client);var e}setupOnce(){}}Ai.__initStatic();const Wi="CaptureConsole",Vi=(0,g._C)(((t={})=>{const e=t.levels||p.Ow;return{name:Wi,setupOnce(){},setup(t){"console"in Ye.OW&&An((({args:n,level:s})=>{(0,a.KU)()===t&&e.includes(s)&&function(t,e){const n={level:vn(e),extra:{arguments:t}};(0,a.v4)((s=>{if(s.addEventProcessor((t=>(t.logger="console",(0,b.M6)(t,{handled:!1,type:"console"}),t))),"assert"===e&&!1===t[0]){const e=`Assertion failed: ${(0,h.gt)(t.slice(1)," ")||"console.assert"}`;return s.setExtra("arguments",t.slice(1)),void(0,a.wd)(e,n)}const i=t.find((t=>t instanceof Error));if("error"===e&&i)return void(0,a.Cp)(i,n);const o=(0,h.gt)(t," ");(0,a.wd)(o,n)}))}(n,s)}))}}}));(0,g.F)(Wi,Vi);const vi="Debug",fi=(0,g._C)(((t={})=>{const e={debugger:!1,stringify:!1,...t};return{name:vi,setupOnce(){},setup(t){t.on&&t.on("beforeSendEvent",((t,n)=>{e.debugger,(0,p.pq)((()=>{e.stringify?(console.log(JSON.stringify(t,null,2)),n&&Object.keys(n).length&&console.log(JSON.stringify(n,null,2))):(console.log(t),n&&Object.keys(n).length&&console.log(n))}))}))}}})),Ri=((0,g.F)(vi,fi),"undefined"==typeof __SENTRY_DEBUG__||__SENTRY_DEBUG__),Yi="Dedupe",Xi=(0,g._C)((()=>{let t;return{name:Yi,setupOnce(){},processEvent(e){if(e.type)return e;try{if(function(t,e){return!!e&&(!!function(t,e){const n=t.message,s=e.message;return!(!n&&!s)&&(!(n&&!s||!n&&s)&&(n===s&&(!!Si(t,e)&&!!Hi(t,e))))}(t,e)||!!function(t,e){const n=Ni(e),s=Ni(t);return!(!n||!s)&&(n.type===s.type&&n.value===s.value&&(!!Si(t,e)&&!!Hi(t,e)))}(t,e))}(e,t))return Ri&&p.vF.warn("Event dropped due to being a duplicate of previously captured event."),null}catch(t){}return t=e}}}));function Hi(t,e){let n=Ki(t),s=Ki(e);if(!n&&!s)return!0;if(n&&!s||!n&&s)return!1;if(s.length!==n.length)return!1;for(let t=0;t{const e=t.depth||3,n=t.captureErrorCause||!1;return{name:wi,setupOnce(){},processEvent:(t,s)=>function(t,e={},n,s){if(!e.originalException||!(0,V.bJ)(e.originalException))return t;const i=e.originalException.name||e.originalException.constructor.name,o=function(t,e){try{const n=["name","message","stack","line","column","fileName","lineNumber","columnNumber","toJSON"],s={};for(const e of Object.keys(t)){if(-1!==n.indexOf(e))continue;const i=t[e];s[e]=(0,V.bJ)(i)?i.toString():i}if(e&&void 0!==t.cause&&(s.cause=(0,V.bJ)(t.cause)?t.cause.toString():t.cause),"function"==typeof t.toJSON){const e=t.toJSON();for(const t of Object.keys(e)){const n=e[t];s[t]=(0,V.bJ)(n)?n.toString():n}}return s}catch(t){Ri&&p.vF.error("Unable to extract extra data from the Error object:",t)}return null}(e.originalException,s);if(o){const e={...t.contexts},s=(0,X.S8)(o,n);return(0,V.Qd)(s)&&((0,c.my)(s,"__sentry_skip_normalization__",!0),e[i]=s),{...t,contexts:e}}return t}(t,s,e,n)}}));(0,g.F)(wi,Fi);const Ji=(0,Ye.VZ)();function ki(t){return t&&/^function fetch\(\)\s+\{\s+\[native code\]\s+\}$/.test(t.toString())}function _i(){if("string"==typeof EdgeRuntime)return!0;if(!function(){if(!("fetch"in Ji))return!1;try{return new Headers,new Request("http://www.example.com"),new Response,!0}catch(t){return!1}}())return!1;if(ki(Ji.fetch))return!0;let t=!1;const e=Ji.document;if(e&&"function"==typeof e.createElement)try{const n=e.createElement("iframe");n.hidden=!0,e.head.appendChild(n),n.contentWindow&&n.contentWindow.fetch&&(t=ki(n.contentWindow.fetch)),e.head.removeChild(n)}catch(t){U.T&&p.vF.warn("Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ",t)}return t}function zi(){_i()&&(0,c.GS)(Ye.OW,"fetch",(function(t){return function(...e){const{method:n,url:s}=function(t){if(0===t.length)return{method:"GET",url:""};if(2===t.length){const[e,n]=t;return{url:xi(e),method:Ui(n,"method")?String(n.method).toUpperCase():"GET"}}const e=t[0];return{url:xi(e),method:Ui(e,"method")?String(e.method).toUpperCase():"GET"}}(e),i={args:e,fetchData:{method:n,url:s},startTimestamp:Date.now()};return we("fetch",{...i}),t.apply(Ye.OW,e).then((t=>(we("fetch",{...i,endTimestamp:Date.now(),response:t}),t)),(t=>{throw we("fetch",{...i,endTimestamp:Date.now(),error:t}),t}))}}))}function Ui(t,e){return!!t&&"object"==typeof t&&!!t[e]}function xi(t){return"string"==typeof t?t:t?Ui(t,"url")?t.url:t.toString?t.toString():"":""}const Ti=Ye.OW,Ei="__sentry_xhr_v3__";function Li(){if(!Ti.XMLHttpRequest)return;const t=XMLHttpRequest.prototype;(0,c.GS)(t,"open",(function(t){return function(...e){const n=Date.now(),s=(0,V.Kg)(e[0])?e[0].toUpperCase():void 0,i=function(t){if((0,V.Kg)(t))return t;try{return t.toString()}catch(t){}}(e[1]);if(!s||!i)return t.apply(this,e);this[Ei]={method:s,url:i,request_headers:{}},"POST"===s&&i.match(/sentry_key/)&&(this.__sentry_own_request__=!0);const o=()=>{const t=this[Ei];if(t&&4===this.readyState){try{t.status_code=this.status}catch(t){}we("xhr",{args:[s,i],endTimestamp:Date.now(),startTimestamp:n,xhr:this})}};return"onreadystatechange"in this&&"function"==typeof this.onreadystatechange?(0,c.GS)(this,"onreadystatechange",(function(t){return function(...e){return o(),t.apply(this,e)}})):this.addEventListener("readystatechange",o),(0,c.GS)(this,"setRequestHeader",(function(t){return function(...e){const[n,s]=e,i=this[Ei];return i&&(0,V.Kg)(n)&&(0,V.Kg)(s)&&(i.request_headers[n.toLowerCase()]=s),t.apply(this,e)}})),t.apply(this,e)}})),(0,c.GS)(t,"send",(function(t){return function(...e){const n=this[Ei];return n?(void 0!==e[0]&&(n.body=e[0]),we("xhr",{args:[n.method,n.url],startTimestamp:Date.now(),xhr:this}),t.apply(this,e)):t.apply(this,e)}}))}const Qi="HttpClient",ji=(0,g._C)(((t={})=>{const e={failedRequestStatusCodes:[[500,599]],failedRequestTargets:[/.*/],...t};return{name:Qi,setupOnce(){},setup(t){!function(t,e){_i()&&function(){const n="fetch";Ne(n,(n=>{if((0,a.KU)()!==t)return;const{response:s,args:i}=n,[o,r]=i;s&&function(t,e,n,s){if(Pi(t,n.status,n.url)){const t=function(t,e){return!e&&t instanceof Request||t instanceof Request&&t.bodyUsed?t:new Request(t,e)}(e,s);let i,o,r,c;qi()&&([{headers:i,cookies:r},{headers:o,cookies:c}]=[{cookieHeader:"Cookie",obj:t},{cookieHeader:"Set-Cookie",obj:n}].map((({cookieHeader:t,obj:e})=>{const n=function(t){const e={};return t.forEach(((t,n)=>{e[n]=t})),e}(e.headers);let s;try{const e=n[t]||n[t.toLowerCase()]||void 0;e&&(s=Mi(e))}catch(e){Ri&&p.vF.log(`Could not extract cookies from header ${t}`)}return{headers:n,cookies:s}})));const g=Di({url:t.url,method:t.method,status:n.status,requestHeaders:i,responseHeaders:o,requestCookies:r,responseCookies:c});(0,a.r)(g)}}(e,o,s,r)})),Ke(n,zi)}()}(t,e),function(t,e){var n;"XMLHttpRequest"in Ye.OW&&(n=n=>{if((0,a.KU)()!==t)return;const s=n.xhr,i=s[Ei];if(!i)return;const{method:o,request_headers:r}=i;try{!function(t,e,n,s){if(Pi(t,e.status,e.responseURL)){let t,i,o;if(qi()){try{const t=e.getResponseHeader("Set-Cookie")||e.getResponseHeader("set-cookie")||void 0;t&&(i=Mi(t))}catch(t){Ri&&p.vF.log("Could not extract cookies from response headers")}try{o=function(t){const e=t.getAllResponseHeaders();return e?e.split("\r\n").reduce(((t,e)=>{const[n,s]=e.split(": ");return t[n]=s,t}),{}):{}}(e)}catch(t){Ri&&p.vF.log("Could not extract headers from response")}t=s}const r=Di({url:e.responseURL,method:n,status:e.status,requestHeaders:t,responseHeaders:o,responseCookies:i});(0,a.r)(r)}}(e,s,o,r)}catch(t){Ri&&p.vF.warn("Error while extracting response event form XHR response",t)}},Ne("xhr",n),Ke("xhr",Li))}(t,e)}}}));function Oi(t){if(t){const e=t["Content-Length"]||t["content-length"];if(e)return parseInt(e,10)}}function Mi(t){return t.split("; ").reduce(((t,e)=>{const[n,s]=e.split("=");return t[n]=s,t}),{})}function Pi(t,e,n){return function(t,e){return t.some((t=>"number"==typeof t?t===e:e>=t[0]&&e<=t[1]))}(t.failedRequestStatusCodes,e)&&(s=t.failedRequestTargets,i=n,s.some((t=>"string"==typeof t?i.includes(t):t.test(i))))&&!Pn(n,(0,a.KU)());var s,i}function Di(t){const e=`HTTP Client Error with status code: ${t.status}`,n={message:e,exception:{values:[{type:"Error",value:e}]},request:{url:t.url,method:t.method,headers:t.requestHeaders,cookies:t.requestCookies},contexts:{response:{status_code:t.status,headers:t.responseHeaders,cookies:t.responseCookies,body_size:Oi(t.responseHeaders)}}};return(0,b.M6)(n,{type:"http.client",handled:!1}),n}function qi(){const t=(0,a.KU)();return!!t&&Boolean(t.getOptions().sendDefaultPii)}(0,g.F)(Qi,ji);const $i=Ye.OW,to="ReportingObserver",eo=new WeakMap,no=(0,g._C)(((t={})=>{const e=t.types||["crash","deprecation","intervention"];function n(t){if(eo.has((0,a.KU)()))for(const e of t)(0,a.v4)((t=>{t.setExtra("url",e.url);const n=`ReportingObserver [${e.type}]`;let s="No details available";if(e.body){const n={};for(const t in e.body)n[t]=e.body[t];if(t.setExtra("body",n),"crash"===e.type){const t=e.body;s=[t.crashId||"",t.reason||""].join(" ").trim()||s}else s=e.body.message||s}(0,a.wd)(`${n}: ${s}`)}))}return{name:to,setupOnce(){"ReportingObserver"in Ji&&new $i.ReportingObserver(n,{buffered:!0,types:e}).observe()},setup(t){eo.set(t,!0)}}})),so=((0,g.F)(to,no),"RewriteFrames"),io=(0,g._C)(((t={})=>{const e=t.root,n=t.prefix||"app:///",s=t.iteratee||(t=>{if(!t.filename)return t;const s=/^[a-zA-Z]:\\/.test(t.filename)||t.filename.includes("\\")&&!t.filename.includes("/"),i=/^\//.test(t.filename);if(s||i){const i=s?t.filename.replace(/^[a-zA-Z]:/,"").replace(/\\/g,"/"):t.filename,o=e?function(t,e){t=Fs(t).slice(1),e=Fs(e).slice(1);const n=Js(t.split("/")),s=Js(e.split("/")),i=Math.min(n.length,s.length);let o=i;for(let t=0;ts(t)))}}return{name:so,setupOnce(){},processEvent(t){let e=t;return t.exception&&Array.isArray(t.exception.values)&&(e=function(t){try{return{...t,exception:{...t.exception,values:t.exception.values.map((t=>({...t,...t.stacktrace&&{stacktrace:i(t.stacktrace)}})))}}}catch(e){return t}}(e)),e}}})),oo=((0,g.F)(so,io),"SessionTiming"),ro=(0,g._C)((()=>{const t=Date.now();return{name:oo,setupOnce(){},processEvent(e){const n=Date.now();return{...e,extra:{...e.extra,"session:start":t,"session:duration":n-t,"session:end":n}}}}})),co=((0,g.F)(oo,ro),[["january","1"],["february","2"],["march","3"],["april","4"],["may","5"],["june","6"],["july","7"],["august","8"],["september","9"],["october","10"],["november","11"],["december","12"],["jan","1"],["feb","2"],["mar","3"],["apr","4"],["may","5"],["jun","6"],["jul","7"],["aug","8"],["sep","9"],["oct","10"],["nov","11"],["dec","12"],["sunday","0"],["monday","1"],["tuesday","2"],["wednesday","3"],["thursday","4"],["friday","5"],["saturday","6"],["sun","0"],["mon","1"],["tue","2"],["wed","3"],["thu","4"],["fri","5"],["sat","6"]]);function ao(t){return co.reduce(((t,[e,n])=>t.replace(new RegExp(e,"gi"),n)),t)}const go="Automatic instrumentation of CronJob only supports crontab string",lo=_s(),Io={...F,...o,...r},uo={instrumentCron:function(t,e){let n=!1;return new Proxy(t,{construct(t,s){const[i,o,r,c,g,...l]=s;if("string"!=typeof i)throw new Error(go);if(n)throw new Error(`A job named '${e}' has already been scheduled`);n=!0;const d=ao(i);return new t(i,(function(t,n){return(0,a.T$)(e,(()=>o(t,n)),{schedule:{type:"crontab",value:d},timezone:g||void 0})}),r,c,g,...l)},get:(t,s)=>"from"===s?s=>{const{cronTime:i,onTick:o,timeZone:r}=s;if("string"!=typeof i)throw new Error(go);if(n)throw new Error(`A job named '${e}' has already been scheduled`);n=!0;const c=ao(i);return s.onTick=(t,n)=>(0,a.T$)(e,(()=>o(t,n)),{schedule:{type:"crontab",value:c},timezone:r||void 0}),t.from(s)}:t[s]})},instrumentNodeCron:function(t){return new Proxy(t,{get:(t,e)=>"schedule"===e&&t.schedule?new Proxy(t.schedule,{apply(t,e,n){const[s,,i]=n;if(!(0,nn.z)([i,"optionalAccess",t=>t.name]))throw new Error('Missing "name" for scheduled job. A name is required for Sentry check-in monitoring.');return(0,a.T$)(i.name,(()=>t.apply(e,n)),{schedule:{type:"crontab",value:ao(s)},timezone:(0,nn.z)([i,"optionalAccess",t=>t.timezone])})}}):t[e]})},instrumentNodeSchedule:function(t){return new Proxy(t,{get:(t,e)=>"scheduleJob"===e?new Proxy(t.scheduleJob,{apply(t,e,n){const[s,i]=n;if("string"!=typeof s||"string"!=typeof i)throw new Error("Automatic instrumentation of 'node-schedule' requires the first parameter of 'scheduleJob' to be a job name string and the second parameter to be a crontab string");const o=s,r=i;return(0,a.T$)(o,(()=>t.apply(e,n)),{schedule:{type:"crontab",value:ao(r)}})}}):t[e]})}}},1615:(t,e,n)=>{"use strict";n.d(e,{M:()=>m,a:()=>h});var s=n(853);function i(t){const e=(0,s.z)(t);return null==e||e}var o=n(7016),r=n(2486),c=n(1535),a=n(6641),g=n(3741),l=n(5836),d=n(7412),I=n(6341),u=n(6284),C=n(3245);function p(t,...e){d.vF.log(`[ANR] ${t}`,...e)}function b(){const t=(0,r.m6)().getScopeData();return(0,c.Rg)(t,(0,a.rm)().getScopeData()),(0,c.Rg)(t,(0,g.o5)().getScopeData()),t.attachments=[],t.eventProcessors=[],t}t=n.hmd(t);const h=(0,l._C)(((e={})=>{if(C.S.major<16||16===C.S.major&&C.S.minor<17)throw new Error("ANR detection requires Node 16.17.0 or later");let r,c;return I.OW.__SENTRY_GET_SCOPES__=b,{name:"Anr",setupOnce(){},startWorker:()=>{r||c&&(r=async function(e,r){const c=e.getDsn();if(!c)return()=>{};const a=await async function(t){let e={message:"ANR"};const n={};for(const s of t.getEventProcessors()){if(null===e)break;e=await s(e,n)}return(0,s.z)([e,"optionalAccess",t=>t.contexts])||{}}(e);i([a,"access",t=>t.app,"optionalAccess",t=>delete t.app_memory]),i([a,"access",t=>t.device,"optionalAccess",t=>delete t.free_memory]);const l=e.getOptions(),I=e.getSdkMetadata()||{};I.sdk&&(I.sdk.integrations=l.integrations.map((t=>t.name)));const C={debug:d.vF.isEnabled(),dsn:c,environment:l.environment||"production",release:l.release,dist:l.dist,sdkMetadata:I,appRootPath:r.appRootPath,pollInterval:r.pollInterval||50,anrThreshold:r.anrThreshold||5e3,captureStackTrace:!!r.captureStackTrace,staticTags:r.staticTags||{},contexts:a};if(C.captureStackTrace){const t=n(264);t.url()||t.open(0)}const{Worker:b}=(0,u.fj)(t,"worker_threads"),h=new b(new o.URL("data:application/javascript;base64,aW1wb3J0IHsgU2Vzc2lvbiB9IGZyb20gJ2luc3BlY3Rvcic7CmltcG9ydCB7IHdvcmtlckRhdGEsIHBhcmVudFBvcnQgfSBmcm9tICd3b3JrZXJfdGhyZWFkcyc7CmltcG9ydCB7IHBvc2l4LCBzZXAgfSBmcm9tICdwYXRoJzsKaW1wb3J0ICogYXMgaHR0cCBmcm9tICdodHRwJzsKaW1wb3J0ICogYXMgaHR0cHMgZnJvbSAnaHR0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zb2x2ZSwgcmVqZWN0KSA9PiB7CiAgICAgIHRoaXMuX2hhbmRsZXJzLnB1c2goWwogICAgICAgIGZhbHNlLAogICAgICAgIHJlc3VsdCA9PiB7CiAgICAgICAgICBpZiAoIW9uZnVsZmlsbGVkKSB7CiAgICAgICAgICAgIC8vIFRPRE86IMKvXF8o44OEKV8vwq8KICAgICAgICAgICAgLy8gVE9ETzogRklYTUUKICAgICAgICAgICAgcmVzb2x2ZShyZXN1bHQgKTsKICAgICAgICAgIH0gZWxzZSB7CiAgICAgICAgICAgIHRyeSB7CiAgICAgICAgICAgICAgcmVzb2x2ZShvbmZ1bGZpbGxlZChyZXN1bHQpKTsKICAgICAgICAgICAgfSBjYXRjaCAoZSkgewogICAgICAgICAgICAgIHJlamVjdChlKTsKICAgICAgICAgICAgfQogICAgICAgICAgfQogICAgICAgIH0sCiAgICAgICAgcmVhc29uID0+IHsKICAgICAgICAgIGlmICghb25yZWplY3RlZCkgewogICAgICAgICAgICByZWplY3QocmVhc29uKTsKICAgICAgICAgIH0gZWxzZSB7CiAgICAgICAgICAgIHRyeSB7CiAgICAgICAgICAgICAgcmVzb2x2ZShvbnJlamVjdGVkKHJlYXNvbikpOwogICAgICAgICAgICB9IGNhdGNoIChlKSB7CiAgICAgICAgICAgICAgcmVqZWN0KGUpOwogICAgICAgICAgICB9CiAgICAgICAgICB9CiAgICAgICAgfSwKICAgICAgXSk7CiAgICAgIHRoaXMuX2V4ZWN1dGVIYW5kbGVycygpOwogICAgfSk7CiAgfQoKICAvKiogSlNEb2MgKi8KICAgY2F0Y2goCiAgICBvbnJlamVjdGVkLAogICkgewogICAgcmV0dXJuIHRoaXMudGhlbih2YWwgPT4gdmFsLCBvbnJlamVjdGVkKTsKICB9CgogIC8qKiBKU0RvYyAqLwogICBmaW5hbGx5KG9uZmluYWxseSkgewogICAgcmV0dXJuIG5ldyBTeW5jUHJvbWlzZSgocmVzb2x2ZSwgcmVqZWN0KSA9PiB7CiAgICAgIGxldCB2YWw7CiAgICAgIGxldCBpc1JlamVjdGVkOwoKICAgICAgcmV0dXJuIHRoaXMudGhlbigKICAgICAgICB2YWx1ZSA9PiB7CiAgICAgICAgICBpc1JlamVjdGVkID0gZmFsc2U7CiAgICAgICAgICB2YWwgPSB2YWx1ZTsKICAgICAgICAgIGlmIChvbmZpbmFsbHkpIHsKICAgICAgICAgICAgb25maW5hbGx5KCk7CiAgICAgICAgICB9CiAgICAgICAgfSwKICAgICAgICByZWFzb24gPT4gewogICAgICAgICAgaXNSZWplY3RlZCA9IHRydWU7CiAgICAgICAgICB2YWwgPSByZWFzb247CiAgICAgICAgICBpZiAob25maW5hbGx5KSB7CiAgICAgICAgICAgIG9uZmluYWxseSgpOwogICAgICAgICAgfQogICAgICAgIH0sCiAgICAgICkudGhlbigoKSA9PiB7CiAgICAgICAgaWYgKGlzUmVqZWN0ZWQpIHsKICAgICAgICAgIHJlamVjdCh2YWwpOwogICAgICAgICAgcmV0dXJuOwogICAgICAgIH0KCiAgICAgICAgcmVzb2x2ZSh2YWwgKTsKICAgICAgfSk7CiAgICB9KTsKICB9CgogIC8qKiBKU0RvYyAqLwogICAgX19pbml0KCkge3RoaXMuX3Jlc29sdmUgPSAodmFsdWUpID0+IHsKICAgIHRoaXMuX3NldFJlc3VsdChTdGF0ZXMuUkVTT0xWRUQsIHZhbHVlKTsKICB9O30KCiAgLyoqIEpTRG9jICovCiAgICBfX2luaXQyKCkge3RoaXMuX3JlamVjdCA9IChyZWFzb24pID0+IHsKICAgIHRoaXMuX3NldFJlc3VsdChTdGF0ZXMuUkVKRUNURUQsIHJlYXNvbik7CiAgfTt9CgogIC8qKiBKU0RvYyAqLwogICAgX19pbml0MygpIHt0aGlzLl9zZXRSZXN1bHQgPSAoc3RhdGUsIHZhbHVlKSA9PiB7CiAgICBpZiAodGhpcy5fc3RhdGUgIT09IFN0YXRlcy5QRU5ESU5HKSB7CiAgICAgIHJldHVybjsKICAgIH0KCiAgICBpZiAoaXNUaGVuYWJsZSh2YWx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VuZXJzKCk7CiAgICByZXR1cm4gdGhpczsKICB9CgogIC8qKgogICAqIEBpbmhlcml0RG9jCiAgICovCiAgIHNldFRhZyhrZXksIHZhbHVlKSB7CiAgICB0aGlzLl90YWdzID0geyAuLi50aGlzLl90YWdzLCBba2V5XTogdmFsdWUgfTsKICAgIHRoaXMuX25vdGlmeVNjb3BlTGlzdGVuZXJzKCk7CiAgICByZXR1cm4gdGhpczsKICB9CgogIC8qKgogICAqIEBpbmhlcml0RG9jCiAgICovCiAgIHNldEV4dHJhcyhleHRyYXMpIHsKICAgIHRoaXMuX2V4dHJhID0gewogICAgICAuLi50aGlzLl9leHRyYSwKICAgICAgLi4uZXh0cmFzLAogICAgfTsKICAgIHRoaXMuX25vdGlmeVNjb3BlTGlzdGVuZXJzKCk7CiAgICByZXR1cm4gdGhpczsKICB9CgogIC8qKgogICAqIEBpbmhlcml0RG9jCiAgICovCiAgIHNldEV4dHJhKGtleSwgZXh0cmEpIHsKICAgIHRoaXMuX2V4dHJhID0geyAuLi50aGlzLl9leHRyYSwgW2tleV06IGV4dHJhIH07CiAgICB0aGlzLl9ub3RpZnlTY29wZUxpc3RlbmVycygpOwogICAgcmV0dXJuIHRoaXM7CiAgfQoKICAvKioKICAgKiBAaW5oZXJpdERvYwogICAqLwogICBzZXRGaW5nZXJwcmludChmaW5nZXJwcmludCkgewogICAgdGhpcy5fZmluZ2VycHJpbnQgPSBmaW5nZXJwcmludDsKICAgIHRoaXMuX25vdGlmeVNjb3BlTGlzdGVuZXJzKCk7CiAgICByZXR1cm4gdGhpczsKICB9CgogIC8qKgogICAqIEBpbmhlcml0RG9jCiAgICovCiAgIHNldExldmVsKAogICAgLy8gZXNsaW50LWRpc2FibGUtbmV4dC1saW5lIGRlcHJlY2F0aW9uL2RlcHJlY2F0aW9uCiAgICBsZXZlbCwKICApIHsKICAgIHRoaXMuX2xldmVsID0gbGV2ZWw7CiAgICB0aGlzLl9ub3RpZnlTY29wZUxpc3RlbmVycygpOwogICAgcm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ckJyZWFkY3J1bWJzKCkgewogICAgdGhpcy5fYnJlYWRjcnVtYnMgPSBbXTsKICAgIHRoaXMuX25vdGlmeVNjb3BlTGlzdGVuZXJzKCk7CiAgICByZXR1cm4gdGhpczsKICB9CgogIC8qKgogICAqIEBpbmhlcml0RG9jCiAgICovCiAgIGFkZEF0dGFjaG1lbnQoYXR0YWNobWVudCkgewogICAgdGhpcy5fYXR0YWNobWVudHMucHVzaChhdHRhY2htZW50KTsKICAgIHJldHVybiB0aGlzOwogIH0KCiAgLyoqCiAgICogQGluaGVyaXREb2MKICAgKiBAZGVwcmVjYXRlZCBVc2UgYGdldFNjb3BlRGF0YSgpYCBpbnN0ZWFkLgogICAqLwogICBnZXRBdHRhY2htZW50cygpIHsKICAgIGNvbnN0IGRhdGEgPSB0aGlzLmdldFNjb3BlRGF0YSgpOwoKICAgIHJldHVybiBkYXRhLmF0dGFjaG1lbnRzOwogIH0KCiAgLyoqCiAgICogQGluaGVyaXREb2MKICAgKi8KICAgY2xlYXJBdHRhY2htZW50cygpIHsKICAgIHRoaXMuX2F0dGFjaG1lbnRzID0gW107CiAgICByZXR1cm4gdGhpczsKICB9CgogIC8qKiBAaW5oZXJpdERvYyAqLwogICBnZXRTY29wZURhdGEoKSB7CiAgICBjb25zdCB7CiAgICAgIF9icmVhZGNydW1icywKICAgICAgX2F0dGFjaG1lbnRzLAogICAgICBfY29udGV4dHMsCiAgICAgIF90YWdzLAogICAgICBfZXh0cmEsCiAgICAgIF91c2VyLAogICAgICBfbGV2ZWwsCiAgICAgIF9maW5nZXJwcmludCwKICAgICAgX2V2ZW50UHJvY2Vzc29ycywKICAgICAgX3Byb3BhZ2F0aW9uQ29udGV4dCwKICAgICAgX3Nka1Byb2Nlc3NpbmdNZXRhZGF0YSwKICAgICAgX3RyYW5zYWN0aW9uTmFtZSwKICAgICAgX3NwYW4sCiAgICB9ID0gdGhpczsKCiAgICByZXR1cm4gewogICAgICBicmVhZGNydW1iczogX2JyZWFkY3J1bWJzL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Q2xpZW50KGNsaWVudCk7CiAgICogICAgY2xpZW50LmluaXQoKTsKICAgKiB9KTsKICAgKiBgYGAKICAgKgogICAqIElmIHlvdSBhcmUgdXNpbmcgdGhlIEh1YiB0byBjYXB0dXJlIGV2ZW50cyBsaWtlIHNvOgogICAqCiAgICogYGBgCiAgICogLy8gT0xECiAgICogY29uc3QgY2xpZW50ID0gbmV3IENsaWVudCgpOwogICAqIGNvbnN0IGh1YiA9IG5ldyBIdWIoY2xpZW50KTsKICAgKiBodWIuY2FwdHVyZUV4Y2VwdGlvbigpCiAgICogYGBgCiAgICoKICAgKiBpbnN0ZWFkIGNhcHR1cmUgaXNvbGF0ZWQgZXZlbnRzIGFzIGZvbGxvd3M6CiAgICoKICAgKiBgYGAKICAgKiAvLyBORVcKICAgKiBjb25zdCBjbGllbnQgPSBuZXcgQ2xpZW50KCk7CiAgICogY29uc3Qgc2NvcGUgPSBuZXcgU2NvcGUoKTsKICAgKiBzY29wZS5zZXRDbGllbnQoY2xpZW50KTsKICAgKiBzY29wZS5jYXB0dXJlRXhjZXB0aW9uKCk7CiAgICogYGBgCiAgICovCiAgIGNvbnN0cnVjdG9yKAogICAgY2xpZW50LAogICAgc2NvcGUsCiAgICBpc29sYXRpb25TY29wZSwKICAgICAgX3ZlcnNpb24gPSBBUElfVkVSU0lPTiwKICApIHt0aGlzLl92ZXJzaW9uID0gX3ZlcnNpb247CiAgICBsZXQgYXNzaWduZWRTY29wZTsKICAgIGlmICghc2NvcGUpIHsKICAgICAgYXNzaWduZWRTY29wZSA9IG5ldyBTY29wZSgpOwogICAgICBhc3NpZ25lZFNjb3BlLnNldENsaWVudChjbGllbnQpOwogICAgfSBlbHNlIHsKICAgICAgYXNzaWduZWRTY29wZSA9IHNjb3BlOwogICAgfQoKICAgIGxldCBhc3NpZ25lZElzb2xhdGlvblNjb3BlOwogICAgaWYgKCFpc29sYXRpb25TY29wZSkgewogICAgICBhc3NpZ25lZElzb2xhdGlvblNjb3BlID0gbmV3IFN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bHksIG9yIGBzZXRDdXJyZW50Q2xpZW50KClgIGFuZC9vciBgY2xpZW50LmluaXQoKWAgaW5zdGVhZC4KICAgKi8KICAgYmluZENsaWVudChjbGllbnQpIHsKICAgIC8vIGVzbGludC1kaXNhYmxlLW5leHQtbGluZSBkZXByZWNhdGlvbi9kZXByZWNhdGlvbgogICAgY29uc3QgdG9wID0gdGhpcy5nZXRTdGFja1RvcCgpOwogICAgdG9wLmNsaWVudCA9IGNsaWVudDsKICAgIHRvcC5zY29wZS5zZXRDbGllbnQoY2xpZW50KTsKICAgIC8vIGVzbGludC1kaXNhYmxlLW5leHQtbGluZSBkZXByZWNhdGlvbi9kZXByZWNhdGlvbgogICAgaWYgKGNsaWVudCAmJiBjbGllbnQuc2V0dXBJbnRlZ3JhdGlvbnMpIHsKICAgICAgLy8gZXNsaW50LWRpc2FibGUtbmV4dC1saW5lIGRlcHJlY2F0aW9uL2RlcHJlY2F0aW9uCiAgICAgIGNsaWVudC5zZXR1cEludGVncmF0aW9ucygpOwogICAgfQogIH0KCiAgLyoqCiAgICogQGluaGVyaXREb2MKICAgKgogICAqIEBkZXByZWNhdGVkIFVzZSBgd2l0aFNjb3BlYCBpbnN0ZWFkLgogICAqLwogICBwdXNoU2NvcGUoKSB7CiAgICAvLyBXZSB3YW50IHRvIGNsb25lIHRoZSBjb250ZW50IG9mIHByZXYgc2NvcGUKICAgIC8vIGVzbGludC1kaXNhYmxlLW5leHQtbGluZSBkZXByZWNhdGlvbi9kZXByZWNhdGlvbgogICAgY29uc3Qgc2NvcGUgPSB0aGlzLmdldFNjb3BlKCkuY2xvbmUoKTsKICAgIC8vIGVzbGludC1kaXNhYmxlLW5leHQtbGluZSBkZXByZWNhdGlvbi9kZXByZWNhdGlvbgogICAgdGhpcy5nZXRTdGFjaygpLnB1c2goewogICAgICAvLyBlc2xpbnQtZGlzYWJsZS1uZXh0LWxpbmUgZGVwcmVjYXRpb24vZGVwcmVjYXRpb24KICAgICAgY2xpZW50OiB0aGlz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YmxlIHJldHVybnMgdGhlIHdyb25nIHR5cGUKICAgICAgcmV0dXJuIG1heWJlUHJvbWlzZVJlc3VsdC50aGVuKAogICAgICAgIHJlcyA9PiB7CiAgICAgICAgICAvLyBlc2xpbnQtZGlzYWJsZS1uZXh0LWxpbmUgZGVwcmVjYXRpb24vZGVwcmVjYXRpb24KICAgICAgICAgIHRoaXMucG9wU2NvcGUoKTsKICAgICAgICAgIHJldHVybiByZXM7CiAgICAgICAgfSwKICAgICAgICBlID0+IHsKICAgICAgICAgIC8vIGVzbGludC1kaXNhYmxlLW5leHQtbGluZSBkZXByZWNhdGlvbi9kZXByZWNhdGlvbgogICAgICAgICAgdGhpcy5wb3BTY29wZSgpOwogICAgICAgICAgdGhyb3cgZTsKICAgICAgICB9LAogICAgICApOwogICAgfQoKICAgIC8vIGVzbGludC1kaXNhYmxlLW5leHQtbGluZSBkZXByZWNhdGlvbi9kZXByZWNhdGlvbgogICAgdGhpcy5wb3BTY29wZSgpOwogICAgcmV0dXJuIG1heWJlUHJvbWlzZVJlc3VsdDsKICB9CgogIC8qKgogICAqIEBpbmhlcml0RG9jCiAgICoKICAgKiBAZGVwcmVjYXRlZCBVc2UgYFNlbnRyeS5nZXRDbGllbnQoKWAgaW5zdGVhZC4KICAgKi8KICAgZ2V0Q2xpZW50KCkgewogICAgLy8gZXNsaW50LWRpc2FibGUtbmV4dC1saW5lIGRlcHJlY2F0aW9uL2RlcHJlY2F0aW9uCiAgICByZXR1cm4gdGhpcy5nZXRTdGFja1RvcCgpLmNsaWVudCA7CiAgfQoKICAvKioKICAgKiBSZXR1cm5zIHRoZSBzY29wZSBvZiB0aGUgdG9wIHN0YWNrLgogICAqCiAgICogQGRlcHJlY2F0ZWQgVXNlIGBTZW50cnkuZ2V0Q3VycmVudFNjb3BlKClgIGluc3RlYWQuCiAgICovCiAgIGdldFNjb3BlKCkgewogICAgLy8gZXNsaW50LWRpc2FibGUtbmV4dC1saW5lIGRlcHJlY2F0aW9uL2RlcHJlY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9kOiAnUE9TVCcsCiAgICAgICAgICBhZ2VudCwKICAgICAgICAgIGhlYWRlcnMsCiAgICAgICAgICBob3N0bmFtZSwKICAgICAgICAgIHBhdGg6IGAke3BhdGhuYW1lfSR7c2VhcmNofWAsCiAgICAgICAgICBwb3J0LAogICAgICAgICAgcHJvdG9jb2wsCiAgICAgICAgICBjYTogb3B0aW9ucy5jYUNlcnRzLAogICAgICAgIH0sCiAgICAgICAgcmVzID0+IHsKICAgICAgICAgIHJlcy5vbignZGF0YScsICgpID0+IHsKICAgICAgICAgICAgLy8gRHJhaW4gc29ja2V0CiAgICAgICAgICB9KTsKCiAgICAgICAgICByZXMub24oJ2VuZCcsICgpID0+IHsKICAgICAgICAgICAgLy8gRHJhaW4gc29ja2V0CiAgICAgICAgICB9KTsKCiAgICAgICAgICByZXMuc2V0RW5jb2RpbmcoJ3V0ZjgnKTsKCiAgICAgICAgICAvLyAiS2V5LXZhbHVlIHBhaXJzIG9mIGhlYWRlciBuYW1lcyBhbmQgdmFsdWVzLiBIZWFkZXIgbmFtZXMgYXJlIGxvd2VyLWNhc2VkLiIKICAgICAgICAgIC8vIGh0dHBzOi8vbm9kZWpzLm9yZy9hcGkvaHR0cC5odG1sI2h0dHBfbWVzc2FnZV9oZWFkZXJzCiAgICAgICAgICBjb25zdCByZXRyeUFmdGVySGVhZGVyID0gX251bGxpc2hDb2FsZXNjZShyZXMuaGVhZGVyc1sncmV0cnktYWZ0ZXInXSwgKCkgPT4gKCBudWxsKSk7CiAgICAgICAgICBjb25zdCByYXRlTGltaXRzSGVhZGVyID0gX251bGxpc2hDb2FsZXNjZShyZXMuaGVhZGVyc1sneC1zZW50cnktcmF0ZS1saW1pdHMnXSwgKCkgPT4gKCBudWxsKSk7CgogICAgICAgICAgcmVzb2x2ZSh7CiAgICAgICAgICAgIHN0YXR1c0NvZGU6IHJlcy5zdGF0dXNDb2RlLAogICAgICAgICAgICBoZWFkZXJzOiB7CiAgICAgICAgICAgICAgJ3JldHJ5LWF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yAxZTYpOwogICAgfSwKICAgIHJlc2V0OiAoKSA9PiB7CiAgICAgIGxhc3RQb2xsID0gcHJvY2Vzcy5ocnRpbWUoKTsKICAgIH0sCiAgfTsKfQoKZnVuY3Rpb24gd2F0Y2hkb2dUaW1lb3V0KCkgewogIGxvZygnV2F0Y2hkb2cgdGltZW91dCcpOwoKICBpZiAoZGVidWdnZXJQYXVzZSkgewogICAgbG9nKCdQYXVzaW5nIGRlYnVnZ2VyIHRvIGNhcHR1cmUgc3RhY2sgdHJhY2UnKTsKICAgIGRlYnVnZ2VyUGF1c2UoKTsKICB9IGVsc2UgewogICAgbG9nKCdDYXB0dXJpbmcgZXZlbnQgd2l0aG91dCBhIHN0YWNrIHRyYWNlJyk7CiAgICBzZW5kQW5yRXZlbnQoKS50aGVuKG51bGwsICgpID0+IHsKICAgICAgbG9nKCdTZW5kaW5nIEFOUiBldmVudCBmYWlsZWQgb24gd2F0Y2hkb2cgdGltZW91dC4nKTsKICAgIH0pOwogIH0KfQoKY29uc3QgeyBwb2xsIH0gPSB3YXRjaGRvZ1RpbWVyKGNyZWF0ZUhyVGltZXIsIG9wdGlvbnMucG9sbEludGVydmFsLCBvcHRpb25zLmFuclRocmVzaG9sZCwgd2F0Y2hkb2dUaW1lb3V0KTsKCl9vcHRpb25hbENoYWluKFtwYXJlbnRQb3J0LCAnb3B0aW9uYWxBY2Nlc3MnLCBfNiA9PiBfNi5vbiwgJ2NhbGwnLCBfNyA9PiBfNygnbWVzc2FnZScsIChtc2cpID0+IHsKICBpZiAobXNnLnNlc3Npb24pIHsKICAgIHNlc3Npb24gPSBtYWtlU2Vzc2lvbihtc2cuc2Vzc2lvbik7CiAgfQoKICBwb2xsKCk7Cn0pXSk7"),{workerData:C});process.on("exit",(()=>{h.terminate()}));const m=setInterval((()=>{try{const t=(0,g.o5)().getSession(),e=t?{...t,toJSON:void 0}:void 0;h.postMessage({session:e})}catch(t){}}),C.pollInterval);return m.unref(),h.on("message",(t=>{"session-ended"===t&&(p("ANR event sent from ANR worker. Clearing session in this thread."),(0,g.o5)().setSession(void 0))})),h.once("error",(t=>{clearInterval(m),p("ANR worker error",t)})),h.once("exit",(t=>{clearInterval(m),p("ANR worker exit",t)})),h.unref(),()=>{h.terminate(),clearInterval(m)}}(c,e))},stopWorker:()=>{r&&r.then((t=>{t(),r=void 0}))},setup(t){c=t,setImmediate((()=>this.startWorker()))}}})),m=(0,l.F)("Anr",h)},3245:(t,e,n)=>{"use strict";n.d(e,{S:()=>s});const s=(0,n(6936).kf)(process.versions.node)},2786:(t,e,n)=>{"use strict";n.d(e,{j:()=>i});var s=n(6284);t=n.hmd(t);const i=[()=>new((0,s.fj)(t,"./apollo").Apollo),()=>new((0,s.fj)(t,"./apollo").Apollo)({useNestjs:!0}),()=>new((0,s.fj)(t,"./graphql").GraphQL),()=>new((0,s.fj)(t,"./mongo").Mongo),()=>new((0,s.fj)(t,"./mongo").Mongo)({mongoose:!0}),()=>new((0,s.fj)(t,"./mysql").Mysql),()=>new((0,s.fj)(t,"./postgres").Postgres)]},5664:(t,e,n)=>{"use strict";n.r(e),n.d(e,{BROWSER_TRACING_INTEGRATION_ID:()=>He,BrowserTracing:()=>We,IdleTransaction:()=>Fe,Integrations:()=>ze,Span:()=>Xe,SpanStatus:()=>_e,TRACEPARENT_REGEXP:()=>we,Transaction:()=>Ye,addExtensionMethods:()=>Ve,defaultRequestInstrumentationOptions:()=>Se,extractTraceparentData:()=>fe,getActiveTransaction:()=>ve,hasTracingEnabled:()=>Ne,instrumentOutgoingRequests:()=>Je,spanStatusfromHttpCode:()=>Re,startIdleTransaction:()=>ke,stripUrlQueryAndFragment:()=>Ke});var s=n(683),i=n(1763),o=n(1692),r=n(5071),c=n(9071),a=n(6202),g=n(1206),l=n(138),d=n(2231);const I=(0,d.VZ)(),u=80;function C(t,e={}){if(!t)return"";try{let n=t;const s=5,i=[];let o=0,r=0;const c=" > ",a=c.length;let g;const l=Array.isArray(e)?e:e.keyAttrs,d=!Array.isArray(e)&&e.maxStringLength||u;for(;n&&o++1&&r+i.length*a+g.length>=d));)i.push(g),r+=g.length,n=n.parentNode;return i.reverse().join(c)}catch(t){return""}}function p(t,e){const n=t,s=[];let i,o,r,c,a;if(!n||!n.tagName)return"";if(I.HTMLElement&&n instanceof HTMLElement&&n.dataset&&n.dataset.sentryComponent)return n.dataset.sentryComponent;s.push(n.tagName.toLowerCase());const g=e&&e.length?e.filter((t=>n.getAttribute(t))).map((t=>[t,n.getAttribute(t)])):null;if(g&&g.length)g.forEach((t=>{s.push(`[${t[0]}="${t[1]}"]`)}));else if(n.id&&s.push(`#${n.id}`),i=n.className,i&&(0,l.Kg)(i))for(o=i.split(/\s+/),a=0;a{let s,i;return o=>{e.value>=0&&(o||n)&&(i=e.value-(s||0),(i||void 0===s)&&(s=e.value,e.delta=i,t(e)))}},y=()=>Z.__WEB_VITALS_POLYFILL__?Z.performance&&(performance.getEntriesByType&&performance.getEntriesByType("navigation")[0]||(()=>{const t=Z.performance.timing,e=Z.performance.navigation.type,n={entryType:"navigation",startTime:0,type:2==e?"back_forward":1===e?"reload":"navigate"};for(const e in t)"navigationStart"!==e&&"toJSON"!==e&&(n[e]=Math.max(t[e]-t.navigationStart,0));return n})()):Z.performance&&performance.getEntriesByType&&performance.getEntriesByType("navigation")[0],A=()=>{const t=y();return t&&t.activationStart||0},W=(t,e)=>{const n=y();let s="navigate";return n&&(s=Z.document&&Z.document.prerendering||A()>0?"prerender":n.type.replace(/_/g,"-")),{name:t,value:void 0===e?-1:e,rating:"good",delta:0,entries:[],id:`v3-${Date.now()}-${Math.floor(8999999999999*Math.random())+1e12}`,navigationType:s}},V=(t,e,n)=>{try{if(PerformanceObserver.supportedEntryTypes.includes(t)){const s=new PerformanceObserver((t=>{e(t.getEntries())}));return s.observe(Object.assign({type:t,buffered:!0},n||{})),s}}catch(t){}},v=(t,e)=>{const n=s=>{"pagehide"!==s.type&&"hidden"!==Z.document.visibilityState||(t(s),e&&(removeEventListener("visibilitychange",n,!0),removeEventListener("pagehide",n,!0)))};Z.document&&(addEventListener("visibilitychange",n,!0),addEventListener("pagehide",n,!0))},f=(t,e={})=>{const n=W("CLS",0);let s,i=0,o=[];const r=t=>{t.forEach((t=>{if(!t.hadRecentInput){const e=o[0],r=o[o.length-1];i&&0!==o.length&&t.startTime-r.startTime<1e3&&t.startTime-e.startTime<5e3?(i+=t.value,o.push(t)):(i=t.value,o=[t]),i>n.value&&(n.value=i,n.entries=o,s&&s())}}))},c=V("layout-shift",r);if(c){s=B(t,n,e.reportAllChanges);const i=()=>{r(c.takeRecords()),s(!0)};return v(i),i}};let R=-1;const Y=()=>(R<0&&(Z.document&&Z.document.visibilityState&&(R="hidden"!==Z.document.visibilityState||Z.document.prerendering?1/0:0),v((({timeStamp:t})=>{R=t}),!0)),{get firstHiddenTime(){return R}}),X=t=>{const e=Y(),n=W("FID");let s;const i=t=>{t.startTime{t.forEach(i)},r=V("first-input",o);s=B(t,n),r&&v((()=>{o(r.takeRecords()),r.disconnect()}),!0)};let H=0,S=1/0,N=0;const K=t=>{t.forEach((t=>{t.interactionId&&(S=Math.min(S,t.interactionId),N=Math.max(N,t.interactionId),H=N?(N-S)/7+1:0)}))};let w;const F=()=>{"interactionCount"in performance||w||(w=V("event",K,{type:"event",buffered:!0,durationThreshold:0}))},J=()=>w?H:performance.interactionCount||0,k=[],_={},z=t=>{const e=k[k.length-1],n=_[t.interactionId];if(n||k.length<10||t.duration>e.latency){if(n)n.entries.push(t),n.latency=Math.max(n.latency,t.duration);else{const e={id:t.interactionId,latency:t.duration,entries:[t]};_[e.id]=e,k.push(e)}k.sort(((t,e)=>e.latency-t.latency)),k.splice(10).forEach((t=>{delete _[t.id]}))}},U=(t,e)=>{e=e||{},F();const n=W("INP");let s;const i=t=>{t.forEach((t=>{t.interactionId&&z(t),"first-input"===t.entryType&&!k.some((e=>e.entries.some((e=>t.duration===e.duration&&t.startTime===e.startTime))))&&z(t)}));const e=(()=>{const t=Math.min(k.length-1,Math.floor(J()/50));return k[t]})();e&&e.latency!==n.value&&(n.value=e.latency,n.entries=e.entries,s())},o=V("event",i,{durationThreshold:e.durationThreshold||40});s=B(t,n,e.reportAllChanges),o&&(o.observe({type:"first-input",buffered:!0}),v((()=>{i(o.takeRecords()),n.value<0&&J()>0&&(n.value=0,n.entries=[]),s(!0)})))},x={},T=t=>{const e=Y(),n=W("LCP");let s;const i=t=>{const i=t[t.length-1];if(i){const t=Math.max(i.startTime-A(),0);t{x[n.id]||(i(o.takeRecords()),o.disconnect(),x[n.id]=!0,s(!0))};return["keydown","click"].forEach((t=>{Z.document&&addEventListener(t,e,{once:!0,capture:!0})})),v(e,!0),e}},E=t=>{Z.document&&(Z.document.prerendering?addEventListener("prerenderingchange",(()=>E(t)),!0):"complete"!==Z.document.readyState?addEventListener("load",(()=>E(t)),!0):setTimeout(t,0))},L=(t,e)=>{e=e||{};const n=W("TTFB"),s=B(t,n,e.reportAllChanges);E((()=>{const t=y();if(t){if(n.value=Math.max(t.responseStart-A(),0),n.value<0||n.value>performance.now())return;n.entries=[t],s(!0)}}))},Q={},j={};let O,M,P,D,q;function $(t,e){return ct(t,e),j[t]||(function(t){const e={};"event"===t&&(e.durationThreshold=0),V(t,(e=>{tt(t,{entries:e})}),e)}(t),j[t]=!0),at(t,e)}function tt(t,e){const n=Q[t];if(n&&n.length)for(const s of n)try{s(e)}catch(e){h&&a.vF.error(`Error while triggering instrumentation handler.\nType: ${t}\nName: ${(0,G.qQ)(s)}\nError:`,e)}}function et(){return f((t=>{tt("cls",{metric:t}),O=t}),{reportAllChanges:!0})}function nt(){return X((t=>{tt("fid",{metric:t}),M=t}))}function st(){return T((t=>{tt("lcp",{metric:t}),P=t}))}function it(){return L((t=>{tt("ttfb",{metric:t}),D=t}))}function ot(){return U((t=>{tt("inp",{metric:t}),q=t}))}function rt(t,e,n,s,i=!1){let o;return ct(t,e),j[t]||(o=n(),j[t]=!0),s&&e({metric:s}),at(t,e,i?o:void 0)}function ct(t,e){Q[t]=Q[t]||[],Q[t].push(e)}function at(t,e,n){return()=>{n&&n();const s=Q[t];if(!s)return;const i=s.indexOf(e);-1!==i&&s.splice(i,1)}}var gt=n(7037);function lt(t){return[{type:"span"},t]}var dt=n(5177),It=n(6056),ut=n(7567);function Ct(t){if(!t)return{};const e=t.match(/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);if(!e)return{};const n=e[6]||"",s=e[8]||"";return{host:e[4],path:e[5],protocol:e[2],search:n,hash:s,relative:e[5]+n+s}}function pt(t){return t.split(/[\?#]/,1)[0]}function bt(t){return t.split(/\\?\//).filter((t=>t.length>0&&","!==t)).length}function ht(t){return"number"==typeof t&&isFinite(t)}function mt(t,{startTimestamp:e,...n}){return e&&t.startTimestamp>e&&(t.startTimestamp=e),t.startChild({startTimestamp:e,...n})}const Zt=2147483647;function Gt(t){return t/1e3}function Bt(){return Z&&Z.addEventListener&&Z.performance}let yt,At,Wt=0,Vt={};function vt(){const t=Bt();if(t&&ut.k3){t.mark&&Z.performance.mark("sentry-tracing-init");const e=rt("fid",(({metric:t})=>{const e=t.entries[t.entries.length-1];if(!e)return;const n=Gt(ut.k3),s=Gt(e.startTime);h&&a.vF.log("[Measurements] Adding FID"),Vt.fid={value:t.value,unit:"millisecond"},Vt["mark.fid"]={value:n+s,unit:"second"}}),nt,M),n=function(t,e=!1){return rt("cls",t,et,O,e)}((({metric:t})=>{const e=t.entries[t.entries.length-1];e&&(h&&a.vF.log("[Measurements] Adding CLS"),Vt.cls={value:t.value,unit:""},At=e)}),!0),s=function(t,e=!1){return rt("lcp",t,st,P,e)}((({metric:t})=>{const e=t.entries[t.entries.length-1];e&&(h&&a.vF.log("[Measurements] Adding LCP"),Vt.lcp={value:t.value,unit:"millisecond"},yt=e)}),!0),i=rt("ttfb",(({metric:t})=>{t.entries[t.entries.length-1]&&(h&&a.vF.log("[Measurements] Adding TTFB"),Vt.ttfb={value:t.value,unit:"millisecond"})}),it,D);return()=>{e(),n(),s(),i()}}return()=>{}}const ft={click:"click",pointerdown:"click",pointerup:"click",mousedown:"click",mouseup:"click",touchstart:"click",touchend:"click",mouseover:"hover",mouseout:"hover",mouseenter:"hover",mouseleave:"hover",pointerover:"hover",pointerout:"hover",pointerenter:"hover",pointerleave:"hover",dragstart:"drag",dragend:"drag",drag:"drag",dragenter:"drag",dragleave:"drag",dragover:"drag",drop:"drag",keydown:"press",keyup:"press",keypress:"press",input:"press"};function Rt(t,e,n,s,i,o){const r=o?e[o]:e[`${n}End`],c=e[`${n}Start`];c&&r&&mt(t,{op:"browser",origin:"auto.browser.browser.metrics",description:i||n,startTimestamp:s+Gt(c),endTimestamp:s+Gt(r)})}function Yt(t,e,n,s){const i=e[n];null!=i&&i{const e={...i,endTimestamp:Date.now(),response:t};return(0,kt.aj)("fetch",e),t}),(t=>{const e={...i,endTimestamp:Date.now(),error:t};throw(0,kt.aj)("fetch",e),t}))}}))}function zt(t,e){return!!t&&"object"==typeof t&&!!t[e]}function Ut(t){return"string"==typeof t?t:t?zt(t,"url")?t.url:t.toString?t.toString():"":""}const xt=d.OW,Tt="__sentry_xhr_v3__";function Et(){if(!xt.XMLHttpRequest)return;const t=XMLHttpRequest.prototype;(0,Kt.GS)(t,"open",(function(t){return function(...e){const n=Date.now(),s=(0,l.Kg)(e[0])?e[0].toUpperCase():void 0,i=function(t){if((0,l.Kg)(t))return t;try{return t.toString()}catch(t){}}(e[1]);if(!s||!i)return t.apply(this,e);this[Tt]={method:s,url:i,request_headers:{}},"POST"===s&&i.match(/sentry_key/)&&(this.__sentry_own_request__=!0);const o=()=>{const t=this[Tt];if(t&&4===this.readyState){try{t.status_code=this.status}catch(t){}const e={args:[s,i],endTimestamp:Date.now(),startTimestamp:n,xhr:this};(0,kt.aj)("xhr",e)}};return"onreadystatechange"in this&&"function"==typeof this.onreadystatechange?(0,Kt.GS)(this,"onreadystatechange",(function(t){return function(...e){return o(),t.apply(this,e)}})):this.addEventListener("readystatechange",o),(0,Kt.GS)(this,"setRequestHeader",(function(t){return function(...e){const[n,s]=e,i=this[Tt];return i&&(0,l.Kg)(n)&&(0,l.Kg)(s)&&(i.request_headers[n.toLowerCase()]=s),t.apply(this,e)}})),t.apply(this,e)}})),(0,Kt.GS)(t,"send",(function(t){return function(...e){const n=this[Tt];if(!n)return t.apply(this,e);void 0!==e[0]&&(n.body=e[0]);const s={args:[n.method,n.url],startTimestamp:Date.now(),xhr:this};return(0,kt.aj)("xhr",s),t.apply(this,e)}}))}var Lt=n(8562);const Qt=["localhost",/^\/(?!\/)/],jt={traceFetch:!0,traceXHR:!0,enableHTTPTimings:!0,tracingOrigins:Qt,tracePropagationTargets:Qt};function Ot(t){const{traceFetch:e,traceXHR:n,tracePropagationTargets:s,tracingOrigins:i,shouldCreateSpanForRequest:o,enableHTTPTimings:a}={traceFetch:jt.traceFetch,traceXHR:jt.traceXHR,...t},d="function"==typeof o?o:t=>!0,I=t=>function(t,e){return function(t,e=[],n=!1){return e.some((e=>function(t,e,n=!1){return!!(0,l.Kg)(t)&&((0,l.gd)(e)?e.test(t):!!(0,l.Kg)(e)&&(n?t===e:t.includes(e)))}(t,e,n)))}(t,e||Qt)}(t,s||i),u={};var C;e&&function(){const t="fetch";(0,kt.s5)(t,(t=>{const e=function(t,e,n,s,i="auto.http.browser"){if(!(0,dt.w)()||!t.fetchData)return;const o=e(t.fetchData.url);if(t.endTimestamp&&o){const e=t.fetchData.__span;if(!e)return;const n=s[e];return void(n&&(function(t,e){if(e.response){(0,Xt.N8)(t,e.response.status);const n=e.response&&e.response.headers&&e.response.headers.get("content-length");if(n){const e=parseInt(n);e>0&&t.setAttribute("http.response_content_length",e)}}else e.error&&t.setStatus("internal_error");t.end()}(n,t),delete s[e]))}const a=(0,c.o5)(),d=(0,c.KU)(),{method:I,url:u}=t.fetchData,C=function(t){try{return new URL(t).href}catch(t){return}}(u),p=C?Ct(C).host:void 0,b=o?(0,St.Uk)({name:`${I} ${u}`,onlyIfParent:!0,attributes:{url:u,type:"fetch","http.method":I,"http.url":C,"server.address":p,[r.JD]:i},op:"http.client"}):void 0;if(b&&(t.fetchData.__span=b.spanContext().spanId,s[b.spanContext().spanId]=b),n(t.fetchData.url)&&d){const e=t.args[0];t.args[1]=t.args[1]||{};const n=t.args[1];n.headers=function(t,e,n,s,i){const o=i||n.getSpan(),r=(0,Ht.rm)(),{traceId:c,spanId:a,sampled:d,dsc:I}={...r.getPropagationContext(),...n.getPropagationContext()},u=o?(0,m.Qh)(o):(0,g.TC)(c,a,d),C=(0,Lt.De)(I||(o?(0,Nt.k)(o):(0,Nt.l)(c,e,n))),p=s.headers||("undefined"!=typeof Request&&(0,l.tH)(t,Request)?t.headers:void 0);if(p){if("undefined"!=typeof Headers&&(0,l.tH)(p,Headers)){const t=new Headers(p);return t.append("sentry-trace",u),C&&t.append(Lt.hF,C),t}if(Array.isArray(p)){const t=[...p,["sentry-trace",u]];return C&&t.push([Lt.hF,C]),t}{const t="baggage"in p?p.baggage:void 0,e=[];return Array.isArray(t)?e.push(...t):t&&e.push(t),C&&e.push(C),{...p,"sentry-trace":u,baggage:e.length>0?e.join(","):void 0}}}return{"sentry-trace":u,baggage:C}}(e,d,a,n,b)}return b}(t,d,I,u);if(e){const n=Dt(t.fetchData.url),s=n?Ct(n).host:void 0;e.setAttributes({"http.url":n,"server.address":s})}a&&e&&Mt(e)})),(0,kt.AS)(t,_t)}(),n&&(C=t=>{const e=function(t,e,n,s){const i=t.xhr,o=i&&i[Tt];if(!(0,dt.w)()||!i||i.__sentry_own_request__||!o)return;const a=e(o.url);if(t.endTimestamp&&a){const t=i.__sentry_xhr_span_id__;if(!t)return;const e=s[t];return void(e&&void 0!==o.status_code&&((0,Xt.N8)(e,o.status_code),e.end(),delete s[t]))}const l=(0,c.o5)(),d=(0,Ht.rm)(),I=Dt(o.url),u=I?Ct(I).host:void 0,C=a?(0,St.Uk)({name:`${o.method} ${o.url}`,onlyIfParent:!0,attributes:{type:"xhr","http.method":o.method,"http.url":I,url:o.url,"server.address":u,[r.JD]:"auto.http.browser"},op:"http.client"}):void 0;C&&(i.__sentry_xhr_span_id__=C.spanContext().spanId,s[i.__sentry_xhr_span_id__]=C);const p=(0,c.KU)();if(i.setRequestHeader&&n(o.url)&&p){const{traceId:t,spanId:e,sampled:n,dsc:s}={...d.getPropagationContext(),...l.getPropagationContext()};!function(t,e,n){try{t.setRequestHeader("sentry-trace",e),n&&t.setRequestHeader(Lt.hF,n)}catch(t){}}(i,C?(0,m.Qh)(C):(0,g.TC)(t,e,n),(0,Lt.De)(s||(C?(0,Nt.k)(C):(0,Nt.l)(t,p,l))))}return C}(t,d,I,u);a&&e&&Mt(e)},(0,kt.s5)("xhr",C),(0,kt.AS)("xhr",Et))}function Mt(t){const{url:e}=(0,m.et)(t).data||{};if(!e||"string"!=typeof e)return;const n=$("resource",(({entries:s})=>{s.forEach((s=>{(function(t){return"resource"===t.entryType&&"initiatorType"in t&&"string"==typeof t.nextHopProtocol&&("fetch"===t.initiatorType||"xmlhttprequest"===t.initiatorType)})(s)&&s.name.endsWith(e)&&(function(t){const{name:e,version:n}=function(t){let e="unknown",n="unknown",s="";for(const i of t){if("/"===i){[e,n]=t.split("/");break}if(!isNaN(Number(i))){e="h"===s?"http":s,n=t.split(s)[1];break}s+=i}return s===t&&(e=s),{name:e,version:n}}(t.nextHopProtocol),s=[];return s.push(["network.protocol.version",n],["network.protocol.name",e]),ut.k3?[...s,["http.request.redirect_start",Pt(t.redirectStart)],["http.request.fetch_start",Pt(t.fetchStart)],["http.request.domain_lookup_start",Pt(t.domainLookupStart)],["http.request.domain_lookup_end",Pt(t.domainLookupEnd)],["http.request.connect_start",Pt(t.connectStart)],["http.request.secure_connection_start",Pt(t.secureConnectionStart)],["http.request.connection_end",Pt(t.connectEnd)],["http.request.request_start",Pt(t.requestStart)],["http.request.response_start",Pt(t.responseStart)],["http.request.response_end",Pt(t.responseEnd)]]:s}(s).forEach((e=>t.setAttribute(...e))),setTimeout(n))}))}))}function Pt(t=0){return((ut.k3||performance.timeOrigin)+t)/1e3}function Dt(t){try{return new URL(t,Z.location.origin).href}catch(t){return}}const qt=(0,d.VZ)(),$t=d.OW;let te;function ee(){if(!function(){const t=qt.chrome,e=t&&t.app&&t.app.runtime,n="history"in qt&&!!qt.history.pushState&&!!qt.history.replaceState;return!e&&n}())return;const t=$t.onpopstate;function e(t){return function(...e){const n=e.length>2?e[2]:void 0;if(n){const t=te,e=String(n);te=e;const s={from:t,to:e};(0,kt.aj)("history",s)}return t.apply(this,e)}}$t.onpopstate=function(...e){const n=$t.location.href,s=te;te=n;const i={from:s,to:n};if((0,kt.aj)("history",i),t)try{return t.apply(this,e)}catch(t){}},(0,Kt.GS)($t.history,"pushState",e),(0,Kt.GS)($t.history,"replaceState",e)}const ne="BrowserTracing",se={...s.Cq,markBackgroundTransactions:!0,routingInstrumentation:function(t,e=!0,n=!0){if(!Z||!Z.location)return void(h&&a.vF.warn("Could not initialize routing instrumentation due to invalid location"));let s,i=Z.location.href;e&&(s=t({name:Z.location.pathname,startTimestamp:ut.k3?ut.k3/1e3:void 0,op:"pageload",origin:"auto.pageload.browser",metadata:{source:"url"}})),n&&function(){const e="history";(0,kt.s5)(e,(({to:e,from:n})=>{void 0===n&&i&&-1!==i.indexOf(e)?i=void 0:n!==e&&(i=void 0,s&&(h&&a.vF.log(`[Tracing] Finishing current transaction with op: ${s.op}`),s.end()),s=t({name:Z.location.pathname,op:"navigation",origin:"auto.navigation.browser",metadata:{source:"url"}}))})),(0,kt.AS)(e,ee)}()},startTransactionOnLocationChange:!0,startTransactionOnPageLoad:!0,enableLongTask:!0,enableInp:!1,interactionsSampleRate:1,_experiments:{},...jt};function ie(t){const e=(n=`meta[name=${t}]`,I.document&&I.document.querySelector?I.document.querySelector(n):null);var n;return e?e.getAttribute("content"):void 0}function oe(t){const e=t.attributes&&t.attributes[r.i_],n=t.data&&t.data[r.i_],s=t.metadata&&t.metadata.source;return e||n||s}var re=n(2581),ce=n(9049);function ae(t){let e,n=t[0],s=1;for(;sn.call(e,...t))),e=void 0)}return n}var ge=n(8560),le=n(4902);function de(t){const e=ae([t,"call",t=>t(),"access",t=>t.getClient,"call",t=>t(),"optionalAccess",t=>t.getOptions,"call",t=>t()]);return"sentry"!==(ae([e,"optionalAccess",t=>t.instrumenter])||"sentry")}class Ie{static __initStatic(){this.id="Apollo"}constructor(t={useNestjs:!1}){this.name=Ie.id,this._useNest=!!t.useNestjs}loadDependency(){return this._useNest?this._module=this._module||(0,ge.Vw)("@nestjs/graphql"):this._module=this._module||(0,ge.Vw)("apollo-server-core"),this._module}setupOnce(t,e){if(de(e))h&&a.vF.log("Apollo Integration is skipped because of instrumenter configuration.");else if(this._useNest){const t=this.loadDependency();if(!t)return void(h&&a.vF.error("Apollo-NestJS Integration was unable to require @nestjs/graphql package."));(0,Kt.GS)(t.GraphQLFactory.prototype,"mergeWithSchema",(function(t){return function(...n){return(0,Kt.GS)(this.resolversExplorerService,"explore",(function(t){return function(){return ue((0,le.k9)(t.call(this)),e)}})),t.call(this,...n)}}))}else{const t=this.loadDependency();if(!t)return void(h&&a.vF.error("Apollo Integration was unable to require apollo-server-core package."));(0,Kt.GS)(t.ApolloServerBase.prototype,"constructSchema",(function(t){return function(){if(!this.config.resolvers)return h&&(this.config.schema?(a.vF.warn("Apollo integration is not able to trace `ApolloServer` instances constructed via `schema` property.If you are using NestJS with Apollo, please use `Sentry.Integrations.Apollo({ useNestjs: true })` instead."),a.vF.warn()):this.config.modules&&a.vF.warn("Apollo integration is not able to trace `ApolloServer` instances constructed via `modules` property."),a.vF.error("Skipping tracing as no resolvers found on the `ApolloServer` instance.")),t.call(this);const n=(0,le.k9)(this.config.resolvers);return this.config.resolvers=ue(n,e),t.call(this)}}))}}}function ue(t,e){return t.map((t=>(Object.keys(t).forEach((n=>{Object.keys(t[n]).forEach((s=>{"function"==typeof t[n][s]&&function(t,e,n,s){(0,Kt.GS)(t[e],n,(function(t){return function(...i){const o=ae([s().getScope().getSpan(),"optionalAccess",t=>t.startChild,"call",t=>t({description:`${e}.${n}`,op:"graphql.resolve",origin:"auto.graphql.apollo"})]),r=t.call(this,...i);return(0,l.Qg)(r)?r.then((t=>(ae([o,"optionalAccess",t=>t.end,"call",t=>t()]),t))):(ae([o,"optionalAccess",t=>t.end,"call",t=>t()]),r)}}))}(t,n,s,e)}))})),t)))}Ie.__initStatic();class Ce{static __initStatic(){this.id="Express"}constructor(t={}){this.name=Ce.id,this._router=t.router||t.app,this._methods=(Array.isArray(t.methods)?t.methods:[]).concat("use")}setupOnce(t,e){this._router?de(e)?h&&a.vF.log("Express Integration is skipped because of instrumenter configuration."):(function(t,e=[]){e.forEach((e=>function(t,e){const n=t[e];return t[e]=function(...t){return n.call(this,...function(t,e){return t.map((t=>"function"==typeof t?pe(t,e):Array.isArray(t)?t.map((t=>"function"==typeof t?pe(t,e):t)):t))}(t,e))},t}(t,e)))}(this._router,this._methods),function(t){const e="settings"in t;e&&void 0===t._router&&t.lazyrouter&&t.lazyrouter();const n=e?t._router:t;if(!n)return h&&a.vF.debug("Cannot instrument router for URL Parameterization (did not find a valid router)."),void(h&&a.vF.debug("Routing instrumentation is currently only supported in Express 4."));const s=Object.getPrototypeOf(n),i=s.process_params;s.process_params=function(t,e,n,s,o){n._reconstructedRoute||(n._reconstructedRoute="");const{layerRoutePath:c,isRegex:a,isArray:g,numExtraSegments:I}=function(t){let e=ae([t,"access",t=>t.route,"optionalAccess",t=>t.path]);const n=(0,l.gd)(e),s=Array.isArray(e);if(!e){const[n]=d.OW.process.versions.node.split(".").map(Number);n>=16&&(e=be(t.path,t.regexp,t.keys))}if(!e)return{isRegex:n,isArray:s,numExtraSegments:0};const i=s?Math.max(e.reduce(((t,e)=>t+bt(e.toString())),0)-bt(t.path||""),0):0,o=function(t,e){return t?e.map((t=>t.toString())).join(","):e&&e.toString()}(s,e);return{layerRoutePath:o,isRegex:n,isArray:s,numExtraSegments:i}}(t);let u;(c||a||g)&&(n._hasParameters=!0),u=c||function(t,e,n){const s=ae([pt(t||""),"optionalAccess",t=>t.split,"call",t=>t("/"),"access",t=>t.filter,"call",t=>t((t=>!!t))]);let i=0;const o=ae([e,"optionalAccess",t=>t.split,"call",t=>t("/"),"access",t=>t.filter,"call",t=>t((t=>!!t)),"access",t=>t.length])||0;return ae([n,"optionalAccess",t=>t.split,"call",t=>t("/"),"access",t=>t.filter,"call",t=>t((t=>ae([s,"optionalAccess",t=>t[o+i]])===t&&(i+=1,!0))),"access",t=>t.join,"call",t=>t("/")])}(n.originalUrl,n._reconstructedRoute,t.path)||"";const C=u.split("/").filter((t=>t.length>0&&(a||g||!t.includes("*")))).join("/");if(C&&C.length>0&&(n._reconstructedRoute+=`/${C}${a?"/":""}`),bt(pt(n.originalUrl||""))+I===bt(n._reconstructedRoute)){n._hasParameters||n._reconstructedRoute!==n.originalUrl&&(n._reconstructedRoute=n.originalUrl?pt(n.originalUrl):n.originalUrl);const t=s.__sentry_transaction,e=t&&(0,m.et)(t).data||{};if(t&&"custom"!==e[r.i_]){const e=n._reconstructedRoute||"/",[s,i]=function(t,e={}){const n=t.method&&t.method.toUpperCase();let s="",i="url";e.customRoute||t.route?(s=e.customRoute||`${t.baseUrl||""}${t.route&&t.route.path}`,i="route"):(t.originalUrl||t.url)&&(s=pt(t.originalUrl||t.url||""));let o="";return e.method&&n&&(o+=n),e.method&&e.path&&(o+=" "),e.path&&s&&(o+=s),[o,i]}(n,{path:!0,method:!0,customRoute:e});t.updateName(s),t.setAttribute(r.i_,i)}}return i.call(this,t,e,n,s,o)}}(this._router)):h&&a.vF.error("ExpressIntegration is missing an Express instance")}}function pe(t,e){const n=t.length;switch(n){case 2:return function(n,s){const i=s.__sentry_transaction;if(i){const n=i.startChild({description:t.name,op:`middleware.express.${e}`,origin:"auto.middleware.express"});s.once("finish",(()=>{n.end()}))}return t.call(this,n,s)};case 3:return function(n,s,i){const o=ae([s.__sentry_transaction,"optionalAccess",t=>t.startChild,"call",n=>n({description:t.name,op:`middleware.express.${e}`,origin:"auto.middleware.express"})]);t.call(this,n,s,(function(...t){ae([o,"optionalAccess",t=>t.end,"call",t=>t()]),i.call(this,...t)}))};case 4:return function(n,s,i,o){const r=ae([i.__sentry_transaction,"optionalAccess",t=>t.startChild,"call",n=>n({description:t.name,op:`middleware.express.${e}`,origin:"auto.middleware.express"})]);t.call(this,n,s,i,(function(...t){ae([r,"optionalAccess",t=>t.end,"call",t=>t()]),o.call(this,...t)}))};default:throw new Error(`Express middleware takes 2-4 arguments. Got: ${n}`)}}Ce.__initStatic();const be=(t,e,n)=>{if(!(t&&e&&n&&0!==Object.keys(n).length&&ae([n,"access",t=>t[0],"optionalAccess",t=>t.offset])))return;const s=n.sort(((t,e)=>t.offset-e.offset)),i=new RegExp(e,`${e.flags}d`).exec(t);if(!i||!i.indices)return;const[,...o]=i.indices;if(o.length!==s.length)return;let r=t,c=0;return o.forEach(((t,e)=>{if(t){const[n,i]=t,o=r.substring(0,n-c),a=`:${s[e].name}`,g=r.substring(i-c);r=o+a+g,c+=i-n-a.length}})),r};class he{static __initStatic(){this.id="GraphQL"}constructor(){this.name=he.id}loadDependency(){return this._module=this._module||(0,ge.Vw)("graphql/execution/execute.js")}setupOnce(t,e){if(de(e))return void(h&&a.vF.log("GraphQL Integration is skipped because of instrumenter configuration."));const n=this.loadDependency();n?(0,Kt.GS)(n,"execute",(function(t){return function(...n){const s=e().getScope(),i=s.getSpan(),o=ae([i,"optionalAccess",t=>t.startChild,"call",t=>t({description:"execute",op:"graphql.execute",origin:"auto.graphql.graphql"})]);ae([s,"optionalAccess",t=>t.setSpan,"call",t=>t(o)]);const r=t.call(this,...n);return(0,l.Qg)(r)?r.then((t=>(ae([o,"optionalAccess",t=>t.end,"call",t=>t()]),ae([s,"optionalAccess",t=>t.setSpan,"call",t=>t(i)]),t))):(ae([o,"optionalAccess",t=>t.end,"call",t=>t()]),ae([s,"optionalAccess",t=>t.setSpan,"call",t=>t(i)]),r)}})):h&&a.vF.error("GraphQL Integration was unable to require graphql/execution package.")}}he.__initStatic();const me=["aggregate","bulkWrite","countDocuments","createIndex","createIndexes","deleteMany","deleteOne","distinct","drop","dropIndex","dropIndexes","estimatedDocumentCount","find","findOne","findOneAndDelete","findOneAndReplace","findOneAndUpdate","indexes","indexExists","indexInformation","initializeOrderedBulkOp","insertMany","insertOne","isCapped","mapReduce","options","parallelCollectionScan","rename","replaceOne","stats","updateMany","updateOne"],Ze={bulkWrite:["operations"],countDocuments:["query"],createIndex:["fieldOrSpec"],createIndexes:["indexSpecs"],deleteMany:["filter"],deleteOne:["filter"],distinct:["key","query"],dropIndex:["indexName"],find:["query"],findOne:["query"],findOneAndDelete:["filter"],findOneAndReplace:["filter","replacement"],findOneAndUpdate:["filter","update"],indexExists:["indexes"],insertMany:["docs"],insertOne:["doc"],mapReduce:["map","reduce"],rename:["newName"],replaceOne:["filter","doc"],updateMany:["filter","update"],updateOne:["filter","update"]};class Ge{static __initStatic(){this.id="Mongo"}constructor(t={}){this.name=Ge.id,this._operations=Array.isArray(t.operations)?t.operations:me,this._describeOperations=!("describeOperations"in t)||t.describeOperations,this._useMongoose=!!t.useMongoose}loadDependency(){const t=this._useMongoose?"mongoose":"mongodb";return this._module=this._module||(0,ge.Vw)(t)}setupOnce(t,e){if(de(e))return void(h&&a.vF.log("Mongo Integration is skipped because of instrumenter configuration."));const n=this.loadDependency();if(n)this._instrumentOperations(n.Collection,this._operations,e);else{const t=this._useMongoose?"mongoose":"mongodb";h&&a.vF.error(`Mongo Integration was unable to require \`${t}\` package.`)}}_instrumentOperations(t,e,n){e.forEach((e=>this._patchOperation(t,e,n)))}_patchOperation(t,e,n){if(!(e in t.prototype))return;const s=this._getSpanContextFromOperationArguments.bind(this);(0,Kt.GS)(t.prototype,e,(function(t){return function(...i){const o=i[i.length-1],r=n(),c=r.getScope(),a=r.getClient(),g=c.getSpan(),d=ae([a,"optionalAccess",t=>t.getOptions,"call",t=>t(),"access",t=>t.sendDefaultPii]);if("function"!=typeof o||"mapReduce"===e&&2===i.length){const n=ae([g,"optionalAccess",t=>t.startChild,"call",t=>t(s(this,e,i,d))]),o=t.call(this,...i);if((0,l.Qg)(o))return o.then((t=>(ae([n,"optionalAccess",t=>t.end,"call",t=>t()]),t)));if((I=o)&&"object"==typeof I&&I.once&&"function"==typeof I.once){const t=o;try{t.once("close",(()=>{ae([n,"optionalAccess",t=>t.end,"call",t=>t()])}))}catch(t){ae([n,"optionalAccess",t=>t.end,"call",t=>t()])}return t}return ae([n,"optionalAccess",t=>t.end,"call",t=>t()]),o}var I;const u=ae([g,"optionalAccess",t=>t.startChild,"call",t=>t(s(this,e,i.slice(0,-1)))]);return t.call(this,...i.slice(0,-1),(function(t,e){ae([u,"optionalAccess",t=>t.end,"call",t=>t()]),o(t,e)}))}}))}_getSpanContextFromOperationArguments(t,e,n,s=!1){const i={"db.system":"mongodb","db.name":t.dbName,"db.operation":e,"db.mongodb.collection":t.collectionName},o={op:"db",origin:"auto.db.mongo",description:e,data:i},r=Ze[e],c=Array.isArray(this._describeOperations)?this._describeOperations.includes(e):this._describeOperations;if(!r||!c||!s)return o;try{if("mapReduce"===e){const[t,e]=n;i[r[0]]="string"==typeof t?t:t.name||"",i[r[1]]="string"==typeof e?e:e.name||""}else for(let t=0;t(s||(s=e.config),t.apply(e,n))})}catch(t){h&&a.vF.error("Mysql Integration was unable to instrument `mysql` config.")}function i(t){if(!t)return;const e=s?{"server.address":s.host,"server.port":s.port,"db.user":s.user}:{};Object.keys(e).forEach((n=>{t.setAttribute(n,e[n])})),t.end()}(0,Kt.GS)(n,"createQuery",(function(t){return function(n,s,o){const r=ae([e().getScope().getSpan(),"optionalAccess",t=>t.startChild,"call",t=>t({description:"string"==typeof n?n:n.sql,op:"db",origin:"auto.db.mysql",data:{"db.system":"mysql"}})]);if("function"==typeof o)return t.call(this,n,s,(function(t,e,n){i(r),o(t,e,n)}));if("function"==typeof s)return t.call(this,n,(function(t,e,n){i(r),s(t,e,n)}));const c=t.call(this,n,s);return c.on("end",(()=>{i(r)})),c}}))}}Be.__initStatic();class ye{static __initStatic(){this.id="Postgres"}constructor(t={}){this.name=ye.id,this._usePgNative=!!t.usePgNative,this._module=t.module}loadDependency(){return this._module=this._module||(0,ge.Vw)("pg")}setupOnce(t,e){if(de(e))return void(h&&a.vF.log("Postgres Integration is skipped because of instrumenter configuration."));const n=this.loadDependency();if(!n)return void(h&&a.vF.error("Postgres Integration was unable to require `pg` package."));const s=this._usePgNative?ae([n,"access",t=>t.native,"optionalAccess",t=>t.Client]):n.Client;s?(0,Kt.GS)(s.prototype,"query",(function(t){return function(n,s,i){const o=e().getScope().getSpan(),r={"db.system":"postgresql"};try{this.database&&(r["db.name"]=this.database),this.host&&(r["server.address"]=this.host),this.port&&(r["server.port"]=this.port),this.user&&(r["db.user"]=this.user)}catch(t){}const c=ae([o,"optionalAccess",t=>t.startChild,"call",t=>t({description:"string"==typeof n?n:n.text,op:"db",origin:"auto.db.postgres",data:r})]);if("function"==typeof i)return t.call(this,n,s,(function(t,e){ae([c,"optionalAccess",t=>t.end,"call",t=>t()]),i(t,e)}));if("function"==typeof s)return t.call(this,n,(function(t,e){ae([c,"optionalAccess",t=>t.end,"call",t=>t()]),s(t,e)}));const a=void 0!==s?t.call(this,n,s):t.call(this,n);return(0,l.Qg)(a)?a.then((t=>(ae([c,"optionalAccess",t=>t.end,"call",t=>t()]),t))):(ae([c,"optionalAccess",t=>t.end,"call",t=>t()]),a)}})):h&&a.vF.error("Postgres Integration was unable to access 'pg-native' bindings.")}}ye.__initStatic();class Ae{static __initStatic(){this.id="Prisma"}constructor(t={}){if(this.name=Ae.id,(e=t.client)&&e.$use&&!t.client._sentryInstrumented){(0,Kt.my)(t.client,"_sentryInstrumented",!0);const e={};try{const n=t.client._engineConfig;if(n){const{activeProvider:t,clientVersion:s}=n;t&&(e["db.system"]=t),s&&(e["db.prisma.version"]=s)}}catch(t){}t.client.$use(((t,n)=>{if(de(Ht.BF))return n(t);const s=t.action,i=t.model;return(0,St.Lk)({name:i?`${i} ${s}`:s,onlyIfParent:!0,op:"db.prisma",attributes:{[r.JD]:"auto.db.prisma"},data:{...e,"db.operation":s}},(()=>n(t)))}))}else h&&a.vF.warn("Unsupported Prisma client provided to PrismaIntegration. Provided client:",t.client);var e}setupOnce(){}}Ae.__initStatic();const We=class{constructor(t){this.name=ne,this._hasSetTracePropagationTargets=!1,(0,i.U)(),h&&(this._hasSetTracePropagationTargets=!(!t||!t.tracePropagationTargets&&!t.tracingOrigins)),this.options={...se,...t},void 0!==this.options._experiments.enableLongTask&&(this.options.enableLongTask=this.options._experiments.enableLongTask),t&&!t.tracePropagationTargets&&t.tracingOrigins&&(this.options.tracePropagationTargets=t.tracingOrigins),this._collectWebVitals=vt(),this._interactionIdToRouteNameMapping={},this.options.enableInp&&function(t,e){if(Bt()&&ut.k3){const n=function(t,e){return n=({metric:n})=>{if(void 0===n.value)return;const s=n.entries.find((t=>t.duration===n.value&&void 0!==ft[t.name])),i=(0,c.KU)();if(!s||!i)return;const o=ft[s.name],r=i.getOptions(),g=Gt(ut.k3+s.startTime),l=Gt(n.value),d=void 0!==s.interactionId?t[s.interactionId]:void 0;if(void 0===d)return;const{routeName:I,parentContext:u,activeTransaction:p,user:b,replayId:m}=d,G=void 0!==b?b.email||b.id||b.ip_address:void 0,B=void 0!==p?p.getProfileId():void 0,y=new gt.L({startTimestamp:g,endTimestamp:g+l,op:`ui.interaction.${o}`,name:C(s.target),attributes:{release:r.release,environment:r.environment,transaction:I,...void 0!==G&&""!==G?{user:G}:{},...void 0!==B?{profile_id:B}:{},...void 0!==m?{replay_id:m}:{}},exclusiveTime:n.value,measurements:{inp:{value:n.value,unit:"millisecond"}}}),A=function(t,e,n){if(!(0,dt.w)(e))return!1;let s;return s=void 0!==t&&"function"==typeof e.tracesSampler?e.tracesSampler({transactionContext:t,name:t.name,parentSampled:t.parentSampled,attributes:{...t.data,...t.attributes},location:Z.location}):void 0!==t&&void 0!==t.sampled?t.sampled:void 0!==e.tracesSampleRate?e.tracesSampleRate:1,(0,It.v)(s)?!0===s?n:!1===s?0:s*n:(h&&a.vF.warn("[Tracing] Discarding interaction span because of invalid sample rate."),!1)}(u,r,e);if(A&&Math.random(){h&&a.vF.error("Error while sending interaction:",t)}))}},rt("inp",n,ot,q);var n}(t,e);return()=>{n()}}}(this._interactionIdToRouteNameMapping,this.options.interactionsSampleRate),this.options.enableLongTask&&$("longtask",(({entries:t})=>{for(const e of t){const t=(0,o.Z7)();if(!t)return;const n=Gt(ut.k3+e.startTime),s=Gt(e.duration);t.startChild({description:"Main UI thread blocked",op:"ui.long-task",origin:"auto.ui.browser.metrics",startTimestamp:n,endTimestamp:n+s})}})),this.options._experiments.enableInteractions&&$("event",(({entries:t})=>{for(const e of t){const t=(0,o.Z7)();if(!t)return;if("click"===e.name){const n=Gt(ut.k3+e.startTime),s=Gt(e.duration),i={description:C(e.target),op:`ui.interaction.${e.name}`,origin:"auto.ui.browser.metrics",startTimestamp:n,endTimestamp:n+s},o=b(e.target);o&&(i.attributes={"ui.component_name":o}),t.startChild(i)}}})),this._latestRoute={name:void 0,context:void 0}}setupOnce(t,e){this._getCurrentHub=e;const n=e().getClient(),s=n&&n.getOptions(),{routingInstrumentation:i,startTransactionOnLocationChange:r,startTransactionOnPageLoad:c,markBackgroundTransactions:g,traceFetch:l,traceXHR:d,shouldCreateSpanForRequest:I,enableHTTPTimings:u,_experiments:C}=this.options,p=s&&s.tracePropagationTargets,b=p||this.options.tracePropagationTargets;h&&this._hasSetTracePropagationTargets&&p&&a.vF.warn("[Tracing] The `tracePropagationTargets` option was set in the BrowserTracing integration and top level `Sentry.init`. The top level `Sentry.init` value is being used."),i((t=>{const n=this._createRouteTransaction(t);return this.options._experiments.onStartRouteTransaction&&this.options._experiments.onStartRouteTransaction(n,t,e),n}),c,r),g&&(Z.document?Z.document.addEventListener("visibilitychange",(()=>{const t=(0,o.Z7)();if(Z.document.hidden&&t){const e="cancelled",{op:n,status:s}=(0,m.et)(t);h&&a.vF.log(`[Tracing] Transaction: ${e} -> since tab moved to the background, op: ${n}`),s||t.setStatus(e),t.setTag("visibilitychange","document.hidden"),t.end()}})):h&&a.vF.warn("[Tracing] Could not set up background tab detection due to lack of global document")),C.enableInteractions&&this._registerInteractionListener(),this.options.enableInp&&this._registerInpInteractionListener(),Ot({traceFetch:l,traceXHR:d,tracePropagationTargets:b,shouldCreateSpanForRequest:I,enableHTTPTimings:u})}_createRouteTransaction(t){if(!this._getCurrentHub)return void(h&&a.vF.warn(`[Tracing] Did not create ${t.op} transaction because _getCurrentHub is invalid.`));const e=this._getCurrentHub(),{beforeNavigate:n,idleTimeout:s,finalTimeout:r,heartbeatInterval:c}=this.options,l="pageload"===t.op;let d;if(l){const e=l?ie("sentry-trace"):"",n=l?ie("baggage"):void 0,{traceId:s,dsc:i,parentSpanId:o,sampled:r}=(0,g.kM)(e,n);d={traceId:s,parentSpanId:o,parentSampled:r,...t,metadata:{...t.metadata,dynamicSamplingContext:i},trimEnd:!0}}else d={trimEnd:!0,...t};const I="function"==typeof n?n(d):d,u=void 0===I?{...d,sampled:!1}:I;u.metadata=u.name!==d.name?{...u.metadata,source:"custom"}:u.metadata,this._latestRoute.name=u.name,this._latestRoute.context=u,!1===u.sampled&&h&&a.vF.log(`[Tracing] Will not send ${u.op} transaction because of beforeNavigate.`),h&&a.vF.log(`[Tracing] Starting ${u.op} transaction on scope`);const{location:p}=Z,b=(0,i.p)(e,u,s,r,!0,{location:p},c,l);return l&&Z.document&&(Z.document.addEventListener("readystatechange",(()=>{["interactive","complete"].includes(Z.document.readyState)&&b.sendAutoFinishSignal()})),["interactive","complete"].includes(Z.document.readyState)&&b.sendAutoFinishSignal()),b.registerBeforeFinishCallback((t=>{this._collectWebVitals(),function(t){const e=Bt();if(!e||!Z.performance.getEntries||!ut.k3)return;h&&a.vF.log("[Tracing] Adding & adjusting spans using Performance API");const n=Gt(ut.k3),s=e.getEntries(),{op:i,start_timestamp:r}=(0,m.et)(t);if(s.slice(Wt).forEach((e=>{const s=Gt(e.startTime),i=Gt(e.duration);if(!("navigation"===t.op&&r&&n+s{Rt(t,e,s,n)})),Rt(t,e,"secureConnection",n,"TLS/SSL","connectEnd"),Rt(t,e,"fetch",n,"cache","domainLookupStart"),Rt(t,e,"domainLookup",n,"DNS"),function(t,e,n){e.responseEnd&&(mt(t,{op:"browser",origin:"auto.browser.browser.metrics",description:"request",startTimestamp:n+Gt(e.requestStart),endTimestamp:n+Gt(e.responseEnd)}),mt(t,{op:"browser",origin:"auto.browser.browser.metrics",description:"response",startTimestamp:n+Gt(e.responseStart),endTimestamp:n+Gt(e.responseEnd)}))}(t,e,n)}(t,e,n);break;case"mark":case"paint":case"measure":{!function(t,e,n,s,i){const o=i+n,r=o+s;mt(t,{description:e.name,endTimestamp:r,op:e.entryType,origin:"auto.resource.browser.metrics",startTimestamp:o})}(t,e,s,i,n);const o=Y(),r=e.startTime{if(!Vt[t]||!r||n>=r)return;const e=Vt[t].value,s=n+Gt(e),i=Math.abs(1e3*(s-r)),o=i-e;h&&a.vF.log(`[Measurements] Normalized ${t} from ${e} to ${i} (${o})`),Vt[t].value=i}));const e=Vt["mark.fid"];e&&Vt.fid&&(mt(t,{description:"first input delay",endTimestamp:e.value+Gt(Vt.fid.value),op:"ui.action",origin:"auto.ui.browser.metrics",startTimestamp:e.value}),delete Vt["mark.fid"]),"fcp"in Vt||delete Vt.cls,Object.keys(Vt).forEach((t=>{!function(t,e,n){const s=(0,o.Z7)();s&&s.setMeasurement(t,e,n)}(t,Vt[t].value,Vt[t].unit)})),function(t){yt&&(h&&a.vF.log("[Measurements] Adding LCP Data"),yt.element&&t.setTag("lcp.element",C(yt.element)),yt.id&&t.setTag("lcp.id",yt.id),yt.url&&t.setTag("lcp.url",yt.url.trim().slice(0,200)),t.setTag("lcp.size",yt.size)),At&&At.sources&&(h&&a.vF.log("[Measurements] Adding CLS Data"),At.sources.forEach(((e,n)=>t.setTag(`cls.source.${n+1}`,C(e.node)))))}(t)}yt=void 0,At=void 0,Vt={}}(t)})),b}_registerInteractionListener(){let t;const e=()=>{const{idleTimeout:e,finalTimeout:n,heartbeatInterval:s}=this.options,c="ui.action.click",g=(0,o.Z7)();if(g&&g.op&&["navigation","pageload"].includes(g.op))return void(h&&a.vF.warn(`[Tracing] Did not create ${c} transaction because a pageload or navigation transaction is in progress.`));if(t&&(t.setFinishReason("interactionInterrupted"),t.end(),t=void 0),!this._getCurrentHub)return void(h&&a.vF.warn(`[Tracing] Did not create ${c} transaction because _getCurrentHub is invalid.`));if(!this._latestRoute.name)return void(h&&a.vF.warn(`[Tracing] Did not create ${c} transaction because _latestRouteName is missing.`));const l=this._getCurrentHub(),{location:d}=Z,I={name:this._latestRoute.name,op:c,trimEnd:!0,data:{[r.i_]:this._latestRoute.context?oe(this._latestRoute.context):"url"}};t=(0,i.p)(l,I,e,n,!0,{location:d},s)};["click"].forEach((t=>{Z.document&&addEventListener(t,e,{once:!1,capture:!0})}))}_registerInpInteractionListener(){const t=({entries:t})=>{const e=(0,c.KU)(),n=void 0!==e&&void 0!==e.getIntegrationByName?e.getIntegrationByName("Replay"):void 0,s=void 0!==n?n.getReplayId():void 0,i=(0,o.Z7)(),r=(0,c.o5)(),a=void 0!==r?r.getUser():void 0;t.forEach((t=>{if(function(t){return"duration"in t}(t)){const e=t.interactionId;if(void 0===e)return;const n=this._interactionIdToRouteNameMapping[e],o=t.duration,r=t.startTime,c=Object.keys(this._interactionIdToRouteNameMapping),g=c.length>0?c.reduce(((t,e)=>this._interactionIdToRouteNameMapping[t].durationthis._interactionIdToRouteNameMapping[t])).some((t=>t.duration===o&&t.startTime===r)))return;if(!e)return;if(n)n.duration=Math.max(n.duration,o);else if(c.length<10||void 0===g||o>this._interactionIdToRouteNameMapping[g].duration){const t=this._latestRoute.name,n=this._latestRoute.context;t&&n&&(g&&Object.keys(this._interactionIdToRouteNameMapping).length>=10&&delete this._interactionIdToRouteNameMapping[g],this._interactionIdToRouteNameMapping[e]={routeName:t,duration:o,parentContext:n,user:a,activeTransaction:i,replayId:s,startTime:r})}}}))};$("event",t),$("first-input",t)}},Ve=re.l,ve=o.Z7,fe=o.nc,Re=Xt.o6,Ye=ce.Z,Xe=gt.L,He=ne,Se=jt,Ne=dt.w,Ke=pt,we=g.MI,Fe=s.zX,Je=Ot,ke=i.p,_e=Xt.Fp,ze={BrowserTracing:We,Apollo:Ie,Express:Ce,GraphQL:he,Mongo:Ge,Mysql:Be,Postgres:ye,Prisma:Ae};("undefined"==typeof __SENTRY_TRACING__||__SENTRY_TRACING__)&&(0,re.l)()},5584:(t,e,n)=>{"use strict";n.d(e,{De:()=>l,yD:()=>g});var s=n(5644),i=n(3816),o=n(7412);const r="sentry-",c=/^sentry-/,a=8192;function g(t){if(!(0,i.Kg)(t)&&!Array.isArray(t))return;let e={};if(Array.isArray(t))e=t.reduce(((t,e)=>{const n=d(e);for(const e of Object.keys(n))t[e]=n[e];return t}),{});else{if(!t)return;e=d(t)}const n=Object.entries(e).reduce(((t,[e,n])=>(e.match(c)&&(t[e.slice(r.length)]=n),t)),{});return Object.keys(n).length>0?n:void 0}function l(t){if(t)return function(t){if(0!==Object.keys(t).length)return Object.entries(t).reduce(((t,[e,n],i)=>{const r=`${encodeURIComponent(e)}=${encodeURIComponent(n)}`,c=0===i?r:`${t},${r}`;return c.length>a?(s.T&&o.vF.warn(`Not adding key: ${e} with val: ${n} to baggage header due to exceeding baggage size limits.`),t):c}),"")}(Object.entries(t).reduce(((t,[e,n])=>(n&&(t[`${r}${e}`]=n),t)),{}))}function d(t){return t.split(",").map((t=>t.split("=").map((t=>decodeURIComponent(t.trim()))))).reduce(((t,[e,n])=>(t[e]=n,t)),{})}},853:(t,e,n)=>{"use strict";function s(t){let e,n=t[0],s=1;for(;sn.call(e,...t))),e=void 0)}return n}n.d(e,{z:()=>s})},5644:(t,e,n)=>{"use strict";n.d(e,{T:()=>s});const s="undefined"==typeof __SENTRY_DEBUG__||__SENTRY_DEBUG__},3816:(t,e,n)=>{"use strict";n.d(e,{Kg:()=>r,L2:()=>h,NF:()=>c,Qd:()=>g,Qg:()=>u,bJ:()=>i,gd:()=>I,mE:()=>C,sO:()=>a,tH:()=>b,vq:()=>d,xH:()=>l,yr:()=>p});const s=Object.prototype.toString;function i(t){switch(s.call(t)){case"[object Error]":case"[object Exception]":case"[object DOMException]":return!0;default:return b(t,Error)}}function o(t,e){return s.call(t)===`[object ${e}]`}function r(t){return o(t,"String")}function c(t){return"object"==typeof t&&null!==t&&"__sentry_template_string__"in t&&"__sentry_template_values__"in t}function a(t){return null===t||c(t)||"object"!=typeof t&&"function"!=typeof t}function g(t){return o(t,"Object")}function l(t){return"undefined"!=typeof Event&&b(t,Event)}function d(t){return"undefined"!=typeof Element&&b(t,Element)}function I(t){return o(t,"RegExp")}function u(t){return Boolean(t&&t.then&&"function"==typeof t.then)}function C(t){return g(t)&&"nativeEvent"in t&&"preventDefault"in t&&"stopPropagation"in t}function p(t){return"number"==typeof t&&t!=t}function b(t,e){try{return t instanceof e}catch(t){return!1}}function h(t){return!("object"!=typeof t||null===t||!t.__isVue&&!t._isVue)}},7412:(t,e,n)=>{"use strict";n.d(e,{Ow:()=>o,Z9:()=>r,pq:()=>c,vF:()=>a});var s=n(5644),i=n(6341);const o=["debug","info","warn","error","log","assert","trace"],r={};function c(t){if(!("console"in i.OW))return t();const e=i.OW.console,n={},s=Object.keys(r);s.forEach((t=>{const s=r[t];n[t]=e[t],e[t]=s}));try{return t()}finally{s.forEach((t=>{e[t]=n[t]}))}}const a=function(){let t=!1;const e={enable:()=>{t=!0},disable:()=>{t=!1},isEnabled:()=>t};return s.T?o.forEach((n=>{e[n]=(...e)=>{t&&c((()=>{i.OW.console[n](`Sentry Logger [${n}]:`,...e)}))}})):o.forEach((t=>{e[t]=()=>{}})),e}()},6936:(t,e,n)=>{"use strict";n.d(e,{$X:()=>a,GR:()=>C,M6:()=>l,db:()=>u,eJ:()=>r,gO:()=>g,k9:()=>p,kf:()=>I});var s=n(4022),i=n(9653),o=n(6341);function r(){const t=o.OW,e=t.crypto||t.msCrypto;let n=()=>16*Math.random();try{if(e&&e.randomUUID)return e.randomUUID().replace(/-/g,"");e&&e.getRandomValues&&(n=()=>{const t=new Uint8Array(1);return e.getRandomValues(t),t[0]})}catch(t){}return([1e7]+1e3+4e3+8e3+1e11).replace(/[018]/g,(t=>(t^(15&n())>>t/4).toString(16)))}function c(t){return t.exception&&t.exception.values?t.exception.values[0]:void 0}function a(t){const{message:e,event_id:n}=t;if(e)return e;const s=c(t);return s?s.type&&s.value?`${s.type}: ${s.value}`:s.type||s.value||n||"":n||""}function g(t,e,n){const s=t.exception=t.exception||{},i=s.values=s.values||[],o=i[0]=i[0]||{};o.value||(o.value=e||""),o.type||(o.type=n||"Error")}function l(t,e){const n=c(t);if(!n)return;const s=n.mechanism;if(n.mechanism={type:"generic",handled:!0,...s,...e},e&&"data"in e){const t={...s&&s.data,...e.data};n.mechanism.data=t}}const d=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/;function I(t){const e=t.match(d)||[],n=parseInt(e[1],10),s=parseInt(e[2],10),i=parseInt(e[3],10);return{buildmetadata:e[5],major:isNaN(n)?void 0:n,minor:isNaN(s)?void 0:s,patch:isNaN(i)?void 0:i,prerelease:e[4]}}function u(t,e,n=5){if(void 0===e.lineno)return;const s=t.length,o=Math.max(Math.min(s-1,e.lineno-1),0);e.pre_context=t.slice(Math.max(0,o-n),o).map((t=>(0,i.nC)(t,0))),e.context_line=(0,i.nC)(t[Math.min(s-1,o)],e.colno||0),e.post_context=t.slice(Math.min(o+1,s),o+1+n).map((t=>(0,i.nC)(t,0)))}function C(t){if(t&&t.__sentry_captured__)return!0;try{(0,s.my)(t,"__sentry_captured__",!0)}catch(t){}return!1}function p(t){return Array.isArray(t)?t:[t]}},6284:(t,e,n)=>{"use strict";function s(t,e){return t.require(e)}function i(e){let n;try{n=s(t,e)}catch(t){}try{const{cwd:i}=s(t,"process");n=s(t,`${i()}/node_modules/${e}`)}catch(t){}return n}n.d(e,{Vw:()=>i,fj:()=>s}),t=n.hmd(t)},2181:(t,e,n)=>{"use strict";n.d(e,{S8:()=>r,cd:()=>c});var s=n(3816),i=n(4022),o=n(7930);function r(t,e=100,n=1/0){try{return a("",t,e,n)}catch(t){return{ERROR:`**non-serializable** (${t})`}}}function c(t,e=3,n=102400){const s=r(t,e);return i=s,function(t){return~-encodeURI(t).split(/%..|./).length}(JSON.stringify(i))>n?c(t,e-1,n):s;var i}function a(t,e,n=1/0,r=1/0,c=function(){const t="function"==typeof WeakSet,e=t?new WeakSet:[];return[function(n){if(t)return!!e.has(n)||(e.add(n),!1);for(let t=0;t=r){C[t]="[MaxProperties ~]";break}const e=b[t];C[t]=a(t,e,I-1,r,c),p++}return l(e),C}},4022:(t,e,n)=>{"use strict";n.d(e,{my:()=>d,W4:()=>C,Ce:()=>m,HF:()=>h,GS:()=>l,sp:()=>I,u4:()=>u});var s=n(3816);const i=(0,n(6341).VZ)(),o=80;function r(t,e){const n=t,o=[];let r,c,a,g,l;if(!n||!n.tagName)return"";if(i.HTMLElement&&n instanceof HTMLElement&&n.dataset&&n.dataset.sentryComponent)return n.dataset.sentryComponent;o.push(n.tagName.toLowerCase());const d=e&&e.length?e.filter((t=>n.getAttribute(t))).map((t=>[t,n.getAttribute(t)])):null;if(d&&d.length)d.forEach((t=>{o.push(`[${t[0]}="${t[1]}"]`)}));else if(n.id&&o.push(`#${n.id}`),r=n.className,r&&(0,s.Kg)(r))for(c=r.split(/\s+/),l=0;l`${encodeURIComponent(e)}=${encodeURIComponent(t[e])}`)).join("&")}function C(t){if((0,s.bJ)(t))return{message:t.message,name:t.name,stack:t.stack,...b(t)};if((0,s.xH)(t)){const e={type:t.type,target:p(t.target),currentTarget:p(t.currentTarget),...b(t)};return"undefined"!=typeof CustomEvent&&(0,s.tH)(t,CustomEvent)&&(e.detail=t.detail),e}return t}function p(t){try{return(0,s.vq)(t)?function(t,e={}){if(!t)return"";try{let n=t;const s=5,i=[];let c=0,a=0;const g=" > ",l=g.length;let d;const I=Array.isArray(e)?e:e.keyAttrs,u=!Array.isArray(e)&&e.maxStringLength||o;for(;n&&c++1&&a+i.length*l+d.length>=u));)i.push(d),a+=d.length,n=n.parentNode;return i.reverse().join(g)}catch(t){return""}}(t):Object.prototype.toString.call(t)}catch(t){return""}}function b(t){if("object"==typeof t&&null!==t){const e={};for(const n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e}return{}}function h(t,e=40){const n=Object.keys(C(t));if(n.sort(),!n.length)return"[object has no keys]";if(n[0].length>=e)return(0,g.xv)(n[0],e);for(let t=n.length;t>0;t--){const s=n.slice(0,t).join(", ");if(!(s.length>e))return t===n.length?s:(0,g.xv)(s,e)}return""}function m(t){return Z(t,new Map)}function Z(t,e){if(function(t){if(!(0,s.Qd)(t))return!1;try{const e=Object.getPrototypeOf(t).constructor.name;return!e||"Object"===e}catch(t){return!0}}(t)){const n=e.get(t);if(void 0!==n)return n;const s={};e.set(t,s);for(const n of Object.keys(t))void 0!==t[n]&&(s[n]=Z(t[n],e));return s}if(Array.isArray(t)){const n=e.get(t);if(void 0!==n)return n;const s=[];return e.set(t,s),t.forEach((t=>{s.push(Z(t,e))})),s}return t}},7930:(t,e,n)=>{"use strict";function s(t,e=!1){return!(e||t&&!t.startsWith("/")&&!t.match(/^[A-Z]:/)&&!t.startsWith(".")&&!t.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//)||void 0===t||t.includes("node_modules/"))}function i(t){const e=/^\s*[-]{4,}$/,n=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/;return i=>{const o=i.match(n);if(o){let e,n,i,r,c;if(o[1]){i=o[1];let t=i.lastIndexOf(".");if("."===i[t-1]&&t--,t>0){e=i.slice(0,t),n=i.slice(t+1);const s=e.indexOf(".Module");s>0&&(i=i.slice(s+1),e=e.slice(0,s))}r=void 0}n&&(r=e,c=n),""===n&&(c=void 0,i=void 0),void 0===i&&(c=c||"",i=r?`${r}.${c}`:c);let a=o[2]&&o[2].startsWith("file://")?o[2].slice(7):o[2];const g="native"===o[5];return a&&a.match(/\/[A-Z]:/)&&(a=a.slice(1)),a||!o[5]||g||(a=o[5]),{filename:a,module:t?t(a):void 0,function:i,lineno:parseInt(o[3],10)||void 0,colno:parseInt(o[4],10)||void 0,in_app:s(a,g)}}if(i.match(e))return{filename:i}}}n.d(e,{gd:()=>a,qQ:()=>d,o:()=>I,vk:()=>g});const o=50,r=/\(error: (.*)\)/,c=/captureMessage|captureException/;function a(...t){const e=t.sort(((t,e)=>t[0]-e[0])).map((t=>t[1]));return(t,n=0)=>{const s=[],i=t.split("\n");for(let t=n;t1024)continue;const c=r.test(n)?n.replace(r,"$1"):n;if(!c.match(/\S*Error: /)){for(const t of e){const e=t(c);if(e){s.push(e);break}}if(s.length>=o)break}}return function(t){if(!t.length)return[];const e=Array.from(t);return/sentryWrapped/.test(e[e.length-1].function||"")&&e.pop(),e.reverse(),c.test(e[e.length-1].function||"")&&(e.pop(),c.test(e[e.length-1].function||"")&&e.pop()),e.slice(0,o).map((t=>({...t,filename:t.filename||e[e.length-1].filename,function:t.function||"?"})))}(s)}}function g(t){return Array.isArray(t)?a(...t):t}const l="";function d(t){try{return t&&"function"==typeof t&&t.name||l}catch(t){return l}}function I(t){return[90,i(t)]}},9653:(t,e,n)=>{"use strict";n.d(e,{Xr:()=>c,gt:()=>r,nC:()=>o,xv:()=>i});var s=n(3816);function i(t,e=0){return"string"!=typeof t||0===e||t.length<=e?t:`${t.slice(0,e)}...`}function o(t,e){let n=t;const s=n.length;if(s<=150)return n;e>s&&(e=s);let i=Math.max(e-60,0);i<5&&(i=0);let o=Math.min(i+140,s);return o>s-5&&(o=s),o===s&&(i=Math.max(o-140,0)),n=n.slice(i,o),i>0&&(n=`'{snip} ${n}`),ofunction(t,e,n=!1){return!!(0,s.Kg)(t)&&((0,s.gd)(e)?e.test(t):!!(0,s.Kg)(e)&&(n?t===e:t.includes(e)))}(t,e,n)))}},690:(t,e,n)=>{"use strict";n.d(e,{T2:()=>c,XW:()=>o,xg:()=>r});var s,i=n(3816);function o(t){return new c((e=>{e(t)}))}function r(t){return new c(((e,n)=>{n(t)}))}!function(t){t[t.PENDING=0]="PENDING",t[t.RESOLVED=1]="RESOLVED",t[t.REJECTED=2]="REJECTED"}(s||(s={}));class c{constructor(t){c.prototype.__init.call(this),c.prototype.__init2.call(this),c.prototype.__init3.call(this),c.prototype.__init4.call(this),this._state=s.PENDING,this._handlers=[];try{t(this._resolve,this._reject)}catch(t){this._reject(t)}}then(t,e){return new c(((n,s)=>{this._handlers.push([!1,e=>{if(t)try{n(t(e))}catch(t){s(t)}else n(e)},t=>{if(e)try{n(e(t))}catch(t){s(t)}else s(t)}]),this._executeHandlers()}))}catch(t){return this.then((t=>t),t)}finally(t){return new c(((e,n)=>{let s,i;return this.then((e=>{i=!1,s=e,t&&t()}),(e=>{i=!0,s=e,t&&t()})).then((()=>{i?n(s):e(s)}))}))}__init(){this._resolve=t=>{this._setResult(s.RESOLVED,t)}}__init2(){this._reject=t=>{this._setResult(s.REJECTED,t)}}__init3(){this._setResult=(t,e)=>{this._state===s.PENDING&&((0,i.Qg)(e)?e.then(this._resolve,this._reject):(this._state=t,this._value=e,this._executeHandlers()))}}__init4(){this._executeHandlers=()=>{if(this._state===s.PENDING)return;const t=this._handlers.slice();this._handlers=[],t.forEach((t=>{t[0]||(this._state===s.RESOLVED&&t[1](this._value),this._state===s.REJECTED&&t[2](this._value),t[0]=!0)}))}}}},9297:(t,e,n)=>{"use strict";n.d(e,{lu:()=>o,zf:()=>r});var s=n(6341);const i=1e3;function o(){return Date.now()/i}const r=function(){const{performance:t}=s.OW;if(!t||!t.now)return o;const e=Date.now()-t.now(),n=null==t.timeOrigin?e:t.timeOrigin;return()=>(n+t.now())/i}();let c;(()=>{const{performance:t}=s.OW;if(!t||!t.now)return void(c="none");const e=36e5,n=t.now(),i=Date.now(),o=t.timeOrigin?Math.abs(t.timeOrigin+n-i):e,r=o{"use strict";n.d(e,{E0:()=>c,TC:()=>g,kM:()=>a,nc:()=>r});var s=n(5584),i=n(6936);const o=new RegExp("^[ \\t]*([0-9a-f]{32})?-?([0-9a-f]{16})?-?([01])?[ \\t]*$");function r(t){if(!t)return;const e=t.match(o);if(!e)return;let n;return"1"===e[3]?n=!0:"0"===e[3]&&(n=!1),{traceId:e[1],parentSampled:n,parentSpanId:e[2]}}function c(t,e){const n=r(t),o=(0,s.yD)(e),{traceId:c,parentSpanId:a,parentSampled:g}=n||{};return n?{traceparentData:n,dynamicSamplingContext:o||{},propagationContext:{traceId:c||(0,i.eJ)(),parentSpanId:a||(0,i.eJ)().substring(16),spanId:(0,i.eJ)().substring(16),sampled:g,dsc:o||{}}}:{traceparentData:n,dynamicSamplingContext:void 0,propagationContext:{traceId:c||(0,i.eJ)(),spanId:(0,i.eJ)().substring(16)}}}function a(t,e){const n=r(t),o=(0,s.yD)(e),{traceId:c,parentSpanId:a,parentSampled:g}=n||{};return n?{traceId:c||(0,i.eJ)(),parentSpanId:a||(0,i.eJ)().substring(16),spanId:(0,i.eJ)().substring(16),sampled:g,dsc:o||{}}:{traceId:c||(0,i.eJ)(),spanId:(0,i.eJ)().substring(16)}}function g(t=(0,i.eJ)(),e=(0,i.eJ)().substring(16),n){let s="";return void 0!==n&&(s=n?"-1":"-0"),`${t}-${e}${s}`}},6341:(t,e,n)=>{"use strict";function s(t){return t&&t.Math==Math?t:void 0}n.d(e,{BY:()=>r,OW:()=>i,VZ:()=>o});const i="object"==typeof globalThis&&s(globalThis)||"object"==typeof window&&s(window)||"object"==typeof self&&s(self)||"object"==typeof global&&s(global)||function(){return this}()||{};function o(){return i}function r(t,e,n){const s=n||i,o=s.__SENTRY__=s.__SENTRY__||{};return o[t]||(o[t]=e())}},9797:(t,e,n)=>{"use strict";const s=n(4865);t.exports=(t,e={})=>{if("function"!=typeof t)throw new TypeError(`Expected the first argument to be a function, got \`${typeof t}\``);const{wait:n=0,maxWait:i=0,before:o=!1,after:r=!0}=e;if(!o&&!r)throw new Error("Both `before` and `after` are false, function wouldn't be called.");let c,a,g;const l=function(...e){const s=this,l=o&&!c;return clearTimeout(c),c=setTimeout((()=>{c=void 0,a&&(clearTimeout(a),a=void 0),r&&(g=t.apply(s,e))}),n),i>0&&!a&&r&&(a=setTimeout((()=>{a=void 0,c&&(clearTimeout(c),c=void 0),g=t.apply(s,e)}),i)),l&&(g=t.apply(s,e)),g};return s(l,t),l.cancel=()=>{c&&(clearTimeout(c),c=void 0),a&&(clearTimeout(a),a=void 0)},l}},6022:t=>{!function(){"use strict";var e=[,function(t,e){function n(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,s=new Array(e);n255)throw new Error("Not ascii. Base64.encode can only take ascii strings.");t[n]=i}}for(var r=[],c=null,a=null,g=null,l=null,d=0;d>2&63,a=(3&t[d])<<4;break;case 1:a|=t[d]>>4&15,g=(15&t[d])<<2;break;case 2:g|=t[d]>>6&3,l=63&t[d],r.push(s(c)),r.push(s(a)),r.push(s(g)),r.push(s(l)),c=null,a=null,g=null,l=null}return null!=c&&(r.push(s(c)),r.push(s(a)),null==g?r.push("="):r.push(s(g)),null==l&&r.push("=")),r.join("")},decode:function(t){var e=Math.floor(3*t.length/4);"="==t.charAt(t.length-1)&&(e--,"="==t.charAt(t.length-2)&&e--);for(var s,i=o(e),r=null,c=null,a=null,g=0,l=0;l>4,i[g++]=r,c=(15&d)<<4;break;case 2:d>=0&&(c|=d>>2,i[g++]=c,a=(3&d)<<6);break;case 3:d>=0&&(i[g++]=a|d)}}return i},newBinary:o};e.Base64=r},function(t){t.exports={_noYieldsAllowed:function(t){return t()}}},function(t,e){function n(t){return n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},n(t)}function s(t){return JSON.stringify(t)}Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i=function t(e,i,o,r,c){var a=i[e];switch(n(a)){case"string":return s(a);case"number":return isFinite(a)?String(a):"null";case"boolean":return String(a);case"object":if(!a)return"null";var g,l=r+o,d=[];if(Array.isArray(a)||{}.hasOwnProperty.call(a,"callee")){for(var I=a.length,u=0;u0&&void 0!==arguments[0]&&arguments[0]?c:(0,o.convertMapToObject)(c)},r._getConverters=function(){return a};var g=function(t){for(var e=0;e=d.length||i!==d[s]||!r.equals(t[i],e[d[s]],n)||(s++,0))}))):(s=0,c=l.every((function(i){return!!(0,o.hasOwn)(e,i)&&!!r.equals(t[i],e[i],n)&&(s++,!0)}))),c&&s===d.length},r.clone=function(t){var e;if(!(0,o.isObject)(t))return t;if(null===t)return null;if(t instanceof Date)return new Date(t.getTime());if(t instanceof RegExp)return t;if(r.isBinary(t)){e=r.newBinary(t.length);for(var n=0;n{"use strict";var e=Object.prototype.hasOwnProperty,n="~";function s(){}function i(t,e,n){this.fn=t,this.context=e,this.once=n||!1}function o(t,e,s,o,r){if("function"!=typeof s)throw new TypeError("The listener must be a function");var c=new i(s,o||t,r),a=n?n+e:e;return t._events[a]?t._events[a].fn?t._events[a]=[t._events[a],c]:t._events[a].push(c):(t._events[a]=c,t._eventsCount++),t}function r(t,e){0==--t._eventsCount?t._events=new s:delete t._events[e]}function c(){this._events=new s,this._eventsCount=0}Object.create&&(s.prototype=Object.create(null),(new s).__proto__||(n=!1)),c.prototype.eventNames=function(){var t,s,i=[];if(0===this._eventsCount)return i;for(s in t=this._events)e.call(t,s)&&i.push(n?s.slice(1):s);return Object.getOwnPropertySymbols?i.concat(Object.getOwnPropertySymbols(t)):i},c.prototype.listeners=function(t){var e=n?n+t:t,s=this._events[e];if(!s)return[];if(s.fn)return[s.fn];for(var i=0,o=s.length,r=new Array(o);i{"use strict";t.exports=function t(e,n){if(e===n)return!0;if(e&&n&&"object"==typeof e&&"object"==typeof n){if(e.constructor!==n.constructor)return!1;var s,i,o;if(Array.isArray(e)){if((s=e.length)!=n.length)return!1;for(i=s;0!=i--;)if(!t(e[i],n[i]))return!1;return!0}if(e.constructor===RegExp)return e.source===n.source&&e.flags===n.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===n.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===n.toString();if((s=(o=Object.keys(e)).length)!==Object.keys(n).length)return!1;for(i=s;0!=i--;)if(!Object.prototype.hasOwnProperty.call(n,o[i]))return!1;for(i=s;0!=i--;){var r=o[i];if(!t(e[r],n[r]))return!1}return!0}return e!=e&&n!=n}},4865:t=>{"use strict";const e=(t,e,s,i)=>{if("length"===s||"prototype"===s)return;if("arguments"===s||"caller"===s)return;const o=Object.getOwnPropertyDescriptor(t,s),r=Object.getOwnPropertyDescriptor(e,s);!n(o,r)&&i||Object.defineProperty(t,s,r)},n=function(t,e){return void 0===t||t.configurable||t.writable===e.writable&&t.enumerable===e.enumerable&&t.configurable===e.configurable&&(t.writable||t.value===e.value)},s=(t,e)=>`/* Wrapped ${t}*/\n${e}`,i=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),o=Object.getOwnPropertyDescriptor(Function.prototype.toString,"name");t.exports=(t,n,{ignoreNonConfigurable:r=!1}={})=>{const{name:c}=t;for(const s of Reflect.ownKeys(n))e(t,n,s,r);return((t,e)=>{const n=Object.getPrototypeOf(e);n!==Object.getPrototypeOf(t)&&Object.setPrototypeOf(t,n)})(t,n),((t,e,n)=>{const r=""===n?"":`with ${n.trim()}() `,c=s.bind(null,r,e.toString());Object.defineProperty(c,"name",o),Object.defineProperty(t,"toString",{...i,value:c})})(t,n,c),t}},4617:t=>{"use strict";t.exports=(t,e)=>(e=e||(()=>{}),t.then((t=>new Promise((t=>{t(e())})).then((()=>t))),(t=>new Promise((t=>{t(e())})).then((()=>{throw t})))))},3290:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0});const s=n(228),i=n(7685),o=n(4774),r=()=>{},c=new i.TimeoutError;e.default=class extends s{constructor(t){var e,n,s,i;if(super(),this._intervalCount=0,this._intervalEnd=0,this._pendingCount=0,this._resolveEmpty=r,this._resolveIdle=r,!("number"==typeof(t=Object.assign({carryoverConcurrencyCount:!1,intervalCap:1/0,interval:0,concurrency:1/0,autoStart:!0,queueClass:o.default},t)).intervalCap&&t.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${null!==(n=null===(e=t.intervalCap)||void 0===e?void 0:e.toString())&&void 0!==n?n:""}\` (${typeof t.intervalCap})`);if(void 0===t.interval||!(Number.isFinite(t.interval)&&t.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${null!==(i=null===(s=t.interval)||void 0===s?void 0:s.toString())&&void 0!==i?i:""}\` (${typeof t.interval})`);this._carryoverConcurrencyCount=t.carryoverConcurrencyCount,this._isIntervalIgnored=t.intervalCap===1/0||0===t.interval,this._intervalCap=t.intervalCap,this._interval=t.interval,this._queue=new t.queueClass,this._queueClass=t.queueClass,this.concurrency=t.concurrency,this._timeout=t.timeout,this._throwOnTimeout=!0===t.throwOnTimeout,this._isPaused=!1===t.autoStart}get _doesIntervalAllowAnother(){return this._isIntervalIgnored||this._intervalCount{this._onResumeInterval()}),e)),!0;this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0}return!1}_tryToStartAnother(){if(0===this._queue.size)return this._intervalId&&clearInterval(this._intervalId),this._intervalId=void 0,this._resolvePromises(),!1;if(!this._isPaused){const t=!this._isIntervalPaused();if(this._doesIntervalAllowAnother&&this._doesConcurrentAllowAnother){const e=this._queue.dequeue();return!!e&&(this.emit("active"),e(),t&&this._initializeIntervalIfNeeded(),!0)}}return!1}_initializeIntervalIfNeeded(){this._isIntervalIgnored||void 0!==this._intervalId||(this._intervalId=setInterval((()=>{this._onInterval()}),this._interval),this._intervalEnd=Date.now()+this._interval)}_onInterval(){0===this._intervalCount&&0===this._pendingCount&&this._intervalId&&(clearInterval(this._intervalId),this._intervalId=void 0),this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0,this._processQueue()}_processQueue(){for(;this._tryToStartAnother(););}get concurrency(){return this._concurrency}set concurrency(t){if(!("number"==typeof t&&t>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${t}\` (${typeof t})`);this._concurrency=t,this._processQueue()}async add(t,e={}){return new Promise(((n,s)=>{this._queue.enqueue((async()=>{this._pendingCount++,this._intervalCount++;try{const o=void 0===this._timeout&&void 0===e.timeout?t():i.default(Promise.resolve(t()),void 0===e.timeout?this._timeout:e.timeout,(()=>{(void 0===e.throwOnTimeout?this._throwOnTimeout:e.throwOnTimeout)&&s(c)}));n(await o)}catch(t){s(t)}this._next()}),e),this._tryToStartAnother(),this.emit("add")}))}async addAll(t,e){return Promise.all(t.map((async t=>this.add(t,e))))}start(){return this._isPaused?(this._isPaused=!1,this._processQueue(),this):this}pause(){this._isPaused=!0}clear(){this._queue=new this._queueClass}async onEmpty(){if(0!==this._queue.size)return new Promise((t=>{const e=this._resolveEmpty;this._resolveEmpty=()=>{e(),t()}}))}async onIdle(){if(0!==this._pendingCount||0!==this._queue.size)return new Promise((t=>{const e=this._resolveIdle;this._resolveIdle=()=>{e(),t()}}))}get size(){return this._queue.size}sizeBy(t){return this._queue.filter(t).length}get pending(){return this._pendingCount}get isPaused(){return this._isPaused}get timeout(){return this._timeout}set timeout(t){this._timeout=t}}},9998:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t,e,n){let s=0,i=t.length;for(;i>0;){const o=i/2|0;let r=s+o;n(t[r],e)<=0?(s=++r,i-=o+1):i=o}return s}},4774:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0});const s=n(9998);e.default=class{constructor(){this._queue=[]}enqueue(t,e){const n={priority:(e=Object.assign({priority:0},e)).priority,run:t};if(this.size&&this._queue[this.size-1].priority>=e.priority)return void this._queue.push(n);const i=s.default(this._queue,n,((t,e)=>e.priority-t.priority));this._queue.splice(i,0,n)}dequeue(){const t=this._queue.shift();return null==t?void 0:t.run}filter(t){return this._queue.filter((e=>e.priority===t.priority)).map((t=>t.run))}get size(){return this._queue.length}}},7685:(t,e,n)=>{"use strict";const s=n(4617);class i extends Error{constructor(t){super(t),this.name="TimeoutError"}}const o=(t,e,n)=>new Promise(((o,r)=>{if("number"!=typeof e||e<0)throw new TypeError("Expected `milliseconds` to be a positive number");if(e===1/0)return void o(t);const c=setTimeout((()=>{if("function"==typeof n){try{o(n())}catch(t){r(t)}return}const s=n instanceof Error?n:new i("string"==typeof n?n:`Promise timed out after ${e} milliseconds`);"function"==typeof t.cancel&&t.cancel(),r(s)}),e);s(t.then(o,r),(()=>{clearTimeout(c)}))}));t.exports=o,t.exports.default=o,t.exports.TimeoutError=i},6982:t=>{"use strict";t.exports=require("crypto")},7194:t=>{"use strict";t.exports=require("dgram")},1637:t=>{"use strict";t.exports=require("diagnostics_channel")},1943:t=>{"use strict";t.exports=require("fs/promises")},8611:t=>{"use strict";t.exports=require("http")},5692:t=>{"use strict";t.exports=require("https")},264:t=>{"use strict";t.exports=require("inspector")},9278:t=>{"use strict";t.exports=require("net")},2203:t=>{"use strict";t.exports=require("stream")},7016:t=>{"use strict";t.exports=require("url")},4581:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0})},4326:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.runEntrypoint=void 0;const s=n(1635),i=n(9967),o=s.__importDefault(n(1943)),r=n(360),c=n(6497);n(5664);const a=n(4044);let g,l=!1;e.runEntrypoint=function(t,e){Promise.resolve().then((async()=>{if(l)throw new Error("runEntrypoint can only be called once");l=!0;const n=process.env.MODULE_MANIFEST;if(!n)throw new Error("Module initialise is missing MODULE_MANIFEST");const s=await o.default.readFile(n),d=JSON.parse(s.toString());if(d.runtime?.api!==i.HostApiNodeJsIpc)throw new Error("Module manifest 'api' mismatch");if(!d.runtime.apiVersion)throw new Error("Module manifest 'apiVersion' missing");const I=d.runtime.apiVersion;if(!process.send)throw new Error("Module is not being run with ipc");console.log(`Starting up module class: ${t.name}`);const u=process.env.CONNECTION_ID;if("string"!=typeof u||!u)throw new Error("Module initialise is missing CONNECTION_ID");const C=process.env.VERIFICATION_TOKEN;if("string"!=typeof C||!C)throw new Error("Module initialise is missing VERIFICATION_TOKEN");const p=process.env.SENTRY_DSN,b=process.env.SENTRY_USERID,h=process.env.SENTRY_COMPANION_VERSION;p&&b&&"https://"==p.substring(0,8)?(console.log("Sentry enabled"),(0,c.init)({dsn:p,release:`${d.name}@${d.version}`,beforeSend:t=>(t.exception&&console.log("sentry","error",t.exception),t)}),(0,c.configureScope)((t=>{t.setUser({id:b}),t.setTag("companion",h)}))):console.log("Sentry disabled");const m=new a.IpcWrapper({},(t=>{process.send(t)}),5e3);process.once("message",(t=>{m.receivedMessage(t)})),g=new t((0,r.literal)({id:u,upgradeScripts:e,_isInstanceBaseProps:!0})),m.sendWithCb("register",{apiVersion:I,connectionId:u,verificationToken:C}).then((()=>{console.log("Module-host accepted registration")}),(t=>{console.error("Module registration failed",t),process.exit(11)}))})).catch((t=>{console.error("Failed to startup module:"),console.error(t.stack||t.message),process.exit(1)}))}},6160:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.UDPHelper=e.TelnetHelper=e.TCPHelper=void 0;var s=n(8895);Object.defineProperty(e,"TCPHelper",{enumerable:!0,get:function(){return s.TCPHelper}});var i=n(1118);Object.defineProperty(e,"TelnetHelper",{enumerable:!0,get:function(){return i.TelnetHelper}});var o=n(6259);Object.defineProperty(e,"UDPHelper",{enumerable:!0,get:function(){return o.UDPHelper}})},8895:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.TCPHelper=void 0;const s=n(1635).__importDefault(n(9278)),i=n(228),o=n(1400);class r extends i.EventEmitter{#t;#e;_socket;#n;#s=!1;#i=!1;#o=!1;#r;#c;get isConnected(){return this.#s}get isConnecting(){return this.#i}get isDestroyed(){return this.#o}constructor(t,e,n){super(),this.#t=t,this.#e=e,this.#n={reconnect_interval:2e3,reconnect:!0,...n},this._socket=new s.default.Socket,this._socket.setKeepAlive(!0),this._socket.setNoDelay(!0),this._socket.on("error",(t=>{this.#i=!1,this.#s=!1,this.#n.reconnect&&this.#a(),this.#g(o.InstanceStatus.UnknownError,t.message),this.emit("error",t)})),this._socket.on("ready",(()=>{this.#s=!0,this.#i=!1,this.#g(o.InstanceStatus.Ok),this.emit("connect")})),this._socket.on("end",(()=>{this.#s=!1,this.#g(o.InstanceStatus.Disconnected),!this.#i&&this.#n.reconnect&&this.#a(),this.emit("end")})),this._socket.on("data",(t=>this.emit("data",t))),this._socket.on("drain",(()=>this.emit("drain"))),setImmediate((()=>this.connect())),setTimeout((()=>{this.#o||this.listenerCount("error")||console.error(`Danger: TCP client for ${this.#t}:${this.#e} is missing an error handler!`)}),5e3)}connect(){if(this.#o)throw new Error("Cannot connect destroyed socket");return!this.#i&&(this.#i=!0,this._socket.connect(this.#e,this.#t),!0)}async send(t){if(this.#o||this._socket.destroyed)throw new Error("Cannot write to destroyed socket");if(!t||!t.length)throw new Error("No message to send");if(!this.#s)return!1;try{return new Promise(((e,n)=>{this._socket.write(t,(t=>{t?n(t):e(!0)}))}))}catch(t){this.#s=!1;const e=t instanceof Error?t:new Error(`${t}`);throw this.#g(o.InstanceStatus.UnknownError,e.message),this.emit("error",e),e}}destroy(){this.#o=!0,void 0!==this.#c&&clearTimeout(this.#c),this._socket.removeAllListeners(),this.removeAllListeners(),this._socket.destroy()}#a(){void 0!==this.#c&&clearTimeout(this.#c),this.#c=setTimeout((()=>{this.#c=void 0,this.#g(o.InstanceStatus.Connecting),this.connect()}),this.#n.reconnect_interval)}#g(t,e){this.#r!=t&&(this.#r=t,this.emit("status_change",t,e))}}e.TCPHelper=r},1118:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.TelnetHelper=void 0;const s=n(1635).__importDefault(n(228)),i=n(2203),o=n(8895);class r extends s.default{#l;#d;get isConnected(){return this.#l.isConnected}get isConnecting(){return this.#l.isConnecting}get isDestroyed(){return this.#l.isDestroyed}constructor(t,e,n){super(),this.#l=new o.TCPHelper(t,e,n),this.#d=new c,this.#l._socket.pipe(this.#d),this.#l.on("connect",(()=>this.emit("connect"))),this.#l.on("end",(()=>this.emit("end"))),this.#l.on("error",(t=>this.emit("error",t))),this.#l.on("status_change",((t,e)=>this.emit("status_change",t,e))),this.#d.on("iac",((t,e)=>this.emit("iac",t,e))),this.#d.on("sb",(t=>this.emit("sb",t))),this.#d.on("data",(t=>this.emit("data",t))),this.#d.on("drain",(()=>this.emit("drain"))),setTimeout((()=>{this.isDestroyed||this.listenerCount("error")||console.error(`Danger: Telnet client for ${t}:${e} is missing an error handler!`)}),5e3)}connect(){return this.#l.connect()}async send(t){return this.#l.send(t)}destroy(){this.#l.destroy(),this.#d.removeAllListeners(),this.#d.destroy()}}e.TelnetHelper=r;class c extends i.Transform{#I;#u;#C;constructor(t){super(t),this.#I=Buffer.alloc(0),this.#u=Buffer.alloc(0),this.#C=0}_transform(t,e,n){for(let e=0;e=251&&this.#C<=254){let e;switch(this.#C){case 251:e="WILL";break;case 252:e="WONT";break;case 253:e="DO";break;case 254:e="DONT";break;default:return}return this.emit("iac",e,t),void(this.#C=0)}if(250===this.#C){if(240===t)return this.emit("sb",this.#u),this.#C=0,void(this.#u=Buffer.alloc(0));this.#u=Buffer.concat([this.#u,Buffer.from([t])])}}}#b(){const t=this.#I;return this.#I=Buffer.alloc(0),t}}},6259:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.UDPHelper=void 0;const s=n(1635).__importDefault(n(7194)),i=n(228),o=n(1400);class r extends i.EventEmitter{#t;#e;#h;#n;#o=!1;#r;get isDestroyed(){return this.#o}constructor(t,e,n){super(),this.#t=t,this.#e=e,this.#n={...n},this.#h=s.default.createSocket("udp4");try{this.#h.bind(this.#n.bind_port||0,this.#n.bind_ip)}catch(t){throw new Error(`Unable to bind to ip/port: ${this.#n.bind_ip}:${this.#n.bind_port}`)}this.#n.broadcast&&this.#h.setBroadcast(!0),void 0!==this.#n.ttl&&this.#h.setTTL(this.#n.ttl),void 0!==this.#n.multicast_ttl&&this.#h.setMulticastTTL(this.#n.multicast_ttl),this.#h.on("error",(t=>{this.#g(o.InstanceStatus.UnknownError,t.message),this.emit("error",t)})),this.#h.on("listening",(()=>{this.#n.multicast_interface&&this.#h.setMulticastInterface(this.#n.multicast_interface),this.#g(o.InstanceStatus.Ok),this.emit("listening")})),this.#h.on("message",(t=>this.emit("data",t))),setTimeout((()=>{this.#o||this.listenerCount("error")||console.error(`Danger: UDP socket for ${this.#t}:${this.#e} is missing an error handler!`)}),5e3)}async send(t){if(this.#o)throw new Error("Cannot write to destroyed socket");if(!t||!t.length)throw new Error("No message to send");return new Promise(((e,n)=>{this.#h.send(t,this.#e,this.#t,(t=>{t?n(t):e()}))}))}destroy(){this.#o=!0,this.#h.removeAllListeners(),this.#h.close(),this.removeAllListeners()}#g(t,e){this.#r!=t&&(this.#r=t,this.emit("status_change",t,e))}}e.UDPHelper=r},4044:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.IpcWrapper=void 0;const s=n(1635),i=n(1154),o=n(360),r=s.__importDefault(n(6022));e.IpcWrapper=class{#m;#Z;#G;#B={};constructor(t,e,n){this.#m=t,this.#Z=e,this.#G=n}async sendWithCb(t,e,n,s=0){s<=0&&(s=this.#G);const o={timeout:void 0,resolve:()=>null,reject:()=>null},c=new Promise(((t,e)=>{o.resolve=t,o.reject=e})),a=(0,i.nanoid)();this.#B[a]=o,this.#Z({direction:"call",name:String(t),payload:r.default.stringify(e),callbackId:a});const g=new Error("Call timed out");return o.timeout=setTimeout((()=>{o.reject(n?n():g)}),s),c}sendWithNoCb(t,e){this.#Z({direction:"call",name:String(t),payload:r.default.stringify(e),callbackId:void 0})}receivedMessage(t){const e=t;switch(t.direction){case"call":{const e=this.#m[t.name];if(!e)return void(t.callbackId&&this.#Z({direction:"response",callbackId:t.callbackId,success:!1,payload:r.default.stringify({message:`Unknown command "${t.name}"`})}));e(t.payload?r.default.parse(t.payload):void 0).then((e=>{t.callbackId&&this.#Z({direction:"response",callbackId:t.callbackId,success:!0,payload:r.default.stringify(e)})}),(e=>{t.callbackId&&this.#Z({direction:"response",callbackId:t.callbackId,success:!1,payload:e instanceof Error?JSON.stringify(e,Object.getOwnPropertyNames(e)):r.default.stringify(e)})}));break}case"response":{if(!t.callbackId)return void console.error("Ipc: Response message has no callbackId");const e=this.#B[t.callbackId];if(!e)return;clearTimeout(e.timeout);const n=t.payload?r.default.parse(t.payload):void 0;if(t.success)e.resolve(n);else{let t=n;n&&"message"in n&&(t=new Error(n.message),n.stack&&(t.stack=n.stack)),e.reject(t)}break}default:(0,o.assertNever)(t),console.error(`Ipc: Message of unknown direction "${e.direction}"`)}}}},9967:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.HostApiNodeJsIpc=void 0,e.HostApiNodeJsIpc="nodejs-ipc"},6278:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.runEntrypoint=e.assertNever=e.splitRgb=e.combineRgb=e.literal=void 0;const s=n(1635);s.__exportStar(n(9077),e),s.__exportStar(n(2018),e),s.__exportStar(n(4581),e);var i=n(360);Object.defineProperty(e,"literal",{enumerable:!0,get:function(){return i.literal}}),Object.defineProperty(e,"combineRgb",{enumerable:!0,get:function(){return i.combineRgb}}),Object.defineProperty(e,"splitRgb",{enumerable:!0,get:function(){return i.splitRgb}}),Object.defineProperty(e,"assertNever",{enumerable:!0,get:function(){return i.assertNever}}),s.__exportStar(n(6160),e);var o=n(4326);Object.defineProperty(e,"runEntrypoint",{enumerable:!0,get:function(){return o.runEntrypoint}})},4289:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.ActionManager=void 0;const s=n(2593);function i(t){return{id:t.id,actionId:t.actionId,controlId:t.controlId,options:t.options}}e.ActionManager=class{#y;#A;#W;#V=new Map;#v=new Map;constructor(t,e,n){this.#y=t,this.#A=e,this.#W=n}async handleExecuteAction(t){const e=this.#V.get(t.action.actionId);if(!e)throw new Error(`Unknown action: ${t.action.actionId}`);const n={parseVariablesInString:async e=>(await this.#y({text:e,controlId:t.action.controlId,actionInstanceId:t.action.id,feedbackInstanceId:void 0})).text};await e.callback({id:t.action.id,actionId:t.action.actionId,controlId:t.action.controlId,options:t.action.options,_deviceId:t.deviceId,_page:t.action.page,_bank:t.action.bank},n)}handleUpdateActions(t){for(const[e,n]of Object.entries(t)){const t=this.#v.get(e);if(t){const e=this.#V.get(t.actionId);if(e?.unsubscribe){const n={parseVariablesInString:async e=>(await this.#y({text:e,controlId:t.controlId,actionInstanceId:t.id,feedbackInstanceId:void 0})).text};Promise.resolve(e.unsubscribe(i(t),n)).catch((e=>{this.#W("error",`Action unsubscribe failed: ${JSON.stringify(t)} - ${e?.message??e} ${e?.stack}`)}))}}if(!n||n.disabled)this.#v.delete(e);else{this.#v.set(e,n);const t=this.#V.get(n.actionId);if(t?.subscribe){const e={parseVariablesInString:async t=>(await this.#y({text:t,controlId:n.controlId,actionInstanceId:n.id,feedbackInstanceId:void 0})).text};Promise.resolve(t.subscribe(i(n),e)).catch((t=>{this.#W("error",`Action subscribe failed: ${JSON.stringify(n)} - ${t?.message??t} ${t?.stack}`)}))}}}}async handleLearnAction(t){const e=this.#V.get(t.action.actionId);if(e&&e.learn){const n={parseVariablesInString:async e=>(await this.#y({text:e,controlId:t.action.controlId,actionInstanceId:t.action.id,feedbackInstanceId:void 0})).text};return{options:await e.learn({id:t.action.id,actionId:t.action.actionId,controlId:t.action.controlId,options:t.action.options,_deviceId:void 0,_page:t.action.page,_bank:t.action.bank},n)}}return{options:void 0}}setActionDefinitions(t){const e=[];this.#V.clear();for(const[n,i]of Object.entries(t))i&&(e.push({id:n,name:i.name,description:i.description,options:(0,s.serializeIsVisibleFn)(i.options),hasLearn:!!i.learn}),this.#V.set(n,i));this.#A({actions:e})}_getAllActions(){return Array.from(this.#v.values()).map((t=>({id:t.id,actionId:t.actionId,controlId:t.controlId,options:t.options})))}subscribeActions(t){let e=Array.from(this.#v.values());const n=new Set(t);n.size&&(e=e.filter((t=>n.has(t.actionId))));for(const t of e){const e=this.#V.get(t.actionId);if(e?.subscribe){const n={parseVariablesInString:async e=>(await this.#y({text:e,controlId:t.controlId,actionInstanceId:t.id,feedbackInstanceId:void 0})).text};Promise.resolve(e.subscribe(i(t),n)).catch((e=>{this.#W("error",`Action subscribe failed: ${JSON.stringify(t)} - ${e?.message??e} ${e?.stack}`)}))}}}unsubscribeActions(t){let e=Array.from(this.#v.values());const n=new Set(t);n.size&&(e=e.filter((t=>n.has(t.actionId))));for(const t of e){const e=this.#V.get(t.actionId);if(e&&e.unsubscribe){const n={parseVariablesInString:async e=>(await this.#y({text:e,controlId:t.controlId,actionInstanceId:t.id,feedbackInstanceId:void 0})).text};Promise.resolve(e.unsubscribe(i(t),n)).catch((e=>{this.#W("error",`Action unsubscribe failed: ${JSON.stringify(t)} - ${e?.message??e} ${e?.stack}`)}))}}}}},2593:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.isInstanceBaseProps=e.serializeIsVisibleFn=void 0,e.serializeIsVisibleFn=function(t){return t.map((t=>"isVisible"in t&&"function"==typeof t.isVisible?{...t,isVisibleFn:t.isVisible.toString(),isVisible:void 0}:{...t,isVisibleFn:void 0}))},e.isInstanceBaseProps=function(t){const e=t;return"object"==typeof e&&"string"==typeof e.id&&!0===e._isInstanceBaseProps}},8039:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.FeedbackManager=void 0;const s=n(1635),i=n(2593),o=s.__importDefault(n(9797));function r(t,e){return{type:t,id:e.id,feedbackId:e.feedbackId,controlId:e.controlId,options:e.options}}e.FeedbackManager=class{#y;#f;#R;#W;#Y=new Map;#X=new Map;#H=new Map;#S=new Map;#N;get parseVariablesContext(){return this.#N}constructor(t,e,n,s){this.#y=t,this.#f=e,this.#R=n,this.#W=s}getDefinitionIds(){return Array.from(this.#Y.keys())}getInstanceIds(){return Array.from(this.#X.keys())}handleUpdateFeedbacks(t){for(const[e,n]of Object.entries(t)){const t=this.#X.get(e);if(t){const e=this.#Y.get(t.feedbackId);if(e?.unsubscribe){const n={parseVariablesInString:async e=>(await this.#y({text:e,controlId:t.controlId,actionInstanceId:void 0,feedbackInstanceId:t.id})).text};Promise.resolve(e.unsubscribe(r(e.type,t),n)).catch((e=>{this.#W("error",`Feedback unsubscribe failed: ${JSON.stringify(t)} - ${e?.message??e} ${e?.stack}`)}))}}if(!n||n.disabled)this.#X.delete(e);else{this.#X.set(e,{...n,referencedVariables:null});const t=this.#Y.get(n.feedbackId);if(t?.subscribe){const e={parseVariablesInString:async t=>(await this.#y({text:t,controlId:n.controlId,actionInstanceId:void 0,feedbackInstanceId:n.id})).text};Promise.resolve(t.subscribe(r(t.type,n),e)).catch((t=>{this.#W("error",`Feedback subscribe failed: ${JSON.stringify(n)} - ${t?.message??t} ${t?.stack}`)}))}this.#K(e)}}}async handleLearnFeedback(t){const e=this.#Y.get(t.feedback.feedbackId);if(e&&e.learn){const n={parseVariablesInString:async e=>(await this.#y({text:e,controlId:t.feedback.controlId,actionInstanceId:void 0,feedbackInstanceId:t.feedback.id})).text};return{options:await e.learn({id:t.feedback.id,feedbackId:t.feedback.feedbackId,controlId:t.feedback.controlId,options:t.feedback.options,type:e.type},n)}}return{options:void 0}}handleVariablesChanged(t){if(!t.variablesIds.length)return;const e=new Set(t.variablesIds);for(const e of this.#S.values())for(const n of t.variablesIds)e.changedVariables.add(n);const n=new Set;for(const t of this.#X.values())if(!this.#S.has(t.id)&&t.referencedVariables)for(const s of t.referencedVariables)if(e.has(s)){n.add(t.id);break}for(const t of n)setImmediate((()=>{this.#K(t)}))}#K(t){const e=this.#S.get(t);if(e)return void(e.needsRecheck=!0);const n=this.#X.get(t);if(!n)return;const s=n,i={needsRecheck:!1,changedVariables:new Set};this.#S.set(t,i),Promise.resolve().then((async()=>{const e=this.#Y.get(s.feedbackId);let n;const i=new Set;if(e){this.#N=`Feedback ${s.feedbackId} (${t})`;const o={parseVariablesInString:async e=>{const n=await this.#y({text:e,controlId:s.controlId,actionInstanceId:void 0,feedbackInstanceId:t});if(n.variableIds&&n.variableIds.length)for(const t of n.variableIds)i.add(t);return n.text}};n="boolean"===e.type?e.callback({...r("boolean",s),type:"boolean",_rawBank:s.rawBank},o):e.callback({...r("advanced",s),type:"advanced",image:s.image,_page:s.page,_bank:s.bank,_rawBank:s.rawBank},o),this.#N=void 0}const o=await n;this.#H.set(t,{id:t,controlId:s.controlId,value:o}),this.#w(),s.referencedVariables=i.size>0?Array.from(i):null})).catch((t=>{console.error(`Feedback check failed: ${JSON.stringify(s)} - ${t?.message??t} ${t?.stack}`)})).finally((()=>{this.#N=void 0,this.#S.delete(t);let e=!1;if(s.referencedVariables)for(const t of s.referencedVariables)if(i.changedVariables.has(t)){e=!0;break}(e||i.needsRecheck)&&setImmediate((()=>{this.#K(t)}))}))}#w=(0,o.default)((()=>{const t=this.#H;this.#H=new Map,t.size>0&&this.#f({values:Array.from(t.values())})}),{wait:5,maxWait:25});setFeedbackDefinitions(t){const e=[];this.#Y.clear();for(const[n,s]of Object.entries(t))s&&(e.push({id:n,name:s.name,description:s.description,options:(0,i.serializeIsVisibleFn)(s.options),type:s.type,defaultStyle:"defaultStyle"in s?s.defaultStyle:void 0,hasLearn:!!s.learn}),this.#Y.set(n,s));this.#R({feedbacks:e})}checkFeedbacks(t){const e=new Set(t);for(const[t,n]of this.#X.entries())this.#Y.get(n.feedbackId)&&(0===e.size||e.has(n.feedbackId))&&this.#K(t)}checkFeedbacksById(t){for(const e of t)this.#K(e)}_getAllFeedbacks(){return Array.from(this.#X.values()).map((t=>({id:t.id,feedbackId:t.feedbackId,controlId:t.controlId,options:t.options})))}subscribeFeedbacks(t){let e=Array.from(this.#X.values());const n=new Set(t);n.size&&(e=e.filter((t=>n.has(t.feedbackId))));for(const t of e){const e=this.#Y.get(t.feedbackId);if(e?.subscribe){const n={parseVariablesInString:async e=>(await this.#y({text:e,controlId:t.controlId,actionInstanceId:void 0,feedbackInstanceId:t.id})).text};Promise.resolve(e.subscribe(r(e.type,t),n)).catch((e=>{this.#W("error",`Feedback subscribe failed: ${JSON.stringify(t)} - ${e?.message??e} ${e?.stack}`)}))}}}unsubscribeFeedbacks(t){let e=Array.from(this.#X.values());const n=new Set(t);n.size&&(e=e.filter((t=>n.has(t.feedbackId))));for(const t of e){const e=this.#Y.get(t.feedbackId);if(e&&e.unsubscribe){const n={parseVariablesInString:async e=>(await this.#y({text:e,controlId:t.controlId,actionInstanceId:void 0,feedbackInstanceId:t.id})).text};Promise.resolve(e.unsubscribe(r(e.type,t),n)).catch((e=>{this.#W("error",`Feedback unsubscribe failed: ${JSON.stringify(t)} - ${e?.message??e} ${e?.stack}`)}))}}}}},1706:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.runThroughUpgradeScripts=void 0,e.runThroughUpgradeScripts=function(t,e,n,s,i){const o=new Map,r=t=>{let e=o.get(t);return e||(e={actions:[],feedbacks:[]},o.set(t,e)),e};for(const e of Object.values(t)){const t=e?.upgradeIndex??n;e&&"number"==typeof t&&r(t).actions.push(e.id)}for(const t of Object.values(e)){const e=t?.upgradeIndex??n;t&&"number"==typeof e&&r(e).feedbacks.push(t.id)}const c={},a={};if(o.size>0){const r=Array.from(o.keys()).sort(),g=Math.min(...r,n??Number.POSITIVE_INFINITY)+1,l=[],d=[],I=s.length;for(let r=g;rn;if(!I&&0===l.length&&0===d.length)continue;const u=(0,s[r])({},{config:I?i:null,actions:l.map((e=>{const n=t[e];if(n)return{id:n.id,controlId:n.controlId,actionId:n.actionId,options:n.options}})).filter((t=>!!t)),feedbacks:d.map((t=>{const n=e[t];if(n)return{id:n.id,controlId:n.controlId,feedbackId:n.feedbackId,options:n.options}})).filter((t=>!!t))});I&&u.updatedConfig&&(i=u.updatedConfig);for(const e of u.updatedActions)if(e){const n=t[e.id];n&&(n.actionId=e.actionId,n.options=e.options,a[e.id]=n)}for(const t of u.updatedFeedbacks)if(t){const n=e[t.id];n&&(n.feedbackId=t.feedbackId,n.options=t.options,c[t.id]={...n,style:c[t.id]?.style??t.style})}}for(const[e,n]of Object.entries(t))a[e]||"number"!=typeof n?.upgradeIndex||(a[e]=n);for(const[t,n]of Object.entries(e))c[t]||"number"!=typeof n?.upgradeIndex||(c[t]=n)}return{updatedActions:a,updatedFeedbacks:c,updatedConfig:i}}},9077:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.validateManifest=void 0;const s=n(1635).__importDefault(n(7281));e.validateManifest=function(t){if(!(0,s.default)(t)){const t=s.default.errors;if(!t)throw new Error("Manifest failed validation with unknown reason");throw new Error(`Manifest validation failed: ${JSON.stringify(t)}`)}}},3730:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0})},1649:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.InstanceBase=void 0;const s=n(1635),i=n(360),o=s.__importDefault(n(3290)),r=n(2593),c=n(1706),a=n(8039),g=n(4044),l=n(4289);e.InstanceBase=class{#F;#J;id;#k=new o.default({concurrency:1});#_=!1;#z=!1;#U;#x;#T=new Map;#E=new Map;#n;get instanceOptions(){return this.#n}constructor(t){if(!(0,r.isInstanceBaseProps)(t)||!t._isInstanceBaseProps)throw new Error("Module instance is being constructed incorrectly. Make sure you aren't trying to do this manually");this.#n={disableVariableValidation:!1},this.#F=new g.IpcWrapper({init:this._handleInit.bind(this),destroy:this._handleDestroy.bind(this),updateConfig:this._handleConfigUpdate.bind(this),executeAction:this._handleExecuteAction.bind(this),updateFeedbacks:this._handleUpdateFeedbacks.bind(this),updateActions:this._handleUpdateActions.bind(this),getConfigFields:this._handleGetConfigFields.bind(this),handleHttpRequest:this._handleHttpRequest.bind(this),learnAction:this._handleLearnAction.bind(this),learnFeedback:this._handleLearnFeedback.bind(this),startStopRecordActions:this._handleStartStopRecordActions.bind(this),variablesChanged:this._handleVariablesChanged.bind(this)},(t=>{process.send(t)}),5e3),process.on("message",(t=>{this.#F.receivedMessage(t)})),this.#U=new l.ActionManager((async t=>this.#F.sendWithCb("parseVariablesInString",t)),(t=>this.#F.sendWithNoCb("setActionDefinitions",t)),this.log.bind(this)),this.#x=new a.FeedbackManager((async t=>this.#F.sendWithCb("parseVariablesInString",t)),(t=>this.#F.sendWithNoCb("updateFeedbackValues",t)),(t=>this.#F.sendWithNoCb("setFeedbackDefinitions",t)),this.log.bind(this)),this.#J=t.upgradeScripts,this.id=t.id,this.log("debug","Initializing")}async _handleInit(t){return this.#k.add((async()=>{if(this.#_)throw new Error("Already initialized");const e=t.actions,n=t.feedbacks;let s=t.config;if(t.isFirstInit){const t={},e=this.getConfigFields();for(const n of e)"default"in n&&(t[n.id]=n.default);s=t,this.saveConfig(s)}const{updatedActions:i,updatedFeedbacks:o,updatedConfig:r}=(0,c.runThroughUpgradeScripts)(e,n,t.lastUpgradeIndex,this.#J,s);s=r??s;const a=this.#F.sendWithCb("upgradedItems",{updatedActions:i,updatedFeedbacks:o});try{await this.init(s,!!t.isFirstInit),this.#_=!0}catch(t){throw console.trace(`Init failed: ${t}`),t}finally{await a}return setImmediate((()=>{this._handleUpdateActions({actions:e},!0).catch((t=>{this.log("error",`Receive actions failed: ${t}`)})),this._handleUpdateFeedbacks({feedbacks:n},!0).catch((t=>{this.log("error",`Receive feedbacks failed: ${t}`)}))})),{hasHttpHandler:"function"==typeof this.handleHttpRequest,hasRecordActionsHandler:"function"==typeof this.handleStartStopRecordActions,newUpgradeIndex:this.#J.length-1,updatedConfig:s}}))}async _handleDestroy(){await this.#k.add((async()=>{if(!this.#_)throw new Error("Not initialized");await this.destroy(),this.#_=!1}))}async _handleConfigUpdate(t){await this.#k.add((async()=>{if(!this.#_)throw new Error("Not initialized");await this.configUpdated(t)}))}async _handleExecuteAction(t){return this.#U.handleExecuteAction(t)}async _handleUpdateFeedbacks(t,e){if(!e){const e=(0,c.runThroughUpgradeScripts)({},t.feedbacks,null,this.#J,void 0);this.#F.sendWithCb("upgradedItems",{updatedActions:e.updatedActions,updatedFeedbacks:e.updatedFeedbacks}).catch((t=>{this.log("error",`Failed to save upgraded feedbacks: ${t}`)}))}this.#x.handleUpdateFeedbacks(t.feedbacks)}async _handleUpdateActions(t,e){if(!e){const e=(0,c.runThroughUpgradeScripts)(t.actions,{},null,this.#J,void 0);this.#F.sendWithCb("upgradedItems",{updatedActions:e.updatedActions,updatedFeedbacks:e.updatedFeedbacks}).catch((t=>{this.log("error",`Failed to save upgraded actions: ${t}`)}))}this.#U.handleUpdateActions(t.actions)}async _handleGetConfigFields(t){return{fields:(0,r.serializeIsVisibleFn)(this.getConfigFields())}}async _handleHttpRequest(t){if(!this.handleHttpRequest)throw new Error("handleHttpRequest is not supported!");return{response:await this.handleHttpRequest(t.request)}}async _handleLearnAction(t){return this.#U.handleLearnAction(t)}async _handleLearnFeedback(t){return this.#x.handleLearnFeedback(t)}async _handleStartStopRecordActions(t){if(t.recording){if(this.#z)return}else if(!this.#z)return;if(!this.handleStartStopRecordActions)throw this.#z=!1,new Error("Recording actions is not supported by this module!");this.#z=t.recording,this.handleStartStopRecordActions(this.#z)}async _handleVariablesChanged(t){this.#x.handleVariablesChanged(t)}saveConfig(t){this.#F.sendWithNoCb("saveConfig",{config:t})}setActionDefinitions(t){this.#U.setActionDefinitions(t)}setFeedbackDefinitions(t){this.#x.setFeedbackDefinitions(t)}setPresetDefinitions(t){const e=[];for(const[n,s]of Object.entries(t))s&&e.push({...s,id:n});this.#F.sendWithNoCb("setPresetDefinitions",{presets:e})}setVariableDefinitions(t){const e=[];this.#T.clear();for(const n of t)e.push({id:n.variableId,name:n.name}),this.#T.set(n.variableId,n),this.#E.has(n.variableId)||this.#E.set(n.variableId,"");if(!this.#n.disableVariableValidation){const t=new Set(this.#T.keys());for(const e of this.#E.keys())t.has(e)||this.#E.delete(e)}this.#F.sendWithNoCb("setVariableDefinitions",{variables:e})}setVariableValues(t){const e=[];for(const[n,s]of Object.entries(t))this.#n.disableVariableValidation?(void 0===s?this.#E.delete(n):this.#E.set(n,s),e.push({id:n,value:s})):this.#T.has(n)?(this.#E.set(n,s??""),e.push({id:n,value:s??""})):e.push({id:n,value:void 0});this.#F.sendWithNoCb("setVariableValues",{newValues:e})}getVariableValue(t){return this.#E.get(t)}async parseVariablesInString(t){const e=this.#x.parseVariablesContext;return e&&this.log("debug",`parseVariablesInString called while in: ${e}. You should use the parseVariablesInString provided to the callback instead`),(await this.#F.sendWithCb("parseVariablesInString",{text:t,controlId:void 0,actionInstanceId:void 0,feedbackInstanceId:void 0})).text}checkFeedbacks(...t){this.#x.checkFeedbacks(t)}checkFeedbacksById(...t){this.#x.checkFeedbacksById(t)}_getAllActions(){return this.#U._getAllActions()}subscribeActions(...t){this.#U.subscribeActions(t)}unsubscribeActions(...t){this.#U.unsubscribeActions(t)}_getAllFeedbacks(){return this.#x._getAllFeedbacks()}subscribeFeedbacks(...t){this.#x.subscribeFeedbacks(t)}unsubscribeFeedbacks(...t){this.#x.unsubscribeFeedbacks(t)}recordAction(t,e){if(!this.#z)throw new Error("Not currently recording actions");this.#F.sendWithNoCb("recordAction",{uniquenessId:e??null,actionId:t.actionId,options:t.options})}setCustomVariableValue(t,e){this.#F.sendWithNoCb("setCustomVariable",{customVariableId:t,value:e})}oscSend(t,e,n,s){this.#F.sendWithNoCb("send-osc",(0,i.literal)({host:t,port:e,path:n,args:s}))}updateStatus(t,e){this.#F.sendWithNoCb("set-status",(0,i.literal)({status:t,message:e??null}))}log(t,e){this.#F.sendWithNoCb("log-message",(0,i.literal)({level:t,message:e}))}}},7386:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0})},1400:(t,e)=>{"use strict";var n,s;Object.defineProperty(e,"__esModule",{value:!0}),e.Regex=e.InstanceStatus=void 0,(s=e.InstanceStatus||(e.InstanceStatus={})).Ok="ok",s.Connecting="connecting",s.Disconnected="disconnected",s.ConnectionFailure="connection_failure",s.BadConfig="bad_config",s.UnknownError="unknown_error",s.UnknownWarning="unknown_warning",(n=e.Regex||(e.Regex={})).IP="/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/",n.HOSTNAME="/^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9])\\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9-]*[A-Za-z0-9])$/",n.BOOLEAN="/^(true|false|0|1)$/i",n.PORT="/^([1-9]|[1-8][0-9]|9[0-9]|[1-8][0-9]{2}|9[0-8][0-9]|99[0-9]|[1-8][0-9]{3}|9[0-8][0-9]{2}|99[0-8][0-9]|999[0-9]|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-4])$/",n.PERCENT="/^(100|[0-9]|[0-9][0-9])$/",n.FLOAT="/^([0-9]*\\.)?[0-9]+$/",n.SIGNED_FLOAT="/^[+-]?([0-9]*\\.)?[0-9]+$/",n.FLOAT_OR_INT="/^([0-9]+)(\\.[0-9]+)?$/",n.NUMBER="/^\\d+$/",n.SIGNED_NUMBER="/^[+-]?\\d+$/",n.SOMETHING="/^.+$/",n.TIMECODE="/^(0*[0-9]|1[0-9]|2[0-4]):(0*[0-9]|[1-5][0-9]|60):(0*[0-9]|[1-5][0-9]|60):(0*[0-9]|[12][0-9]|30)$/"},8983:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0})},8104:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0})},2018:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0});const s=n(1635);s.__exportStar(n(3730),e),s.__exportStar(n(1649),e),s.__exportStar(n(7386),e),s.__exportStar(n(1400),e),s.__exportStar(n(8983),e),s.__exportStar(n(8104),e),s.__exportStar(n(3258),e),s.__exportStar(n(131),e),s.__exportStar(n(3371),e),s.__exportStar(n(9786),e),s.__exportStar(n(6132),e)},3258:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0})},131:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0})},3371:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0})},9786:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.CreateConvertToBooleanFeedbackUpgradeScript=e.EmptyUpgradeScript=void 0,e.EmptyUpgradeScript=()=>({updatedConfig:null,updatedActions:[],updatedFeedbacks:[]}),e.CreateConvertToBooleanFeedbackUpgradeScript=function(t){return(e,n)=>{const s=[];for(const e of n.feedbacks){let n=t[e.feedbackId];if(!0===n&&(n={bg:"bgcolor",bgcolor:"bgcolor",fg:"color",color:"color",png64:"png64",png:"png64"}),n){e.style||(e.style={});for(const[t,i]of Object.entries(n))void 0!==e.options[t]&&(e.style[i]=e.options[t],delete e.options[t],s.push(e))}}return{updatedConfig:null,updatedActions:[],updatedFeedbacks:s}}}},6132:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0})},360:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.splitRgb=e.combineRgb=e.assertNever=e.literal=void 0,e.literal=function(t){return t},e.assertNever=function(t){},e.combineRgb=function(t,e,n){return(255&t)<<16|(255&e)<<8|255&n},e.splitRgb=function(t){return{r:(16711680&t)>>16,g:(65280&t)>>8,b:255&t}}},7281:(t,e,n)=>{"use strict";t.exports=o,t.exports.default=o;const s={$schema:"http://json-schema.org/draft-07/schema#",type:"object",title:"ModuleManifest",properties:{id:{type:"string",description:"Unique identifier for the module"},name:{type:"string",description:"Name of the module"},shortname:{type:"string"},description:{type:"string",description:"Description of the module "},version:{type:"string",description:"Current version of the module"},license:{type:"string",description:"SPDX identifier for license of the module"},repository:{type:"string",description:"URL to the source repository"},bugs:{type:"string",description:"URL to bug tracker"},maintainers:{type:"array",description:"List of active maintiners",uniqueItems:!0,items:{type:"object",title:"ModuleManifestMaintainer",properties:{name:{type:"string"},email:{type:"string"},github:{type:"string"}},required:["name"]}},legacyIds:{type:"array",description:"If the module had a different unique identifier previously, then specify it here",uniqueItems:!0,items:{type:"string"}},runtime:{type:"object",title:"ModuleManifestRuntime",description:"Information on how to execute the module",properties:{type:{type:"string",description:"Type of the module. Must be: node18"},api:{type:"string",description:"Which host-api does it use. In the future alternate options will be allowed",enum:["nodejs-ipc"]},apiVersion:{type:"string",description:"The version of the host-api used"},entrypoint:{type:"string",description:"Entrypoint to pass to the runtime. eg index.js"}},required:["type","api","apiVersion","entrypoint"]},manufacturer:{type:"string"},products:{type:"array",uniqueItems:!0,items:{type:"string"}},keywords:{type:"array",uniqueItems:!0,items:{type:"string"}}},required:["id","name","shortname","description","version","license","repository","bugs","maintainers","legacyIds","runtime","manufacturer","products","keywords"]},i=n(7169).A;function o(t,{instancePath:e="",parentData:n,parentDataProperty:r,rootData:c=t}={}){if(!t||"object"!=typeof t||Array.isArray(t))return o.errors=[{instancePath:e,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;{let n;if(void 0===t.id&&(n="id")||void 0===t.name&&(n="name")||void 0===t.shortname&&(n="shortname")||void 0===t.description&&(n="description")||void 0===t.version&&(n="version")||void 0===t.license&&(n="license")||void 0===t.repository&&(n="repository")||void 0===t.bugs&&(n="bugs")||void 0===t.maintainers&&(n="maintainers")||void 0===t.legacyIds&&(n="legacyIds")||void 0===t.runtime&&(n="runtime")||void 0===t.manufacturer&&(n="manufacturer")||void 0===t.products&&(n="products")||void 0===t.keywords&&(n="keywords"))return o.errors=[{instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:n},message:"must have required property '"+n+"'"}],!1;if(void 0!==t.id){const n=0;if("string"!=typeof t.id)return o.errors=[{instancePath:e+"/id",schemaPath:"#/properties/id/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;var a=0===n}else a=!0;if(a){if(void 0!==t.name){const n=0;if("string"!=typeof t.name)return o.errors=[{instancePath:e+"/name",schemaPath:"#/properties/name/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;a=0===n}else a=!0;if(a){if(void 0!==t.shortname){const n=0;if("string"!=typeof t.shortname)return o.errors=[{instancePath:e+"/shortname",schemaPath:"#/properties/shortname/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;a=0===n}else a=!0;if(a){if(void 0!==t.description){const n=0;if("string"!=typeof t.description)return o.errors=[{instancePath:e+"/description",schemaPath:"#/properties/description/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;a=0===n}else a=!0;if(a){if(void 0!==t.version){const n=0;if("string"!=typeof t.version)return o.errors=[{instancePath:e+"/version",schemaPath:"#/properties/version/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;a=0===n}else a=!0;if(a){if(void 0!==t.license){const n=0;if("string"!=typeof t.license)return o.errors=[{instancePath:e+"/license",schemaPath:"#/properties/license/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;a=0===n}else a=!0;if(a){if(void 0!==t.repository){const n=0;if("string"!=typeof t.repository)return o.errors=[{instancePath:e+"/repository",schemaPath:"#/properties/repository/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;a=0===n}else a=!0;if(a){if(void 0!==t.bugs){const n=0;if("string"!=typeof t.bugs)return o.errors=[{instancePath:e+"/bugs",schemaPath:"#/properties/bugs/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;a=0===n}else a=!0;if(a){if(void 0!==t.maintainers){let n=t.maintainers;const s=0;if(0===s){if(!Array.isArray(n))return o.errors=[{instancePath:e+"/maintainers",schemaPath:"#/properties/maintainers/type",keyword:"type",params:{type:"array"},message:"must be array"}],!1;{var g=!0;const t=n.length;for(let s=0;s1)for(;s--;)for(t=s;t--;)if(i(n[s],n[t]))return o.errors=[{instancePath:e+"/maintainers",schemaPath:"#/properties/maintainers/uniqueItems",keyword:"uniqueItems",params:{i:s,j:t},message:"must NOT have duplicate items (items ## "+t+" and "+s+" are identical)"}],!1}}}a=0===s}else a=!0;if(a){if(void 0!==t.legacyIds){let n=t.legacyIds;const s=0;if(0===s){if(!Array.isArray(n))return o.errors=[{instancePath:e+"/legacyIds",schemaPath:"#/properties/legacyIds/type",keyword:"type",params:{type:"array"},message:"must be array"}],!1;{var d=!0;const t=n.length;for(let s=0;s1){const i={};for(;s--;){let r=n[s];if("string"==typeof r){if("number"==typeof i[r])return t=i[r],o.errors=[{instancePath:e+"/legacyIds",schemaPath:"#/properties/legacyIds/uniqueItems",keyword:"uniqueItems",params:{i:s,j:t},message:"must NOT have duplicate items (items ## "+t+" and "+s+" are identical)"}],!1;i[r]=s}}}}}}a=0===s}else a=!0;if(a){if(void 0!==t.runtime){let n=t.runtime;const i=0;if(0===i){if(!n||"object"!=typeof n||Array.isArray(n))return o.errors=[{instancePath:e+"/runtime",schemaPath:"#/properties/runtime/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;{let t;if(void 0===n.type&&(t="type")||void 0===n.api&&(t="api")||void 0===n.apiVersion&&(t="apiVersion")||void 0===n.entrypoint&&(t="entrypoint"))return o.errors=[{instancePath:e+"/runtime",schemaPath:"#/properties/runtime/required",keyword:"required",params:{missingProperty:t},message:"must have required property '"+t+"'"}],!1;if(void 0!==n.type){const t=0;if("string"!=typeof n.type)return o.errors=[{instancePath:e+"/runtime/type",schemaPath:"#/properties/runtime/properties/type/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;var I=0===t}else I=!0;if(I){if(void 0!==n.api){let t=n.api;const i=0;if("string"!=typeof t)return o.errors=[{instancePath:e+"/runtime/api",schemaPath:"#/properties/runtime/properties/api/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;if("nodejs-ipc"!==t)return o.errors=[{instancePath:e+"/runtime/api",schemaPath:"#/properties/runtime/properties/api/enum",keyword:"enum",params:{allowedValues:s.properties.runtime.properties.api.enum},message:"must be equal to one of the allowed values"}],!1;I=0===i}else I=!0;if(I){if(void 0!==n.apiVersion){const t=0;if("string"!=typeof n.apiVersion)return o.errors=[{instancePath:e+"/runtime/apiVersion",schemaPath:"#/properties/runtime/properties/apiVersion/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;I=0===t}else I=!0;if(I)if(void 0!==n.entrypoint){const t=0;if("string"!=typeof n.entrypoint)return o.errors=[{instancePath:e+"/runtime/entrypoint",schemaPath:"#/properties/runtime/properties/entrypoint/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;I=0===t}else I=!0}}}}a=0===i}else a=!0;if(a){if(void 0!==t.manufacturer){const n=0;if("string"!=typeof t.manufacturer)return o.errors=[{instancePath:e+"/manufacturer",schemaPath:"#/properties/manufacturer/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;a=0===n}else a=!0;if(a){if(void 0!==t.products){let n=t.products;const s=0;if(0===s){if(!Array.isArray(n))return o.errors=[{instancePath:e+"/products",schemaPath:"#/properties/products/type",keyword:"type",params:{type:"array"},message:"must be array"}],!1;{var u=!0;const t=n.length;for(let s=0;s1){const i={};for(;s--;){let r=n[s];if("string"==typeof r){if("number"==typeof i[r])return t=i[r],o.errors=[{instancePath:e+"/products",schemaPath:"#/properties/products/uniqueItems",keyword:"uniqueItems",params:{i:s,j:t},message:"must NOT have duplicate items (items ## "+t+" and "+s+" are identical)"}],!1;i[r]=s}}}}}}a=0===s}else a=!0;if(a)if(void 0!==t.keywords){let n=t.keywords;const s=0;if(0===s){if(!Array.isArray(n))return o.errors=[{instancePath:e+"/keywords",schemaPath:"#/properties/keywords/type",keyword:"type",params:{type:"array"},message:"must be array"}],!1;{var C=!0;const t=n.length;for(let s=0;s1){const i={};for(;s--;){let r=n[s];if("string"==typeof r){if("number"==typeof i[r])return t=i[r],o.errors=[{instancePath:e+"/keywords",schemaPath:"#/properties/keywords/uniqueItems",keyword:"uniqueItems",params:{i:s,j:t},message:"must NOT have duplicate items (items ## "+t+" and "+s+" are identical)"}],!1;i[r]=s}}}}}}a=0===s}else a=!0}}}}}}}}}}}}}return o.errors=null,!0}},1154:(t,e,n)=>{let s,i,o=n(6982),{urlAlphabet:r}=n(7362),c=t=>{!s||s.lengths.length&&(o.randomFillSync(s),i=0),i+=t},a=t=>(c(t-=0),s.subarray(i-t,i)),g=(t,e,n)=>{let s=(2<<31-Math.clz32(t.length-1|1))-1,i=Math.ceil(1.6*s*e/t.length);return(o=e)=>{let r="";for(;;){let e=n(i),c=i;for(;c--;)if(r+=t[e[c]&s]||"",r.length===o)return r}}};t.exports={nanoid:(t=21)=>{c(t-=0);let e="";for(let n=i-t;ng(t,e,a),customRandom:g,urlAlphabet:r,random:a}},7362:t=>{t.exports={urlAlphabet:"useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"}},8654:(t,e,n)=>{"use strict";var s=n(6278);const i=[{type:"static-text",id:"info",label:"Information",width:12,value:'\n\t\t\t\t
\n\t\t\t\t\t

IMPORTANT MESSAGE

\n\t\t\t\t\t
\n\t\t\t\t\t\tPlease read and understand the following before using this module\n\t\t\t\t\t\t
\n\t\t\t\t\t\tThis software is for use as a stopwatch, making it easier to manipulate times through the companion.\n\t\t\t\t\t
\n\t\t\t\t
\n\t\t\t'},{type:"textinput",id:"host",label:"Target Host name or IP",default:"127.0.0.1",width:8,regex:"/^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3})$|^((([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9]).)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9-]*[A-Za-z0-9]))$/"},{type:"textinput",id:"port",label:"Target Port",default:"7600",width:4,regex:s.Regex.PORT}];class o extends s.InstanceBase{async init(t){this.config=t,this.setActionDefinitions(function(t){const e={},n=(e,n)=>({name:`${e}`,options:[],callback:async()=>{const e=n,s=Buffer.from(e,"latin1");t.log("debug",`sending to ${t.config.host}: ${s.toString()}`),void 0!==t.socket&&t.socket.isConnected?t.socket.send(s):t.log("debug","Socket not connected :(")}}),s={ESC:"esc",NEXT:"next",PREVIOUS:"previous",FECHAR_PPT:"pptexit",FECHAR_VIDEO:"videoexit",START:"start",STOP:"stop",SET:"set",RESET:"reset",SET1:"set1",SET5:"set5",SET15:"set15",SET30:"set30",SET45:"set45",SET60:"set60",addMinute:"addMinute",addFiveMinutes:"addFiveMinutes",subtractMinute:"subtractMinute",subtractFiveMinutes:"subtractFiveMinutes",addHour:"addHour",subtractHour:"subtractHour",addMin:"addMin",subtractMin:"subtractMin",AA:"AA",aa:"aa"};for(const[t,i]of Object.entries(s))e[t]=n(t,i);return e}(this)),this.setPresetDefinitions(function(){const t={preset_start:{type:"button",category:"Control",name:"Start Timer",style:{text:"START",size:"18",color:"16777215",bgcolor:"43520",show_topbar:!1},steps:[{down:[{actionId:"START"}],up:[]}]},preset_stop:{type:"button",category:"Control",name:"Stop Timer",style:{text:"STOP",size:"18",color:"16777215",bgcolor:"9109504",show_topbar:!1},steps:[{down:[{actionId:"STOP"}],up:[]}]},preset_reset:{type:"button",category:"Control",name:"Reset Timer",style:{text:"RESET",size:"18",color:"0",bgcolor:"8421504",show_topbar:!1},steps:[{down:[{actionId:"RESET"}],up:[]}]},preset_set:{type:"button",category:"Control",name:"Set Timer",style:{text:"SET",size:"18",color:"16777215",bgcolor:"43520",show_topbar:!1},steps:[{down:[{actionId:"SET"}],up:[]}]},preset_hour:{type:"button",category:"Display",name:"HOUR",style:{text:"$(Cronos:timer_hours)",size:"AUTO",color:"16777215",bgcolor:"9109504",show_topbar:!1},steps:[{down:[],up:[]}]},preset_minute:{type:"button",category:"Display",name:"MINUTE",style:{text:"$(Cronos:timer_minutes)",size:"AUTO",color:"16777215",bgcolor:"9109504",show_topbar:!1},steps:[{down:[],up:[]}]},preset_second:{type:"button",category:"Display",name:"SECOND",style:{text:"$(Cronos:timer_seconds)",size:"AUTO",color:"16777215",bgcolor:"9109504",show_topbar:!1},steps:[{down:[],up:[]}]},preset_timer:{type:"button",category:"Display",name:"TIMER",style:{text:"$(Cronos:timer)",size:"AUTO",color:"16777215",bgcolor:"9109504",show_topbar:!1},steps:[{down:[],up:[]}]}};function e(e){t[`preset_set${e}`]={type:"button",category:"SET",name:`Set ${e} Minutes`,style:{text:`SET\n${e} MIN`,size:"18",color:"16777215",bgcolor:"180",show_topbar:!1},steps:[{down:[{actionId:`SET${e}`,options:{minutes:e}}],up:[]}]}}function n(e,n,s){t[`preset_${e}`]={type:"button",category:"Function",name:s,style:{text:n,size:"18",color:"16777215",bgcolor:"0",show_topbar:!1},steps:[{down:[{actionId:e}],up:[]}]}}e(1),e(5),e(15),e(30),e(45),e(60),n("addMinute","ADD\n1 MIN","Add 1 Minute"),n("addFiveMinutes","ADD\n5 MIN","Add 5 Minutes"),n("subtractMinute","SUB\n1 MIN","Subtract 1 Minute"),n("subtractFiveMinutes","SUB\n5 MIN","Subtract 5 Minutes"),n("addHour","ADD\n1 HR","Add 1 Hour"),n("subtractHour","SUB\n1 HR","Subtract 1 Hour"),n("addMin","ADD\nMIN","Add Minute"),n("subtractMin","SUB\nMIN","Subtract Minute"),n("AA","AA","AA"),n("aa","aa","aa");for(let e=1;e<=20;e++){const n=e<10?`preset\n0${e}`:`preset\n${e}`,s=`preset${e}`,i=`$(Cronos:item${e})`;t[`preset_${n}`]={type:"button",category:"Preset",name:`Send ${n.toUpperCase()} Command`,style:{text:i,size:"14",color:"16777215",bgcolor:"25600",show_topbar:!1},steps:[{down:[{actionId:"send",options:{id_send:s}}],up:[]}]}}return t}()),await this.configUpdated(t)}async configUpdated(t){this.socket&&(this.socket.destroy(),delete this.socket),this.config=t,this.init_tcp()}async destroy(){this.socket?this.socket.destroy():this.updateStatus(s.InstanceStatus.Disconnected)}getConfigFields(){return i}init_tcp(){this.socket&&(this.socket.destroy(),delete this.socket),this.updateStatus(s.InstanceStatus.Connecting),this.config.host?(this.socket=new s.TCPHelper(this.config.host,this.config.port),this.socket.on("status_change",((t,e)=>{this.updateStatus(t,e)})),this.socket.on("error",(t=>{this.updateStatus(s.InstanceStatus.ConnectionFailure,t.message),this.log("error","Network error: "+t.message)}))):this.updateStatus(s.InstanceStatus.BadConfig)}}(0,s.runEntrypoint)(o,[])},1635:(t,e,n)=>{"use strict";n.r(e),n.d(e,{__addDisposableResource:()=>K,__assign:()=>o,__asyncDelegator:()=>V,__asyncGenerator:()=>W,__asyncValues:()=>v,__await:()=>A,__awaiter:()=>C,__classPrivateFieldGet:()=>H,__classPrivateFieldIn:()=>N,__classPrivateFieldSet:()=>S,__createBinding:()=>b,__decorate:()=>c,__disposeResources:()=>F,__esDecorate:()=>g,__exportStar:()=>h,__extends:()=>i,__generator:()=>p,__importDefault:()=>X,__importStar:()=>Y,__makeTemplateObject:()=>f,__metadata:()=>u,__param:()=>a,__propKey:()=>d,__read:()=>Z,__rest:()=>r,__runInitializers:()=>l,__setFunctionName:()=>I,__spread:()=>G,__spreadArray:()=>y,__spreadArrays:()=>B,__values:()=>m,default:()=>J});var s=function(t,e){return s=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},s(t,e)};function i(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");function n(){this.constructor=t}s(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}var o=function(){return o=Object.assign||function(t){for(var e,n=1,s=arguments.length;n=0;c--)(i=t[c])&&(r=(o<3?i(r):o>3?i(e,n,r):i(e,n))||r);return o>3&&r&&Object.defineProperty(e,n,r),r}function a(t,e){return function(n,s){e(n,s,t)}}function g(t,e,n,s,i,o){function r(t){if(void 0!==t&&"function"!=typeof t)throw new TypeError("Function expected");return t}for(var c,a=s.kind,g="getter"===a?"get":"setter"===a?"set":"value",l=!e&&t?s.static?t:t.prototype:null,d=e||(l?Object.getOwnPropertyDescriptor(l,s.name):{}),I=!1,u=n.length-1;u>=0;u--){var C={};for(var p in s)C[p]="access"===p?{}:s[p];for(var p in s.access)C.access[p]=s.access[p];C.addInitializer=function(t){if(I)throw new TypeError("Cannot add initializers after decoration has completed");o.push(r(t||null))};var b=(0,n[u])("accessor"===a?{get:d.get,set:d.set}:d[g],C);if("accessor"===a){if(void 0===b)continue;if(null===b||"object"!=typeof b)throw new TypeError("Object expected");(c=r(b.get))&&(d.get=c),(c=r(b.set))&&(d.set=c),(c=r(b.init))&&i.unshift(c)}else(c=r(b))&&("field"===a?i.unshift(c):d[g]=c)}l&&Object.defineProperty(l,s.name,d),I=!0}function l(t,e,n){for(var s=arguments.length>2,i=0;i0&&i[i.length-1])||6!==c[0]&&2!==c[0])){o=0;continue}if(3===c[0]&&(!i||c[1]>i[0]&&c[1]=t.length&&(t=void 0),{value:t&&t[s++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function Z(t,e){var n="function"==typeof Symbol&&t[Symbol.iterator];if(!n)return t;var s,i,o=n.call(t),r=[];try{for(;(void 0===e||e-- >0)&&!(s=o.next()).done;)r.push(s.value)}catch(t){i={error:t}}finally{try{s&&!s.done&&(n=o.return)&&n.call(o)}finally{if(i)throw i.error}}return r}function G(){for(var t=[],e=0;e1||c(t,e)}))},e&&(s[t]=e(s[t])))}function c(t,e){try{(n=i[t](e)).value instanceof A?Promise.resolve(n.value.v).then(a,g):l(o[0][2],n)}catch(t){l(o[0][3],t)}var n}function a(t){c("next",t)}function g(t){c("throw",t)}function l(t,e){t(e),o.shift(),o.length&&c(o[0][0],o[0][1])}}function V(t){var e,n;return e={},s("next"),s("throw",(function(t){throw t})),s("return"),e[Symbol.iterator]=function(){return this},e;function s(s,i){e[s]=t[s]?function(e){return(n=!n)?{value:A(t[s](e)),done:!1}:i?i(e):e}:i}}function v(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e,n=t[Symbol.asyncIterator];return n?n.call(t):(t=m(t),e={},s("next"),s("throw"),s("return"),e[Symbol.asyncIterator]=function(){return this},e);function s(n){e[n]=t[n]&&function(e){return new Promise((function(s,i){!function(t,e,n,s){Promise.resolve(s).then((function(e){t({value:e,done:n})}),e)}(s,i,(e=t[n](e)).done,e.value)}))}}}function f(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}var R=Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e};function Y(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var n in t)"default"!==n&&Object.prototype.hasOwnProperty.call(t,n)&&b(e,t,n);return R(e,t),e}function X(t){return t&&t.__esModule?t:{default:t}}function H(t,e,n,s){if("a"===n&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!s:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?s:"a"===n?s.call(t):s?s.value:e.get(t)}function S(t,e,n,s,i){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!i)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!i:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?i.call(t,n):i?i.value=n:e.set(t,n),n}function N(t,e){if(null===e||"object"!=typeof e&&"function"!=typeof e)throw new TypeError("Cannot use 'in' operator on non-object");return"function"==typeof t?e===t:t.has(e)}function K(t,e,n){if(null!=e){if("object"!=typeof e&&"function"!=typeof e)throw new TypeError("Object expected.");var s,i;if(n){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");s=e[Symbol.asyncDispose]}if(void 0===s){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");s=e[Symbol.dispose],n&&(i=s)}if("function"!=typeof s)throw new TypeError("Object not disposable.");i&&(s=function(){try{i.call(this)}catch(t){return Promise.reject(t)}}),t.stack.push({value:e,dispose:s,async:n})}else n&&t.stack.push({async:!0});return e}var w="function"==typeof SuppressedError?SuppressedError:function(t,e,n){var s=new Error(n);return s.name="SuppressedError",s.error=t,s.suppressed=e,s};function F(t){function e(e){t.error=t.hasError?new w(e,t.error,"An error was suppressed during disposal."):e,t.hasError=!0}var n,s=0;return function i(){for(;n=t.stack.pop();)try{if(!n.async&&1===s)return s=0,t.stack.push(n),Promise.resolve().then(i);if(n.dispose){var o=n.dispose.call(n.value);if(n.async)return s|=2,Promise.resolve(o).then(i,(function(t){return e(t),i()}))}else s|=1}catch(t){e(t)}if(1===s)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}const J={__extends:i,__assign:o,__rest:r,__decorate:c,__param:a,__metadata:u,__awaiter:C,__generator:p,__createBinding:b,__exportStar:h,__values:m,__read:Z,__spread:G,__spreadArrays:B,__spreadArray:y,__await:A,__asyncGenerator:W,__asyncDelegator:V,__asyncValues:v,__makeTemplateObject:f,__importStar:Y,__importDefault:X,__classPrivateFieldGet:H,__classPrivateFieldSet:S,__classPrivateFieldIn:N,__addDisposableResource:K,__disposeResources:F}}},e={};function n(s){var i=e[s];if(void 0!==i)return i.exports;var o=e[s]={id:s,loaded:!1,exports:{}};return t[s](o,o.exports,n),o.loaded=!0,o.exports}n.c=e,n.d=(t,e)=>{for(var s in e)n.o(e,s)&&!n.o(t,s)&&Object.defineProperty(t,s,{enumerable:!0,get:e[s]})},n.hmd=t=>((t=Object.create(t)).children||(t.children=[]),Object.defineProperty(t,"exports",{enumerable:!0,set:()=>{throw new Error("ES Modules may not assign module.exports or exports.*, Use ESM export syntax, instead: "+t.id)}}),t),n.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),n.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},n(n.s=8654)})(); \ No newline at end of file +(()=>{var e={169:(e,t,r)=>{"use strict";const n=r(17);n.code='require("ajv/dist/runtime/equal").default',t.A=n},284:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0});var r={grad:.9,turn:360,rad:360/(2*Math.PI)},n=function(e){return"string"==typeof e?e.length>0:"number"==typeof e},s=function(e,t,r){return void 0===t&&(t=0),void 0===r&&(r=Math.pow(10,t)),Math.round(r*e)/r+0},i=function(e,t,r){return void 0===t&&(t=0),void 0===r&&(r=1),e>r?r:e>t?e:t},o=function(e){return(e=isFinite(e)?e%360:0)>0?e:e+360},a=function(e){return{r:i(e.r,0,255),g:i(e.g,0,255),b:i(e.b,0,255),a:i(e.a)}},c=function(e){return{r:s(e.r),g:s(e.g),b:s(e.b),a:s(e.a,3)}},u=/^#([0-9a-f]{3,8})$/i,l=function(e){var t=e.toString(16);return t.length<2?"0"+t:t},d=function(e){var t=e.r,r=e.g,n=e.b,s=e.a,i=Math.max(t,r,n),o=i-Math.min(t,r,n),a=o?i===t?(r-n)/o:i===r?2+(n-t)/o:4+(t-r)/o:0;return{h:60*(a<0?a+6:a),s:i?o/i*100:0,v:i/255*100,a:s}},p=function(e){var t=e.h,r=e.s,n=e.v,s=e.a;t=t/360*6,r/=100,n/=100;var i=Math.floor(t),o=n*(1-r),a=n*(1-(t-i)*r),c=n*(1-(1-t+i)*r),u=i%6;return{r:255*[n,a,o,o,c,n][u],g:255*[c,n,n,a,o,o][u],b:255*[o,o,c,n,n,a][u],a:s}},f=function(e){return{h:o(e.h),s:i(e.s,0,100),l:i(e.l,0,100),a:i(e.a)}},h=function(e){return{h:s(e.h),s:s(e.s),l:s(e.l),a:s(e.a,3)}},y=function(e){return p((r=(t=e).s,{h:t.h,s:(r*=((n=t.l)<50?n:100-n)/100)>0?2*r/(n+r)*100:0,v:n+r,a:t.a}));var t,r,n},b=function(e){return{h:(t=d(e)).h,s:(s=(200-(r=t.s))*(n=t.v)/100)>0&&s<200?r*n/100/(s<=100?s:200-s)*100:0,l:s/2,a:t.a};var t,r,n,s},m=/^hsla?\(\s*([+-]?\d*\.?\d+)(deg|rad|grad|turn)?\s*,\s*([+-]?\d*\.?\d+)%\s*,\s*([+-]?\d*\.?\d+)%\s*(?:,\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,g=/^hsla?\(\s*([+-]?\d*\.?\d+)(deg|rad|grad|turn)?\s+([+-]?\d*\.?\d+)%\s+([+-]?\d*\.?\d+)%\s*(?:\/\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,v=/^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*(?:,\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,_=/^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s*(?:\/\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,w={string:[[function(e){var t=u.exec(e);return t?(e=t[1]).length<=4?{r:parseInt(e[0]+e[0],16),g:parseInt(e[1]+e[1],16),b:parseInt(e[2]+e[2],16),a:4===e.length?s(parseInt(e[3]+e[3],16)/255,2):1}:6===e.length||8===e.length?{r:parseInt(e.substr(0,2),16),g:parseInt(e.substr(2,2),16),b:parseInt(e.substr(4,2),16),a:8===e.length?s(parseInt(e.substr(6,2),16)/255,2):1}:null:null},"hex"],[function(e){var t=v.exec(e)||_.exec(e);return t?t[2]!==t[4]||t[4]!==t[6]?null:a({r:Number(t[1])/(t[2]?100/255:1),g:Number(t[3])/(t[4]?100/255:1),b:Number(t[5])/(t[6]?100/255:1),a:void 0===t[7]?1:Number(t[7])/(t[8]?100:1)}):null},"rgb"],[function(e){var t=m.exec(e)||g.exec(e);if(!t)return null;var n,s,i=f({h:(n=t[1],s=t[2],void 0===s&&(s="deg"),Number(n)*(r[s]||1)),s:Number(t[3]),l:Number(t[4]),a:void 0===t[5]?1:Number(t[5])/(t[6]?100:1)});return y(i)},"hsl"]],object:[[function(e){var t=e.r,r=e.g,s=e.b,i=e.a,o=void 0===i?1:i;return n(t)&&n(r)&&n(s)?a({r:Number(t),g:Number(r),b:Number(s),a:Number(o)}):null},"rgb"],[function(e){var t=e.h,r=e.s,s=e.l,i=e.a,o=void 0===i?1:i;if(!n(t)||!n(r)||!n(s))return null;var a=f({h:Number(t),s:Number(r),l:Number(s),a:Number(o)});return y(a)},"hsl"],[function(e){var t=e.h,r=e.s,s=e.v,a=e.a,c=void 0===a?1:a;if(!n(t)||!n(r)||!n(s))return null;var u=function(e){return{h:o(e.h),s:i(e.s,0,100),v:i(e.v,0,100),a:i(e.a)}}({h:Number(t),s:Number(r),v:Number(s),a:Number(c)});return p(u)},"hsv"]]},k=function(e,t){for(var r=0;r=.5},e.prototype.toHex=function(){return t=(e=c(this.rgba)).r,r=e.g,n=e.b,o=(i=e.a)<1?l(s(255*i)):"","#"+l(t)+l(r)+l(n)+o;var e,t,r,n,i,o},e.prototype.toRgb=function(){return c(this.rgba)},e.prototype.toRgbString=function(){return t=(e=c(this.rgba)).r,r=e.g,n=e.b,(s=e.a)<1?"rgba("+t+", "+r+", "+n+", "+s+")":"rgb("+t+", "+r+", "+n+")";var e,t,r,n,s},e.prototype.toHsl=function(){return h(b(this.rgba))},e.prototype.toHslString=function(){return t=(e=h(b(this.rgba))).h,r=e.s,n=e.l,(s=e.a)<1?"hsla("+t+", "+r+"%, "+n+"%, "+s+")":"hsl("+t+", "+r+"%, "+n+"%)";var e,t,r,n,s},e.prototype.toHsv=function(){return e=d(this.rgba),{h:s(e.h),s:s(e.s),v:s(e.v),a:s(e.a,3)};var e},e.prototype.invert=function(){return A({r:255-(e=this.rgba).r,g:255-e.g,b:255-e.b,a:e.a});var e},e.prototype.saturate=function(e){return void 0===e&&(e=.1),A(S(this.rgba,e))},e.prototype.desaturate=function(e){return void 0===e&&(e=.1),A(S(this.rgba,-e))},e.prototype.grayscale=function(){return A(S(this.rgba,-1))},e.prototype.lighten=function(e){return void 0===e&&(e=.1),A(P(this.rgba,e))},e.prototype.darken=function(e){return void 0===e&&(e=.1),A(P(this.rgba,-e))},e.prototype.rotate=function(e){return void 0===e&&(e=15),this.hue(this.hue()+e)},e.prototype.alpha=function(e){return"number"==typeof e?A({r:(t=this.rgba).r,g:t.g,b:t.b,a:e}):s(this.rgba.a,3);var t},e.prototype.hue=function(e){var t=b(this.rgba);return"number"==typeof e?A({h:e,s:t.s,l:t.l,a:t.a}):s(t.h)},e.prototype.isEqual=function(e){return this.toHex()===A(e).toHex()},e}(),A=function(e){return e instanceof j?e:new j(e)},E=[];t.Colord=j,t.colord=A,t.extend=function(e){e.forEach((function(e){E.indexOf(e)<0&&(e(j,w),E.push(e))}))},t.getFormat=function(e){return I(e)[1]},t.random=function(){return new j({r:255*Math.random(),g:255*Math.random(),b:255*Math.random()})}},22:e=>{!function(){"use strict";var t=[,function(e,t){function r(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r255)throw new Error("Not ascii. Base64.encode can only take ascii strings.");e[r]=s}}for(var o=[],a=null,c=null,u=null,l=null,d=0;d>2&63,c=(3&e[d])<<4;break;case 1:c|=e[d]>>4&15,u=(15&e[d])<<2;break;case 2:u|=e[d]>>6&3,l=63&e[d],o.push(n(a)),o.push(n(c)),o.push(n(u)),o.push(n(l)),a=null,c=null,u=null,l=null}return null!=a&&(o.push(n(a)),o.push(n(c)),null==u?o.push("="):o.push(n(u)),null==l&&o.push("=")),o.join("")},decode:function(e){var t=Math.floor(3*e.length/4);"="==e.charAt(e.length-1)&&(t--,"="==e.charAt(e.length-2)&&t--);for(var n,s=i(t),o=null,a=null,c=null,u=0,l=0;l>4,s[u++]=o,a=(15&d)<<4;break;case 2:d>=0&&(a|=d>>2,s[u++]=a,c=(3&d)<<6);break;case 3:d>=0&&(s[u++]=c|d)}}return s},newBinary:i};t.Base64=o},function(e){e.exports={_noYieldsAllowed:function(e){return e()}}},function(e,t){function r(e){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},r(e)}function n(e){return JSON.stringify(e)}Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var s=function e(t,s,i,o,a){var c=s[t];switch(r(c)){case"string":return n(c);case"number":return isFinite(c)?String(c):"null";case"boolean":return String(c);case"object":if(!c)return"null";var u,l=o+i,d=[];if(Array.isArray(c)||{}.hasOwnProperty.call(c,"callee")){for(var p=c.length,f=0;f0&&void 0!==arguments[0]&&arguments[0]?a:(0,i.convertMapToObject)(a)},o._getConverters=function(){return c};var u=function(e){for(var t=0;t=d.length||s!==d[n]||!o.equals(e[s],t[d[n]],r)||(n++,0))}))):(n=0,a=l.every((function(s){return!!(0,i.hasOwn)(t,s)&&!!o.equals(e[s],t[s],r)&&(n++,!0)}))),a&&n===d.length},o.clone=function(e){var t;if(!(0,i.isObject)(e))return e;if(null===e)return null;if(e instanceof Date)return new Date(e.getTime());if(e instanceof RegExp)return e;if(o.isBinary(e)){t=o.newBinary(e.length);for(var r=0;r{"use strict";var t=Object.prototype.hasOwnProperty,r="~";function n(){}function s(e,t,r){this.fn=e,this.context=t,this.once=r||!1}function i(e,t,n,i,o){if("function"!=typeof n)throw new TypeError("The listener must be a function");var a=new s(n,i||e,o),c=r?r+t:t;return e._events[c]?e._events[c].fn?e._events[c]=[e._events[c],a]:e._events[c].push(a):(e._events[c]=a,e._eventsCount++),e}function o(e,t){0==--e._eventsCount?e._events=new n:delete e._events[t]}function a(){this._events=new n,this._eventsCount=0}Object.create&&(n.prototype=Object.create(null),(new n).__proto__||(r=!1)),a.prototype.eventNames=function(){var e,n,s=[];if(0===this._eventsCount)return s;for(n in e=this._events)t.call(e,n)&&s.push(r?n.slice(1):n);return Object.getOwnPropertySymbols?s.concat(Object.getOwnPropertySymbols(e)):s},a.prototype.listeners=function(e){var t=r?r+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var s=0,i=n.length,o=new Array(i);s{"use strict";e.exports=function e(t,r){if(t===r)return!0;if(t&&r&&"object"==typeof t&&"object"==typeof r){if(t.constructor!==r.constructor)return!1;var n,s,i;if(Array.isArray(t)){if((n=t.length)!=r.length)return!1;for(s=n;0!=s--;)if(!e(t[s],r[s]))return!1;return!0}if(t.constructor===RegExp)return t.source===r.source&&t.flags===r.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===r.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===r.toString();if((n=(i=Object.keys(t)).length)!==Object.keys(r).length)return!1;for(s=n;0!=s--;)if(!Object.prototype.hasOwnProperty.call(r,i[s]))return!1;for(s=n;0!=s--;){var o=i[s];if(!e(t[o],r[o]))return!1}return!0}return t!=t&&r!=r}},865:e=>{"use strict";const t=(e,t,n,s)=>{if("length"===n||"prototype"===n)return;if("arguments"===n||"caller"===n)return;const i=Object.getOwnPropertyDescriptor(e,n),o=Object.getOwnPropertyDescriptor(t,n);!r(i,o)&&s||Object.defineProperty(e,n,o)},r=function(e,t){return void 0===e||e.configurable||e.writable===t.writable&&e.enumerable===t.enumerable&&e.configurable===t.configurable&&(e.writable||e.value===t.value)},n=(e,t)=>`/* Wrapped ${e}*/\n${t}`,s=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),i=Object.getOwnPropertyDescriptor(Function.prototype.toString,"name");e.exports=(e,r,{ignoreNonConfigurable:o=!1}={})=>{const{name:a}=e;for(const n of Reflect.ownKeys(r))t(e,r,n,o);return((e,t)=>{const r=Object.getPrototypeOf(t);r!==Object.getPrototypeOf(e)&&Object.setPrototypeOf(e,r)})(e,r),((e,t,r)=>{const o=""===r?"":`with ${r.trim()}() `,a=n.bind(null,o,t.toString());Object.defineProperty(a,"name",i),Object.defineProperty(e,"toString",{...s,value:a})})(e,r,a),e}},617:e=>{"use strict";e.exports=(e,t)=>(t=t||(()=>{}),e.then((e=>new Promise((e=>{e(t())})).then((()=>e))),(e=>new Promise((e=>{e(t())})).then((()=>{throw e})))))},290:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(368),s=r(685),i=r(774),o=()=>{},a=new s.TimeoutError;t.default=class extends n{constructor(e){var t,r,n,s;if(super(),this._intervalCount=0,this._intervalEnd=0,this._pendingCount=0,this._resolveEmpty=o,this._resolveIdle=o,!("number"==typeof(e=Object.assign({carryoverConcurrencyCount:!1,intervalCap:1/0,interval:0,concurrency:1/0,autoStart:!0,queueClass:i.default},e)).intervalCap&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${null!==(r=null===(t=e.intervalCap)||void 0===t?void 0:t.toString())&&void 0!==r?r:""}\` (${typeof e.intervalCap})`);if(void 0===e.interval||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${null!==(s=null===(n=e.interval)||void 0===n?void 0:n.toString())&&void 0!==s?s:""}\` (${typeof e.interval})`);this._carryoverConcurrencyCount=e.carryoverConcurrencyCount,this._isIntervalIgnored=e.intervalCap===1/0||0===e.interval,this._intervalCap=e.intervalCap,this._interval=e.interval,this._queue=new e.queueClass,this._queueClass=e.queueClass,this.concurrency=e.concurrency,this._timeout=e.timeout,this._throwOnTimeout=!0===e.throwOnTimeout,this._isPaused=!1===e.autoStart}get _doesIntervalAllowAnother(){return this._isIntervalIgnored||this._intervalCount{this._onResumeInterval()}),t)),!0;this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0}return!1}_tryToStartAnother(){if(0===this._queue.size)return this._intervalId&&clearInterval(this._intervalId),this._intervalId=void 0,this._resolvePromises(),!1;if(!this._isPaused){const e=!this._isIntervalPaused();if(this._doesIntervalAllowAnother&&this._doesConcurrentAllowAnother){const t=this._queue.dequeue();return!!t&&(this.emit("active"),t(),e&&this._initializeIntervalIfNeeded(),!0)}}return!1}_initializeIntervalIfNeeded(){this._isIntervalIgnored||void 0!==this._intervalId||(this._intervalId=setInterval((()=>{this._onInterval()}),this._interval),this._intervalEnd=Date.now()+this._interval)}_onInterval(){0===this._intervalCount&&0===this._pendingCount&&this._intervalId&&(clearInterval(this._intervalId),this._intervalId=void 0),this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0,this._processQueue()}_processQueue(){for(;this._tryToStartAnother(););}get concurrency(){return this._concurrency}set concurrency(e){if(!("number"==typeof e&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this._concurrency=e,this._processQueue()}async add(e,t={}){return new Promise(((r,n)=>{this._queue.enqueue((async()=>{this._pendingCount++,this._intervalCount++;try{const i=void 0===this._timeout&&void 0===t.timeout?e():s.default(Promise.resolve(e()),void 0===t.timeout?this._timeout:t.timeout,(()=>{(void 0===t.throwOnTimeout?this._throwOnTimeout:t.throwOnTimeout)&&n(a)}));r(await i)}catch(e){n(e)}this._next()}),t),this._tryToStartAnother(),this.emit("add")}))}async addAll(e,t){return Promise.all(e.map((async e=>this.add(e,t))))}start(){return this._isPaused?(this._isPaused=!1,this._processQueue(),this):this}pause(){this._isPaused=!0}clear(){this._queue=new this._queueClass}async onEmpty(){if(0!==this._queue.size)return new Promise((e=>{const t=this._resolveEmpty;this._resolveEmpty=()=>{t(),e()}}))}async onIdle(){if(0!==this._pendingCount||0!==this._queue.size)return new Promise((e=>{const t=this._resolveIdle;this._resolveIdle=()=>{t(),e()}}))}get size(){return this._queue.size}sizeBy(e){return this._queue.filter(e).length}get pending(){return this._pendingCount}get isPaused(){return this._isPaused}get timeout(){return this._timeout}set timeout(e){this._timeout=e}}},998:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t,r){let n=0,s=e.length;for(;s>0;){const i=s/2|0;let o=n+i;r(e[o],t)<=0?(n=++o,s-=i+1):s=i}return n}},774:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(998);t.default=class{constructor(){this._queue=[]}enqueue(e,t){const r={priority:(t=Object.assign({priority:0},t)).priority,run:e};if(this.size&&this._queue[this.size-1].priority>=t.priority)return void this._queue.push(r);const s=n.default(this._queue,r,((e,t)=>t.priority-e.priority));this._queue.splice(s,0,r)}dequeue(){const e=this._queue.shift();return null==e?void 0:e.run}filter(e){return this._queue.filter((t=>t.priority===e.priority)).map((e=>e.run))}get size(){return this._queue.length}}},368:e=>{"use strict";var t=Object.prototype.hasOwnProperty,r="~";function n(){}function s(e,t,r){this.fn=e,this.context=t,this.once=r||!1}function i(e,t,n,i,o){if("function"!=typeof n)throw new TypeError("The listener must be a function");var a=new s(n,i||e,o),c=r?r+t:t;return e._events[c]?e._events[c].fn?e._events[c]=[e._events[c],a]:e._events[c].push(a):(e._events[c]=a,e._eventsCount++),e}function o(e,t){0==--e._eventsCount?e._events=new n:delete e._events[t]}function a(){this._events=new n,this._eventsCount=0}Object.create&&(n.prototype=Object.create(null),(new n).__proto__||(r=!1)),a.prototype.eventNames=function(){var e,n,s=[];if(0===this._eventsCount)return s;for(n in e=this._events)t.call(e,n)&&s.push(r?n.slice(1):n);return Object.getOwnPropertySymbols?s.concat(Object.getOwnPropertySymbols(e)):s},a.prototype.listeners=function(e){var t=r?r+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var s=0,i=n.length,o=new Array(i);s{"use strict";const n=r(617);class s extends Error{constructor(e){super(e),this.name="TimeoutError"}}const i=(e,t,r)=>new Promise(((i,o)=>{if("number"!=typeof t||t<0)throw new TypeError("Expected `milliseconds` to be a positive number");if(t===1/0)return void i(e);const a=setTimeout((()=>{if("function"==typeof r){try{i(r())}catch(e){o(e)}return}const n=r instanceof Error?r:new s("string"==typeof r?r:`Promise timed out after ${t} milliseconds`);"function"==typeof e.cancel&&e.cancel(),o(n)}),t);n(e.then(i,o),(()=>{clearTimeout(a)}))}));e.exports=i,e.exports.default=i,e.exports.TimeoutError=s},194:e=>{"use strict";e.exports=require("dgram")},943:e=>{"use strict";e.exports=require("fs/promises")},897:e=>{"use strict";e.exports=require("net")},928:e=>{"use strict";e.exports=require("path")},203:e=>{"use strict";e.exports=require("stream")},581:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0})},326:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.runEntrypoint=function(e,t){Promise.resolve().then((async()=>{if(l)throw new Error("runEntrypoint can only be called once");l=!0;const r=process.env.MODULE_MANIFEST;if(!r)throw new Error("Module initialise is missing MODULE_MANIFEST");const n=await i.default.readFile(r),d=JSON.parse(n.toString());if(d.runtime?.api!==s.HostApiNodeJsIpc)throw new Error("Module manifest 'api' mismatch");if(!d.runtime.apiVersion)throw new Error("Module manifest 'apiVersion' missing");let p=d.runtime.apiVersion;if("0.0.0"===p)try{const e=await i.default.readFile(c.default.join(__dirname,"../package.json")),t=JSON.parse(e.toString());"@companion-module/base"===t.name&&(p=t.version)}catch(e){throw new Error("Failed to determine module api version")}if(!process.send)throw new Error("Module is not being run with ipc");console.log(`Starting up module class: ${e.name}`);const f=process.env.CONNECTION_ID;if("string"!=typeof f||!f)throw new Error("Module initialise is missing CONNECTION_ID");const h=process.env.VERIFICATION_TOKEN;if("string"!=typeof h||!h)throw new Error("Module initialise is missing VERIFICATION_TOKEN");const y=new a.IpcWrapper({},(e=>{process.send(e)}),5e3);process.once("message",(e=>{y.receivedMessage(e)})),u=new e((0,o.literal)({id:f,upgradeScripts:t,_isInstanceBaseProps:!0})),y.sendWithCb("register",{apiVersion:p,connectionId:f,verificationToken:h}).then((()=>{console.log("Module-host accepted registration")}),(e=>{console.error("Module registration failed",e),process.exit(11)}))})).catch((e=>{console.error("Failed to startup module:"),console.error(e.stack||e.message),process.exit(1)}))};const n=r(635),s=r(967),i=n.__importDefault(r(943)),o=r(360),a=r(44),c=n.__importDefault(r(928));let u,l=!1},160:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UDPHelper=t.TelnetHelper=t.TCPHelper=void 0;var n=r(895);Object.defineProperty(t,"TCPHelper",{enumerable:!0,get:function(){return n.TCPHelper}});var s=r(118);Object.defineProperty(t,"TelnetHelper",{enumerable:!0,get:function(){return s.TelnetHelper}});var i=r(259);Object.defineProperty(t,"UDPHelper",{enumerable:!0,get:function(){return i.UDPHelper}})},895:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TCPHelper=void 0;const n=r(635).__importDefault(r(897)),s=r(228),i=r(400);class o extends s.EventEmitter{#e;#t;_socket;#r;#n=!1;#s=!1;#i=!1;#o;#a;#c;get isConnected(){return this.#n}get isConnecting(){return this.#s}get isDestroyed(){return this.#i}constructor(e,t,r){super(),this.#e=e,this.#t=t,this.#r={reconnect_interval:2e3,reconnect:!0,...r},this._socket=new n.default.Socket,this._socket.setKeepAlive(!0),this._socket.setNoDelay(!0),this._socket.on("error",(e=>{this.#s=!1,this.#n=!1,this.#r.reconnect&&this.#u(),this.#l(i.InstanceStatus.UnknownError,e.message),this.emit("error",e)})),this._socket.on("ready",(()=>{this.#n=!0,this.#s=!1,this.#l(i.InstanceStatus.Ok),this.emit("connect")})),this._socket.on("end",(()=>{this.#n=!1,this.#l(i.InstanceStatus.Disconnected),!this.#s&&this.#r.reconnect&&this.#u(),this.emit("end")})),this._socket.on("data",(e=>this.emit("data",e))),this._socket.on("drain",(()=>this.emit("drain"))),setImmediate((()=>{this.#i||this.connect()})),this.#c=setTimeout((()=>{this.#c=void 0,this.#i||this.listenerCount("error")||console.error(`Danger: TCP client for ${this.#e}:${this.#t} is missing an error handler!`)}),5e3)}connect(){if(this.#i)throw new Error("Cannot connect destroyed socket");return!this.#s&&(this.#s=!0,this._socket.connect(this.#t,this.#e),!0)}async send(e){if(this.#i||this._socket.destroyed)throw new Error("Cannot write to destroyed socket");if(!e||!e.length)throw new Error("No message to send");if(!this.#n)return!1;try{return new Promise(((t,r)=>{this._socket.write(e,(e=>{e?r(e):t(!0)}))}))}catch(e){this.#n=!1;const t=e instanceof Error?e:new Error(`${e}`);throw this.#l(i.InstanceStatus.UnknownError,t.message),this.emit("error",t),t}}destroy(){this.#i=!0,void 0!==this.#a&&(clearTimeout(this.#a),this.#a=void 0),void 0!==this.#c&&(clearTimeout(this.#c),this.#c=void 0),this._socket.removeAllListeners(),this.removeAllListeners(),this._socket.destroy()}#u(){void 0!==this.#a&&clearTimeout(this.#a),this.#a=setTimeout((()=>{this.#a=void 0,this.#l(i.InstanceStatus.Connecting),this.connect()}),this.#r.reconnect_interval)}#l(e,t){this.#o!=e&&(this.#o=e,this.emit("status_change",e,t))}}t.TCPHelper=o},118:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TelnetHelper=void 0;const n=r(635).__importDefault(r(228)),s=r(203),i=r(895);class o extends n.default{#d;#p;#c;get isConnected(){return this.#d.isConnected}get isConnecting(){return this.#d.isConnecting}get isDestroyed(){return this.#d.isDestroyed}constructor(e,t,r){super(),this.#d=new i.TCPHelper(e,t,r),this.#p=new a,this.#d._socket.pipe(this.#p),this.#d.on("connect",(()=>this.emit("connect"))),this.#d.on("end",(()=>this.emit("end"))),this.#d.on("error",(e=>this.emit("error",e))),this.#d.on("status_change",((e,t)=>this.emit("status_change",e,t))),this.#p.on("iac",((e,t)=>this.emit("iac",e,t))),this.#p.on("sb",(e=>this.emit("sb",e))),this.#p.on("data",(e=>this.emit("data",e))),this.#p.on("drain",(()=>this.emit("drain"))),this.#c=setTimeout((()=>{this.#c=void 0,this.isDestroyed||this.listenerCount("error")||console.error(`Danger: Telnet client for ${e}:${t} is missing an error handler!`)}),5e3)}connect(){return this.#d.connect()}async send(e){return this.#d.send(e)}destroy(){this.#d.destroy(),void 0!==this.#c&&(clearTimeout(this.#c),this.#c=void 0),this.#p.removeAllListeners(),this.#p.destroy()}}t.TelnetHelper=o;class a extends s.Transform{#f;#h;#y;constructor(e){super(e),this.#f=Buffer.alloc(0),this.#h=Buffer.alloc(0),this.#y=0}_transform(e,t,r){for(let t=0;t=251&&this.#y<=254){let t;switch(this.#y){case 251:t="WILL";break;case 252:t="WONT";break;case 253:t="DO";break;case 254:t="DONT";break;default:return}return this.emit("iac",t,e),void(this.#y=0)}if(250===this.#y){if(240===e)return this.emit("sb",this.#h),this.#y=0,void(this.#h=Buffer.alloc(0));this.#h=Buffer.concat([this.#h,Buffer.from([e])])}}}#m(){const e=this.#f;return this.#f=Buffer.alloc(0),e}}},259:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UDPHelper=void 0;const n=r(635).__importDefault(r(194)),s=r(228),i=r(400);class o extends s.EventEmitter{#e;#t;#g;#r;#i=!1;#o;#c;get isDestroyed(){return this.#i}constructor(e,t,r){super(),this.#e=e,this.#t=t,this.#r={...r},this.#g=n.default.createSocket("udp4");try{this.#g.bind(this.#r.bind_port||0,this.#r.bind_ip)}catch(e){throw new Error(`Unable to bind to ip/port: ${this.#r.bind_ip||"0.0.0.0"}:${this.#r.bind_port||0}`)}this.#r.broadcast&&this.#g.setBroadcast(!0),void 0!==this.#r.ttl&&this.#g.setTTL(this.#r.ttl),void 0!==this.#r.multicast_ttl&&this.#g.setMulticastTTL(this.#r.multicast_ttl),this.#g.on("error",(e=>{this.#l(i.InstanceStatus.UnknownError,e.message),this.emit("error",e)})),this.#g.on("listening",(()=>{this.#r.multicast_interface&&this.#g.setMulticastInterface(this.#r.multicast_interface),this.#l(i.InstanceStatus.Ok),this.emit("listening")})),this.#g.on("message",(e=>this.emit("data",e))),this.#c=setTimeout((()=>{this.#i||this.listenerCount("error")||console.error(`Danger: UDP socket for ${this.#e}:${this.#t} is missing an error handler!`)}),5e3)}async send(e){if(this.#i)throw new Error("Cannot write to destroyed socket");if(!e||!e.length)throw new Error("No message to send");return new Promise(((t,r)=>{this.#g.send(e,this.#t,this.#e,(e=>{e?r(e):t()}))}))}destroy(){this.#i=!0,void 0!==this.#c&&(clearTimeout(this.#c),this.#c=void 0),this.#g.removeAllListeners(),this.#g.close(),this.removeAllListeners()}#l(e,t){this.#o!=e&&(this.#o=e,this.emit("status_change",e,t))}}t.UDPHelper=o},44:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.IpcWrapper=void 0;const n=r(635),s=r(360),i=n.__importDefault(r(22));t.IpcWrapper=class{#v;#_;#w;#k=1;#I=new Map;constructor(e,t,r){this.#v=e,this.#_=t,this.#w=r}async sendWithCb(e,t,r,n=0){n<=0&&(n=this.#w);const s={timeout:void 0,resolve:()=>null,reject:()=>null},o=new Promise(((e,t)=>{s.resolve=e,s.reject=t}));this.#k>268435456&&(this.#k=1);const a=this.#k++;this.#I.set(a,s),this.#_({direction:"call",name:String(e),payload:i.default.stringify(t),callbackId:a});const c=new Error("Call timed out");return s.timeout=setTimeout((()=>{s.reject(r?r():c),this.#I.delete(a)}),n),o}sendWithNoCb(e,t){this.#_({direction:"call",name:String(e),payload:i.default.stringify(t),callbackId:void 0})}receivedMessage(e){const t=e;switch(e.direction){case"call":{const t=this.#v[e.name];if(!t)return void(e.callbackId&&this.#_({direction:"response",callbackId:e.callbackId,success:!1,payload:i.default.stringify({message:`Unknown command "${e.name}"`})}));t(e.payload?i.default.parse(e.payload):void 0).then((t=>{e.callbackId&&this.#_({direction:"response",callbackId:e.callbackId,success:!0,payload:i.default.stringify(t)})}),(t=>{e.callbackId&&this.#_({direction:"response",callbackId:e.callbackId,success:!1,payload:t instanceof Error?JSON.stringify(t,Object.getOwnPropertyNames(t)):i.default.stringify(t)})}));break}case"response":{if(!e.callbackId)return void console.error("Ipc: Response message has no callbackId");const t=this.#I.get(e.callbackId);if(this.#I.delete(e.callbackId),!t)return;clearTimeout(t.timeout);const r=e.payload?i.default.parse(e.payload):void 0;if(e.success)t.resolve(r);else{let e=r;r&&"object"==typeof r&&"message"in r&&(e=new Error(r.message),r.stack&&(e.stack=r.stack)),t.reject(e)}break}default:(0,s.assertNever)(e),console.error(`Ipc: Message of unknown direction "${t.direction}"`)}}}},967:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HostApiNodeJsIpc=void 0,t.HostApiNodeJsIpc="nodejs-ipc"},278:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.runEntrypoint=t.assertNever=t.splitHex=t.splitHsv=t.splitHsl=t.splitRgb=t.combineRgb=t.literal=void 0;const n=r(635);n.__exportStar(r(77),t),n.__exportStar(r(18),t),n.__exportStar(r(581),t);var s=r(360);Object.defineProperty(t,"literal",{enumerable:!0,get:function(){return s.literal}}),Object.defineProperty(t,"combineRgb",{enumerable:!0,get:function(){return s.combineRgb}}),Object.defineProperty(t,"splitRgb",{enumerable:!0,get:function(){return s.splitRgb}}),Object.defineProperty(t,"splitHsl",{enumerable:!0,get:function(){return s.splitHsl}}),Object.defineProperty(t,"splitHsv",{enumerable:!0,get:function(){return s.splitHsv}}),Object.defineProperty(t,"splitHex",{enumerable:!0,get:function(){return s.splitHex}}),Object.defineProperty(t,"assertNever",{enumerable:!0,get:function(){return s.assertNever}}),n.__exportStar(r(160),t);var i=r(326);Object.defineProperty(t,"runEntrypoint",{enumerable:!0,get:function(){return i.runEntrypoint}})},289:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ActionManager=void 0;const n=r(593);function s(e){return{id:e.id,actionId:e.actionId,controlId:e.controlId,options:e.options}}t.ActionManager=class{#S;#O;#P;#j=new Map;#A=new Map;constructor(e,t,r){this.#S=e,this.#O=t,this.#P=r}async handleExecuteAction(e){const t=this.#j.get(e.action.actionId);if(!t)throw new Error(`Unknown action: ${e.action.actionId}`);const r={parseVariablesInString:async t=>(await this.#S({text:t,controlId:e.action.controlId,actionInstanceId:e.action.id,feedbackInstanceId:void 0})).text};await t.callback({id:e.action.id,actionId:e.action.actionId,controlId:e.action.controlId,options:e.action.options,surfaceId:e.surfaceId},r)}handleUpdateActions(e){for(const[t,r]of Object.entries(e)){const e=this.#A.get(t);if(e){const t=this.#j.get(e.actionId);if(t?.unsubscribe){const r={parseVariablesInString:async t=>(await this.#S({text:t,controlId:e.controlId,actionInstanceId:e.id,feedbackInstanceId:void 0})).text};Promise.resolve(t.unsubscribe(s(e),r)).catch((t=>{this.#P("error",`Action unsubscribe failed: ${JSON.stringify(e)} - ${t?.message??t} ${t?.stack}`)}))}}if(!r||r.disabled)this.#A.delete(t);else{this.#A.set(t,r);const e=this.#j.get(r.actionId);if(e?.subscribe){const t={parseVariablesInString:async e=>(await this.#S({text:e,controlId:r.controlId,actionInstanceId:r.id,feedbackInstanceId:void 0})).text};Promise.resolve(e.subscribe(s(r),t)).catch((e=>{this.#P("error",`Action subscribe failed: ${JSON.stringify(r)} - ${e?.message??e} ${e?.stack}`)}))}}}}async handleLearnAction(e){const t=this.#j.get(e.action.actionId);if(t&&t.learn){const r={parseVariablesInString:async t=>(await this.#S({text:t,controlId:e.action.controlId,actionInstanceId:e.action.id,feedbackInstanceId:void 0})).text};return{options:await t.learn({id:e.action.id,actionId:e.action.actionId,controlId:e.action.controlId,options:e.action.options,surfaceId:void 0},r)}}return{options:void 0}}setActionDefinitions(e){const t=[];this.#j.clear();for(const[r,s]of Object.entries(e))s&&(t.push({id:r,name:s.name,description:s.description,options:(0,n.serializeIsVisibleFn)(s.options),hasLearn:!!s.learn,learnTimeout:s.learnTimeout}),this.#j.set(r,s));this.#O({actions:t})}_getAllActions(){return Array.from(this.#A.values()).map((e=>({id:e.id,actionId:e.actionId,controlId:e.controlId,options:e.options})))}subscribeActions(e){let t=Array.from(this.#A.values());const r=new Set(e);r.size&&(t=t.filter((e=>r.has(e.actionId))));for(const e of t){const t=this.#j.get(e.actionId);if(t?.subscribe){const r={parseVariablesInString:async t=>(await this.#S({text:t,controlId:e.controlId,actionInstanceId:e.id,feedbackInstanceId:void 0})).text};Promise.resolve(t.subscribe(s(e),r)).catch((t=>{this.#P("error",`Action subscribe failed: ${JSON.stringify(e)} - ${t?.message??t} ${t?.stack}`)}))}}}unsubscribeActions(e){let t=Array.from(this.#A.values());const r=new Set(e);r.size&&(t=t.filter((e=>r.has(e.actionId))));for(const e of t){const t=this.#j.get(e.actionId);if(t&&t.unsubscribe){const r={parseVariablesInString:async t=>(await this.#S({text:t,controlId:e.controlId,actionInstanceId:e.id,feedbackInstanceId:void 0})).text};Promise.resolve(t.unsubscribe(s(e),r)).catch((t=>{this.#P("error",`Action unsubscribe failed: ${JSON.stringify(e)} - ${t?.message??t} ${t?.stack}`)}))}}}}},593:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.serializeIsVisibleFn=function(e){return(e??[]).map((e=>"isVisible"in e&&"function"==typeof e.isVisible?{...e,isVisibleFn:e.isVisible.toString(),isVisible:void 0}:{...e,isVisibleFn:void 0}))},t.isInstanceBaseProps=function(e){const t=e;return"object"==typeof t&&"string"==typeof t.id&&!0===t._isInstanceBaseProps}},39:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.FeedbackManager=void 0;const n=r(635),s=r(593),i=n.__importDefault(r(0));function o(e,t){return{type:e,id:t.id,feedbackId:t.feedbackId,controlId:t.controlId,options:t.options}}t.FeedbackManager=class{#S;#E;#x;#P;#C=new Map;#T=new Map;#N=new Map;#M=new Map;#V;get parseVariablesContext(){return this.#V}constructor(e,t,r,n){this.#S=e,this.#E=t,this.#x=r,this.#P=n}getDefinitionIds(){return Array.from(this.#C.keys())}getInstanceIds(){return Array.from(this.#T.keys())}handleUpdateFeedbacks(e){for(const[t,r]of Object.entries(e)){const e=this.#T.get(t);if(e){const t=this.#C.get(e.feedbackId);if(t?.unsubscribe){const r={parseVariablesInString:async t=>(await this.#S({text:t,controlId:e.controlId,actionInstanceId:void 0,feedbackInstanceId:e.id})).text};Promise.resolve(t.unsubscribe(o(t.type,e),r)).catch((t=>{this.#P("error",`Feedback unsubscribe failed: ${JSON.stringify(e)} - ${t?.message??t} ${t?.stack}`)}))}}if(!r||r.disabled)this.#T.delete(t);else{this.#T.set(t,{...r,referencedVariables:null});const e=this.#C.get(r.feedbackId);if(e?.subscribe){const t={parseVariablesInString:async e=>(await this.#S({text:e,controlId:r.controlId,actionInstanceId:void 0,feedbackInstanceId:r.id})).text};Promise.resolve(e.subscribe(o(e.type,r),t)).catch((e=>{this.#P("error",`Feedback subscribe failed: ${JSON.stringify(r)} - ${e?.message??e} ${e?.stack}`)}))}this.#$(t)}}}async handleLearnFeedback(e){const t=this.#C.get(e.feedback.feedbackId);if(t&&t.learn){const r={parseVariablesInString:async t=>(await this.#S({text:t,controlId:e.feedback.controlId,actionInstanceId:void 0,feedbackInstanceId:e.feedback.id})).text};return{options:await t.learn({id:e.feedback.id,feedbackId:e.feedback.feedbackId,controlId:e.feedback.controlId,options:e.feedback.options,type:t.type},r)}}return{options:void 0}}handleVariablesChanged(e){if(!e.variablesIds.length)return;const t=new Set(e.variablesIds);for(const t of this.#M.values())for(const r of e.variablesIds)t.changedVariables.add(r);const r=new Set;for(const e of this.#T.values())if(!this.#M.has(e.id)&&e.referencedVariables)for(const n of e.referencedVariables)if(t.has(n)){r.add(e.id);break}for(const e of r)setImmediate((()=>{this.#$(e)}))}#$(e){const t=this.#M.get(e);if(t)return void(t.needsRecheck=!0);const r=this.#T.get(e);if(!r)return;const n=r,s={needsRecheck:!1,changedVariables:new Set};this.#M.set(e,s),Promise.resolve().then((async()=>{const t=this.#C.get(n.feedbackId);let r;const s=new Set;if(t){this.#V=`Feedback ${n.feedbackId} (${e})`;const i={parseVariablesInString:async t=>{const r=await this.#S({text:t,controlId:n.controlId,actionInstanceId:void 0,feedbackInstanceId:e});if(r.variableIds&&r.variableIds.length)for(const e of r.variableIds)s.add(e);return r.text}};r="boolean"===t.type?t.callback({...o("boolean",n),type:"boolean"},i):t.callback({...o("advanced",n),type:"advanced",image:n.image},i),this.#V=void 0}const i=await r;this.#N.set(e,{id:e,controlId:n.controlId,value:i}),this.#D(),n.referencedVariables=s.size>0?Array.from(s):null})).catch((e=>{console.error(`Feedback check failed: ${JSON.stringify(n)} - ${e?.message??e} ${e?.stack}`)})).finally((()=>{this.#V=void 0,this.#M.delete(e);let t=!1;if(n.referencedVariables)for(const e of n.referencedVariables)if(s.changedVariables.has(e)){t=!0;break}(t||s.needsRecheck)&&setImmediate((()=>{this.#$(e)}))}))}#D=(0,i.default)((()=>{const e=this.#N;this.#N=new Map,e.size>0&&this.#E({values:Array.from(e.values())})}),{wait:5,maxWait:25});setFeedbackDefinitions(e){const t=[];this.#C.clear();for(const[r,n]of Object.entries(e))n&&(t.push({id:r,name:n.name,description:n.description,options:(0,s.serializeIsVisibleFn)(n.options),type:n.type,defaultStyle:"boolean"===n.type?n.defaultStyle:void 0,hasLearn:!!n.learn,learnTimeout:n.learnTimeout,showInvert:"boolean"===n.type&&n.showInvert}),this.#C.set(r,n));this.#x({feedbacks:t})}checkFeedbacks(e){const t=new Set(e);for(const[e,r]of this.#T.entries())this.#C.get(r.feedbackId)&&(0===t.size||t.has(r.feedbackId))&&this.#$(e)}checkFeedbacksById(e){for(const t of e)this.#$(t)}_getAllFeedbacks(){return Array.from(this.#T.values()).map((e=>({id:e.id,feedbackId:e.feedbackId,controlId:e.controlId,options:e.options})))}subscribeFeedbacks(e){let t=Array.from(this.#T.values());const r=new Set(e);r.size&&(t=t.filter((e=>r.has(e.feedbackId))));for(const e of t){const t=this.#C.get(e.feedbackId);if(t?.subscribe){const r={parseVariablesInString:async t=>(await this.#S({text:t,controlId:e.controlId,actionInstanceId:void 0,feedbackInstanceId:e.id})).text};Promise.resolve(t.subscribe(o(t.type,e),r)).catch((t=>{this.#P("error",`Feedback subscribe failed: ${JSON.stringify(e)} - ${t?.message??t} ${t?.stack}`)}))}}}unsubscribeFeedbacks(e){let t=Array.from(this.#T.values());const r=new Set(e);r.size&&(t=t.filter((e=>r.has(e.feedbackId))));for(const e of t){const t=this.#C.get(e.feedbackId);if(t&&t.unsubscribe){const r={parseVariablesInString:async t=>(await this.#S({text:t,controlId:e.controlId,actionInstanceId:void 0,feedbackInstanceId:e.id})).text};Promise.resolve(t.unsubscribe(o(t.type,e),r)).catch((t=>{this.#P("error",`Feedback unsubscribe failed: ${JSON.stringify(e)} - ${t?.message??t} ${t?.stack}`)}))}}}}},706:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.runThroughUpgradeScripts=function(e,t,r,i,o,a){const c=new Map,u=e=>{let t=c.get(e);return t||(t={actions:[],feedbacks:[],config:!1},c.set(e,t)),t};for(const t of Object.values(e)){const e=t?.upgradeIndex??r;t&&"number"==typeof e&&u(e).actions.push(t.id)}for(const e of Object.values(t)){const t=e?.upgradeIndex??r;e&&"number"==typeof t&&u(t).feedbacks.push(e.id)}if(!a)for(let e=r??-1;e0){const a=Array.from(c.keys()).sort(),u=Math.min(...a,r??-1)+1,f=[],h=[],y=i.length;for(let r=u;r{const r=e[t];if(r)return(0,n.literal)({id:r.id,controlId:r.controlId,actionId:r.actionId,options:void 0!==r.options?s(r.options):{}})})).filter((e=>!!e)),feedbacks:h.map((e=>{const r=t[e];if(r)return(0,n.literal)({id:r.id,controlId:r.controlId,feedbackId:r.feedbackId,options:void 0!==r.options?s(r.options):{},isInverted:r.isInverted})})).filter((e=>!!e))});u&&b.updatedConfig&&(p=b.updatedConfig);for(const t of b.updatedActions)if(t){const r=e[t.id];r&&(r.actionId=t.actionId,r.options=t.options,d[t.id]=r)}for(const e of b.updatedFeedbacks)if(e){const r=t[e.id];r&&(r.feedbackId=e.feedbackId,r.options=e.options,l[e.id]={...r,style:l[e.id]?.style??e.style,isInverted:e.isInverted??!1})}}for(const[t,r]of Object.entries(e))d[t]||"number"!=typeof r?.upgradeIndex||(d[t]=r);for(const[e,r]of Object.entries(t))l[e]||"number"!=typeof r?.upgradeIndex||(l[e]=r)}return{updatedActions:d,updatedFeedbacks:l,updatedConfig:p}};const n=r(360);function s(e){return JSON.parse(JSON.stringify(e))}},77:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validateManifest=function(e){const t=JSON.stringify(e);if(t.includes("companion-module-your-module-name"))throw new Error("Manifest incorrectly references template module 'companion-module-your-module-name'");if(t.includes("module-shortname"))throw new Error("Manifest incorrectly references template module 'module-shortname'");if(t.includes("A short one line description of your module"))throw new Error("Manifest incorrectly references template module 'A short one line description of your module'");if(t.includes("Your name"))throw new Error("Manifest incorrectly references template module 'Your name'");if(t.includes("Your email"))throw new Error("Manifest incorrectly references template module 'Your email'");if(t.includes("Your company"))throw new Error("Manifest incorrectly references template module 'Your company'");if(t.includes("Your product"))throw new Error("Manifest incorrectly references template module 'Your product'");if(!(0,n.default)(e)){const e=n.default.errors;if(!e)throw new Error("Manifest failed validation with unknown reason");throw new Error(`Manifest validation failed: ${JSON.stringify(e)}`)}};const n=r(635).__importDefault(r(281))},730:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0})},649:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.InstanceBase=void 0;const n=r(635),s=r(360),i=n.__importDefault(r(290)),o=r(593),a=r(706),c=r(39),u=r(44),l=r(289),d=r(365);t.InstanceBase=class{#F;#q;id;#U=new i.default({concurrency:1});#H=!1;#R=!1;#B={};#z;#J;#W=new Map;#Q=new Map;#L=new Map;#r;#Z;get instanceOptions(){return this.#r}get label(){return this.#Z}constructor(e){if(!(0,o.isInstanceBaseProps)(e)||!e._isInstanceBaseProps)throw new Error("Module instance is being constructed incorrectly. Make sure you aren't trying to do this manually");this.createSharedUdpSocket=this.createSharedUdpSocket.bind(this),this.#r={disableVariableValidation:!1},this.#F=new u.IpcWrapper({init:this._handleInit.bind(this),destroy:this._handleDestroy.bind(this),updateConfigAndLabel:this._handleConfigUpdateAndLabel.bind(this),updateConfig:async()=>{},executeAction:this._handleExecuteAction.bind(this),updateFeedbacks:this._handleUpdateFeedbacks.bind(this),updateActions:this._handleUpdateActions.bind(this),getConfigFields:this._handleGetConfigFields.bind(this),handleHttpRequest:this._handleHttpRequest.bind(this),learnAction:this._handleLearnAction.bind(this),learnFeedback:this._handleLearnFeedback.bind(this),startStopRecordActions:this._handleStartStopRecordActions.bind(this),variablesChanged:this._handleVariablesChanged.bind(this),sharedUdpSocketMessage:this._handleSharedUdpSocketMessage.bind(this),sharedUdpSocketError:this._handleSharedUdpSocketError.bind(this)},(e=>{process.send(e)}),5e3),process.on("message",(e=>{this.#F.receivedMessage(e)})),this.#z=new l.ActionManager((async e=>this.#F.sendWithCb("parseVariablesInString",e)),(e=>this.#F.sendWithNoCb("setActionDefinitions",e)),this.log.bind(this)),this.#J=new c.FeedbackManager((async e=>this.#F.sendWithCb("parseVariablesInString",e)),(e=>this.#F.sendWithNoCb("updateFeedbackValues",e)),(e=>this.#F.sendWithNoCb("setFeedbackDefinitions",e)),this.log.bind(this)),this.#q=e.upgradeScripts,this.id=e.id,this.#Z=e.id,this.log("debug","Initializing")}async _handleInit(e){return this.#U.add((async()=>{if(this.#H)throw new Error("Already initialized");const t=e.actions,r=e.feedbacks;if(this.#B=e.config,this.#Z=e.label,e.isFirstInit){const t={},r=this.getConfigFields();for(const e of r)"default"in e&&(t[e.id]=e.default);this.#B=t,this.saveConfig(this.#B),e.lastUpgradeIndex=this.#q.length-1}const{updatedActions:n,updatedFeedbacks:s,updatedConfig:i}=(0,a.runThroughUpgradeScripts)(t,r,e.lastUpgradeIndex,this.#q,this.#B,!1);this.#B=i??this.#B;const o=this.#F.sendWithCb("upgradedItems",{updatedActions:n,updatedFeedbacks:s});try{await this.init(this.#B,!!e.isFirstInit),this.#H=!0}catch(e){throw console.trace(`Init failed: ${e}`),e}finally{await o}return setImmediate((()=>{this._handleUpdateActions({actions:t},!0).catch((e=>{this.log("error",`Receive actions failed: ${e}`)})),this._handleUpdateFeedbacks({feedbacks:r},!0).catch((e=>{this.log("error",`Receive feedbacks failed: ${e}`)}))})),{hasHttpHandler:"function"==typeof this.handleHttpRequest,hasRecordActionsHandler:"function"==typeof this.handleStartStopRecordActions,newUpgradeIndex:this.#q.length-1,updatedConfig:this.#B}}))}async _handleDestroy(){await this.#U.add((async()=>{if(!this.#H)throw new Error("Not initialized");await this.destroy(),this.#H=!1}))}async _handleConfigUpdateAndLabel(e){await this.#U.add((async()=>{if(!this.#H)throw new Error("Not initialized");this.#Z=e.label,this.#B=e.config,await this.configUpdated(this.#B)}))}async _handleExecuteAction(e){return this.#z.handleExecuteAction(e)}async _handleUpdateFeedbacks(e,t){if(!t){const t=(0,a.runThroughUpgradeScripts)({},e.feedbacks,null,this.#q,this.#B,!0);this.#F.sendWithCb("upgradedItems",{updatedActions:t.updatedActions,updatedFeedbacks:t.updatedFeedbacks}).catch((e=>{this.log("error",`Failed to save upgraded feedbacks: ${e}`)}))}this.#J.handleUpdateFeedbacks(e.feedbacks)}async _handleUpdateActions(e,t){if(!t){const t=(0,a.runThroughUpgradeScripts)(e.actions,{},null,this.#q,this.#B,!0);this.#F.sendWithCb("upgradedItems",{updatedActions:t.updatedActions,updatedFeedbacks:t.updatedFeedbacks}).catch((e=>{this.log("error",`Failed to save upgraded actions: ${e}`)}))}this.#z.handleUpdateActions(e.actions)}async _handleGetConfigFields(e){return{fields:(0,o.serializeIsVisibleFn)(this.getConfigFields())}}async _handleHttpRequest(e){if(!this.handleHttpRequest)throw new Error("handleHttpRequest is not supported!");return{response:await this.handleHttpRequest(e.request)}}async _handleLearnAction(e){return this.#z.handleLearnAction(e)}async _handleLearnFeedback(e){return this.#J.handleLearnFeedback(e)}async _handleStartStopRecordActions(e){if(e.recording){if(this.#R)return}else if(!this.#R)return;if(!this.handleStartStopRecordActions)throw this.#R=!1,new Error("Recording actions is not supported by this module!");this.#R=e.recording,this.handleStartStopRecordActions(this.#R)}async _handleVariablesChanged(e){this.#J.handleVariablesChanged(e)}async _handleSharedUdpSocketMessage(e){for(const t of this.#W.values())t.handleId===e.handleId&&t.receiveSocketMessage(e)}async _handleSharedUdpSocketError(e){for(const t of this.#W.values())t.handleId===e.handleId&&t.receiveSocketError(e.error)}saveConfig(e){this.#B=e,this.#F.sendWithNoCb("saveConfig",{config:e})}setActionDefinitions(e){this.#z.setActionDefinitions(e)}setFeedbackDefinitions(e){this.#J.setFeedbackDefinitions(e)}setPresetDefinitions(e){const t=[];for(const[r,n]of Object.entries(e))n&&t.push({...n,id:r});this.#F.sendWithNoCb("setPresetDefinitions",{presets:t})}setVariableDefinitions(e){const t=[],r=[];this.#Q.clear();for(const n of e)t.push({id:n.variableId,name:n.name}),this.#Q.set(n.variableId,n),this.#L.has(n.variableId)||(this.#L.set(n.variableId,""),r.push({id:n.variableId,value:""}));if(!this.#r.disableVariableValidation){const e=new Set(this.#Q.keys());for(const t of this.#L.keys())e.has(t)||(this.#L.delete(t),r.push({id:t,value:void 0}))}this.#F.sendWithNoCb("setVariableDefinitions",{variables:t,newValues:r})}setVariableValues(e){const t=[];for(const[r,n]of Object.entries(e))this.#r.disableVariableValidation?(void 0===n?this.#L.delete(r):this.#L.set(r,n),t.push({id:r,value:n})):this.#Q.has(r)?(this.#L.set(r,n??""),t.push({id:r,value:n??""})):t.push({id:r,value:void 0});this.#F.sendWithNoCb("setVariableValues",{newValues:t})}getVariableValue(e){return this.#L.get(e)}async parseVariablesInString(e){const t=this.#J.parseVariablesContext;return t&&this.log("debug",`parseVariablesInString called while in: ${t}. You should use the parseVariablesInString provided to the callback instead`),(await this.#F.sendWithCb("parseVariablesInString",{text:e,controlId:void 0,actionInstanceId:void 0,feedbackInstanceId:void 0})).text}checkFeedbacks(...e){this.#J.checkFeedbacks(e)}checkFeedbacksById(...e){this.#J.checkFeedbacksById(e)}_getAllActions(){return this.#z._getAllActions()}subscribeActions(...e){this.#z.subscribeActions(e)}unsubscribeActions(...e){this.#z.unsubscribeActions(e)}_getAllFeedbacks(){return this.#J._getAllFeedbacks()}subscribeFeedbacks(...e){this.#J.subscribeFeedbacks(e)}unsubscribeFeedbacks(...e){this.#J.unsubscribeFeedbacks(e)}recordAction(e,t){if(!this.#R)throw new Error("Not currently recording actions");this.#F.sendWithNoCb("recordAction",{uniquenessId:t??null,actionId:e.actionId,options:e.options,delay:e.delay})}setCustomVariableValue(e,t){this.#F.sendWithNoCb("setCustomVariable",{customVariableId:e,value:t})}oscSend(e,t,r,n){this.#F.sendWithNoCb("send-osc",(0,s.literal)({host:e,port:t,path:r,args:n}))}updateStatus(e,t){this.#F.sendWithNoCb("set-status",(0,s.literal)({status:e,message:t??null}))}log(e,t){this.#F.sendWithNoCb("log-message",(0,s.literal)({level:e,message:t}))}createSharedUdpSocket(e,t){const r="string"==typeof e?{type:e}:e,n=new d.SharedUdpSocketImpl(this.#F,this.#W,r);return t&&n.on("message",t),n}}},386:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0})},400:(e,t)=>{"use strict";var r,n;Object.defineProperty(t,"__esModule",{value:!0}),t.Regex=t.InstanceStatus=void 0,function(e){e.Ok="ok",e.Connecting="connecting",e.Disconnected="disconnected",e.ConnectionFailure="connection_failure",e.BadConfig="bad_config",e.UnknownError="unknown_error",e.UnknownWarning="unknown_warning",e.AuthenticationFailure="authentication_failure"}(r||(t.InstanceStatus=r={})),function(e){e.IP="/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/",e.HOSTNAME="/^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9])\\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9-]*[A-Za-z0-9])$/",e.BOOLEAN="/^(true|false|0|1)$/i",e.PORT="/^([1-9]|[1-8][0-9]|9[0-9]|[1-8][0-9]{2}|9[0-8][0-9]|99[0-9]|[1-8][0-9]{3}|9[0-8][0-9]{2}|99[0-8][0-9]|999[0-9]|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-4])$/",e.MAC_ADDRESS="/^(?:[a-fA-F0-9]{2}:){5}([a-fA-F0-9]{2})$/",e.PERCENT="/^(100|[0-9]|[0-9][0-9])$/",e.FLOAT="/^([0-9]*\\.)?[0-9]+$/",e.SIGNED_FLOAT="/^[+-]?([0-9]*\\.)?[0-9]+$/",e.FLOAT_OR_INT="/^([0-9]+)(\\.[0-9]+)?$/",e.NUMBER="/^\\d+$/",e.SIGNED_NUMBER="/^[+-]?\\d+$/",e.SOMETHING="/^.+$/",e.TIMECODE="/^(0*[0-9]|1[0-9]|2[0-4]):(0*[0-9]|[1-5][0-9]|60):(0*[0-9]|[1-5][0-9]|60):(0*[0-9]|[12][0-9]|30)$/"}(n||(t.Regex=n={}))},983:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0})},104:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0})},18:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(635);n.__exportStar(r(730),t),n.__exportStar(r(649),t),n.__exportStar(r(386),t),n.__exportStar(r(400),t),n.__exportStar(r(983),t),n.__exportStar(r(104),t),n.__exportStar(r(258),t),n.__exportStar(r(131),t),n.__exportStar(r(371),t),n.__exportStar(r(786),t),n.__exportStar(r(132),t)},258:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0})},131:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0})},365:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SharedUdpSocketImpl=void 0;const n=r(635).__importDefault(r(228)),s=r(360);class i extends n.default{#F;#Y;#r;get handleId(){return this.boundState?.handleId}get portNumber(){return this.boundState?.portNumber}get boundState(){return this.#y&&"object"==typeof this.#y?this.#y:void 0}#y="pending";constructor(e,t,r){super(),this.#F=e,this.#Y=t,this.#r={...r}}bind(e,t,r){if(this.#y&&"object"==typeof this.#y)throw new Error("Socket is already bound");switch(this.#y){case"fatalError":throw new Error("Socket has encountered fatal error");case"binding":throw new Error("Socket is already bound");case"closed":throw new Error("Socket is closing");case"pending":break;default:throw(0,s.assertNever)(this.#y),new Error("Invalid socket state")}this.#y="binding",r&&this.on("listening",r),this.#F.sendWithCb("sharedUdpSocketJoin",{family:this.#r.type,portNumber:e}).then((t=>{this.#y={portNumber:e,handleId:t},this.#Y.set(t,this),this.emit("listening")}),(e=>{this.#y="closed",this.emit("error",e instanceof Error?e:new Error(e))})).catch((()=>null))}close(e){if(this.#y&&"object"==typeof this.#y);else switch(this.#y){case"fatalError":throw new Error("Socket has encountered fatal error");case"pending":case"closed":case"binding":throw new Error("Socket is not open");default:throw(0,s.assertNever)(this.#y),new Error("Invalid socket state")}const t=this.#y.handleId;this.#y="closed",e&&this.on("close",e),this.#F.sendWithCb("sharedUdpSocketLeave",{handleId:t}).then((()=>{this.#Y.delete(t),this.emit("close")}),(e=>{this.#Y.delete(t),this.emit("error",e instanceof Error?e:new Error(e))})).catch((()=>null))}send(e,t,r,n,s,i){if("number"!=typeof t)throw new Error("Invalid arguments");if("number"==typeof r){if("number"!=typeof n||"string"!=typeof s)throw new Error("Invalid arguments");if(void 0!==i&&"number"!=typeof i)throw new Error("Invalid arguments");const o=this.#G(e,t,r);this.#K(o,n,s,i)}else{if("string"!=typeof r)throw new Error("Invalid arguments");{if(void 0!==n&&"function"!=typeof n)throw new Error("Invalid arguments");const s=this.#G(e,0,void 0);this.#K(s,t,r,n)}}}#G(e,t,r){let n;if("string"==typeof e)n=Buffer.from(e,"utf-8");else if(Buffer.isBuffer(e))n=e;else{if(Array.isArray(e))return Buffer.from(e);n=Buffer.from(e.buffer,e.byteOffset,e.byteLength)}return n.subarray(t,void 0!==r?r+t:void 0)}#K(e,t,r,n){if(!this.#y||"object"!=typeof this.#y)throw new Error("Socket is not open");this.#F.sendWithCb("sharedUdpSocketSend",{handleId:this.#y.handleId,message:e,address:r,port:t}).then((()=>{n?.()}),(e=>{this.emit("error",e instanceof Error?e:new Error(e))})).catch((()=>null))}receiveSocketMessage(e){try{this.emit("message",e.message,e.source)}catch(e){}}receiveSocketError(e){this.#y="fatalError";const t=this.boundState;t&&this.#Y.delete(t.handleId);try{this.emit("error",e)}catch(e){}}}t.SharedUdpSocketImpl=i},371:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0})},786:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EmptyUpgradeScript=void 0,t.CreateConvertToBooleanFeedbackUpgradeScript=function(e){return(t,r)=>{const n=[];for(const t of r.feedbacks){let r=e[t.feedbackId];if(!0===r&&(r={bg:"bgcolor",bgcolor:"bgcolor",fg:"color",color:"color",png64:"png64",png:"png64"}),r){t.style||(t.style={});for(const[e,s]of Object.entries(r))void 0!==t.options[e]&&(t.style[s]=t.options[e],delete t.options[e],n.push(t))}}return{updatedConfig:null,updatedActions:[],updatedFeedbacks:n}}},t.CreateUseBuiltinInvertForFeedbacksUpgradeScript=function(e){return(t,r)=>{const n=[];for(const t of r.feedbacks){const r=e[t.feedbackId];if("string"!=typeof r)continue;const s=t.options[r];void 0!==s&&(delete t.options[r],t.isInverted="true"===s||!0===s||Number(s)>0,n.push(t))}return{updatedConfig:null,updatedActions:[],updatedFeedbacks:n}}},t.EmptyUpgradeScript=()=>({updatedConfig:null,updatedActions:[],updatedFeedbacks:[]})},132:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0})},360:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.literal=function(e){return e},t.assertNever=function(e){},t.combineRgb=function(e,t,r,n){let s=(255&e)<<16|(255&t)<<8|255&r;return n&&n>=0&&n<1&&(s+=16777216*Math.round(255*(1-n))),s},t.splitRgb=s,t.splitHsl=function(e){const t=s(e);return(0,n.colord)(`rgba(${t.r}, ${t.g}, ${t.b}, ${t.a})`).toHsl()},t.splitHsv=function(e){const t=s(e);return(0,n.colord)(`rgba(${t.r}, ${t.g}, ${t.b}, ${t.a})`).toHsv()},t.splitHex=function(e){const t=s(e);return(0,n.colord)(`rgba(${t.r}, ${t.g}, ${t.b}, ${t.a})`).toHex()};const n=r(284);function s(e){if("number"==typeof e)return e>16777215?{r:e>>16&255,g:e>>8&255,b:255&e,a:(255-(e>>24&255))/255}:{r:e>>16&255,g:e>>8&255,b:255&e,a:1};if("string"==typeof e&&(0,n.colord)(e).isValid()){const t=(0,n.colord)(e).toRgb();return{r:t.r,g:t.g,b:t.b,a:t.a}}return{r:0,g:0,b:0,a:1}}},281:(e,t,r)=>{"use strict";e.exports=c,e.exports.default=c;const n={$schema:"http://json-schema.org/draft-07/schema#",type:"object",title:"ModuleManifest",properties:{$schema:{type:"string"},id:{type:"string",description:"Unique identifier for the module"},name:{type:"string",description:"Name of the module"},shortname:{type:"string"},description:{type:"string",description:"Description of the module "},version:{type:"string",description:"Current version of the module"},license:{type:"string",description:"SPDX identifier for license of the module"},repository:{type:"string",description:"URL to the source repository"},bugs:{type:"string",description:"URL to bug tracker"},maintainers:{type:"array",description:"List of active maintiners",uniqueItems:!0,items:{type:"object",title:"ModuleManifestMaintainer",properties:{name:{type:"string"},email:{type:"string"},github:{type:"string"}},required:["name"]}},legacyIds:{type:"array",description:"If the module had a different unique identifier previously, then specify it here",uniqueItems:!0,items:{type:"string"}},runtime:{type:"object",title:"ModuleManifestRuntime",description:"Information on how to execute the module",properties:{type:{type:"string",description:"Type of the module. Must be: node18 or node22",enum:["node18","node22"]},api:{type:"string",description:"Which host-api does it use. In the future alternate options will be allowed",enum:["nodejs-ipc"]},apiVersion:{type:"string",description:"The version of the host-api used"},entrypoint:{type:"string",description:"Entrypoint to pass to the runtime. eg index.js"}},required:["type","api","apiVersion","entrypoint"]},manufacturer:{type:"string"},products:{type:"array",uniqueItems:!0,items:{type:"string"},minItems:1},keywords:{type:"array",uniqueItems:!0,items:{type:"string"}},bonjourQueries:{type:"object",description:"If the device or software for your module supports bonjour announcements, Companion will offer an easy way to watch for these announcements.\nEach query you define must have a matching config field of type 'bonjour-device' with the same name",patternProperties:{"":{oneOf:[{$ref:"#/definitions/bonjourQuery"},{type:"array",items:{$ref:"#/definitions/bonjourQuery"}}]}},additionalProperties:!1}},additionalProperties:!1,required:["id","name","shortname","description","version","license","repository","bugs","maintainers","legacyIds","runtime","manufacturer","products","keywords"],definitions:{bonjourQuery:{type:"object",title:"ModuleBonjourQuery",description:"",properties:{type:{type:"string"},protocol:{type:"string",enum:["tcp","udp"]},txt:{type:"object",description:"Match on any txt values returned in the query. This is useful to filter out devices of the same 'type' that are not supported",patternProperties:{"":{type:"string"}},additionalProperties:!1}},required:["type","protocol"],additionalProperties:!1}}},s={type:"object",title:"ModuleBonjourQuery",description:"",properties:{type:{type:"string"},protocol:{type:"string",enum:["tcp","udp"]},txt:{type:"object",description:"Match on any txt values returned in the query. This is useful to filter out devices of the same 'type' that are not supported",patternProperties:{"":{type:"string"}},additionalProperties:!1}},required:["type","protocol"],additionalProperties:!1},i=Object.prototype.hasOwnProperty,o=r(169).A,a=new RegExp("","u");function c(e,{instancePath:t="",parentData:r,parentDataProperty:u,rootData:l=e}={}){let d=null,p=0;if(0===p){if(!e||"object"!=typeof e||Array.isArray(e))return c.errors=[{instancePath:t,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;{let r;if(void 0===e.id&&(r="id")||void 0===e.name&&(r="name")||void 0===e.shortname&&(r="shortname")||void 0===e.description&&(r="description")||void 0===e.version&&(r="version")||void 0===e.license&&(r="license")||void 0===e.repository&&(r="repository")||void 0===e.bugs&&(r="bugs")||void 0===e.maintainers&&(r="maintainers")||void 0===e.legacyIds&&(r="legacyIds")||void 0===e.runtime&&(r="runtime")||void 0===e.manufacturer&&(r="manufacturer")||void 0===e.products&&(r="products")||void 0===e.keywords&&(r="keywords"))return c.errors=[{instancePath:t,schemaPath:"#/required",keyword:"required",params:{missingProperty:r},message:"must have required property '"+r+"'"}],!1;{const r=p;for(const r in e)if(!i.call(n.properties,r))return c.errors=[{instancePath:t,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:r},message:"must NOT have additional properties"}],!1;if(r===p){if(void 0!==e.$schema){const r=p;if("string"!=typeof e.$schema)return c.errors=[{instancePath:t+"/$schema",schemaPath:"#/properties/%24schema/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;var f=r===p}else f=!0;if(f){if(void 0!==e.id){const r=p;if("string"!=typeof e.id)return c.errors=[{instancePath:t+"/id",schemaPath:"#/properties/id/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;f=r===p}else f=!0;if(f){if(void 0!==e.name){const r=p;if("string"!=typeof e.name)return c.errors=[{instancePath:t+"/name",schemaPath:"#/properties/name/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;f=r===p}else f=!0;if(f){if(void 0!==e.shortname){const r=p;if("string"!=typeof e.shortname)return c.errors=[{instancePath:t+"/shortname",schemaPath:"#/properties/shortname/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;f=r===p}else f=!0;if(f){if(void 0!==e.description){const r=p;if("string"!=typeof e.description)return c.errors=[{instancePath:t+"/description",schemaPath:"#/properties/description/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;f=r===p}else f=!0;if(f){if(void 0!==e.version){const r=p;if("string"!=typeof e.version)return c.errors=[{instancePath:t+"/version",schemaPath:"#/properties/version/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;f=r===p}else f=!0;if(f){if(void 0!==e.license){const r=p;if("string"!=typeof e.license)return c.errors=[{instancePath:t+"/license",schemaPath:"#/properties/license/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;f=r===p}else f=!0;if(f){if(void 0!==e.repository){const r=p;if("string"!=typeof e.repository)return c.errors=[{instancePath:t+"/repository",schemaPath:"#/properties/repository/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;f=r===p}else f=!0;if(f){if(void 0!==e.bugs){const r=p;if("string"!=typeof e.bugs)return c.errors=[{instancePath:t+"/bugs",schemaPath:"#/properties/bugs/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;f=r===p}else f=!0;if(f){if(void 0!==e.maintainers){let r=e.maintainers;const n=p;if(p===n){if(!Array.isArray(r))return c.errors=[{instancePath:t+"/maintainers",schemaPath:"#/properties/maintainers/type",keyword:"type",params:{type:"array"},message:"must be array"}],!1;{var h=!0;const e=r.length;for(let n=0;n1)for(;n--;)for(e=n;e--;)if(o(r[n],r[e]))return c.errors=[{instancePath:t+"/maintainers",schemaPath:"#/properties/maintainers/uniqueItems",keyword:"uniqueItems",params:{i:n,j:e},message:"must NOT have duplicate items (items ## "+e+" and "+n+" are identical)"}],!1}}}f=n===p}else f=!0;if(f){if(void 0!==e.legacyIds){let r=e.legacyIds;const n=p;if(p===n){if(!Array.isArray(r))return c.errors=[{instancePath:t+"/legacyIds",schemaPath:"#/properties/legacyIds/type",keyword:"type",params:{type:"array"},message:"must be array"}],!1;{var b=!0;const e=r.length;for(let n=0;n1){const s={};for(;n--;){let i=r[n];if("string"==typeof i){if("number"==typeof s[i])return e=s[i],c.errors=[{instancePath:t+"/legacyIds",schemaPath:"#/properties/legacyIds/uniqueItems",keyword:"uniqueItems",params:{i:n,j:e},message:"must NOT have duplicate items (items ## "+e+" and "+n+" are identical)"}],!1;s[i]=n}}}}}}f=n===p}else f=!0;if(f){if(void 0!==e.runtime){let r=e.runtime;const s=p;if(p===s){if(!r||"object"!=typeof r||Array.isArray(r))return c.errors=[{instancePath:t+"/runtime",schemaPath:"#/properties/runtime/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;{let e;if(void 0===r.type&&(e="type")||void 0===r.api&&(e="api")||void 0===r.apiVersion&&(e="apiVersion")||void 0===r.entrypoint&&(e="entrypoint"))return c.errors=[{instancePath:t+"/runtime",schemaPath:"#/properties/runtime/required",keyword:"required",params:{missingProperty:e},message:"must have required property '"+e+"'"}],!1;if(void 0!==r.type){let e=r.type;const s=p;if("string"!=typeof e)return c.errors=[{instancePath:t+"/runtime/type",schemaPath:"#/properties/runtime/properties/type/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;if("node18"!==e&&"node22"!==e)return c.errors=[{instancePath:t+"/runtime/type",schemaPath:"#/properties/runtime/properties/type/enum",keyword:"enum",params:{allowedValues:n.properties.runtime.properties.type.enum},message:"must be equal to one of the allowed values"}],!1;var m=s===p}else m=!0;if(m){if(void 0!==r.api){let e=r.api;const s=p;if("string"!=typeof e)return c.errors=[{instancePath:t+"/runtime/api",schemaPath:"#/properties/runtime/properties/api/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;if("nodejs-ipc"!==e)return c.errors=[{instancePath:t+"/runtime/api",schemaPath:"#/properties/runtime/properties/api/enum",keyword:"enum",params:{allowedValues:n.properties.runtime.properties.api.enum},message:"must be equal to one of the allowed values"}],!1;m=s===p}else m=!0;if(m){if(void 0!==r.apiVersion){const e=p;if("string"!=typeof r.apiVersion)return c.errors=[{instancePath:t+"/runtime/apiVersion",schemaPath:"#/properties/runtime/properties/apiVersion/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;m=e===p}else m=!0;if(m)if(void 0!==r.entrypoint){const e=p;if("string"!=typeof r.entrypoint)return c.errors=[{instancePath:t+"/runtime/entrypoint",schemaPath:"#/properties/runtime/properties/entrypoint/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;m=e===p}else m=!0}}}}f=s===p}else f=!0;if(f){if(void 0!==e.manufacturer){const r=p;if("string"!=typeof e.manufacturer)return c.errors=[{instancePath:t+"/manufacturer",schemaPath:"#/properties/manufacturer/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;f=r===p}else f=!0;if(f){if(void 0!==e.products){let r=e.products;const n=p;if(p===n){if(!Array.isArray(r))return c.errors=[{instancePath:t+"/products",schemaPath:"#/properties/products/type",keyword:"type",params:{type:"array"},message:"must be array"}],!1;if(r.length<1)return c.errors=[{instancePath:t+"/products",schemaPath:"#/properties/products/minItems",keyword:"minItems",params:{limit:1},message:"must NOT have fewer than 1 items"}],!1;{var g=!0;const e=r.length;for(let n=0;n1){const s={};for(;n--;){let i=r[n];if("string"==typeof i){if("number"==typeof s[i])return e=s[i],c.errors=[{instancePath:t+"/products",schemaPath:"#/properties/products/uniqueItems",keyword:"uniqueItems",params:{i:n,j:e},message:"must NOT have duplicate items (items ## "+e+" and "+n+" are identical)"}],!1;s[i]=n}}}}}}f=n===p}else f=!0;if(f){if(void 0!==e.keywords){let r=e.keywords;const n=p;if(p===n){if(!Array.isArray(r))return c.errors=[{instancePath:t+"/keywords",schemaPath:"#/properties/keywords/type",keyword:"type",params:{type:"array"},message:"must be array"}],!1;{var v=!0;const e=r.length;for(let n=0;n1){const s={};for(;n--;){let i=r[n];if("string"==typeof i){if("number"==typeof s[i])return e=s[i],c.errors=[{instancePath:t+"/keywords",schemaPath:"#/properties/keywords/uniqueItems",keyword:"uniqueItems",params:{i:n,j:e},message:"must NOT have duplicate items (items ## "+e+" and "+n+" are identical)"}],!1;s[i]=n}}}}}}f=n===p}else f=!0;if(f)if(void 0!==e.bonjourQueries){let r=e.bonjourQueries;const n=p;if(p===n){if(!r||"object"!=typeof r||Array.isArray(r))return c.errors=[{instancePath:t+"/bonjourQueries",schemaPath:"#/properties/bonjourQueries/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;{const e=p;for(const e in r)if(!a.test(e))return c.errors=[{instancePath:t+"/bonjourQueries",schemaPath:"#/properties/bonjourQueries/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:e},message:"must NOT have additional properties"}],!1;if(e===p)for(const e in r)if(a.test(e)){let n=r[e];const i=p,o=p;let u=!1,l=null;const f=p;if(p==p)if(n&&"object"==typeof n&&!Array.isArray(n)){let r;if(void 0===n.type&&(r="type")||void 0===n.protocol&&(r="protocol")){const n={instancePath:t+"/bonjourQueries/"+e.replace(/~/g,"~0").replace(/\//g,"~1"),schemaPath:"#/definitions/bonjourQuery/required",keyword:"required",params:{missingProperty:r},message:"must have required property '"+r+"'"};null===d?d=[n]:d.push(n),p++}else{const r=p;for(const r in n)if("type"!==r&&"protocol"!==r&&"txt"!==r){const n={instancePath:t+"/bonjourQueries/"+e.replace(/~/g,"~0").replace(/\//g,"~1"),schemaPath:"#/definitions/bonjourQuery/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:r},message:"must NOT have additional properties"};null===d?d=[n]:d.push(n),p++;break}if(r===p){if(void 0!==n.type){const r=p;if("string"!=typeof n.type){const r={instancePath:t+"/bonjourQueries/"+e.replace(/~/g,"~0").replace(/\//g,"~1")+"/type",schemaPath:"#/definitions/bonjourQuery/properties/type/type",keyword:"type",params:{type:"string"},message:"must be string"};null===d?d=[r]:d.push(r),p++}var _=r===p}else _=!0;if(_){if(void 0!==n.protocol){let r=n.protocol;const i=p;if("string"!=typeof r){const r={instancePath:t+"/bonjourQueries/"+e.replace(/~/g,"~0").replace(/\//g,"~1")+"/protocol",schemaPath:"#/definitions/bonjourQuery/properties/protocol/type",keyword:"type",params:{type:"string"},message:"must be string"};null===d?d=[r]:d.push(r),p++}if("tcp"!==r&&"udp"!==r){const r={instancePath:t+"/bonjourQueries/"+e.replace(/~/g,"~0").replace(/\//g,"~1")+"/protocol",schemaPath:"#/definitions/bonjourQuery/properties/protocol/enum",keyword:"enum",params:{allowedValues:s.properties.protocol.enum},message:"must be equal to one of the allowed values"};null===d?d=[r]:d.push(r),p++}_=i===p}else _=!0;if(_)if(void 0!==n.txt){let r=n.txt;const s=p;if(p===s)if(r&&"object"==typeof r&&!Array.isArray(r)){const n=p;for(const n in r)if(!a.test(n)){const r={instancePath:t+"/bonjourQueries/"+e.replace(/~/g,"~0").replace(/\//g,"~1")+"/txt",schemaPath:"#/definitions/bonjourQuery/properties/txt/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:n},message:"must NOT have additional properties"};null===d?d=[r]:d.push(r),p++;break}if(n===p)for(const n in r)if(a.test(n)){const s=p;if("string"!=typeof r[n]){const r={instancePath:t+"/bonjourQueries/"+e.replace(/~/g,"~0").replace(/\//g,"~1")+"/txt/"+n.replace(/~/g,"~0").replace(/\//g,"~1"),schemaPath:"#/definitions/bonjourQuery/properties/txt/patternProperties//type",keyword:"type",params:{type:"string"},message:"must be string"};null===d?d=[r]:d.push(r),p++}if(s!==p)break}}else{const r={instancePath:t+"/bonjourQueries/"+e.replace(/~/g,"~0").replace(/\//g,"~1")+"/txt",schemaPath:"#/definitions/bonjourQuery/properties/txt/type",keyword:"type",params:{type:"object"},message:"must be object"};null===d?d=[r]:d.push(r),p++}_=s===p}else _=!0}}}}else{const r={instancePath:t+"/bonjourQueries/"+e.replace(/~/g,"~0").replace(/\//g,"~1"),schemaPath:"#/definitions/bonjourQuery/type",keyword:"type",params:{type:"object"},message:"must be object"};null===d?d=[r]:d.push(r),p++}f===p&&(u=!0,l=0);const h=p;if(p===h)if(Array.isArray(n)){const r=n.length;for(let i=0;i{"use strict";const n=r(865);e.exports=(e,t={})=>{if("function"!=typeof e)throw new TypeError(`Expected the first argument to be a function, got \`${typeof e}\``);const{wait:r=0,maxWait:s=0,before:i=!1,after:o=!0}=t;if(!i&&!o)throw new Error("Both `before` and `after` are false, function wouldn't be called.");let a,c,u;const l=function(...t){const n=this,l=i&&!a;return clearTimeout(a),a=setTimeout((()=>{a=void 0,c&&(clearTimeout(c),c=void 0),o&&(u=e.apply(n,t))}),r),s>0&&!c&&o&&(c=setTimeout((()=>{c=void 0,a&&(clearTimeout(a),a=void 0),u=e.apply(n,t)}),s)),l&&(u=e.apply(n,t)),u};return n(l,e),l.cancel=()=>{a&&(clearTimeout(a),a=void 0),c&&(clearTimeout(c),c=void 0)},l}},635:(e,t,r)=>{"use strict";r.r(t),r.d(t,{__addDisposableResource:()=>M,__assign:()=>i,__asyncDelegator:()=>O,__asyncGenerator:()=>S,__asyncValues:()=>P,__await:()=>I,__awaiter:()=>h,__classPrivateFieldGet:()=>C,__classPrivateFieldIn:()=>N,__classPrivateFieldSet:()=>T,__createBinding:()=>b,__decorate:()=>a,__disposeResources:()=>$,__esDecorate:()=>u,__exportStar:()=>m,__extends:()=>s,__generator:()=>y,__importDefault:()=>x,__importStar:()=>E,__makeTemplateObject:()=>j,__metadata:()=>f,__param:()=>c,__propKey:()=>d,__read:()=>v,__rest:()=>o,__rewriteRelativeImportExtension:()=>D,__runInitializers:()=>l,__setFunctionName:()=>p,__spread:()=>_,__spreadArray:()=>k,__spreadArrays:()=>w,__values:()=>g,default:()=>F});var n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},n(e,t)};function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}var i=function(){return i=Object.assign||function(e){for(var t,r=1,n=arguments.length;r=0;a--)(s=e[a])&&(o=(i<3?s(o):i>3?s(t,r,o):s(t,r))||o);return i>3&&o&&Object.defineProperty(t,r,o),o}function c(e,t){return function(r,n){t(r,n,e)}}function u(e,t,r,n,s,i){function o(e){if(void 0!==e&&"function"!=typeof e)throw new TypeError("Function expected");return e}for(var a,c=n.kind,u="getter"===c?"get":"setter"===c?"set":"value",l=!t&&e?n.static?e:e.prototype:null,d=t||(l?Object.getOwnPropertyDescriptor(l,n.name):{}),p=!1,f=r.length-1;f>=0;f--){var h={};for(var y in n)h[y]="access"===y?{}:n[y];for(var y in n.access)h.access[y]=n.access[y];h.addInitializer=function(e){if(p)throw new TypeError("Cannot add initializers after decoration has completed");i.push(o(e||null))};var b=(0,r[f])("accessor"===c?{get:d.get,set:d.set}:d[u],h);if("accessor"===c){if(void 0===b)continue;if(null===b||"object"!=typeof b)throw new TypeError("Object expected");(a=o(b.get))&&(d.get=a),(a=o(b.set))&&(d.set=a),(a=o(b.init))&&s.unshift(a)}else(a=o(b))&&("field"===c?s.unshift(a):d[u]=a)}l&&Object.defineProperty(l,n.name,d),p=!0}function l(e,t,r){for(var n=arguments.length>2,s=0;s0&&s[s.length-1])||6!==a[0]&&2!==a[0])){i=0;continue}if(3===a[0]&&(!s||a[1]>s[0]&&a[1]=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function v(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,s,i=r.call(e),o=[];try{for(;(void 0===t||t-- >0)&&!(n=i.next()).done;)o.push(n.value)}catch(e){s={error:e}}finally{try{n&&!n.done&&(r=i.return)&&r.call(i)}finally{if(s)throw s.error}}return o}function _(){for(var e=[],t=0;t1||a(e,t)}))},t&&(n[e]=t(n[e])))}function a(e,t){try{(r=s[e](t)).value instanceof I?Promise.resolve(r.value.v).then(c,u):l(i[0][2],r)}catch(e){l(i[0][3],e)}var r}function c(e){a("next",e)}function u(e){a("throw",e)}function l(e,t){e(t),i.shift(),i.length&&a(i[0][0],i[0][1])}}function O(e){var t,r;return t={},n("next"),n("throw",(function(e){throw e})),n("return"),t[Symbol.iterator]=function(){return this},t;function n(n,s){t[n]=e[n]?function(t){return(r=!r)?{value:I(e[n](t)),done:!1}:s?s(t):t}:s}}function P(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,r=e[Symbol.asyncIterator];return r?r.call(e):(e=g(e),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(r){t[r]=e[r]&&function(t){return new Promise((function(n,s){!function(e,t,r,n){Promise.resolve(n).then((function(t){e({value:t,done:r})}),t)}(n,s,(t=e[r](t)).done,t.value)}))}}}function j(e,t){return Object.defineProperty?Object.defineProperty(e,"raw",{value:t}):e.raw=t,e}var A=Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t};function E(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&b(t,e,r);return A(t,e),t}function x(e){return e&&e.__esModule?e:{default:e}}function C(e,t,r,n){if("a"===r&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?n:"a"===r?n.call(e):n?n.value:t.get(e)}function T(e,t,r,n,s){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?s.call(e,r):s?s.value=r:t.set(e,r),r}function N(e,t){if(null===t||"object"!=typeof t&&"function"!=typeof t)throw new TypeError("Cannot use 'in' operator on non-object");return"function"==typeof e?t===e:e.has(t)}function M(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,s;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(s=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");s&&(n=function(){try{s.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}var V="function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n};function $(e){function t(t){e.error=e.hasError?new V(t,e.error,"An error was suppressed during disposal."):t,e.hasError=!0}var r,n=0;return function s(){for(;r=e.stack.pop();)try{if(!r.async&&1===n)return n=0,e.stack.push(r),Promise.resolve().then(s);if(r.dispose){var i=r.dispose.call(r.value);if(r.async)return n|=2,Promise.resolve(i).then(s,(function(e){return t(e),s()}))}else n|=1}catch(e){t(e)}if(1===n)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}()}function D(e,t){return"string"==typeof e&&/^\.\.?\//.test(e)?e.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i,(function(e,r,n,s,i){return r?t?".jsx":".js":!n||s&&i?n+s+"."+i.toLowerCase()+"js":e})):e}const F={__extends:s,__assign:i,__rest:o,__decorate:a,__param:c,__esDecorate:u,__runInitializers:l,__propKey:d,__setFunctionName:p,__metadata:f,__awaiter:h,__generator:y,__createBinding:b,__exportStar:m,__values:g,__read:v,__spread:_,__spreadArrays:w,__spreadArray:k,__await:I,__asyncGenerator:S,__asyncDelegator:O,__asyncValues:P,__makeTemplateObject:j,__importStar:E,__importDefault:x,__classPrivateFieldGet:C,__classPrivateFieldSet:T,__classPrivateFieldIn:N,__addDisposableResource:M,__disposeResources:$,__rewriteRelativeImportExtension:D}}},t={};function r(n){var s=t[n];if(void 0!==s)return s.exports;var i=t[n]={exports:{}};return e[n](i,i.exports,r),i.exports}r.d=(e,t)=>{for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},(()=>{"use strict";var e=r(278);const t=[{type:"static-text",id:"info",label:"Information",width:12,value:'\n\t\t\t\t
\n\t\t\t\t\t

IMPORTANT MESSAGE

\n\t\t\t\t\t
\n\t\t\t\t\t\tPlease read and understand the following before using this module\n\t\t\t\t\t\t
\n\t\t\t\t\t\tThis software is for use as a stopwatch, making it easier to manipulate times through the companion.\n\t\t\t\t\t
\n\t\t\t\t
\n\t\t\t'},{type:"textinput",id:"host",label:"Target Host name or IP",default:"127.0.0.1",width:8,regex:"/^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3})$|^((([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9]).)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9-]*[A-Za-z0-9]))$/"},{type:"textinput",id:"port",label:"Target Port",default:"7600",width:4,regex:e.Regex.PORT}];class n extends e.InstanceBase{async init(e){this.config=e,this.setActionDefinitions(function(e){const t={},r=(t,r)=>({name:`${t}`,options:[],callback:async()=>{const t=r,n=Buffer.from(t,"latin1");e.log("debug",`sending to ${e.config.host}: ${n.toString()}`),void 0!==e.socket&&e.socket.isConnected?e.socket.send(n):e.log("debug","Socket not connected :(")}});for(let e=1;e<=20;e++){const n="preset"+(e<10?`0${e}`:`${e}`);t[`preset${e}`]=r(`Preset ${e}`,n)}const n={ESC:"esc",NEXT:"next",PREVIOUS:"previous",FECHAR_PPT:"pptexit",FECHAR_VIDEO:"videoexit",START:"start",STOP:"stop",SET:"set",RESET:"reset",SET1:"set1",SET5:"set5",SET15:"set15",SET30:"set30",SET45:"set45",SET60:"set60",addMinute:"addMinute",addFiveMinutes:"addFiveMinutes",subtractMinute:"subtractMinute",subtractFiveMinutes:"subtractFiveMinutes",addHour:"addHour",subtractHour:"subtractHour",addMin:"addMin",subtractMin:"subtractMin",AA:"AA",aa:"aa",BB:"BB",bb:"bb"};for(const[e,s]of Object.entries(n))t[e]=r(e,s);return t}(this)),this.setPresetDefinitions(function(){const e={preset_start:{type:"button",category:"Control",name:"Start Timer",style:{text:"START",size:"18",color:"16777215",bgcolor:"43520",show_topbar:!1},steps:[{down:[{actionId:"START"}],up:[]}]},preset_stop:{type:"button",category:"Control",name:"Stop Timer",style:{text:"STOP",size:"18",color:"16777215",bgcolor:"9109504",show_topbar:!1},steps:[{down:[{actionId:"STOP"}],up:[]}]},preset_reset:{type:"button",category:"Control",name:"Reset Timer",style:{text:"RESET",size:"18",color:"0",bgcolor:"8421504",show_topbar:!1},steps:[{down:[{actionId:"RESET"}],up:[]}]},preset_set:{type:"button",category:"Control",name:"Set Timer",style:{text:"SET",size:"18",color:"16777215",bgcolor:"43520",show_topbar:!1},steps:[{down:[{actionId:"SET"}],up:[]}]},preset_hour:{type:"button",category:"Display",name:"HOUR",style:{text:"$(Cronos:timer_hours)",size:"AUTO",color:"16777215",bgcolor:"9109504",show_topbar:!1},steps:[{down:[],up:[]}]},preset_minute:{type:"button",category:"Display",name:"MINUTE",style:{text:"$(Cronos:timer_minutes)",size:"AUTO",color:"16777215",bgcolor:"9109504",show_topbar:!1},steps:[{down:[],up:[]}]},preset_second:{type:"button",category:"Display",name:"SECOND",style:{text:"$(Cronos:timer_seconds)",size:"AUTO",color:"16777215",bgcolor:"9109504",show_topbar:!1},steps:[{down:[],up:[]}]},preset_timer:{type:"button",category:"Display",name:"TIMER",style:{text:"$(Cronos:timer)",size:"AUTO",color:"16777215",bgcolor:"9109504",show_topbar:!1},steps:[{down:[],up:[]}]}};function t(t){e[`preset_set${t}`]={type:"button",category:"SET",name:`Set ${t} Minutes`,style:{text:`SET\n${t} MIN`,size:"18",color:"16777215",bgcolor:"180",show_topbar:!1},steps:[{down:[{actionId:`SET${t}`,options:{minutes:t}}],up:[]}]}}function r(t,r,n){e[`preset_${t}`]={type:"button",category:"Function",name:n,style:{text:r,size:"18",color:"16777215",bgcolor:"0",show_topbar:!1},steps:[{down:[{actionId:t}],up:[]}]}}t(1),t(5),t(15),t(30),t(45),t(60),r("addMinute","ADD\n1 MIN","Add 1 Minute"),r("addFiveMinutes","ADD\n5 MIN","Add 5 Minutes"),r("subtractMinute","SUB\n1 MIN","Subtract 1 Minute"),r("subtractFiveMinutes","SUB\n5 MIN","Subtract 5 Minutes"),r("addHour","ADD\n1 HR","Add 1 Hour"),r("subtractHour","SUB\n1 HR","Subtract 1 Hour"),r("addMin","ADD\nMIN","Add Minute"),r("subtractMin","SUB\nMIN","Subtract Minute"),r("AA","AA\nTimer","AA"),r("aa","aa\nTimer","aa"),r("BB","AA\nMsg","BB"),r("bb","aa\nMsg","bb");for(let t=1;t<=20;t++){const r=t<10?`0${t}`:`${t}`,n=`preset${r}`,s=`preset${r}`,i=`$(Cronos:item${t})`;e[`preset_${n}`]={type:"button",category:"Preset",name:`Send ${s.toUpperCase()} Command`,style:{text:i,size:"14",color:"16777215",bgcolor:"25600",show_topbar:!1},steps:[{down:[{actionId:n,options:{presetId:t}}],up:[]}]}}return e}()),await this.configUpdated(e),this.init_tcp_variables()}async configUpdated(e){this.socket&&(this.socket.destroy(),delete this.socket),this.config=e,this.init_tcp(),this.init_tcp_variables()}async destroy(){this.socket?this.socket.destroy():this.updateStatus(e.InstanceStatus.Disconnected)}getConfigFields(){return t}init_tcp(){this.socket&&(this.socket.destroy(),delete this.socket),this.updateStatus(e.InstanceStatus.Connecting),this.config.host?(this.socket=new e.TCPHelper(this.config.host,this.config.port),this.socket.on("status_change",((e,t)=>{this.updateStatus(e,t),this.socket.send("VERSION\r\n").catch((e=>{this.log("error",`Socket error: ${e}`)}))})),this.socket.on("data",(e=>{const t=e.toString("utf8"),r=new URLSearchParams(t),n=r.get("hours"),s=r.get("minutes"),i=r.get("seconds"),o=r.get("time");if(n&&s&&i&&o)this.setVariableValues({timer_hours:n,timer_minutes:s,timer_seconds:i,timer:o}),this.log("info",`Received time: ${o} (H: ${n}, M: ${s}, S: ${i})`);else{const e={};for(let t=1;t<=20;t++){const n=r.get(`item${t}`);null!==n&&(e[`item${t}`]=n)}this.setVariableValues(e);const t=Object.values(e).filter((e=>""!==e));this.log("info",`Received items: ${t.join(", ")}`)}})),this.socket.on("error",(t=>{this.updateStatus(e.InstanceStatus.ConnectionFailure,t.message),this.log("error","Network error: "+t.message)}))):this.updateStatus(e.InstanceStatus.BadConfig)}init_tcp_variables(){const e=[{name:"Timer",variableId:"timer"},{name:"Timer Hours",variableId:"timer_hours"},{name:"Timer Minutes",variableId:"timer_minutes"},{name:"Timer Seconds",variableId:"timer_seconds"}];for(let t=1;t<=20;t++)e.push({name:`Item ${t}`,variableId:`item${t}`});this.setVariableDefinitions(e);const t=new Date,r=t.getHours().toString().padStart(2,"0"),n=t.getMinutes().toString().padStart(2,"0"),s=t.getSeconds().toString().padStart(2,"0"),i={timer:`${r}:${n}:${s}`,timer_hours:r,timer_minutes:n,timer_seconds:s};for(let e=1;e<=20;e++)i[`item${e}`]=`PRESET\n${e}`;this.setVariableValues(i)}update_tcp_variables(){const e=new Date,t=e.getHours().toString().padStart(2,"0"),r=e.getMinutes().toString().padStart(2,"0"),n=e.getSeconds().toString().padStart(2,"0");this.setVariableValues({timer_hours:t,timer_minutes:r,timer_seconds:n,timer:`${t}:${r}:${n}`})}}(0,e.runEntrypoint)(n,[])})()})(); \ No newline at end of file diff --git a/monteiro-cronosdown/package.json b/monteiro-cronosdown/package.json index 41bd3f1e..c6357ba6 100644 --- a/monteiro-cronosdown/package.json +++ b/monteiro-cronosdown/package.json @@ -1 +1 @@ -{"name":"monteiro-cronosdown","version":"1.0.0","license":"MIT","type":"commonjs","dependencies":{}} \ No newline at end of file +{"name":"monteiro-cronosdown","version":"1.1.0","license":"MIT","type":"commonjs","dependencies":{}} \ No newline at end of file