From 81da0606bce737c3427253d20deb08671d008cfc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Peter=20M=C3=BCller?= Date: Sun, 3 Nov 2024 15:21:55 +0100 Subject: [PATCH] Added more functions to custom parser scripts --- README.md | 14 +++++++++++--- admin/build/index.js | 2 +- admin/build/index.js.map | 4 ++-- build/parsers/custom.js | 5 +++++ build/parsers/custom.js.map | 4 ++-- src/parsers/custom.test.ts | 7 ++++++- src/parsers/custom.ts | 12 +++++++++++- 7 files changed, 38 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 9887893..17b71d8 100644 --- a/README.md +++ b/README.md @@ -75,11 +75,13 @@ In the scripts you are able to use the following features: * Globals `undefined`, `NaN`, `isNaN`, `Infinity`, `isFinite`, `atob`, `btoa`, `encodeURI`, `encodeURIComponent`, `decodeURI`, `decodeURIComponent`, `parseFloat`, `parseInt`, `JSON`, `Number`, `String`, `Array`, `BigInt`, `Blob`, `Boolean`, - `Date`, `Map`, `Math`, `Object`, `RegExp`, `Set`, `Intl`, `Buffer`, `Promise` + `Date`, `Map`, `Math`, `Object`, `RegExp`, `Set`, `Intl`, `Buffer`, `Promise`, + `setTimeout`, `clearTimeout` * `async`/`await` * Adapter log functions `log.warn('something')`, `log.info('something')`, `log.debug('something')` -* `getStateAsync('id')` and `getObjectAsync('id')` where `id` is the partial ID of the state/object below the current adapter instance -* `getForeignStateAsync('id')` and `getForeignObjectAsync('id')` where `id` is the full ID of the state/object +* `getStateAsync('id')`, `getObjectAsync('id')`, `setStateAsync('id', 'value', ack)` where `id` is the partial ID of the state/object below the current adapter instance +* `getForeignStateAsync('id')`, `getForeignObjectAsync('id')` and `setForeignStateAsync('id', 'value', ack)` where `id` is the full ID of the state/object +* Function `wait(ms)` which returns a Promise which resolves after the given time * An object `sharedData` which is shared between all custom scripts of an adapter instance Errors in the scripts will be logged by the adapter. @@ -164,6 +166,12 @@ By writing JSON data to the `raw.send` state you are able to send CAN messages c Placeholder for the next version (at the beginning of the line): ### **WORK IN PROGRESS** --> +### **WORK IN PROGRESS** + +* (crycode-de) Allow `setStateAsync` and `setForeignStateAsync` in custom parser scripts +* (crycode-de) Allow `setTimeout` and `clearTimeout` in custom parser scripts (using the adapters setTimeout implementation) +* (crycode-de) Added `wait` function to custom parser scripts + ### 2.0.0 (2024-11-02) * (crycode-de) Node.js >= 18, Admin >= 6.17, js-contoller >= 5.0.19 are required diff --git a/admin/build/index.js b/admin/build/index.js index e6142b4..cd95933 100644 --- a/admin/build/index.js +++ b/admin/build/index.js @@ -414,7 +414,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho `&&i?(r==="\r"&&(n[o]=n[o].slice(0,-1)),n=u[++a]=[s=""],o=0):n[o]+=s,r=s;return u}renderMarkdown(e){return e=e.replace(/<[^>]+>/,""),e=z_(e),e=e.replace(/]+)>/g,''),e}};Et([Tt],Bi.prototype,"handleExportSelectMsg",1),Et([Tt],Bi.prototype,"fetchPredefinedConfigs",1),Et([Tt],Bi.prototype,"export",1),Et([Tt],Bi.prototype,"importFromFile",1),Et([Tt],Bi.prototype,"handleImportFileSelect",1),Et([Tt],Bi.prototype,"importPredefinedConfig",1);var pt=q(z());var Yie=q(rm()),X_=q(g_());var gB=q(xj()),Jie=q(pB()),Xie=q(Uie()),ht=q(_o());var mB=q(z()),hB=q(Sm()),BI=(0,hB.default)(mB.default.createElement("path",{d:"M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm3 4H8c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 16H8V7h11v14z"}),"ContentCopy"),UI=(0,hB.default)(mB.default.createElement("path",{d:"M19 2h-4.18C14.4.84 13.3 0 12 0c-1.3 0-2.4.84-2.82 2H5c-1.1 0-2 .9-2 2v16c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-7 0c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zm7 18H5V4h2v3h10V4h2v16z"}),"ContentPaste");var Ge=q(z());var $I=q(g_()),Gie=q(h_()),Vie=q(pB()),Kie=q(zie()),He=q(_o());var Js=q(z());var Wie=q(Wm()),$ie=q(zC());var Hie=q(VC());var WI=class extends Js.default.PureComponent{constructor(e){super(e);let r=[];for(let n=0;n0;this.state={value:this.props.value,bits:r}}componentDidUpdate(e){if(e.value!==this.props.value){let r=[];for(let n=0;n0;this.setState({value:this.props.value,bits:r})}}render(){return Js.default.createElement(Ke,{item:!0,xs:this.props.xs,sm:this.props.sm,md:this.props.md,lg:this.props.lg,xl:this.props.xl},Js.default.createElement(Wie.default,null,Js.default.createElement(bd,{shrink:!0,style:{marginTop:"-5px"}},this.props.label),Js.default.createElement("div",null,this.state.bits.map((e,r)=>Js.default.createElement($ie.default,{key:r,control:Js.default.createElement(Hie.default,{checked:e,disabled:this.props.disabled,onChange:()=>this.changeBit(r)}),label:r}))),this.props.children&&Js.default.createElement(ja,null,this.props.children)))}changeBit(e){let r=[...this.state.bits];r[e]=!r[e];let n=0;r.forEach((o,a)=>{o&&(n|=1<{this.props.onChange(this.state.value)})}};var CVe={int8:"int8",uint8:"uint8",int16_be:"int16 BE",int16_le:"int16 LE",uint16_be:"uint16 BE",uint16_le:"uint16 LE",int32_be:"int32 BE",int32_le:"int32 LE",uint32_be:"uint32 BE",uint32_le:"uint32 LE",float32_be:"float32 BE",float32_le:"float32 LE",double64_be:"double64 BE",double64_le:"double64 LE",boolean:"boolean",string:"string",custom:"custom"},IVe=["state","button","indicator","level","level.temperature","switch","switch.power","switch.light","text","value","value.temperature","button.close.blind","button.close.tilt","button.fastforward","button.fastreverse","button.forward","button.long","button.mode.auto","button.mode.manual","button.mode.silent","button.next","button.open.blind","button.open.door","button.open.tilt","button.open.window","button.pause","button.play","button.press","button.prev","button.reverse","button.start","button.stop","button.stop.tilt","button.volume.down","button.volume.up","date","date.end","date.forecast.1","date.start","date.sunrise","date.sunset","dayofweek","html","indicator.alarm","indicator.alarm.fire","indicator.alarm.flood","indicator.alarm.health","indicator.alarm.secure","indicator.connected","indicator.lowbat","indicator.maintenance","indicator.maintenance.alarm","indicator.maintenance.lowbat","indicator.maintenance.unreach","indicator.maintenance.waste","indicator.reachable","indicator.working","info.address","info.display","info.ip","info.mac","info.name","info.port","info.standby","info.status","json","level.bass","level.blind","level.co2","level.color.blue","level.color.green","level.color.hue","level.color.luminance","level.color.red","level.color.rgb","level.color.saturation","level.color.temperature","level.color.white","level.curtain","level.dimmer","level.mode.cleanup","level.mode.fan","level.mode.swing","level.mode.thermostat","level.mode.work","level.tilt","level.timer","level.timer.sleep","level.treble","level.valve","level.volume","level.volume.group","list","location","media.add","media.album","media.artist","media.bitrate","media.broadcastDate","media.browser","media.clear","media.content","media.cover","media.cover.big","media.cover.small","media.date","media.duration","media.duration.text","media.elapsed","media.elapsed.text","media.episode","media.genre","media.input","media.jump","media.link","media.mode.repeat","media.mode.shuffle","media.mute","media.mute.group","media.playid","media.playlist","media.season","media.seek","media.state","media.title","media.title.next","media.track","media.tts","media.url","media.url.announcement","sensor.alarm","sensor.alarm.fire","sensor.alarm.flood","sensor.alarm.power","sensor.alarm.secure","sensor.door","sensor.light","sensor.lock","sensor.motion","sensor.noise","sensor.rain","sensor.window","switch.boost","switch.comfort","switch.enable","switch.lock","switch.lock.door","switch.lock.window","switch.mode.auto","switch.mode.color","switch.mode.manual","switch.mode.moonlight","switch.mode.silent","switch.pause","switch.power.zone","text.phone","text.url","url","url.audio","url.blank","url.cam","url.icon","url.same","value.battery","value.blind","value.blood.sugar","value.brightness","value.clouds","value.current","value.curtain","value.default","value.direction","value.direction.max.wind","value.direction.min.wind","value.direction.wind","value.direction.wind.forecast.0","value.direction.wind.forecast.1","value.distance","value.distance.visibility","value.fill","value.gps","value.gps.elevation","value.gps.latitude","value.gps.longitude","value.health.bmi","value.health.bpm","value.health.calories","value.health.fat","value.health.steps","value.health.weight","value.humidity","value.humidity.max","value.humidity.min","value.interval","value.lock","value.max","value.min","value.power.consumption","value.precipitation","value.precipitation.day.forecast.0","value.precipitation.forecast.0","value.precipitation.forecast.1","value.precipitation.hour","value.precipitation.night.forecast.0","value.precipitation.today","value.pressure","value.pressure.forecast.0","value.pressure.forecast.1","value.radiation","value.rain","value.rain.hour","value.rain.today","value.severity","value.snow","value.snow.hour","value.snow.today","value.snowline","value.speed","value.speed.max.wind","value.speed.min.wind","value.speed.wind","value.speed.wind.forecast.0","value.speed.wind.forecast.1","value.speed.wind.gust","value.state","value.sun.azimuth","value.sun.elevation","value.temperature.dewpoint","value.temperature.feelslike","value.temperature.max","value.temperature.max.forecast.0","value.temperature.max.forecast.1","value.temperature.min","value.temperature.min.forecast.0","value.temperature.min.forecast.1","value.temperature.windchill","value.tilt","value.time","value.uv","value.valve","value.voltage","value.warning","value.waste","value.water","value.window","weather.chart.url","weather.chart.url.forecast","weather.direction.wind","weather.direction.wind.forecast.0","weather.html","weather.icon","weather.icon.forecast.1","weather.icon.name","weather.icon.wind","weather.json","weather.state","weather.state.forecast.0","weather.state.forecast.1","weather.title","weather.title.forecast.0","weather.title.short","weather.type"],gh=class extends Ge.default.PureComponent{constructor(e){super(e),this.state=this.validateState(this.updateDependedElements({...this.props.config,idError:null,commonStatesError:null,disabledDataLengths:[],disabledDataOffsets:[],disabledDataEncoding:!1,disabledDataUnit:!1,disabledDataOffsetAndLength:!1}))}render(){let{classes:e}=this.props,r="number";return(this.state.dataType==="boolean"||this.state.dataType==="custom"&&this.state.customDataType==="boolean")&&(r="boolean"),(this.state.dataType==="string"||this.state.dataType==="custom"&&this.state.customDataType==="string")&&(r="string"),Ge.default.createElement(Ge.default.Fragment,null,Ge.default.createElement("div",{className:e.fabTopRight},Ge.default.createElement($I.default,{size:"small",color:"primary","aria-label":"copy",title:He.default.t("Copy"),onClick:this.copy},Ge.default.createElement(BI,null)),Ge.default.createElement($I.default,{size:"small",color:"primary","aria-label":"paste",title:He.default.t("Paste"),onClick:this.paste,disabled:this.props.readonly||!Mi.parser},Ge.default.createElement(UI,null)),Ge.default.createElement($I.default,{size:"small",color:"primary","aria-label":"delete",title:He.default.t("Remove"),onClick:()=>this.props.onDelete&&this.props.onDelete(this.props.uuid),disabled:this.props.readonly||!this.props.onDelete},Ge.default.createElement(Vie.default,null))),Ge.default.createElement(Ke,{container:!0,spacing:3},Ge.default.createElement(tn,{xs:12,sm:6,md:4,lg:4,label:He.default.t("Parser ID"),value:this.state.id,disabled:this.props.readonly,onChange:n=>this.handleChange("id",n),errorMsg:this.state.idError,transform:"lowerCase",maxLength:64},Ge.default.createElement("code",null,this.props.context.adapterName,".",this.props.context.instance,".",this.props.msgId||"",".",this.state.id||"")),Ge.default.createElement(tn,{xs:12,sm:6,md:6,lg:4,label:He.default.t("Name"),value:this.state.name,disabled:this.props.readonly,onChange:n=>this.handleChange("name",n)},He.default.t("e.g.")," ",Ge.default.createElement("code",null,He.default.t("Temperature")))),Ge.default.createElement(Ke,{container:!0,spacing:3},Ge.default.createElement(No,{xs:12,sm:6,md:4,lg:2,label:He.default.t("Data type"),value:this.state.dataType,disabled:this.props.readonly,onChange:n=>this.handleChange("dataType",n),options:CVe},He.default.t("Data type in the can message")),this.state.dataType==="custom"&&Ge.default.createElement(No,{xs:12,sm:6,md:4,lg:2,label:He.default.t("Data type"),value:this.state.customDataType,disabled:this.props.readonly,onChange:n=>this.handleChange("customDataType",n),options:["boolean","number","string","mixed"]},He.default.t("Data type in ioBroker")),!this.state.disabledDataOffsetAndLength&&Ge.default.createElement(Ge.default.Fragment,null,Ge.default.createElement(No,{xs:12,sm:6,md:2,lg:1,label:He.default.t("Offset"),value:this.state.dataOffset.toString(),disabled:this.props.readonly,onChange:n=>this.handleChange("dataOffset",parseInt(n,10)),options:["0","1","2","3","4","5","6","7"],disabledOptions:this.state.disabledDataOffsets}),Ge.default.createElement(No,{xs:12,sm:6,md:2,lg:1,label:He.default.t("Length"),value:this.state.dataLength.toString(),disabled:this.props.readonly,onChange:n=>this.handleChange("dataLength",parseInt(n,10)),options:["1","2","3","4","5","6","7","8"],disabledOptions:this.state.disabledDataLengths})),!this.state.disabledDataEncoding&&Ge.default.createElement(No,{xs:12,sm:6,md:2,lg:1,label:He.default.t("Encoding"),value:this.state.dataEncoding,disabled:this.props.readonly,onChange:n=>this.handleChange("dataEncoding",n),options:["ascii","base64","hex","latin1","utf8","utf16le"]}),!this.state.disabledDataUnit&&Ge.default.createElement(tn,{xs:12,sm:6,md:2,lg:1,label:He.default.t("Unit"),value:this.state.dataUnit,disabled:this.props.readonly,onChange:n=>this.handleChange("dataUnit",n)},He.default.t("e.g.")," ",Ge.default.createElement("code",null,"\xB0C")),Ge.default.createElement(tn,{xs:12,sm:6,md:4,lg:3,label:He.default.t("Role"),value:this.state.commonRole,disabled:this.props.readonly,onChange:n=>this.handleChange("commonRole",n),autoCompleteOptions:IVe},He.default.t('Select a suitable role for the ioBroker state or just use "state" if you are not sure.'),Ge.default.createElement(Gie.default,{color:"primary",size:"small",title:He.default.t("Information about the state roles in ioBroker on GitHub"),onClick:()=>window.open("https://github.com/ioBroker/ioBroker.docs/blob/master/docs/en/dev/stateroles.md")},Ge.default.createElement(Kie.default,{fontSize:"inherit"}))),Ge.default.createElement(xr,{xs:12,sm:6,md:4,lg:3,label:He.default.t("Define possible states"),value:!!this.state.commonStates,disabled:this.props.readonly,onChange:n=>this.handleChange("commonStates",n?"":!1)},He.default.t("Setup a list of predefined state values"))),typeof this.state.commonStates=="string"&&Ge.default.createElement(Ke,{container:!0,spacing:3},Ge.default.createElement(tn,{xs:12,sm:12,md:12,lg:12,label:He.default.t("Possible states"),value:this.state.commonStates,disabled:this.props.readonly,onChange:n=>this.handleChange("commonStates",n),errorMsg:this.state.commonStatesError},He.default.t("Comma separated list of real values and display values. Example: 0=Off,1=On,2=Auto"))),this.state.dataType==="boolean"&&Ge.default.createElement(Ke,{container:!0,spacing:3},Ge.default.createElement(WI,{xs:12,sm:12,md:12,lg:8,label:He.default.t("Boolean bitmask"),bits:8,value:this.state.booleanMask,disabled:this.props.readonly,onChange:n=>this.handleChange("booleanMask",n)},Ge.default.createElement("span",{dangerouslySetInnerHTML:{__html:He.default.t("Bitmask to apply to detect/set a %s value. If no bits are selected any byte value greater than 0 will be interpreted as %s.","true","true")}})),Ge.default.createElement(xr,{xs:12,sm:12,md:6,lg:3,label:He.default.t("Boolean invert"),value:this.state.booleanInvert,disabled:this.props.readonly,onChange:n=>this.handleChange("booleanInvert",n)},He.default.t("Invert the boolean value"))),this.state.dataType==="custom"&&Ge.default.createElement(Ke,{container:!0,spacing:3},Ge.default.createElement(tn,{xs:12,sm:12,md:6,label:He.default.t("Custom script read"),multiline:!0,value:this.state.customScriptRead,disabled:this.props.readonly,onChange:n=>this.handleChange("customScriptRead",n),placeholder:`// example: value = buffer[0] + buffer[1];`},Ge.default.createElement("span",{dangerouslySetInnerHTML:{__html:He.default.t("Script to read the value from the buffer. The buffer is available as %s and the value has to be written into %s.","buffer","value")}})),Ge.default.createElement(tn,{xs:12,sm:12,md:6,label:He.default.t("Custom script write"),multiline:!0,value:this.state.customScriptWrite,disabled:this.props.readonly,onChange:n=>this.handleChange("customScriptWrite",n),placeholder:`// example: buffer[0] = value & 0xff; -buffer[1] = (value >> 8);`},Ge.default.createElement("span",{dangerouslySetInnerHTML:{__html:He.default.t("Script to write the value to the buffer. The buffer is available as %s and the value as %s.","buffer","value")}}))),this.props.msgSend&&Ge.default.createElement(Ke,{container:!0,spacing:3},Ge.default.createElement(xr,{xs:12,sm:6,md:4,lg:3,label:He.default.t("Automatically set a certain value"),value:typeof this.state.autoSetInterval=="number",disabled:this.props.readonly,onChange:n=>this.handleChange("autoSetInterval",n?6e4:!1)},He.default.t("Set a certain value automatically in a given interval")),typeof this.state.autoSetInterval=="number"&&Ge.default.createElement(Ge.default.Fragment,null,Ge.default.createElement(tn,{xs:12,sm:6,md:4,lg:3,label:He.default.t("Interval for automatic set"),value:this.state.autoSetInterval.toString(),disabled:this.props.readonly,onChange:n=>this.handleChange("autoSetInterval",parseInt(n,10)||0),transform:n=>n.replace(/\D/g,"")},He.default.t("Interval in milliseconds to automatically set the value")),r==="number"&&Ge.default.createElement(tn,{xs:12,sm:6,md:4,lg:3,label:He.default.t("Value to set"),value:(this.state.autoSetValue||0).toString(),disabled:this.props.readonly,onChange:n=>this.handleChange("autoSetValue",parseFloat(n)||0),transform:n=>n.replace(",",".").replace(/[^\d.]/g,"")},He.default.t("The value to set automatically in the given interval (%s)",r)),r==="boolean"&&Ge.default.createElement(xr,{xs:12,sm:6,md:4,lg:3,label:He.default.t("Value to set"),value:!!this.state.autoSetValue,disabled:this.props.readonly,onChange:n=>this.handleChange("autoSetValue",n)},He.default.t("The value to set automatically in the given interval (%s)",r)),r==="string"&&Ge.default.createElement(tn,{xs:12,sm:6,md:4,lg:3,label:He.default.t("Value to set"),value:this.state.autoSetValue||"",disabled:this.props.readonly,onChange:n=>this.handleChange("autoSetValue",n)},He.default.t("The value to set automatically in the given interval (%s)",r)),!this.props.msgAutoSend&&Ge.default.createElement(xr,{xs:12,sm:6,md:4,lg:3,label:He.default.t("Trigger send"),value:!!this.state.autoSetTriggerSend,disabled:this.props.readonly,onChange:n=>this.handleChange("autoSetTriggerSend",n)},He.default.t("Trigger the send action every time the value is set automatically")))))}onChange(){this.props.onChange(this.props.uuid,{id:this.state.id,name:this.state.name,dataType:this.state.dataType,dataLength:this.state.dataLength,dataOffset:this.state.dataOffset,dataUnit:this.state.dataUnit,dataEncoding:this.state.dataEncoding,booleanMask:this.state.booleanMask,booleanInvert:this.state.booleanInvert,customScriptRead:this.state.customScriptRead,customScriptWrite:this.state.customScriptWrite,customDataType:this.state.customDataType,commonRole:this.state.commonRole,commonStates:this.state.commonStates,autoSetInterval:this.state.autoSetInterval,autoSetValue:this.state.autoSetValue,autoSetTriggerSend:this.state.autoSetTriggerSend})}handleChange(e,r){let n={[e]:r};this.updateDependedElements(n),this.validateState(n),this.setState(n,()=>{this.onChange()})}updateDependedElements(e){var n,o,a;switch(e.dataType||((n=this.state)==null?void 0:n.dataType)||"uint8"){case"boolean":e.disabledDataOffsets=[],e.disabledDataLengths=["2","3","4","5","6","7","8"],e.dataLength=1,e.disabledDataEncoding=!0,e.disabledDataUnit=!0,e.disabledDataOffsetAndLength=!1,e.dataUnit="";break;case"int8":case"uint8":e.disabledDataOffsets=[],e.disabledDataLengths=["2","3","4","5","6","7","8"],e.dataLength=1,e.disabledDataEncoding=!0,e.disabledDataUnit=!1,e.disabledDataOffsetAndLength=!1;break;case"int16_be":case"int16_le":case"uint16_be":case"uint16_le":e.disabledDataOffsets=["7"],e.disabledDataLengths=["1","3","4","5","6","7","8"],e.dataLength=2,e.disabledDataEncoding=!0,e.disabledDataUnit=!1,e.disabledDataOffsetAndLength=!1;break;case"int32_be":case"int32_le":case"uint32_be":case"uint32_le":case"float32_be":case"float32_le":e.disabledDataOffsets=["5","6","7"],e.disabledDataLengths=["1","2","3","5","6","7","8"],e.dataLength=4,e.disabledDataEncoding=!0,e.disabledDataUnit=!1,e.disabledDataOffsetAndLength=!1;break;case"double64_be":case"double64_le":e.disabledDataOffsets=["1","2","3","4","5","6","7"],e.disabledDataLengths=["1","2","3","4","5","6","7"],e.dataLength=8,e.disabledDataEncoding=!0,e.disabledDataUnit=!1,e.disabledDataOffsetAndLength=!1;break;case"string":{e.disabledDataOffsets=[],e.disabledDataLengths=[],e.disabledDataEncoding=!1,e.disabledDataUnit=!0,e.disabledDataOffsetAndLength=!1,e.dataUnit="";let i=(o=e.dataOffset)!=null?o:this.state.dataOffset;((a=e.dataLength)!=null?a:this.state.dataLength)+i>8&&(e.dataLength=8-i);for(let u=1;u<=8;u++)u+i>8&&e.disabledDataLengths.push(u.toString());break}case"custom":e.disabledDataOffsets=[],e.disabledDataLengths=[],e.dataOffset=0,e.dataLength=8,e.disabledDataEncoding=!0,e.disabledDataUnit=!1,e.disabledDataOffsetAndLength=!0;break}return e}validateState(e){var n,o;let r=!0;return e.id!==void 0?goe.includes(e.id)?(e.idError=He.default.t("This ID is reserved and can't be used"),r=!1):e.id.match(hoe)?e.idError=null:(e.idError=He.default.t("Only allowed chars: %s","0-9a-z-_"),r=!1):((n=this.state)==null?void 0:n.idError)!==null&&(r=!1),e.commonStates!==void 0?e.commonStates!==!1&&!e.commonStates.match(voe)?(e.commonStatesError=He.default.t("Invalid format! Please use the format value=text,value=text,..."),r=!1):e.commonStatesError=null:(o=this.state)!=null&&o.commonStatesError&&(r=!1),this.props.onValidate(this.props.uuid,r),e}copy(){Mi.parser=JSON.stringify(this.state),this.props.showToast&&this.props.showToast(He.default.t("Parser configuration copied. Use the paste button to paste this configuration to an other parser."))}paste(){if(!Mi.parser){this.props.showToast&&this.props.showToast(He.default.t("Nothing to paste. Please use the copy button first."));return}try{let e=JSON.parse(Mi.parser);this.setState(this.validateState({...e}),()=>{this.onChange(),this.props.showToast&&this.props.showToast(He.default.t("Pasted"))})}catch(e){this.props.showToast&&this.props.showToast(He.default.t("Error while pasting: %s",`${e}`))}}};Et([Tt],gh.prototype,"copy",1),Et([Tt],gh.prototype,"paste",1);var da=class extends pt.default.Component{constructor(e){super(e),this.state=this.validateState({tabIndex:0,id:this.props.config.id||"",idError:null,name:this.props.config.name||"",dlc:typeof this.props.config.dlc=="number"?this.props.config.dlc:-1,receive:this.props.config.receive||!1,send:this.props.config.send||!1,autosend:this.props.config.autosend||!1,parsers:this.props.config.parsers||{},parsersValid:{},showRemoveConfirm:!1})}componentDidMount(){this.validateState()}render(){let{classes:e,context:r}=this.props;return pt.default.createElement(pt.default.Fragment,null,pt.default.createElement("div",{className:e.fabTopRight},pt.default.createElement(X_.default,{size:"small",color:"primary","aria-label":"copy",title:ht.default.t("Copy"),onClick:this.copy},pt.default.createElement(BI,null)),pt.default.createElement(X_.default,{size:"small",color:"primary","aria-label":"paste",title:ht.default.t("Paste"),onClick:this.paste,disabled:this.props.readonly||!Mi.message},pt.default.createElement(UI,null)),pt.default.createElement(X_.default,{size:"small",color:"primary","aria-label":"delete",title:ht.default.t("Remove"),onClick:()=>this.setState({showRemoveConfirm:!0}),disabled:this.props.readonly||!this.props.onDelete},pt.default.createElement(Jie.default,null)),this.props.onAdd&&pt.default.createElement(X_.default,{size:"small",color:"primary","aria-label":"add",title:ht.default.t("Add"),onClick:()=>this.props.onAdd&&this.props.onAdd(this.props.uuid)},pt.default.createElement(gB.default,null))),pt.default.createElement("h2",null,ht.default.t("Message")),pt.default.createElement(Ke,{container:!0,spacing:3},pt.default.createElement(tn,{xs:12,sm:6,md:4,lg:2,label:ht.default.t("Message ID"),value:this.state.id,required:!0,errorMsg:this.state.idError,disabled:this.props.readonly,transform:"upperCase",onChange:n=>this.handleChange("id",n)},ht.default.t("CAN message ID in hex"),", ",ht.default.t("e.g.")," ",pt.default.createElement("code",null,"00A0123B")," ",ht.default.t("or")," ",pt.default.createElement("code",null,"1AB")),pt.default.createElement(tn,{xs:12,sm:6,md:4,lg:4,label:ht.default.t("Name"),value:this.state.name,disabled:this.props.readonly,onChange:n=>this.handleChange("name",n)},ht.default.t("e.g.")," ",pt.default.createElement("code",null,ht.default.t("My super message"))),pt.default.createElement(No,{xs:12,sm:6,md:4,lg:3,label:ht.default.t("Data length"),value:this.state.dlc.toString(),options:{"-1":ht.default.t("Not set"),0:"0",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8"},disabled:this.props.readonly,onChange:n=>this.handleChange("dlc",parseInt(n,10))},ht.default.t("Optionally set a fixed data length for this message"))),pt.default.createElement(Ke,{container:!0,spacing:3},pt.default.createElement(xr,{xs:12,sm:12,md:4,lg:4,label:ht.default.t("Receive"),value:this.state.receive,disabled:this.props.readonly,onChange:n=>this.handleChange("receive",n)},ht.default.t("Receive messages with the given ID")),pt.default.createElement(xr,{xs:12,sm:12,md:4,lg:4,label:ht.default.t("Send"),value:this.state.send,disabled:this.props.readonly,onChange:n=>this.handleChange("send",n)},ht.default.t("Send messages with the given ID")),pt.default.createElement(xr,{xs:12,sm:12,md:4,lg:4,label:ht.default.t("Autosend"),value:this.state.autosend,disabled:this.props.readonly,onChange:n=>this.handleChange("autosend",n)},ht.default.t("Automatically send the message when some data part changed"))),pt.default.createElement("h2",null,ht.default.t("Parsers")),pt.default.createElement("div",{className:e.root},pt.default.createElement(C_,{orientation:"vertical",variant:"scrollable",value:this.state.tabIndex,onChange:this.handleTabChange,className:e.tabs},Object.keys(this.state.parsers).map((n,o)=>pt.default.createElement(vl,{key:`tab-${o}`,label:this.getParserTabLabel(this.state.parsers[n]),id:`${this.props.uuid}-tab-${o}`,className:e.tab,style:{color:this.state.parsersValid[n]===!1?"red":void 0,fontStyle:this.state.parsers[n].id?void 0:"italic"}})),!this.props.readonly&&pt.default.createElement(Yie.default,{color:"primary",startIcon:pt.default.createElement(gB.default,null),onClick:this.onParserAdd},ht.default.t("Add"))),Object.keys(this.state.parsers).map((n,o)=>pt.default.createElement($s,{key:`tabpanel-${o}`,value:this.state.tabIndex,index:o,className:e.tabpanel},pt.default.createElement(gh,{uuid:n,config:this.state.parsers[n],msgId:this.state.dlc>=0?`${this.state.id}-${this.state.dlc}`:this.state.id,msgReceive:this.state.receive,msgSend:this.state.send,msgAutoSend:this.state.autosend,onChange:this.onParserChange,onValidate:this.onParserValidate,onDelete:this.onParserDelete,showToast:this.props.showToast,context:r,classes:e,readonly:this.props.readonly})))),this.state.showRemoveConfirm&&pt.default.createElement(Xie.default,{title:ht.default.t("Remove this message?"),text:ht.default.t("Are you sure you want to remove this message? This will also remove all it's parsers. The message will be treated as unconfigured and may be deleted on adapter restart."),onClose:n=>{n&&this.props.onDelete&&this.props.onDelete(this.props.uuid),this.setState({showRemoveConfirm:!1})}}))}getParserTabLabel(e){return e!=null&&e.id?e.name?`${e.name} (${e.id})`:e.id:ht.default.t("ID missing")}handleTabChange(e,r){this.setState({tabIndex:r})}async handleChange(e,r){let n={[e]:r};e==="id"&&n.dlc===void 0?n.dlc=this.state.dlc:e==="dlc"&&n.id===void 0&&(n.id=this.state.id),this.validateState(n),await new Promise(o=>{this.setState(n,()=>{this.onChange(),o()})})}onChange(){this.props.onChange&&this.props.onChange(this.props.uuid,{id:this.state.id,name:this.state.name,dlc:this.state.dlc,receive:this.state.receive,send:this.state.send,autosend:this.state.autosend,parsers:{...this.state.parsers}})}validateState(e={}){var n,o;let r=!0;if(e.id!==void 0?e.id.match(fI)?this.props.knownMessageIds.find(a=>a.id===e.id&&a.dlc===e.dlc&&a.uuid!==this.props.uuid)?(e.idError=ht.default.t("This ID is configured multiple times with this data length"),r=!1):e.idError=null:(e.idError=ht.default.t("Must be a 3 or 8 char hex ID"),r=!1):((n=this.state)==null?void 0:n.idError)!==null&&(r=!1),(o=this.state)!=null&&o.parsersValid)for(let a in this.state.parsersValid)this.state.parsersValid[a]||(r=!1);return this.props.onValidate&&this.props.onValidate(this.props.uuid,r),e}async onParserAdd(){let e=Cl(),r={id:"",name:"",dataType:"int8",dataLength:1,dataOffset:0,dataUnit:"",dataEncoding:"latin1",booleanMask:0,booleanInvert:!1,customScriptRead:"",customScriptWrite:"",customDataType:"number",commonRole:"state",commonStates:!1,autoSetInterval:!1,autoSetValue:void 0},n={...this.state.parsers};n[e]=r,await this.handleChange("parsers",n),await this.onParserValidate(e,!1),this.setState({tabIndex:Object.keys(this.state.parsers).length-1})}async onParserValidate(e,r){let n={...this.state.parsersValid};return n[e]=r,await new Promise(o=>{this.setState({parsersValid:n},()=>{this.validateState(),o()})})}onParserChange(e,r){let n={...this.state.parsers};n[e]=r,this.handleChange("parsers",n)}async onParserDelete(e){let r={...this.state.parsers},n={...this.state.parsersValid};delete r[e],delete n[e],await this.handleChange("parsers",r),this.setState({tabIndex:this.state.tabIndex-1,parsersValid:n},()=>{this.validateState(),this.state.tabIndex<0&&this.setState({tabIndex:0})})}copy(){Mi.message=JSON.stringify(this.state),this.props.showToast&&this.props.showToast(ht.default.t("Message configuration copied. Use the paste button to paste this configuration to an other message."))}paste(){if(!Mi.message){this.props.showToast&&this.props.showToast(ht.default.t("Nothing to paste. Please use the copy button first."));return}try{let e=JSON.parse(Mi.message),r=Object.keys(e.parsers);for(let n of r){let o=Cl();e.parsers[o]=e.parsers[n],delete e.parsers[n]}this.setState(this.validateState({...e}),()=>{this.onChange(),this.props.showToast&&this.props.showToast(ht.default.t("Pasted"))})}catch(e){this.props.showToast&&this.props.showToast(ht.default.t("Error while pasting: %s",`${e}`))}}};Et([Tt],da.prototype,"handleTabChange",1),Et([Tt],da.prototype,"onParserAdd",1),Et([Tt],da.prototype,"onParserValidate",1),Et([Tt],da.prototype,"onParserChange",1),Et([Tt],da.prototype,"onParserDelete",1),Et([Tt],da.prototype,"copy",1),Et([Tt],da.prototype,"paste",1);var kVe=t=>({root:{flexGrow:1,backgroundColor:t.palette.background.paper,display:"flex",height:"calc(100% - 102px)"},tabs:{borderRight:`1px solid ${t.palette.divider}`},tab:{textTransform:"none"},tabpanel:{position:"relative",width:"100%",overflowY:"auto"},fabTopRight:{"& > button":{margin:t.spacing(1)},position:"absolute",top:t.spacing(2),right:t.spacing(2)}}),qo=class extends br.default.Component{constructor(e){var n;super(e);let r=(n=this.props.native.messages)!=null?n:{};this.state={tabIndex:0,generalValid:!0,messages:r,messagesKeys:Object.keys(r).sort((o,a)=>W_(r,o,a)),messagesValid:{},messagesUnconfigured:{},messagesUnconfiguredKeys:[]}}componentDidMount(){let{socket:e,instance:r,adapterName:n}=this.props.context;e.subscribeObject(`${n}.${r}.*`,this.handleObjChange),this.loadUnconfiguredMessages()}componentWillUnmount(){let{socket:e,instance:r,adapterName:n}=this.props.context;e.unsubscribeObject(`${n}.${r}.*`,this.handleObjChange)}render(){let{classes:e,native:r,common:n,context:o}=this.props,a=0,i=Object.keys(this.state.messages).map(s=>({id:this.state.messages[s].id,dlc:this.state.messages[s].dlc,uuid:s}));return br.default.createElement("div",{className:e.root},br.default.createElement(C_,{orientation:"vertical",variant:"scrollable",value:this.state.tabIndex,onChange:this.handleTabChange,className:e.tabs},br.default.createElement(vl,{label:Ad.default.t("General"),id:"tab-0",className:e.tab,style:{color:this.state.generalValid===!1?"red":void 0}}),br.default.createElement(vl,{label:Ad.default.t("Import / Export"),id:"tab-1",className:e.tab}),br.default.createElement(jm,{textAlign:"center"},Ad.default.t("Messages")),this.state.messagesKeys.map((s,u)=>this.state.messages[s]&&br.default.createElement(vl,{key:`tab-${u+1}`,label:this.getMessageTabLabel(this.state.messages[s]),id:`tab-${u+1}`,className:e.tab,style:{color:this.state.messagesValid[s]===!1?"red":void 0,fontStyle:this.state.messages[s].id?void 0:"italic"}})),this.state.messagesUnconfiguredKeys.length>0&&br.default.createElement(jm,{textAlign:"center"},Ad.default.t("Unconfigured messages")),this.state.messagesUnconfiguredKeys.map((s,u)=>this.state.messagesUnconfigured[s]&&br.default.createElement(vl,{key:`tab-unconf-${u}`,label:this.getMessageTabLabel(this.state.messagesUnconfigured[s]),id:`tab-unconf-${u}`,className:e.tab})),br.default.createElement(Zie.default,{color:"primary",startIcon:br.default.createElement(ese.default,null),onClick:this.onMessageAdd},Ad.default.t("Add"))),br.default.createElement($s,{value:this.state.tabIndex,index:a++,className:e.tabpanel},br.default.createElement(pI,{common:n,context:o,native:r,onChange:this.onGeneralChange,onError:this.props.onError,onValidate:this.onGeneralValidate,setNative:this.props.setNative})),br.default.createElement($s,{value:this.state.tabIndex,index:a++,className:e.tabpanel},br.default.createElement(Bi,{context:o,native:r,onError:this.props.onError,setNative:this.props.setNative,showToast:this.props.showToast})),br.default.createElement($s,{value:this.state.tabIndex,index:a++}),this.state.messagesKeys.map((s,u)=>this.state.messages[s]&&br.default.createElement($s,{key:`tabpanel-${u}`,value:this.state.tabIndex,index:a++,className:e.tabpanel},br.default.createElement(da,{key:s,context:o,classes:e,uuid:s,config:this.state.messages[s],knownMessageIds:i,onChange:this.onMessageChange,onDelete:this.onMessageDelete,onValidate:this.onMessageValidate,showToast:this.props.showToast}))),this.state.messagesUnconfiguredKeys.length>0&&br.default.createElement($s,{value:this.state.tabIndex,index:a++}),this.state.messagesUnconfiguredKeys.map((s,u)=>this.state.messagesUnconfigured[s]&&br.default.createElement($s,{key:`tabpanel-${u}`,value:this.state.tabIndex,index:a++,className:e.tabpanel},br.default.createElement(da,{key:s,context:o,classes:e,uuid:s,config:this.state.messagesUnconfigured[s],knownMessageIds:[],readonly:!0,onAdd:this.onMessageAddFromUnconfigured,showToast:this.props.showToast}))))}getMessageTabLabel(e){return e!=null&&e.id?e.dlc>=0?`${e.id}-${e.dlc} ${e.name}`:`${e.id} ${e.name}`:Ad.default.t("ID missing")}handleTabChange(e,r){this.setState({tabIndex:r})}async onGeneralChange(e,r){this.props.onChange(e,r),e==="messages"&&(Object.keys(r).length===0?await new Promise(n=>{this.setState({messages:r,tabIndex:0},n)}):await new Promise(n=>{this.setState({messages:r},n)}))}onMessageChange(e,r){let n={...this.state.messages};n[e]=r,this.onGeneralChange("messages",n)}async onMessageDelete(e){let r={...this.state.messages},n={...this.state.messagesValid},o=this.state.messagesKeys.filter(a=>a!==e);delete r[e],delete n[e],await this.onGeneralChange("messages",r),this.setState({tabIndex:this.state.tabIndex-1,messagesKeys:o,messagesValid:n},()=>{this.validate(),this.state.tabIndex<3&&this.setState({tabIndex:0})}),this.loadUnconfiguredMessages()}async onGeneralValidate(e){return await new Promise(r=>{this.setState({generalValid:e},()=>{this.validate(),r()})})}async onMessageValidate(e,r){let n={...this.state.messagesValid};return n[e]=r,await new Promise(o=>{this.setState({messagesValid:n},()=>{this.validate(),o()})})}async onMessageAdd(){let e=Cl(),r={id:"",name:"",dlc:-1,receive:!1,send:!1,autosend:!1,parsers:{}},n={...this.state.messages},o=[...this.state.messagesKeys,e];n[e]=r,await this.onGeneralChange("messages",n),await this.onMessageValidate(e,!1),this.setState({tabIndex:Object.keys(this.state.messages).length+2,messagesKeys:o})}async onMessageAddFromUnconfigured(e){let r=Cl(),n={...this.state.messagesUnconfigured[e]},o={...this.state.messages},a=[...this.state.messagesKeys,r];o[r]=n,await this.onGeneralChange("messages",o);let i={...this.state.messagesUnconfigured},s=this.state.messagesUnconfiguredKeys.filter(u=>u!==e);delete i[e],this.setState({tabIndex:Object.keys(this.state.messages).length+2,messagesKeys:a,messagesUnconfigured:i,messagesUnconfiguredKeys:s})}async loadUnconfiguredMessages(){let{socket:e,instance:r,adapterName:n}=this.props.context,o=await e.getObjectView(`${n}.${r}.`,`${n}.${r}.\u9999`,"channel"),a={};for(let i in o)this.addPossiblyUnconfiguredMessage(a,o[i]);this.setState({messagesUnconfigured:a,messagesUnconfiguredKeys:Object.keys(a).sort((i,s)=>W_(a,i,s))})}addPossiblyUnconfiguredMessage(e,r){if(r.type!=="channel")return!1;let n=r._id.split(".");if(!n[2].match(moe))return!1;let[o,a]=n[2].split("-"),i=a===void 0?-1:parseInt(a,10);for(let s in this.state.messages)if(this.state.messages[s].id===o&&this.state.messages[s].dlc===i)return!1;return e[n[2]]={id:o,name:r.common.name,dlc:i,receive:!0,send:!1,autosend:!1,parsers:{}},!0}handleObjChange(e,r){let{instance:n,adapterName:o}=this.props.context;if(!e.startsWith(`${o}.${n}.`))return;let a=e.split(".");if(!a[2].match(fI))return;if(!r){this.setState(s=>{let u={...s,messagesUnconfigured:{...s.messagesUnconfigured},messagesUnconfiguredKeys:s.messagesUnconfiguredKeys.filter(l=>l!==a[2])};return delete u.messagesUnconfigured[a[2]],u});return}let i={};this.addPossiblyUnconfiguredMessage(i,r)&&this.setState(s=>({...s,messagesUnconfigured:{...s.messagesUnconfigured,...i},messagesUnconfiguredKeys:[...s.messagesUnconfiguredKeys,a[2]]}))}validate(){let e=this.state.generalValid;if(e)for(let r in this.state.messagesValid)this.state.messagesValid[r]||(e=!1);return this.props.onValidate(e),e}};Et([Tt],qo.prototype,"handleTabChange",1),Et([Tt],qo.prototype,"onGeneralChange",1),Et([Tt],qo.prototype,"onMessageChange",1),Et([Tt],qo.prototype,"onMessageDelete",1),Et([Tt],qo.prototype,"onGeneralValidate",1),Et([Tt],qo.prototype,"onMessageValidate",1),Et([Tt],qo.prototype,"onMessageAdd",1),Et([Tt],qo.prototype,"onMessageAddFromUnconfigured",1),Et([Tt],qo.prototype,"loadUnconfiguredMessages",1),Et([Tt],qo.prototype,"handleObjChange",1);var tse=(0,Qie.withStyles)(kVe)(qo);var HI={name:"canbus",version:"2.0.0",news:{"2.0.0":{en:"Node.js >= 18, Admin >= 6.17, js-contoller >= 5.0.19 are required\nChanged how custom parser scripts are interpreted. Most custom parser scripts should work as before but they have a limited scope now.\nCustom parser scripts now support `getStateAsync`, `getForeignStateAsync`, `getObjectAsync` and `getForeignObjectAsync`. If you have used `getStateAsync`/`getObjectAsync` before you need to change them to `getForeignStateAsync`/`getForeignObjectAsync` or update the IDs if you get data from the same adapter instance.\nCustom write parser scripts an now return false to cancel the write\nUpdated dependencies",de:"Node.js >= 18, Admin >= 6.17, js-contoller >= 5.0.19 sind erforderlich\nWie benutzerdefinierte Parser-Skripte interpretiert werden. Die meisten benutzerdefinierten Parser-Skripte sollten wie fr\xFCher funktionieren, aber sie haben jetzt einen begrenzten Umfang.\nBenutzerdefinierte Parser-Skripte unterst\xFCtzen jetzt `getStateAsync`, `getForeignStateAsync`, `getObjectAsync` und `getForeignObjectAsync`. Wenn Sie `getStateAsync`/`getObjectAsync` verwendet haben, bevor Sie diese auf `getForeignStateAsync`/`getForeignObjectAsync \xE4ndern m\xFCssen oder die IDs aktualisieren, wenn Sie Daten von der gleichen Adapterinstanz erhalten.\nBenutzerdefinierte Schreib-Parser-Skripte eine jetzt falsche zur\xFCck, um den schreiben\nAktualisierte Abh\xE4ngigkeiten",ru:"Node.js >= 18, \u0410\u0434\u043C\u0438\u043D >= 6.17, js-contoller >= 5.0.19 \u0442\u0440\u0435\u0431\u0443\u0435\u0442\u0441\u044F\n\u0418\u0437\u043C\u0435\u043D\u0438\u043B\u0441\u044F \u0441\u043F\u043E\u0441\u043E\u0431 \u0438\u043D\u0442\u0435\u0440\u043F\u0440\u0435\u0442\u0430\u0446\u0438\u0438 \u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044C\u0441\u043A\u0438\u0445 \u0441\u0446\u0435\u043D\u0430\u0440\u0438\u0435\u0432. \u0411\u043E\u043B\u044C\u0448\u0438\u043D\u0441\u0442\u0432\u043E \u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044C\u0441\u043A\u0438\u0445 \u0441\u0446\u0435\u043D\u0430\u0440\u0438\u0435\u0432 \u043F\u0430\u0440\u0441\u0435\u0440\u0430 \u0434\u043E\u043B\u0436\u043D\u044B \u0440\u0430\u0431\u043E\u0442\u0430\u0442\u044C \u0442\u0430\u043A, \u043A\u0430\u043A \u0440\u0430\u043D\u044C\u0448\u0435, \u043D\u043E \u0442\u0435\u043F\u0435\u0440\u044C \u043E\u043D\u0438 \u0438\u043C\u0435\u044E\u0442 \u043E\u0433\u0440\u0430\u043D\u0438\u0447\u0435\u043D\u043D\u044B\u0439 \u043E\u0445\u0432\u0430\u0442.\nCustom parserScripts \u0442\u0435\u043F\u0435\u0440\u044C \u043F\u043E\u0434\u0434\u0435\u0440\u0436\u0438\u0432\u0430\u0435\u0442 `getStateAsync', `getForeignStateAsync', `getObjectAsync' \u0438 `getForeignObjectAsync'. \u0415\u0441\u043B\u0438 \u0432\u044B \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043B\u0438 `getStateAsync'/`getObjectAsync', \u043F\u0440\u0435\u0436\u0434\u0435 \u0447\u0435\u043C \u0432\u0430\u043C \u043D\u0443\u0436\u043D\u043E \u0438\u0437\u043C\u0435\u043D\u0438\u0442\u044C \u0438\u0445 \u043D\u0430 `getForeignStateAsync'/`getForeignObjectAsync' \u0438\u043B\u0438 \u043E\u0431\u043D\u043E\u0432\u0438\u0442\u044C \u0438\u0434\u0435\u043D\u0442\u0438\u0444\u0438\u043A\u0430\u0442\u043E\u0440\u044B, \u0435\u0441\u043B\u0438 \u0432\u044B \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u0435 \u0434\u0430\u043D\u043D\u044B\u0435 \u0438\u0437 \u0442\u043E\u0433\u043E \u0436\u0435 \u044D\u043A\u0437\u0435\u043C\u043F\u043B\u044F\u0440\u0430 \u0430\u0434\u0430\u043F\u0442\u0435\u0440\u0430.\n\u041F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044C\u0441\u043A\u0438\u0439 \u043F\u0438\u0441\u0430\u0442\u044C \u043F\u0430\u0440\u0441\u0435\u0440 \u0441\u043A\u0440\u0438\u043F\u0442\u044B \u0442\u0435\u043F\u0435\u0440\u044C \u0432\u043E\u0437\u0432\u0440\u0430\u0449\u0430\u0435\u0442\u0441\u044F \u043B\u043E\u0436\u043D\u044B\u043C, \u0447\u0442\u043E\u0431\u044B \u043E\u0442\u043C\u0435\u043D\u0438\u0442\u044C \u0437\u0430\u043F\u0438\u0441\u044C\n\u041E\u0431\u043D\u043E\u0432\u043B\u0435\u043D\u043D\u044B\u0435 \u0437\u0430\u0432\u0438\u0441\u0438\u043C\u043E\u0441\u0442\u0438",pt:"Node.js >= 18, Admin >= 6.17, js-contoller >= 5.0.19 s\xE3o necess\xE1rios\nAlterado como scripts de parser personalizados s\xE3o interpretados. A maioria dos scripts de parser personalizados deve funcionar como antes, mas eles t\xEAm um escopo limitado agora.\nScripts de parser personalizados agora suportam `getStateAsync`, `getForeignStateAsync`, `getObjectAsync` e `getForeignObjectAsync`. Se voc\xEA tiver usado `getStateAsync`/`getObjectAsync` antes de precisar alter\xE1-los para `getForeignStateAsync`/`getForeignObjectAsync ou atualizar os IDs se voc\xEA receber dados da mesma inst\xE2ncia do adaptador.\nCustom escrever scripts parser um agora retornar falso para cancelar a grava\xE7\xE3o\nDepend\xEAncias atualizadas",nl:`Voor de toepassing van deze onderverdeling wordt verstaan onder: 5.0.19 zijn vereist +buffer[1] = (value >> 8);`},Ge.default.createElement("span",{dangerouslySetInnerHTML:{__html:He.default.t("Script to write the value to the buffer. The buffer is available as %s and the value as %s.","buffer","value")}}))),this.props.msgSend&&Ge.default.createElement(Ke,{container:!0,spacing:3},Ge.default.createElement(xr,{xs:12,sm:6,md:4,lg:3,label:He.default.t("Automatically set a certain value"),value:typeof this.state.autoSetInterval=="number",disabled:this.props.readonly,onChange:n=>this.handleChange("autoSetInterval",n?6e4:!1)},He.default.t("Set a certain value automatically in a given interval")),typeof this.state.autoSetInterval=="number"&&Ge.default.createElement(Ge.default.Fragment,null,Ge.default.createElement(tn,{xs:12,sm:6,md:4,lg:3,label:He.default.t("Interval for automatic set"),value:this.state.autoSetInterval.toString(),disabled:this.props.readonly,onChange:n=>this.handleChange("autoSetInterval",parseInt(n,10)||0),transform:n=>n.replace(/\D/g,"")},He.default.t("Interval in milliseconds to automatically set the value")),r==="number"&&Ge.default.createElement(tn,{xs:12,sm:6,md:4,lg:3,label:He.default.t("Value to set"),value:(this.state.autoSetValue||0).toString(),disabled:this.props.readonly,onChange:n=>this.handleChange("autoSetValue",parseFloat(n)||0),transform:n=>n.replace(",",".").replace(/[^\d.]/g,"")},He.default.t("The value to set automatically in the given interval (%s)",r)),r==="boolean"&&Ge.default.createElement(xr,{xs:12,sm:6,md:4,lg:3,label:He.default.t("Value to set"),value:!!this.state.autoSetValue,disabled:this.props.readonly,onChange:n=>this.handleChange("autoSetValue",n)},He.default.t("The value to set automatically in the given interval (%s)",r)),r==="string"&&Ge.default.createElement(tn,{xs:12,sm:6,md:4,lg:3,label:He.default.t("Value to set"),value:this.state.autoSetValue||"",disabled:this.props.readonly,onChange:n=>this.handleChange("autoSetValue",n)},He.default.t("The value to set automatically in the given interval (%s)",r)),!this.props.msgAutoSend&&Ge.default.createElement(xr,{xs:12,sm:6,md:4,lg:3,label:He.default.t("Trigger send"),value:!!this.state.autoSetTriggerSend,disabled:this.props.readonly,onChange:n=>this.handleChange("autoSetTriggerSend",n)},He.default.t("Trigger the send action every time the value is set automatically")))))}onChange(){this.props.onChange(this.props.uuid,{id:this.state.id,name:this.state.name,dataType:this.state.dataType,dataLength:this.state.dataLength,dataOffset:this.state.dataOffset,dataUnit:this.state.dataUnit,dataEncoding:this.state.dataEncoding,booleanMask:this.state.booleanMask,booleanInvert:this.state.booleanInvert,customScriptRead:this.state.customScriptRead,customScriptWrite:this.state.customScriptWrite,customDataType:this.state.customDataType,commonRole:this.state.commonRole,commonStates:this.state.commonStates,autoSetInterval:this.state.autoSetInterval,autoSetValue:this.state.autoSetValue,autoSetTriggerSend:this.state.autoSetTriggerSend})}handleChange(e,r){let n={[e]:r};this.updateDependedElements(n),this.validateState(n),this.setState(n,()=>{this.onChange()})}updateDependedElements(e){var n,o,a;switch(e.dataType||((n=this.state)==null?void 0:n.dataType)||"uint8"){case"boolean":e.disabledDataOffsets=[],e.disabledDataLengths=["2","3","4","5","6","7","8"],e.dataLength=1,e.disabledDataEncoding=!0,e.disabledDataUnit=!0,e.disabledDataOffsetAndLength=!1,e.dataUnit="";break;case"int8":case"uint8":e.disabledDataOffsets=[],e.disabledDataLengths=["2","3","4","5","6","7","8"],e.dataLength=1,e.disabledDataEncoding=!0,e.disabledDataUnit=!1,e.disabledDataOffsetAndLength=!1;break;case"int16_be":case"int16_le":case"uint16_be":case"uint16_le":e.disabledDataOffsets=["7"],e.disabledDataLengths=["1","3","4","5","6","7","8"],e.dataLength=2,e.disabledDataEncoding=!0,e.disabledDataUnit=!1,e.disabledDataOffsetAndLength=!1;break;case"int32_be":case"int32_le":case"uint32_be":case"uint32_le":case"float32_be":case"float32_le":e.disabledDataOffsets=["5","6","7"],e.disabledDataLengths=["1","2","3","5","6","7","8"],e.dataLength=4,e.disabledDataEncoding=!0,e.disabledDataUnit=!1,e.disabledDataOffsetAndLength=!1;break;case"double64_be":case"double64_le":e.disabledDataOffsets=["1","2","3","4","5","6","7"],e.disabledDataLengths=["1","2","3","4","5","6","7"],e.dataLength=8,e.disabledDataEncoding=!0,e.disabledDataUnit=!1,e.disabledDataOffsetAndLength=!1;break;case"string":{e.disabledDataOffsets=[],e.disabledDataLengths=[],e.disabledDataEncoding=!1,e.disabledDataUnit=!0,e.disabledDataOffsetAndLength=!1,e.dataUnit="";let i=(o=e.dataOffset)!=null?o:this.state.dataOffset;((a=e.dataLength)!=null?a:this.state.dataLength)+i>8&&(e.dataLength=8-i);for(let u=1;u<=8;u++)u+i>8&&e.disabledDataLengths.push(u.toString());break}case"custom":e.disabledDataOffsets=[],e.disabledDataLengths=[],e.dataOffset=0,e.dataLength=8,e.disabledDataEncoding=!0,e.disabledDataUnit=!1,e.disabledDataOffsetAndLength=!0;break}return e}validateState(e){var n,o;let r=!0;return e.id!==void 0?goe.includes(e.id)?(e.idError=He.default.t("This ID is reserved and can't be used"),r=!1):e.id.match(hoe)?e.idError=null:(e.idError=He.default.t("Only allowed chars: %s","0-9a-z-_"),r=!1):((n=this.state)==null?void 0:n.idError)!==null&&(r=!1),e.commonStates!==void 0?e.commonStates!==!1&&!e.commonStates.match(voe)?(e.commonStatesError=He.default.t("Invalid format! Please use the format value=text,value=text,..."),r=!1):e.commonStatesError=null:(o=this.state)!=null&&o.commonStatesError&&(r=!1),this.props.onValidate(this.props.uuid,r),e}copy(){Mi.parser=JSON.stringify(this.state),this.props.showToast&&this.props.showToast(He.default.t("Parser configuration copied. Use the paste button to paste this configuration to an other parser."))}paste(){if(!Mi.parser){this.props.showToast&&this.props.showToast(He.default.t("Nothing to paste. Please use the copy button first."));return}try{let e=JSON.parse(Mi.parser);this.setState(this.validateState({...e}),()=>{this.onChange(),this.props.showToast&&this.props.showToast(He.default.t("Pasted"))})}catch(e){this.props.showToast&&this.props.showToast(He.default.t("Error while pasting: %s",`${e}`))}}};Et([Tt],gh.prototype,"copy",1),Et([Tt],gh.prototype,"paste",1);var da=class extends pt.default.Component{constructor(e){super(e),this.state=this.validateState({tabIndex:0,id:this.props.config.id||"",idError:null,name:this.props.config.name||"",dlc:typeof this.props.config.dlc=="number"?this.props.config.dlc:-1,receive:this.props.config.receive||!1,send:this.props.config.send||!1,autosend:this.props.config.autosend||!1,parsers:this.props.config.parsers||{},parsersValid:{},showRemoveConfirm:!1})}componentDidMount(){this.validateState()}render(){let{classes:e,context:r}=this.props;return pt.default.createElement(pt.default.Fragment,null,pt.default.createElement("div",{className:e.fabTopRight},pt.default.createElement(X_.default,{size:"small",color:"primary","aria-label":"copy",title:ht.default.t("Copy"),onClick:this.copy},pt.default.createElement(BI,null)),pt.default.createElement(X_.default,{size:"small",color:"primary","aria-label":"paste",title:ht.default.t("Paste"),onClick:this.paste,disabled:this.props.readonly||!Mi.message},pt.default.createElement(UI,null)),pt.default.createElement(X_.default,{size:"small",color:"primary","aria-label":"delete",title:ht.default.t("Remove"),onClick:()=>this.setState({showRemoveConfirm:!0}),disabled:this.props.readonly||!this.props.onDelete},pt.default.createElement(Jie.default,null)),this.props.onAdd&&pt.default.createElement(X_.default,{size:"small",color:"primary","aria-label":"add",title:ht.default.t("Add"),onClick:()=>this.props.onAdd&&this.props.onAdd(this.props.uuid)},pt.default.createElement(gB.default,null))),pt.default.createElement("h2",null,ht.default.t("Message")),pt.default.createElement(Ke,{container:!0,spacing:3},pt.default.createElement(tn,{xs:12,sm:6,md:4,lg:2,label:ht.default.t("Message ID"),value:this.state.id,required:!0,errorMsg:this.state.idError,disabled:this.props.readonly,transform:"upperCase",onChange:n=>this.handleChange("id",n)},ht.default.t("CAN message ID in hex"),", ",ht.default.t("e.g.")," ",pt.default.createElement("code",null,"00A0123B")," ",ht.default.t("or")," ",pt.default.createElement("code",null,"1AB")),pt.default.createElement(tn,{xs:12,sm:6,md:4,lg:4,label:ht.default.t("Name"),value:this.state.name,disabled:this.props.readonly,onChange:n=>this.handleChange("name",n)},ht.default.t("e.g.")," ",pt.default.createElement("code",null,ht.default.t("My super message"))),pt.default.createElement(No,{xs:12,sm:6,md:4,lg:3,label:ht.default.t("Data length"),value:this.state.dlc.toString(),options:{"-1":ht.default.t("Not set"),0:"0",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8"},disabled:this.props.readonly,onChange:n=>this.handleChange("dlc",parseInt(n,10))},ht.default.t("Optionally set a fixed data length for this message"))),pt.default.createElement(Ke,{container:!0,spacing:3},pt.default.createElement(xr,{xs:12,sm:12,md:4,lg:4,label:ht.default.t("Receive"),value:this.state.receive,disabled:this.props.readonly,onChange:n=>this.handleChange("receive",n)},ht.default.t("Receive messages with the given ID")),pt.default.createElement(xr,{xs:12,sm:12,md:4,lg:4,label:ht.default.t("Send"),value:this.state.send,disabled:this.props.readonly,onChange:n=>this.handleChange("send",n)},ht.default.t("Send messages with the given ID")),pt.default.createElement(xr,{xs:12,sm:12,md:4,lg:4,label:ht.default.t("Autosend"),value:this.state.autosend,disabled:this.props.readonly,onChange:n=>this.handleChange("autosend",n)},ht.default.t("Automatically send the message when some data part changed"))),pt.default.createElement("h2",null,ht.default.t("Parsers")),pt.default.createElement("div",{className:e.root},pt.default.createElement(C_,{orientation:"vertical",variant:"scrollable",value:this.state.tabIndex,onChange:this.handleTabChange,className:e.tabs},Object.keys(this.state.parsers).map((n,o)=>pt.default.createElement(vl,{key:`tab-${o}`,label:this.getParserTabLabel(this.state.parsers[n]),id:`${this.props.uuid}-tab-${o}`,className:e.tab,style:{color:this.state.parsersValid[n]===!1?"red":void 0,fontStyle:this.state.parsers[n].id?void 0:"italic"}})),!this.props.readonly&&pt.default.createElement(Yie.default,{color:"primary",startIcon:pt.default.createElement(gB.default,null),onClick:this.onParserAdd},ht.default.t("Add"))),Object.keys(this.state.parsers).map((n,o)=>pt.default.createElement($s,{key:`tabpanel-${o}`,value:this.state.tabIndex,index:o,className:e.tabpanel},pt.default.createElement(gh,{uuid:n,config:this.state.parsers[n],msgId:this.state.dlc>=0?`${this.state.id}-${this.state.dlc}`:this.state.id,msgReceive:this.state.receive,msgSend:this.state.send,msgAutoSend:this.state.autosend,onChange:this.onParserChange,onValidate:this.onParserValidate,onDelete:this.onParserDelete,showToast:this.props.showToast,context:r,classes:e,readonly:this.props.readonly})))),this.state.showRemoveConfirm&&pt.default.createElement(Xie.default,{title:ht.default.t("Remove this message?"),text:ht.default.t("Are you sure you want to remove this message? This will also remove all it's parsers. The message will be treated as unconfigured and may be deleted on adapter restart."),onClose:n=>{n&&this.props.onDelete&&this.props.onDelete(this.props.uuid),this.setState({showRemoveConfirm:!1})}}))}getParserTabLabel(e){return e!=null&&e.id?e.name?`${e.name} (${e.id})`:e.id:ht.default.t("ID missing")}handleTabChange(e,r){this.setState({tabIndex:r})}async handleChange(e,r){let n={[e]:r};e==="id"&&n.dlc===void 0?n.dlc=this.state.dlc:e==="dlc"&&n.id===void 0&&(n.id=this.state.id),this.validateState(n),await new Promise(o=>{this.setState(n,()=>{this.onChange(),o()})})}onChange(){this.props.onChange&&this.props.onChange(this.props.uuid,{id:this.state.id,name:this.state.name,dlc:this.state.dlc,receive:this.state.receive,send:this.state.send,autosend:this.state.autosend,parsers:{...this.state.parsers}})}validateState(e={}){var n,o;let r=!0;if(e.id!==void 0?e.id.match(fI)?this.props.knownMessageIds.find(a=>a.id===e.id&&a.dlc===e.dlc&&a.uuid!==this.props.uuid)?(e.idError=ht.default.t("This ID is configured multiple times with this data length"),r=!1):e.idError=null:(e.idError=ht.default.t("Must be a 3 or 8 char hex ID"),r=!1):((n=this.state)==null?void 0:n.idError)!==null&&(r=!1),(o=this.state)!=null&&o.parsersValid)for(let a in this.state.parsersValid)this.state.parsersValid[a]||(r=!1);return this.props.onValidate&&this.props.onValidate(this.props.uuid,r),e}async onParserAdd(){let e=Cl(),r={id:"",name:"",dataType:"int8",dataLength:1,dataOffset:0,dataUnit:"",dataEncoding:"latin1",booleanMask:0,booleanInvert:!1,customScriptRead:"",customScriptWrite:"",customDataType:"number",commonRole:"state",commonStates:!1,autoSetInterval:!1,autoSetValue:void 0},n={...this.state.parsers};n[e]=r,await this.handleChange("parsers",n),await this.onParserValidate(e,!1),this.setState({tabIndex:Object.keys(this.state.parsers).length-1})}async onParserValidate(e,r){let n={...this.state.parsersValid};return n[e]=r,await new Promise(o=>{this.setState({parsersValid:n},()=>{this.validateState(),o()})})}onParserChange(e,r){let n={...this.state.parsers};n[e]=r,this.handleChange("parsers",n)}async onParserDelete(e){let r={...this.state.parsers},n={...this.state.parsersValid};delete r[e],delete n[e],await this.handleChange("parsers",r),this.setState({tabIndex:this.state.tabIndex-1,parsersValid:n},()=>{this.validateState(),this.state.tabIndex<0&&this.setState({tabIndex:0})})}copy(){Mi.message=JSON.stringify(this.state),this.props.showToast&&this.props.showToast(ht.default.t("Message configuration copied. Use the paste button to paste this configuration to an other message."))}paste(){if(!Mi.message){this.props.showToast&&this.props.showToast(ht.default.t("Nothing to paste. Please use the copy button first."));return}try{let e=JSON.parse(Mi.message),r=Object.keys(e.parsers);for(let n of r){let o=Cl();e.parsers[o]=e.parsers[n],delete e.parsers[n]}this.setState(this.validateState({...e}),()=>{this.onChange(),this.props.showToast&&this.props.showToast(ht.default.t("Pasted"))})}catch(e){this.props.showToast&&this.props.showToast(ht.default.t("Error while pasting: %s",`${e}`))}}};Et([Tt],da.prototype,"handleTabChange",1),Et([Tt],da.prototype,"onParserAdd",1),Et([Tt],da.prototype,"onParserValidate",1),Et([Tt],da.prototype,"onParserChange",1),Et([Tt],da.prototype,"onParserDelete",1),Et([Tt],da.prototype,"copy",1),Et([Tt],da.prototype,"paste",1);var kVe=t=>({root:{flexGrow:1,backgroundColor:t.palette.background.paper,display:"flex",height:"calc(100% - 102px)"},tabs:{borderRight:`1px solid ${t.palette.divider}`},tab:{textTransform:"none"},tabpanel:{position:"relative",width:"100%",overflowY:"auto"},fabTopRight:{"& > button":{margin:t.spacing(1)},position:"absolute",top:t.spacing(2),right:t.spacing(2)}}),qo=class extends br.default.Component{constructor(e){var n;super(e);let r=(n=this.props.native.messages)!=null?n:{};this.state={tabIndex:0,generalValid:!0,messages:r,messagesKeys:Object.keys(r).sort((o,a)=>W_(r,o,a)),messagesValid:{},messagesUnconfigured:{},messagesUnconfiguredKeys:[]}}componentDidMount(){let{socket:e,instance:r,adapterName:n}=this.props.context;e.subscribeObject(`${n}.${r}.*`,this.handleObjChange),this.loadUnconfiguredMessages()}componentWillUnmount(){let{socket:e,instance:r,adapterName:n}=this.props.context;e.unsubscribeObject(`${n}.${r}.*`,this.handleObjChange)}render(){let{classes:e,native:r,common:n,context:o}=this.props,a=0,i=Object.keys(this.state.messages).map(s=>({id:this.state.messages[s].id,dlc:this.state.messages[s].dlc,uuid:s}));return br.default.createElement("div",{className:e.root},br.default.createElement(C_,{orientation:"vertical",variant:"scrollable",value:this.state.tabIndex,onChange:this.handleTabChange,className:e.tabs},br.default.createElement(vl,{label:Ad.default.t("General"),id:"tab-0",className:e.tab,style:{color:this.state.generalValid===!1?"red":void 0}}),br.default.createElement(vl,{label:Ad.default.t("Import / Export"),id:"tab-1",className:e.tab}),br.default.createElement(jm,{textAlign:"center"},Ad.default.t("Messages")),this.state.messagesKeys.map((s,u)=>this.state.messages[s]&&br.default.createElement(vl,{key:`tab-${u+1}`,label:this.getMessageTabLabel(this.state.messages[s]),id:`tab-${u+1}`,className:e.tab,style:{color:this.state.messagesValid[s]===!1?"red":void 0,fontStyle:this.state.messages[s].id?void 0:"italic"}})),this.state.messagesUnconfiguredKeys.length>0&&br.default.createElement(jm,{textAlign:"center"},Ad.default.t("Unconfigured messages")),this.state.messagesUnconfiguredKeys.map((s,u)=>this.state.messagesUnconfigured[s]&&br.default.createElement(vl,{key:`tab-unconf-${u}`,label:this.getMessageTabLabel(this.state.messagesUnconfigured[s]),id:`tab-unconf-${u}`,className:e.tab})),br.default.createElement(Zie.default,{color:"primary",startIcon:br.default.createElement(ese.default,null),onClick:this.onMessageAdd},Ad.default.t("Add"))),br.default.createElement($s,{value:this.state.tabIndex,index:a++,className:e.tabpanel},br.default.createElement(pI,{common:n,context:o,native:r,onChange:this.onGeneralChange,onError:this.props.onError,onValidate:this.onGeneralValidate,setNative:this.props.setNative})),br.default.createElement($s,{value:this.state.tabIndex,index:a++,className:e.tabpanel},br.default.createElement(Bi,{context:o,native:r,onError:this.props.onError,setNative:this.props.setNative,showToast:this.props.showToast})),br.default.createElement($s,{value:this.state.tabIndex,index:a++}),this.state.messagesKeys.map((s,u)=>this.state.messages[s]&&br.default.createElement($s,{key:`tabpanel-${u}`,value:this.state.tabIndex,index:a++,className:e.tabpanel},br.default.createElement(da,{key:s,context:o,classes:e,uuid:s,config:this.state.messages[s],knownMessageIds:i,onChange:this.onMessageChange,onDelete:this.onMessageDelete,onValidate:this.onMessageValidate,showToast:this.props.showToast}))),this.state.messagesUnconfiguredKeys.length>0&&br.default.createElement($s,{value:this.state.tabIndex,index:a++}),this.state.messagesUnconfiguredKeys.map((s,u)=>this.state.messagesUnconfigured[s]&&br.default.createElement($s,{key:`tabpanel-${u}`,value:this.state.tabIndex,index:a++,className:e.tabpanel},br.default.createElement(da,{key:s,context:o,classes:e,uuid:s,config:this.state.messagesUnconfigured[s],knownMessageIds:[],readonly:!0,onAdd:this.onMessageAddFromUnconfigured,showToast:this.props.showToast}))))}getMessageTabLabel(e){return e!=null&&e.id?e.dlc>=0?`${e.id}-${e.dlc} ${e.name}`:`${e.id} ${e.name}`:Ad.default.t("ID missing")}handleTabChange(e,r){this.setState({tabIndex:r})}async onGeneralChange(e,r){this.props.onChange(e,r),e==="messages"&&(Object.keys(r).length===0?await new Promise(n=>{this.setState({messages:r,tabIndex:0},n)}):await new Promise(n=>{this.setState({messages:r},n)}))}onMessageChange(e,r){let n={...this.state.messages};n[e]=r,this.onGeneralChange("messages",n)}async onMessageDelete(e){let r={...this.state.messages},n={...this.state.messagesValid},o=this.state.messagesKeys.filter(a=>a!==e);delete r[e],delete n[e],await this.onGeneralChange("messages",r),this.setState({tabIndex:this.state.tabIndex-1,messagesKeys:o,messagesValid:n},()=>{this.validate(),this.state.tabIndex<3&&this.setState({tabIndex:0})}),this.loadUnconfiguredMessages()}async onGeneralValidate(e){return await new Promise(r=>{this.setState({generalValid:e},()=>{this.validate(),r()})})}async onMessageValidate(e,r){let n={...this.state.messagesValid};return n[e]=r,await new Promise(o=>{this.setState({messagesValid:n},()=>{this.validate(),o()})})}async onMessageAdd(){let e=Cl(),r={id:"",name:"",dlc:-1,receive:!1,send:!1,autosend:!1,parsers:{}},n={...this.state.messages},o=[...this.state.messagesKeys,e];n[e]=r,await this.onGeneralChange("messages",n),await this.onMessageValidate(e,!1),this.setState({tabIndex:Object.keys(this.state.messages).length+2,messagesKeys:o})}async onMessageAddFromUnconfigured(e){let r=Cl(),n={...this.state.messagesUnconfigured[e]},o={...this.state.messages},a=[...this.state.messagesKeys,r];o[r]=n,await this.onGeneralChange("messages",o);let i={...this.state.messagesUnconfigured},s=this.state.messagesUnconfiguredKeys.filter(u=>u!==e);delete i[e],this.setState({tabIndex:Object.keys(this.state.messages).length+2,messagesKeys:a,messagesUnconfigured:i,messagesUnconfiguredKeys:s})}async loadUnconfiguredMessages(){let{socket:e,instance:r,adapterName:n}=this.props.context,o=await e.getObjectView(`${n}.${r}.`,`${n}.${r}.\u9999`,"channel"),a={};for(let i in o)this.addPossiblyUnconfiguredMessage(a,o[i]);this.setState({messagesUnconfigured:a,messagesUnconfiguredKeys:Object.keys(a).sort((i,s)=>W_(a,i,s))})}addPossiblyUnconfiguredMessage(e,r){if(r.type!=="channel")return!1;let n=r._id.split(".");if(!n[2].match(moe))return!1;let[o,a]=n[2].split("-"),i=a===void 0?-1:parseInt(a,10);for(let s in this.state.messages)if(this.state.messages[s].id===o&&this.state.messages[s].dlc===i)return!1;return e[n[2]]={id:o,name:r.common.name,dlc:i,receive:!0,send:!1,autosend:!1,parsers:{}},!0}handleObjChange(e,r){let{instance:n,adapterName:o}=this.props.context;if(!e.startsWith(`${o}.${n}.`))return;let a=e.split(".");if(!a[2].match(fI))return;if(!r){this.setState(s=>{let u={...s,messagesUnconfigured:{...s.messagesUnconfigured},messagesUnconfiguredKeys:s.messagesUnconfiguredKeys.filter(l=>l!==a[2])};return delete u.messagesUnconfigured[a[2]],u});return}let i={};this.addPossiblyUnconfiguredMessage(i,r)&&this.setState(s=>({...s,messagesUnconfigured:{...s.messagesUnconfigured,...i},messagesUnconfiguredKeys:[...s.messagesUnconfiguredKeys,a[2]]}))}validate(){let e=this.state.generalValid;if(e)for(let r in this.state.messagesValid)this.state.messagesValid[r]||(e=!1);return this.props.onValidate(e),e}};Et([Tt],qo.prototype,"handleTabChange",1),Et([Tt],qo.prototype,"onGeneralChange",1),Et([Tt],qo.prototype,"onMessageChange",1),Et([Tt],qo.prototype,"onMessageDelete",1),Et([Tt],qo.prototype,"onGeneralValidate",1),Et([Tt],qo.prototype,"onMessageValidate",1),Et([Tt],qo.prototype,"onMessageAdd",1),Et([Tt],qo.prototype,"onMessageAddFromUnconfigured",1),Et([Tt],qo.prototype,"loadUnconfiguredMessages",1),Et([Tt],qo.prototype,"handleObjChange",1);var tse=(0,Qie.withStyles)(kVe)(qo);var HI={name:"canbus",version:"2.0.0",news:{"2.0.0":{en:"Node.js >= 18, Admin >= 6.17, js-contoller >= 5.0.19 are required\nChanged how custom parser scripts are interpreted. Most custom parser scripts should work as before but they have a limited scope now.\nCustom parser scripts now support `getStateAsync`, `getForeignStateAsync`, `getObjectAsync` and `getForeignObjectAsync`. If you have used `getStateAsync`/`getObjectAsync` before you need to change them to `getForeignStateAsync`/`getForeignObjectAsync` or update the IDs if you get data from the same adapter instance.\nCustom write parser scripts an now return false to cancel the write\nUpdated dependencies",de:"Node.js >= 18, Admin >= 6.17, js-contoller >= 5.0.19 sind erforderlich\nArt der Ausf\xFChrung der Skripte in benutzerdefinierten Parsern ge\xE4ndert. Skripte sollten wie fr\xFCher funktionieren, aber sie werden jetzt in einer eingeschr\xE4nkten Umgebung ausgef\xFChrt.\nSkripte benutzerdefinierter Parser unterst\xFCtzen jetzt `getStateAsync`, `getForeignStateAsync`, `getObjectAsync` und `getForeignObjectAsync`. Wenn zuvor `getStateAsync`/`getObjectAsync` verwendet wurde, m\xFCssen diese ggf. auf `getForeignStateAsync`/`getForeignObjectAsync ge\xE4ndert werden oder die IDs m\xFCssen aktualisiert werden, wenn Sie Daten von der gleichen Adapterinstanz erhalten.\nSchreiben-Skripte benutzerdefinierter Parser k\xF6nnen jetzt `false` zur\xFCckgeben, um das Schreiben abzubrechen\nAbh\xE4ngigkeiten aktualisiert",ru:"Node.js >= 18, \u0410\u0434\u043C\u0438\u043D >= 6.17, js-contoller >= 5.0.19 \u0442\u0440\u0435\u0431\u0443\u0435\u0442\u0441\u044F\n\u0418\u0437\u043C\u0435\u043D\u0438\u043B\u0441\u044F \u0441\u043F\u043E\u0441\u043E\u0431 \u0438\u043D\u0442\u0435\u0440\u043F\u0440\u0435\u0442\u0430\u0446\u0438\u0438 \u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044C\u0441\u043A\u0438\u0445 \u0441\u0446\u0435\u043D\u0430\u0440\u0438\u0435\u0432. \u0411\u043E\u043B\u044C\u0448\u0438\u043D\u0441\u0442\u0432\u043E \u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044C\u0441\u043A\u0438\u0445 \u0441\u0446\u0435\u043D\u0430\u0440\u0438\u0435\u0432 \u043F\u0430\u0440\u0441\u0435\u0440\u0430 \u0434\u043E\u043B\u0436\u043D\u044B \u0440\u0430\u0431\u043E\u0442\u0430\u0442\u044C \u0442\u0430\u043A, \u043A\u0430\u043A \u0440\u0430\u043D\u044C\u0448\u0435, \u043D\u043E \u0442\u0435\u043F\u0435\u0440\u044C \u043E\u043D\u0438 \u0438\u043C\u0435\u044E\u0442 \u043E\u0433\u0440\u0430\u043D\u0438\u0447\u0435\u043D\u043D\u044B\u0439 \u043E\u0445\u0432\u0430\u0442.\nCustom parserScripts \u0442\u0435\u043F\u0435\u0440\u044C \u043F\u043E\u0434\u0434\u0435\u0440\u0436\u0438\u0432\u0430\u0435\u0442 `getStateAsync', `getForeignStateAsync', `getObjectAsync' \u0438 `getForeignObjectAsync'. \u0415\u0441\u043B\u0438 \u0432\u044B \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043B\u0438 `getStateAsync'/`getObjectAsync', \u043F\u0440\u0435\u0436\u0434\u0435 \u0447\u0435\u043C \u0432\u0430\u043C \u043D\u0443\u0436\u043D\u043E \u0438\u0437\u043C\u0435\u043D\u0438\u0442\u044C \u0438\u0445 \u043D\u0430 `getForeignStateAsync'/`getForeignObjectAsync' \u0438\u043B\u0438 \u043E\u0431\u043D\u043E\u0432\u0438\u0442\u044C \u0438\u0434\u0435\u043D\u0442\u0438\u0444\u0438\u043A\u0430\u0442\u043E\u0440\u044B, \u0435\u0441\u043B\u0438 \u0432\u044B \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u0435 \u0434\u0430\u043D\u043D\u044B\u0435 \u0438\u0437 \u0442\u043E\u0433\u043E \u0436\u0435 \u044D\u043A\u0437\u0435\u043C\u043F\u043B\u044F\u0440\u0430 \u0430\u0434\u0430\u043F\u0442\u0435\u0440\u0430.\n\u041F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044C\u0441\u043A\u0438\u0439 \u043F\u0438\u0441\u0430\u0442\u044C \u043F\u0430\u0440\u0441\u0435\u0440 \u0441\u043A\u0440\u0438\u043F\u0442\u044B \u0442\u0435\u043F\u0435\u0440\u044C \u0432\u043E\u0437\u0432\u0440\u0430\u0449\u0430\u0435\u0442\u0441\u044F \u043B\u043E\u0436\u043D\u044B\u043C, \u0447\u0442\u043E\u0431\u044B \u043E\u0442\u043C\u0435\u043D\u0438\u0442\u044C \u0437\u0430\u043F\u0438\u0441\u044C\n\u041E\u0431\u043D\u043E\u0432\u043B\u0435\u043D\u043D\u044B\u0435 \u0437\u0430\u0432\u0438\u0441\u0438\u043C\u043E\u0441\u0442\u0438",pt:"Node.js >= 18, Admin >= 6.17, js-contoller >= 5.0.19 s\xE3o necess\xE1rios\nAlterado como scripts de parser personalizados s\xE3o interpretados. A maioria dos scripts de parser personalizados deve funcionar como antes, mas eles t\xEAm um escopo limitado agora.\nScripts de parser personalizados agora suportam `getStateAsync`, `getForeignStateAsync`, `getObjectAsync` e `getForeignObjectAsync`. Se voc\xEA tiver usado `getStateAsync`/`getObjectAsync` antes de precisar alter\xE1-los para `getForeignStateAsync`/`getForeignObjectAsync ou atualizar os IDs se voc\xEA receber dados da mesma inst\xE2ncia do adaptador.\nCustom escrever scripts parser um agora retornar falso para cancelar a grava\xE7\xE3o\nDepend\xEAncias atualizadas",nl:`Voor de toepassing van deze onderverdeling wordt verstaan onder: 5.0.19 zijn vereist Veranderd hoe aangepaste parser scripts worden ge\xEFnterpreteerd. De meeste aangepaste parser scripts moeten werken als voorheen, maar ze hebben een beperkte reikwijdte nu. Aangepaste parser scripts ondersteunen nu Als u gebruik hebt gemaakt van . Aangepast schrijven parser scripts an now return false to cancel the write diff --git a/admin/build/index.js.map b/admin/build/index.js.map index 8dff69f..96109ab 100644 --- a/admin/build/index.js.map +++ b/admin/build/index.js.map @@ -1,7 +1,7 @@ { "version": 3, "sources": ["../../node_modules/object-assign/index.js", "../../node_modules/react/cjs/react.production.min.js", "../../node_modules/react/index.js", "../../node_modules/scheduler/cjs/scheduler.production.min.js", "../../node_modules/scheduler/index.js", "../../node_modules/react-dom/cjs/react-dom.production.min.js", "../../node_modules/react-dom/index.js", "../../node_modules/@babel/runtime/helpers/interopRequireDefault.js", "../../node_modules/@babel/runtime/helpers/typeof.js", "../../node_modules/@babel/runtime/helpers/interopRequireWildcard.js", "../../node_modules/@material-ui/utils/chainPropTypes.js", "../../node_modules/@babel/runtime/helpers/extends.js", "../../node_modules/@material-ui/utils/deepmerge.js", "../../node_modules/prop-types/lib/ReactPropTypesSecret.js", "../../node_modules/prop-types/factoryWithThrowingShims.js", "../../node_modules/prop-types/index.js", "../../node_modules/@material-ui/utils/elementAcceptingRef.js", "../../node_modules/@material-ui/utils/elementTypeAcceptingRef.js", "../../node_modules/@babel/runtime/helpers/toPrimitive.js", "../../node_modules/@babel/runtime/helpers/toPropertyKey.js", "../../node_modules/@babel/runtime/helpers/defineProperty.js", "../../node_modules/@material-ui/utils/exactProp.js", "../../node_modules/@material-ui/utils/formatMuiErrorMessage.js", "../../node_modules/react-is/cjs/react-is.production.min.js", "../../node_modules/react-is/index.js", "../../node_modules/@material-ui/utils/getDisplayName.js", "../../node_modules/@material-ui/utils/HTMLElementType.js", "../../node_modules/@material-ui/utils/ponyfillGlobal.js", "../../node_modules/@material-ui/utils/refType.js", "../../node_modules/@material-ui/utils/index.js", "../../node_modules/@material-ui/core/styles/colorManipulator.js", "../../node_modules/@babel/runtime/helpers/objectWithoutPropertiesLoose.js", "../../node_modules/@babel/runtime/helpers/objectWithoutProperties.js", "../../node_modules/@material-ui/core/styles/createBreakpoints.js", "../../node_modules/@material-ui/core/styles/createMixins.js", "../../node_modules/@material-ui/core/colors/common.js", "../../node_modules/@material-ui/core/colors/grey.js", "../../node_modules/@material-ui/core/colors/indigo.js", "../../node_modules/@material-ui/core/colors/pink.js", "../../node_modules/@material-ui/core/colors/red.js", "../../node_modules/@material-ui/core/colors/orange.js", "../../node_modules/@material-ui/core/colors/blue.js", "../../node_modules/@material-ui/core/colors/green.js", "../../node_modules/@material-ui/core/styles/createPalette.js", "../../node_modules/@material-ui/core/styles/createTypography.js", "../../node_modules/@material-ui/core/styles/shadows.js", "../../node_modules/@material-ui/core/styles/shape.js", "../../node_modules/@material-ui/system/responsivePropType.js", "../../node_modules/@babel/runtime/helpers/arrayLikeToArray.js", "../../node_modules/@babel/runtime/helpers/arrayWithoutHoles.js", "../../node_modules/@babel/runtime/helpers/iterableToArray.js", "../../node_modules/@babel/runtime/helpers/unsupportedIterableToArray.js", "../../node_modules/@babel/runtime/helpers/nonIterableSpread.js", "../../node_modules/@babel/runtime/helpers/toConsumableArray.js", "../../node_modules/@material-ui/system/merge.js", "../../node_modules/@material-ui/system/breakpoints.js", "../../node_modules/@material-ui/system/style.js", "../../node_modules/@material-ui/system/compose.js", "../../node_modules/@material-ui/system/borders.js", "../../node_modules/@material-ui/system/styleFunctionSx.js", "../../node_modules/@material-ui/system/display.js", "../../node_modules/@material-ui/system/flexbox.js", "../../node_modules/@material-ui/system/grid.js", "../../node_modules/@material-ui/system/palette.js", "../../node_modules/@material-ui/system/positions.js", "../../node_modules/@material-ui/system/shadows.js", "../../node_modules/@material-ui/system/sizing.js", "../../node_modules/@babel/runtime/helpers/arrayWithHoles.js", "../../node_modules/@babel/runtime/helpers/iterableToArrayLimit.js", "../../node_modules/@babel/runtime/helpers/nonIterableRest.js", "../../node_modules/@babel/runtime/helpers/slicedToArray.js", "../../node_modules/@material-ui/system/memoize.js", "../../node_modules/@material-ui/system/spacing.js", "../../node_modules/@material-ui/system/typography.js", "../../node_modules/@material-ui/system/index.js", "../../node_modules/@material-ui/core/styles/createSpacing.js", "../../node_modules/@material-ui/core/styles/transitions.js", "../../node_modules/@material-ui/core/styles/zIndex.js", "../../node_modules/@material-ui/core/styles/createTheme.js", "../../node_modules/@material-ui/core/styles/createMuiStrictModeTheme.js", "../../node_modules/@material-ui/styles/ThemeProvider/nested.js", "../../node_modules/@material-ui/styles/createGenerateClassName/createGenerateClassName.js", "../../node_modules/@material-ui/styles/createGenerateClassName/index.js", "../../node_modules/@material-ui/styles/createStyles/createStyles.js", "../../node_modules/@material-ui/styles/createStyles/index.js", "../../node_modules/@material-ui/styles/getThemeProps/getThemeProps.js", "../../node_modules/@material-ui/styles/getThemeProps/index.js", "../../node_modules/tiny-warning/dist/tiny-warning.cjs.js", "../../node_modules/is-in-browser/dist/index.js", "../../node_modules/@babel/runtime/helpers/createClass.js", "../../node_modules/@babel/runtime/helpers/setPrototypeOf.js", "../../node_modules/@babel/runtime/helpers/inheritsLoose.js", "../../node_modules/@babel/runtime/helpers/assertThisInitialized.js", "../../node_modules/jss/dist/jss.cjs.js", "../../node_modules/jss-plugin-rule-value-function/dist/jss-plugin-rule-value-function.cjs.js", "../../node_modules/jss-plugin-global/dist/jss-plugin-global.cjs.js", "../../node_modules/jss-plugin-nested/dist/jss-plugin-nested.cjs.js", "../../node_modules/hyphenate-style-name/index.cjs.js", "../../node_modules/jss-plugin-camel-case/dist/jss-plugin-camel-case.cjs.js", "../../node_modules/jss-plugin-default-unit/dist/jss-plugin-default-unit.cjs.js", "../../node_modules/css-vendor/dist/css-vendor.cjs.js", "../../node_modules/jss-plugin-vendor-prefixer/dist/jss-plugin-vendor-prefixer.cjs.js", "../../node_modules/jss-plugin-props-sort/dist/jss-plugin-props-sort.cjs.js", "../../node_modules/@material-ui/styles/jssPreset/jssPreset.js", "../../node_modules/@material-ui/styles/jssPreset/index.js", "../../node_modules/@material-ui/styles/mergeClasses/mergeClasses.js", "../../node_modules/@material-ui/styles/mergeClasses/index.js", "../../node_modules/@material-ui/styles/makeStyles/multiKeyStore.js", "../../node_modules/@material-ui/styles/useTheme/ThemeContext.js", "../../node_modules/@material-ui/styles/useTheme/useTheme.js", "../../node_modules/@material-ui/styles/useTheme/index.js", "../../node_modules/@material-ui/styles/StylesProvider/StylesProvider.js", "../../node_modules/@material-ui/styles/StylesProvider/index.js", "../../node_modules/@material-ui/styles/makeStyles/indexCounter.js", "../../node_modules/@material-ui/styles/getStylesCreator/noopTheme.js", "../../node_modules/@material-ui/styles/getStylesCreator/getStylesCreator.js", "../../node_modules/@material-ui/styles/getStylesCreator/index.js", "../../node_modules/@material-ui/styles/makeStyles/makeStyles.js", "../../node_modules/@material-ui/styles/makeStyles/index.js", "../../node_modules/@babel/runtime/helpers/classCallCheck.js", "../../node_modules/@material-ui/styles/ServerStyleSheets/ServerStyleSheets.js", "../../node_modules/@material-ui/styles/ServerStyleSheets/index.js", "../../node_modules/clsx/dist/clsx.js", "../../node_modules/hoist-non-react-statics/node_modules/react-is/cjs/react-is.production.min.js", "../../node_modules/hoist-non-react-statics/node_modules/react-is/index.js", "../../node_modules/hoist-non-react-statics/dist/hoist-non-react-statics.cjs.js", "../../node_modules/@material-ui/styles/styled/styled.js", "../../node_modules/@material-ui/styles/styled/index.js", "../../node_modules/@material-ui/styles/ThemeProvider/ThemeProvider.js", "../../node_modules/@material-ui/styles/ThemeProvider/index.js", "../../node_modules/@material-ui/styles/withStyles/withStyles.js", "../../node_modules/@material-ui/styles/withStyles/index.js", "../../node_modules/@material-ui/styles/withTheme/withTheme.js", "../../node_modules/@material-ui/styles/withTheme/index.js", "../../node_modules/@material-ui/styles/index.js", "../../node_modules/@material-ui/core/styles/createStyles.js", "../../node_modules/@material-ui/core/styles/defaultTheme.js", "../../node_modules/@material-ui/core/styles/makeStyles.js", "../../node_modules/@material-ui/core/styles/cssUtils.js", "../../node_modules/@material-ui/core/styles/responsiveFontSizes.js", "../../node_modules/@material-ui/core/styles/styled.js", "../../node_modules/@material-ui/core/styles/useTheme.js", "../../node_modules/@material-ui/core/styles/withStyles.js", "../../node_modules/@material-ui/core/styles/withTheme.js", "../../node_modules/@material-ui/core/styles/index.js", "../../node_modules/@iobroker/adapter-react/Theme.js", "../../node_modules/@iobroker/adapter-react/i18n.js", "../../node_modules/@iobroker/adapter-react/Components/Utils.js", "../../node_modules/@babel/runtime/helpers/getPrototypeOf.js", "../../node_modules/@babel/runtime/helpers/superPropBase.js", "../../node_modules/@babel/runtime/helpers/get.js", "../../node_modules/@babel/runtime/helpers/inherits.js", "../../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js", "../../node_modules/@iobroker/adapter-react/Connection.js", "../../node_modules/@sentry/src/is.ts", "../../node_modules/@sentry/src/string.ts", "../../node_modules/@sentry/src/aggregate-errors.ts", "../../node_modules/@sentry/src/worldwide.ts", "../../node_modules/@sentry/src/browser.ts", "../../node_modules/@sentry/src/debug-build.ts", "../../node_modules/@sentry/src/logger.ts", "../../node_modules/@sentry/src/dsn.ts", "../../node_modules/@sentry/src/error.ts", "../../node_modules/@sentry/src/object.ts", "../../node_modules/@sentry/src/node-stack-trace.ts", "../../node_modules/@sentry/src/stacktrace.ts", "../../node_modules/@sentry/src/instrument/_handlers.ts", "../../node_modules/@sentry/src/instrument/console.ts", "../../node_modules/@sentry/src/misc.ts", "../../node_modules/@sentry/src/instrument/dom.ts", "../../node_modules/@sentry/src/supports.ts", "../../node_modules/@sentry/src/instrument/fetch.ts", "../../node_modules/@sentry/src/instrument/globalError.ts", "../../node_modules/@sentry/src/instrument/globalUnhandledRejection.ts", "../../node_modules/@sentry/src/vendor/supportsHistory.ts", "../../node_modules/@sentry/src/instrument/history.ts", "../../node_modules/@sentry/src/instrument/xhr.ts", "../../node_modules/@sentry/src/instrument/index.ts", "../../node_modules/@sentry/src/env.ts", "../../node_modules/@sentry/src/node.ts", "../../node_modules/@sentry/src/isBrowser.ts", "../../node_modules/@sentry/src/memo.ts", "../../node_modules/@sentry/src/normalize.ts", "../../node_modules/@sentry/src/path.ts", "../../node_modules/@sentry/src/syncpromise.ts", "../../node_modules/@sentry/src/promisebuffer.ts", "../../node_modules/@sentry/src/cookie.ts", "../../node_modules/@sentry/src/url.ts", "../../node_modules/@sentry/src/requestdata.ts", "../../node_modules/@sentry/src/severity.ts", "../../node_modules/@sentry/src/time.ts", "../../node_modules/@sentry/src/baggage.ts", "../../node_modules/@sentry/src/tracing.ts", "../../node_modules/@sentry/src/envelope.ts", "../../node_modules/@sentry/src/clientreport.ts", "../../node_modules/@sentry/src/ratelimit.ts", "../../node_modules/@sentry/src/userIntegrations.ts", "../../node_modules/@sentry/src/cache.ts", "../../node_modules/@sentry/src/eventbuilder.ts", "../../node_modules/@sentry/src/anr.ts", "../../node_modules/@sentry/src/lru.ts", "../../node_modules/@sentry/src/buildPolyfills/_nullishCoalesce.ts", "../../node_modules/@sentry/src/buildPolyfills/_asyncNullishCoalesce.ts", "../../node_modules/@sentry/src/buildPolyfills/_asyncOptionalChain.ts", "../../node_modules/@sentry/src/buildPolyfills/_asyncOptionalChainDelete.ts", "../../node_modules/@sentry/src/buildPolyfills/_optionalChain.ts", "../../node_modules/@sentry/src/buildPolyfills/_optionalChainDelete.ts", "../../node_modules/@sentry/src/vendor/escapeStringForRegex.ts", "../../node_modules/@sentry/utils/cjs/index.js", "../../node_modules/@sentry/src/debug-build.ts", "../../node_modules/@sentry/src/constants.ts", "../../node_modules/@sentry/src/eventProcessors.ts", "../../node_modules/@sentry/src/session.ts", "../../node_modules/@sentry/src/utils/spanUtils.ts", "../../node_modules/@sentry/src/utils/prepareEvent.ts", "../../node_modules/@sentry/src/exports.ts", "../../node_modules/@sentry/src/utils/getRootSpan.ts", "../../node_modules/@sentry/src/tracing/dynamicSamplingContext.ts", "../../node_modules/@sentry/src/utils/applyScopeDataToEvent.ts", "../../node_modules/@sentry/src/scope.ts", "../../node_modules/@sentry/src/version.ts", "../../node_modules/@sentry/src/hub.ts", "../../node_modules/@sentry/src/tracing/utils.ts", "../../node_modules/@sentry/src/tracing/errors.ts", "../../node_modules/@sentry/src/tracing/spanstatus.ts", "../../node_modules/@sentry/src/utils/handleCallbackErrors.ts", "../../node_modules/@sentry/src/utils/hasTracingEnabled.ts", "../../node_modules/@sentry/src/tracing/trace.ts", "../../node_modules/@sentry/src/metrics/metric-summary.ts", "../../node_modules/@sentry/src/semanticAttributes.ts", "../../node_modules/@sentry/src/tracing/span.ts", "../../node_modules/@sentry/src/tracing/transaction.ts", "../../node_modules/@sentry/src/tracing/idletransaction.ts", "../../node_modules/@sentry/src/tracing/sampling.ts", "../../node_modules/@sentry/src/tracing/hubextensions.ts", "../../node_modules/@sentry/src/tracing/measurement.ts", "../../node_modules/@sentry/src/envelope.ts", "../../node_modules/@sentry/src/sessionflusher.ts", "../../node_modules/@sentry/src/api.ts", "../../node_modules/@sentry/src/integration.ts", "../../node_modules/@sentry/src/metrics/utils.ts", "../../node_modules/@sentry/src/metrics/envelope.ts", "../../node_modules/@sentry/src/baseclient.ts", "../../node_modules/@sentry/src/checkin.ts", "../../node_modules/@sentry/src/metrics/constants.ts", "../../node_modules/@sentry/src/metrics/instance.ts", "../../node_modules/@sentry/src/metrics/aggregator.ts", "../../node_modules/@sentry/src/server-runtime-client.ts", "../../node_modules/@sentry/src/sdk.ts", "../../node_modules/@sentry/src/transports/base.ts", "../../node_modules/@sentry/src/transports/offline.ts", "../../node_modules/@sentry/src/transports/multiplexed.ts", "../../node_modules/@sentry/src/span.ts", "../../node_modules/@sentry/src/utils/isSentryRequestUrl.ts", "../../node_modules/@sentry/src/utils/parameterize.ts", "../../node_modules/@sentry/src/utils/sdkMetadata.ts", "../../node_modules/@sentry/src/metadata.ts", "../../node_modules/@sentry/src/integrations/metadata.ts", "../../node_modules/@sentry/src/integrations/requestdata.ts", "../../node_modules/@sentry/src/integrations/inboundfilters.ts", "../../node_modules/@sentry/src/integrations/functiontostring.ts", "../../node_modules/@sentry/src/integrations/linkederrors.ts", "../../node_modules/@sentry/src/metrics/browser-aggregator.ts", "../../node_modules/@sentry/src/metrics/integration.ts", "../../node_modules/@sentry/src/metrics/exports.ts", "../../node_modules/@sentry/src/index.ts", "../../node_modules/@sentry-internal/src/common/debug-build.ts", "../../node_modules/@sentry-internal/src/node/integrations/utils/node-utils.ts", "../../node_modules/@sentry-internal/src/node/integrations/express.ts", "../../node_modules/@sentry-internal/src/node/integrations/postgres.ts", "../../node_modules/@sentry-internal/src/node/integrations/mysql.ts", "../../node_modules/@sentry-internal/src/node/integrations/mongo.ts", "../../node_modules/@sentry-internal/src/node/integrations/prisma.ts", "../../node_modules/@sentry-internal/src/node/integrations/graphql.ts", "../../node_modules/@sentry-internal/src/node/integrations/apollo.ts", "../../node_modules/@sentry-internal/src/node/integrations/lazy.ts", "../../node_modules/@sentry-internal/src/browser/types.ts", "../../node_modules/@sentry-internal/src/browser/backgroundtab.ts", "../../node_modules/@sentry-internal/src/browser/web-vitals/lib/bindReporter.ts", "../../node_modules/@sentry-internal/src/browser/web-vitals/lib/generateUniqueID.ts", "../../node_modules/@sentry-internal/src/browser/web-vitals/lib/getNavigationEntry.ts", "../../node_modules/@sentry-internal/src/browser/web-vitals/lib/getActivationStart.ts", "../../node_modules/@sentry-internal/src/browser/web-vitals/lib/initMetric.ts", "../../node_modules/@sentry-internal/src/browser/web-vitals/lib/observe.ts", "../../node_modules/@sentry-internal/src/browser/web-vitals/lib/onHidden.ts", "../../node_modules/@sentry-internal/src/browser/web-vitals/getCLS.ts", "../../node_modules/@sentry-internal/src/browser/web-vitals/lib/getVisibilityWatcher.ts", "../../node_modules/@sentry-internal/src/browser/web-vitals/getFID.ts", "../../node_modules/@sentry-internal/src/browser/web-vitals/lib/polyfills/interactionCountPolyfill.ts", "../../node_modules/@sentry-internal/src/browser/web-vitals/getINP.ts", "../../node_modules/@sentry-internal/src/browser/web-vitals/getLCP.ts", "../../node_modules/@sentry-internal/src/browser/web-vitals/onTTFB.ts", "../../node_modules/@sentry-internal/src/browser/instrument.ts", "../../node_modules/@sentry-internal/src/browser/metrics/utils.ts", "../../node_modules/@sentry-internal/src/browser/metrics/index.ts", "../../node_modules/@sentry-internal/src/common/fetch.ts", "../../node_modules/@sentry-internal/src/browser/request.ts", "../../node_modules/@sentry-internal/src/browser/router.ts", "../../node_modules/@sentry-internal/src/browser/browsertracing.ts", "../../node_modules/@sentry-internal/src/browser/browserTracingIntegration.ts", "../../node_modules/@sentry-internal/src/extensions.ts", "../../node_modules/@sentry-internal/tracing/cjs/index.js", "../../node_modules/src/helpers.ts", "../../node_modules/src/debug-build.ts", "../../node_modules/src/eventbuilder.ts", "../../node_modules/src/userfeedback.ts", "../../node_modules/src/client.ts", "../../node_modules/src/transports/utils.ts", "../../node_modules/src/transports/fetch.ts", "../../node_modules/src/transports/xhr.ts", "../../node_modules/src/stack-parsers.ts", "../../node_modules/src/integrations/breadcrumbs.ts", "../../node_modules/src/integrations/dedupe.ts", "../../node_modules/src/integrations/globalhandlers.ts", "../../node_modules/src/integrations/httpcontext.ts", "../../node_modules/src/integrations/linkederrors.ts", "../../node_modules/src/integrations/trycatch.ts", "../../node_modules/src/sdk.ts", "../../node_modules/src/constants.ts", "../../../node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb-snapshot/es/rrweb-snapshot.js", "../../../node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb/src/utils.js", "../../../node_modules/@sentry-internal/rrweb/es/rrweb/packages/types/dist/rrweb-types.js", "../../../node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb/src/record/mutation.js", "../../../node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb/src/record/error-handler.js", "../../../node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb/src/record/observer.js", "../../../node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb/src/record/cross-origin-iframe-mirror.js", "../../../node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb/src/record/iframe-manager.js", "../../../node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb/src/record/shadow-dom-manager.js", "../../../node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb/src/record/observers/canvas/canvas-manager.js", "../../../node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb/src/record/stylesheet-manager.js", "../../../node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb/src/record/processed-node-manager.js", "../../../node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb/src/record/index.js", "../../node_modules/src/types/rrweb.ts", "../../node_modules/src/util/timestamp.ts", "../../node_modules/src/coreHandlers/util/addBreadcrumbEvent.ts", "../../node_modules/src/coreHandlers/util/domUtils.ts", "../../node_modules/src/coreHandlers/util/onWindowOpen.ts", "../../node_modules/src/coreHandlers/handleClick.ts", "../../node_modules/src/util/createBreadcrumb.ts", "../../../node_modules/@sentry-internal/rrweb-snapshot/es/rrweb-snapshot.js", "../../node_modules/src/coreHandlers/util/getAttributesToRecord.ts", "../../node_modules/src/coreHandlers/handleDom.ts", "../../node_modules/src/coreHandlers/handleKeyboardEvent.ts", "../../node_modules/src/util/createPerformanceEntries.ts", "../../node_modules/src/coreHandlers/performanceObserver.ts", "../../node_modules/src/debug-build.ts", "../../replay-worker/build/npm/esm/worker.ts", "../../replay-worker/build/npm/esm/index.js", "../../node_modules/src/util/log.ts", "../../node_modules/src/eventBuffer/error.ts", "../../node_modules/src/eventBuffer/EventBufferArray.ts", "../../node_modules/src/eventBuffer/WorkerHandler.ts", "../../node_modules/src/eventBuffer/EventBufferCompressionWorker.ts", "../../node_modules/src/eventBuffer/EventBufferProxy.ts", "../../node_modules/src/eventBuffer/index.ts", "../../node_modules/src/util/hasSessionStorage.ts", "../../node_modules/src/session/clearSession.ts", "../../node_modules/src/util/isSampled.ts", "../../node_modules/src/session/Session.ts", "../../node_modules/src/session/saveSession.ts", "../../node_modules/src/session/createSession.ts", "../../node_modules/src/session/fetchSession.ts", "../../node_modules/src/util/isExpired.ts", "../../node_modules/src/util/isSessionExpired.ts", "../../node_modules/src/session/shouldRefreshSession.ts", "../../node_modules/src/session/loadOrCreateSession.ts", "../../node_modules/src/util/addEvent.ts", "../../node_modules/src/util/eventUtils.ts", "../../node_modules/src/coreHandlers/handleAfterSendEvent.ts", "../../node_modules/src/coreHandlers/handleBeforeSendEvent.ts", "../../node_modules/src/util/isRrwebError.ts", "../../node_modules/src/coreHandlers/util/addFeedbackBreadcrumb.ts", "../../node_modules/src/coreHandlers/util/shouldSampleForBufferEvent.ts", "../../node_modules/src/coreHandlers/handleGlobalEvent.ts", "../../node_modules/src/util/createPerformanceSpans.ts", "../../node_modules/src/coreHandlers/handleHistory.ts", "../../node_modules/src/util/shouldFilterRequest.ts", "../../node_modules/src/coreHandlers/util/addNetworkBreadcrumb.ts", "../../node_modules/src/coreHandlers/handleFetch.ts", "../../node_modules/src/coreHandlers/handleXhr.ts", "../../node_modules/src/coreHandlers/util/networkUtils.ts", "../../node_modules/src/coreHandlers/util/fetchUtils.ts", "../../node_modules/src/coreHandlers/util/xhrUtils.ts", "../../node_modules/src/coreHandlers/handleNetworkBreadcrumbs.ts", "../../node_modules/src/coreHandlers/handleScope.ts", "../../node_modules/src/util/addGlobalListeners.ts", "../../node_modules/src/util/addMemoryEntry.ts", "../../node_modules/src/util/debounce.ts", "../../node_modules/src/util/handleRecordingEmit.ts", "../../node_modules/src/util/createReplayEnvelope.ts", "../../node_modules/src/util/prepareRecordingData.ts", "../../node_modules/src/util/prepareReplayEvent.ts", "../../node_modules/src/util/sendReplayRequest.ts", "../../node_modules/src/util/sendReplay.ts", "../../node_modules/src/util/throttle.ts", "../../node_modules/src/replay.ts", "../../node_modules/src/util/getPrivacyOptions.ts", "../../node_modules/src/util/maskAttribute.ts", "../../node_modules/src/integration.ts", "../../node_modules/src/util/getReplay.ts", "../../node_modules/src/index.ts", "../../../node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb-snapshot/es/rrweb-snapshot.js", "../../../node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb/src/utils.js", "../../../node_modules/@sentry-internal/rrweb/es/rrweb/packages/types/dist/rrweb-types.js", "../../../node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb/src/record/error-handler.js", "../../../node_modules/@sentry-internal/rrweb/es/rrweb/ext/base64-arraybuffer/dist/base64-arraybuffer.es5.js", "../../../node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb/src/record/observers/canvas/serialize-args.js", "../../../node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb/src/record/observers/canvas/2d.js", "../../../node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb/src/record/observers/canvas/canvas.js", "../../../node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb/src/record/observers/canvas/webgl.js", "../../../node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb-worker/es/rrweb-worker/image-bitmap-data-url-worker.js", "../../../node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb-worker/es/rrweb-worker/index.js", "../../../node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb/src/record/observers/canvas/canvas-manager.js", "../../node_modules/src/canvas.ts", "../../node_modules/src/constants.ts", "../../node_modules/src/util/prepareFeedbackEvent.ts", "../../node_modules/src/util/sendFeedbackRequest.ts", "../../node_modules/src/sendFeedback.ts", "../../node_modules/src/debug-build.ts", "../../node_modules/src/util/mergeOptions.ts", "../../node_modules/src/widget/Actor.css.ts", "../../node_modules/src/widget/Dialog.css.ts", "../../node_modules/src/widget/Main.css.ts", "../../node_modules/src/widget/createShadowHost.ts", "../../node_modules/src/util/handleFeedbackSubmit.ts", "../../node_modules/src/util/setAttributesNS.ts", "../../node_modules/src/widget/Icon.ts", "../../node_modules/src/widget/util/createElement.ts", "../../node_modules/src/widget/Actor.ts", "../../node_modules/src/widget/SubmitButton.ts", "../../node_modules/src/widget/Form.ts", "../../node_modules/src/widget/Logo.ts", "../../node_modules/src/widget/Dialog.ts", "../../node_modules/src/widget/SuccessIcon.ts", "../../node_modules/src/widget/SuccessMessage.ts", "../../node_modules/src/widget/createWidget.ts", "../../node_modules/src/integration.ts", "../../node_modules/src/captureconsole.ts", "../../node_modules/src/debug.ts", "../../node_modules/src/debug-build.ts", "../../node_modules/src/dedupe.ts", "../../node_modules/src/extraerrordata.ts", "../../node_modules/localforage/dist/localforage.js", "../../node_modules/src/offline.ts", "../../node_modules/src/reportingobserver.ts", "../../node_modules/src/rewriteframes.ts", "../../node_modules/src/sessiontiming.ts", "../../node_modules/src/transaction.ts", "../../node_modules/src/httpclient.ts", "../../node_modules/src/contextlines.ts", "../../node_modules/@sentry/integrations/cjs/index.js", "../../node_modules/src/transports/offline.ts", "../../node_modules/src/profiling/utils.ts", "../../node_modules/src/profiling/hubextensions.ts", "../../node_modules/src/profiling/integration.ts", "../../node_modules/src/index.ts", "../../node_modules/@material-ui/core/utils/setRef.js", "../../node_modules/@material-ui/core/utils/useForkRef.js", "../../node_modules/@material-ui/core/utils/useEventCallback.js", "../../node_modules/@material-ui/core/utils/deprecatedPropType.js", "../../node_modules/@material-ui/core/utils/useIsFocusVisible.js", "../../node_modules/dom-helpers/cjs/hasClass.js", "../../node_modules/dom-helpers/cjs/addClass.js", "../../node_modules/dom-helpers/cjs/removeClass.js", "../../node_modules/react-transition-group/cjs/config.js", "../../node_modules/react-transition-group/cjs/utils/PropTypes.js", "../../node_modules/react-transition-group/cjs/TransitionGroupContext.js", "../../node_modules/react-transition-group/cjs/utils/reflow.js", "../../node_modules/react-transition-group/cjs/Transition.js", "../../node_modules/react-transition-group/cjs/CSSTransition.js", "../../node_modules/react-transition-group/cjs/utils/ChildMapping.js", "../../node_modules/react-transition-group/cjs/TransitionGroup.js", "../../node_modules/react-transition-group/cjs/ReplaceTransition.js", "../../node_modules/react-transition-group/cjs/SwitchTransition.js", "../../node_modules/react-transition-group/cjs/index.js", "../../node_modules/@material-ui/core/ButtonBase/Ripple.js", "../../node_modules/@material-ui/core/ButtonBase/TouchRipple.js", "../../node_modules/@material-ui/core/ButtonBase/ButtonBase.js", "../../node_modules/@material-ui/core/ButtonBase/index.js", "../../node_modules/@material-ui/core/utils/capitalize.js", "../../node_modules/@material-ui/core/Button/Button.js", "../../node_modules/@material-ui/core/Button/index.js", "../../node_modules/@material-ui/core/utils/ownerDocument.js", "../../node_modules/@material-ui/core/Portal/Portal.js", "../../node_modules/@material-ui/core/Portal/index.js", "../../node_modules/@material-ui/core/utils/createChainedFunction.js", "../../node_modules/@material-ui/core/utils/getScrollbarSize.js", "../../node_modules/@material-ui/core/utils/ownerWindow.js", "../../node_modules/@material-ui/core/Modal/ModalManager.js", "../../node_modules/@material-ui/core/Unstable_TrapFocus/Unstable_TrapFocus.js", "../../node_modules/@material-ui/core/Unstable_TrapFocus/index.js", "../../node_modules/@material-ui/core/Modal/SimpleBackdrop.js", "../../node_modules/@material-ui/core/Modal/Modal.js", "../../node_modules/@material-ui/core/Modal/index.js", "../../node_modules/@material-ui/core/transitions/utils.js", "../../node_modules/@material-ui/core/Fade/Fade.js", "../../node_modules/@material-ui/core/Fade/index.js", "../../node_modules/@material-ui/core/Backdrop/Backdrop.js", "../../node_modules/@material-ui/core/Backdrop/index.js", "../../node_modules/@material-ui/core/Paper/Paper.js", "../../node_modules/@material-ui/core/Paper/index.js", "../../node_modules/@material-ui/core/Dialog/Dialog.js", "../../node_modules/@material-ui/core/Dialog/index.js", "../../node_modules/@material-ui/core/DialogActions/DialogActions.js", "../../node_modules/@material-ui/core/DialogActions/index.js", "../../node_modules/@material-ui/core/DialogContent/DialogContent.js", "../../node_modules/@material-ui/core/DialogContent/index.js", "../../node_modules/@material-ui/core/Typography/Typography.js", "../../node_modules/@material-ui/core/Typography/index.js", "../../node_modules/@material-ui/core/DialogContentText/DialogContentText.js", "../../node_modules/@material-ui/core/DialogContentText/index.js", "../../node_modules/@material-ui/core/DialogTitle/DialogTitle.js", "../../node_modules/@material-ui/core/DialogTitle/index.js", "../../node_modules/@material-ui/core/SvgIcon/SvgIcon.js", "../../node_modules/@material-ui/core/SvgIcon/index.js", "../../node_modules/@material-ui/core/utils/createSvgIcon.js", "../../node_modules/@material-ui/core/utils/debounce.js", "../../node_modules/@material-ui/core/utils/isMuiElement.js", "../../node_modules/@material-ui/core/utils/requirePropFactory.js", "../../node_modules/@material-ui/core/utils/unsupportedProp.js", "../../node_modules/@material-ui/core/utils/useControlled.js", "../../node_modules/@material-ui/core/utils/unstable_useId.js", "../../node_modules/@material-ui/core/utils/index.js", "../../node_modules/@material-ui/icons/utils/createSvgIcon.js", "../../node_modules/@material-ui/icons/Check.js", "../../node_modules/@iobroker/adapter-react/Dialogs/Error.js", "../../node_modules/@material-ui/core/ClickAwayListener/ClickAwayListener.js", "../../node_modules/@material-ui/core/ClickAwayListener/index.js", "../../node_modules/@material-ui/core/Grow/Grow.js", "../../node_modules/@material-ui/core/Grow/index.js", "../../node_modules/@material-ui/core/SnackbarContent/SnackbarContent.js", "../../node_modules/@material-ui/core/SnackbarContent/index.js", "../../node_modules/@material-ui/core/Snackbar/Snackbar.js", "../../node_modules/@material-ui/core/Snackbar/index.js", "../../node_modules/@material-ui/core/IconButton/IconButton.js", "../../node_modules/@material-ui/core/IconButton/index.js", "../../node_modules/@material-ui/icons/Close.js", "../../node_modules/@iobroker/adapter-react/Prompt.js", "../../node_modules/@iobroker/adapter-react/Components/loader.css", "../../node_modules/@iobroker/adapter-react/Components/Loader.js", "../../node_modules/@iobroker/adapter-react/Components/Router.js", "../../node_modules/@material-ui/core/Fab/Fab.js", "../../node_modules/@material-ui/core/Fab/index.js", "../../node_modules/@material-ui/core/Toolbar/Toolbar.js", "../../node_modules/@material-ui/core/Toolbar/index.js", "../../node_modules/@material-ui/icons/Save.js", "../../node_modules/@iobroker/adapter-react/Components/SaveCloseButtons.js", "../../node_modules/@iobroker/adapter-react/index.css", "../../node_modules/@iobroker/adapter-react/i18n/en.json", "../../node_modules/@iobroker/adapter-react/i18n/de.json", "../../node_modules/@iobroker/adapter-react/i18n/ru.json", "../../node_modules/@iobroker/adapter-react/i18n/pt.json", "../../node_modules/@iobroker/adapter-react/i18n/nl.json", "../../node_modules/@iobroker/adapter-react/i18n/fr.json", "../../node_modules/@iobroker/adapter-react/i18n/it.json", "../../node_modules/@iobroker/adapter-react/i18n/es.json", "../../node_modules/@iobroker/adapter-react/i18n/pl.json", "../../node_modules/@iobroker/adapter-react/i18n/zh-cn.json", "../../node_modules/@iobroker/adapter-react/GenericApp.js", "../../node_modules/@material-ui/icons/Add.js", "../../node_modules/@material-ui/icons/Help.js", "../../node_modules/@material-ui/icons/VerticalAlignTop.js", "../../node_modules/@material-ui/icons/VerticalAlignBottom.js", "../../node_modules/@iobroker/adapter-react/Components/Logo.js", "../../node_modules/@material-ui/core/InputBase/utils.js", "../../node_modules/@material-ui/core/FormControl/FormControlContext.js", "../../node_modules/@material-ui/core/FormControl/FormControl.js", "../../node_modules/@material-ui/core/FormControl/useFormControl.js", "../../node_modules/@material-ui/core/FormControl/index.js", "../../node_modules/@material-ui/core/FormControlLabel/FormControlLabel.js", "../../node_modules/@material-ui/core/FormControlLabel/index.js", "../../node_modules/@material-ui/core/internal/SwitchBase.js", "../../node_modules/@material-ui/core/internal/svg-icons/CheckBoxOutlineBlank.js", "../../node_modules/@material-ui/core/internal/svg-icons/CheckBox.js", "../../node_modules/@material-ui/core/internal/svg-icons/IndeterminateCheckBox.js", "../../node_modules/@material-ui/core/Checkbox/Checkbox.js", "../../node_modules/@material-ui/core/Checkbox/index.js", "../../node_modules/@material-ui/icons/Cached.js", "../../node_modules/@material-ui/icons/Visibility.js", "../../node_modules/punycode/punycode.js", "../../node_modules/es-errors/index.js", "../../node_modules/es-errors/eval.js", "../../node_modules/es-errors/range.js", "../../node_modules/es-errors/ref.js", "../../node_modules/es-errors/syntax.js", "../../node_modules/es-errors/type.js", "../../node_modules/es-errors/uri.js", "../../node_modules/has-symbols/shams.js", "../../node_modules/has-symbols/index.js", "../../node_modules/has-proto/index.js", "../../node_modules/function-bind/implementation.js", "../../node_modules/function-bind/index.js", "../../node_modules/hasown/index.js", "../../node_modules/get-intrinsic/index.js", "../../node_modules/es-define-property/index.js", "../../node_modules/gopd/index.js", "../../node_modules/define-data-property/index.js", "../../node_modules/has-property-descriptors/index.js", "../../node_modules/set-function-length/index.js", "../../node_modules/call-bind/index.js", "../../node_modules/call-bind/callBound.js", "../../node_modules/object-inspect/index.js", "../../node_modules/side-channel/index.js", "../../node_modules/qs/lib/formats.js", "../../node_modules/qs/lib/utils.js", "../../node_modules/qs/lib/stringify.js", "../../node_modules/qs/lib/parse.js", "../../node_modules/qs/lib/index.js", "../../node_modules/url/url.js", "../../node_modules/jsonschema/lib/helpers.js", "../../node_modules/jsonschema/lib/attribute.js", "../../node_modules/jsonschema/lib/scan.js", "../../node_modules/jsonschema/lib/validator.js", "../../node_modules/jsonschema/lib/index.js", "../../well-known-messages/schemas/messages.json", "../../well-known-messages/schemas/index.json", "../../node_modules/@material-ui/icons/Delete.js", "../../node_modules/@iobroker/adapter-react/Dialogs/Confirm.js", "../../node_modules/@material-ui/icons/Info.js", "../src/i18n/en.json", "../src/i18n/de.json", "../src/i18n/ru.json", "../src/i18n/pt.json", "../src/i18n/nl.json", "../src/i18n/fr.json", "../src/i18n/it.json", "../src/i18n/es.json", "../src/i18n/pl.json", "../src/i18n/zh-cn.json", "../src/index.tsx", "../../node_modules/autobind-decorator/lib/esm/index.js", "../src/app.tsx", "../../node_modules/@sentry/react/node_modules/@sentry/utils/src/is.ts", "../../node_modules/@sentry/react/node_modules/@sentry/utils/src/version.ts", "../../node_modules/@sentry/react/node_modules/@sentry/utils/src/worldwide.ts", "../../node_modules/@sentry/react/node_modules/@sentry/utils/src/debug-build.ts", "../../node_modules/@sentry/react/node_modules/@sentry/utils/src/logger.ts", "../../node_modules/@sentry/react/node_modules/@sentry/utils/src/dsn.ts", "../../node_modules/@sentry/react/node_modules/@sentry/utils/src/object.ts", "../../node_modules/@sentry/react/node_modules/@sentry/utils/src/time.ts", "../../node_modules/@sentry/react/node_modules/@sentry/utils/src/misc.ts", "../../node_modules/@sentry/react/node_modules/@sentry/utils/src/propagationContext.ts", "../../node_modules/@sentry/react/node_modules/@sentry/core/src/carrier.ts", "../../node_modules/@sentry/react/node_modules/@sentry/core/src/session.ts", "../../node_modules/@sentry/react/node_modules/@sentry/core/src/utils/spanOnScope.ts", "../../node_modules/@sentry/react/node_modules/@sentry/core/src/scope.ts", "../../node_modules/@sentry/react/node_modules/@sentry/core/src/defaultScopes.ts", "../../node_modules/@sentry/react/node_modules/@sentry/core/src/asyncContext/stackStrategy.ts", "../../node_modules/@sentry/react/node_modules/@sentry/core/src/asyncContext/index.ts", "../../node_modules/@sentry/react/node_modules/@sentry/core/src/currentScopes.ts", "../../node_modules/@sentry/react/node_modules/@sentry/core/src/utils/prepareEvent.ts", "../../node_modules/@sentry/react/node_modules/@sentry/core/src/exports.ts", "../../node_modules/@sentry/react/node_modules/@sentry/core/src/api.ts", "../../node_modules/@sentry/react/node_modules/@sentry/browser/src/helpers.ts", "../../node_modules/@sentry/react/node_modules/@sentry/browser/src/debug-build.ts", "../../node_modules/@sentry/react/node_modules/@sentry/browser/src/sdk.ts", "../../node_modules/@sentry/react/src/error.ts", "../../node_modules/@sentry/react/src/debug-build.ts", "../../node_modules/@sentry/react/src/errorboundary.tsx", "../src/components/settings.tsx", "../../node_modules/@material-ui/core/esm/Box/Box.js", "../../node_modules/@babel/runtime/helpers/esm/extends.js", "../../node_modules/@material-ui/core/esm/styles/styled.js", "../../node_modules/@babel/runtime/helpers/esm/typeof.js", "../../node_modules/@babel/runtime/helpers/esm/toPrimitive.js", "../../node_modules/@babel/runtime/helpers/esm/toPropertyKey.js", "../../node_modules/@babel/runtime/helpers/esm/defineProperty.js", "../../node_modules/@babel/runtime/helpers/esm/objectWithoutPropertiesLoose.js", "../../node_modules/@babel/runtime/helpers/esm/objectWithoutProperties.js", "../../node_modules/@material-ui/core/esm/styles/createTheme.js", "../../node_modules/@material-ui/core/esm/styles/createBreakpoints.js", "../../node_modules/@material-ui/core/esm/styles/createMixins.js", "../../node_modules/@material-ui/core/esm/styles/createPalette.js", "../../node_modules/@material-ui/core/esm/colors/common.js", "../../node_modules/@material-ui/core/esm/colors/grey.js", "../../node_modules/@material-ui/core/esm/colors/indigo.js", "../../node_modules/@material-ui/core/esm/colors/pink.js", "../../node_modules/@material-ui/core/esm/colors/red.js", "../../node_modules/@material-ui/core/esm/colors/orange.js", "../../node_modules/@material-ui/core/esm/colors/blue.js", "../../node_modules/@material-ui/core/esm/colors/green.js", "../../node_modules/@material-ui/core/esm/styles/colorManipulator.js", "../../node_modules/@material-ui/core/esm/styles/createTypography.js", "../../node_modules/@material-ui/core/esm/styles/shadows.js", "../../node_modules/@material-ui/core/esm/styles/shape.js", "../../node_modules/@material-ui/core/esm/styles/createSpacing.js", "../../node_modules/@material-ui/core/esm/styles/transitions.js", "../../node_modules/@material-ui/core/esm/styles/zIndex.js", "../../node_modules/@material-ui/core/esm/styles/defaultTheme.js", "../../node_modules/@material-ui/core/esm/Tab/Tab.js", "../../node_modules/@material-ui/core/esm/styles/withStyles.js", "../../node_modules/@material-ui/core/esm/ButtonBase/ButtonBase.js", "../../node_modules/@material-ui/core/esm/utils/useForkRef.js", "../../node_modules/@material-ui/core/esm/utils/setRef.js", "../../node_modules/@material-ui/core/esm/utils/useEventCallback.js", "../../node_modules/@material-ui/core/esm/utils/useIsFocusVisible.js", "../../node_modules/@babel/runtime/helpers/esm/arrayLikeToArray.js", "../../node_modules/@babel/runtime/helpers/esm/arrayWithoutHoles.js", "../../node_modules/@babel/runtime/helpers/esm/iterableToArray.js", "../../node_modules/@babel/runtime/helpers/esm/unsupportedIterableToArray.js", "../../node_modules/@babel/runtime/helpers/esm/nonIterableSpread.js", "../../node_modules/@babel/runtime/helpers/esm/toConsumableArray.js", "../../node_modules/@material-ui/core/esm/ButtonBase/TouchRipple.js", "../../node_modules/@material-ui/core/esm/ButtonBase/Ripple.js", "../../node_modules/@material-ui/core/esm/utils/capitalize.js", "../../node_modules/@material-ui/core/esm/Tabs/Tabs.js", "../../node_modules/@material-ui/core/esm/utils/debounce.js", "../../node_modules/@material-ui/core/esm/utils/ownerDocument.js", "../../node_modules/@material-ui/core/esm/utils/ownerWindow.js", "../../node_modules/@material-ui/core/esm/utils/scrollLeft.js", "../../node_modules/@material-ui/core/esm/internal/animate.js", "../../node_modules/@material-ui/core/esm/Tabs/ScrollbarSize.js", "../../node_modules/@material-ui/core/esm/Tabs/TabIndicator.js", "../../node_modules/@material-ui/core/esm/TabScrollButton/TabScrollButton.js", "../../node_modules/@material-ui/core/esm/internal/svg-icons/KeyboardArrowLeft.js", "../../node_modules/@material-ui/core/esm/utils/createSvgIcon.js", "../../node_modules/@material-ui/core/esm/SvgIcon/SvgIcon.js", "../../node_modules/@material-ui/core/esm/internal/svg-icons/KeyboardArrowRight.js", "../../node_modules/@material-ui/core/esm/styles/useTheme.js", "../src/components/tab-panel.tsx", "../src/components/general.tsx", "../../node_modules/@material-ui/core/esm/Grid/Grid.js", "../src/components/input-checkbox.tsx", "../../node_modules/@material-ui/core/esm/FormHelperText/FormHelperText.js", "../../node_modules/@material-ui/core/esm/FormControl/formControlState.js", "../../node_modules/@material-ui/core/esm/FormControl/useFormControl.js", "../../node_modules/@material-ui/core/esm/FormControl/FormControlContext.js", "../src/components/input-text.tsx", "../../node_modules/@material-ui/core/esm/TextField/TextField.js", "../../node_modules/@material-ui/core/esm/Input/Input.js", "../../node_modules/@material-ui/core/esm/InputBase/InputBase.js", "../../node_modules/@material-ui/core/esm/TextareaAutosize/TextareaAutosize.js", "../../node_modules/@material-ui/core/esm/InputBase/utils.js", "../../node_modules/@material-ui/core/esm/FilledInput/FilledInput.js", "../../node_modules/@material-ui/core/esm/OutlinedInput/OutlinedInput.js", "../../node_modules/@material-ui/core/esm/OutlinedInput/NotchedOutline.js", "../../node_modules/@material-ui/core/esm/InputLabel/InputLabel.js", "../../node_modules/@material-ui/core/esm/FormLabel/FormLabel.js", "../../node_modules/@material-ui/core/esm/FormControl/FormControl.js", "../../node_modules/@material-ui/core/esm/utils/isMuiElement.js", "../../node_modules/@material-ui/core/esm/Select/Select.js", "../../node_modules/@babel/runtime/helpers/esm/arrayWithHoles.js", "../../node_modules/@babel/runtime/helpers/esm/iterableToArrayLimit.js", "../../node_modules/@babel/runtime/helpers/esm/nonIterableRest.js", "../../node_modules/@babel/runtime/helpers/esm/slicedToArray.js", "../../node_modules/@material-ui/core/esm/Select/SelectInput.js", "../../node_modules/@material-ui/core/esm/Menu/Menu.js", "../../node_modules/@material-ui/core/esm/Popover/Popover.js", "../../node_modules/@material-ui/core/esm/utils/createChainedFunction.js", "../../node_modules/@material-ui/core/esm/Modal/Modal.js", "../../node_modules/@material-ui/core/esm/Portal/Portal.js", "../../node_modules/@babel/runtime/helpers/esm/classCallCheck.js", "../../node_modules/@babel/runtime/helpers/esm/createClass.js", "../../node_modules/@material-ui/core/esm/utils/getScrollbarSize.js", "../../node_modules/@material-ui/core/esm/Modal/ModalManager.js", "../../node_modules/@material-ui/core/esm/Unstable_TrapFocus/Unstable_TrapFocus.js", "../../node_modules/@material-ui/core/esm/Modal/SimpleBackdrop.js", "../../node_modules/@material-ui/core/esm/Grow/Grow.js", "../../node_modules/@material-ui/core/esm/transitions/utils.js", "../../node_modules/@material-ui/core/esm/Paper/Paper.js", "../../node_modules/@material-ui/core/esm/MenuList/MenuList.js", "../../node_modules/@material-ui/core/esm/List/List.js", "../../node_modules/@material-ui/core/esm/List/ListContext.js", "../../node_modules/@material-ui/core/esm/utils/useControlled.js", "../../node_modules/@material-ui/core/esm/internal/svg-icons/ArrowDropDown.js", "../../node_modules/@material-ui/core/esm/NativeSelect/NativeSelect.js", "../../node_modules/@material-ui/core/esm/NativeSelect/NativeSelectInput.js", "../../node_modules/@material-ui/lab/esm/Autocomplete/Autocomplete.js", "../../node_modules/@material-ui/core/esm/Popper/Popper.js", "../../node_modules/popper.js/src/utils/isBrowser.js", "../../node_modules/popper.js/src/utils/debounce.js", "../../node_modules/popper.js/src/utils/isFunction.js", "../../node_modules/popper.js/src/utils/getStyleComputedProperty.js", "../../node_modules/popper.js/src/utils/getParentNode.js", "../../node_modules/popper.js/src/utils/getScrollParent.js", "../../node_modules/popper.js/src/utils/getReferenceNode.js", "../../node_modules/popper.js/src/utils/isIE.js", "../../node_modules/popper.js/src/utils/getOffsetParent.js", "../../node_modules/popper.js/src/utils/isOffsetContainer.js", "../../node_modules/popper.js/src/utils/getRoot.js", "../../node_modules/popper.js/src/utils/findCommonOffsetParent.js", "../../node_modules/popper.js/src/utils/getScroll.js", "../../node_modules/popper.js/src/utils/includeScroll.js", "../../node_modules/popper.js/src/utils/getBordersSize.js", "../../node_modules/popper.js/src/utils/getWindowSizes.js", "../../node_modules/popper.js/src/utils/getClientRect.js", "../../node_modules/popper.js/src/utils/getBoundingClientRect.js", "../../node_modules/popper.js/src/utils/getOffsetRectRelativeToArbitraryNode.js", "../../node_modules/popper.js/src/utils/getViewportOffsetRectRelativeToArtbitraryNode.js", "../../node_modules/popper.js/src/utils/isFixed.js", "../../node_modules/popper.js/src/utils/getFixedPositionOffsetParent.js", "../../node_modules/popper.js/src/utils/getBoundaries.js", "../../node_modules/popper.js/src/utils/computeAutoPlacement.js", "../../node_modules/popper.js/src/utils/getReferenceOffsets.js", "../../node_modules/popper.js/src/utils/getOuterSizes.js", "../../node_modules/popper.js/src/utils/getOppositePlacement.js", "../../node_modules/popper.js/src/utils/getPopperOffsets.js", "../../node_modules/popper.js/src/utils/find.js", "../../node_modules/popper.js/src/utils/findIndex.js", "../../node_modules/popper.js/src/utils/runModifiers.js", "../../node_modules/popper.js/src/methods/update.js", "../../node_modules/popper.js/src/utils/isModifierEnabled.js", "../../node_modules/popper.js/src/utils/getSupportedPropertyName.js", "../../node_modules/popper.js/src/methods/destroy.js", "../../node_modules/popper.js/src/utils/getWindow.js", "../../node_modules/popper.js/src/utils/setupEventListeners.js", "../../node_modules/popper.js/src/methods/enableEventListeners.js", "../../node_modules/popper.js/src/utils/removeEventListeners.js", "../../node_modules/popper.js/src/methods/disableEventListeners.js", "../../node_modules/popper.js/src/utils/isNumeric.js", "../../node_modules/popper.js/src/utils/setStyles.js", "../../node_modules/popper.js/src/utils/setAttributes.js", "../../node_modules/popper.js/src/modifiers/applyStyle.js", "../../node_modules/popper.js/src/utils/getRoundedOffsets.js", "../../node_modules/popper.js/src/modifiers/computeStyle.js", "../../node_modules/popper.js/src/utils/isModifierRequired.js", "../../node_modules/popper.js/src/modifiers/arrow.js", "../../node_modules/popper.js/src/utils/getOppositeVariation.js", "../../node_modules/popper.js/src/methods/placements.js", "../../node_modules/popper.js/src/utils/clockwise.js", "../../node_modules/popper.js/src/modifiers/flip.js", "../../node_modules/popper.js/src/modifiers/keepTogether.js", "../../node_modules/popper.js/src/modifiers/offset.js", "../../node_modules/popper.js/src/modifiers/preventOverflow.js", "../../node_modules/popper.js/src/modifiers/shift.js", "../../node_modules/popper.js/src/modifiers/hide.js", "../../node_modules/popper.js/src/modifiers/inner.js", "../../node_modules/popper.js/src/modifiers/index.js", "../../node_modules/popper.js/src/methods/defaults.js", "../../node_modules/popper.js/src/index.js", "../../node_modules/@material-ui/core/esm/ListSubheader/ListSubheader.js", "../../node_modules/@material-ui/core/esm/Chip/Chip.js", "../../node_modules/@material-ui/core/esm/internal/svg-icons/Cancel.js", "../../node_modules/@material-ui/lab/esm/internal/svg-icons/Close.js", "../../node_modules/@material-ui/lab/esm/internal/svg-icons/ArrowDropDown.js", "../../node_modules/@material-ui/lab/esm/useAutocomplete/useAutocomplete.js", "../../src/consts.ts", "../src/components/import-export.tsx", "../../node_modules/@material-ui/core/esm/Divider/Divider.js", "../../node_modules/snarkdown/src/index.js", "../src/lib/helpers.ts", "../src/components/input-select.tsx", "../../node_modules/@material-ui/core/esm/MenuItem/MenuItem.js", "../../node_modules/@material-ui/core/esm/ListItem/ListItem.js", "../src/components/message.tsx", "../src/lib/icons.tsx", "../src/components/parser.tsx", "../src/components/input-bitmask.tsx", "../../io-package.json"], - "sourcesContent": ["/*\nobject-assign\n(c) Sindre Sorhus\n@license MIT\n*/\n\n'use strict';\n/* eslint-disable no-unused-vars */\nvar getOwnPropertySymbols = Object.getOwnPropertySymbols;\nvar hasOwnProperty = Object.prototype.hasOwnProperty;\nvar propIsEnumerable = Object.prototype.propertyIsEnumerable;\n\nfunction toObject(val) {\n\tif (val === null || val === undefined) {\n\t\tthrow new TypeError('Object.assign cannot be called with null or undefined');\n\t}\n\n\treturn Object(val);\n}\n\nfunction shouldUseNative() {\n\ttry {\n\t\tif (!Object.assign) {\n\t\t\treturn false;\n\t\t}\n\n\t\t// Detect buggy property enumeration order in older V8 versions.\n\n\t\t// https://bugs.chromium.org/p/v8/issues/detail?id=4118\n\t\tvar test1 = new String('abc'); // eslint-disable-line no-new-wrappers\n\t\ttest1[5] = 'de';\n\t\tif (Object.getOwnPropertyNames(test1)[0] === '5') {\n\t\t\treturn false;\n\t\t}\n\n\t\t// https://bugs.chromium.org/p/v8/issues/detail?id=3056\n\t\tvar test2 = {};\n\t\tfor (var i = 0; i < 10; i++) {\n\t\t\ttest2['_' + String.fromCharCode(i)] = i;\n\t\t}\n\t\tvar order2 = Object.getOwnPropertyNames(test2).map(function (n) {\n\t\t\treturn test2[n];\n\t\t});\n\t\tif (order2.join('') !== '0123456789') {\n\t\t\treturn false;\n\t\t}\n\n\t\t// https://bugs.chromium.org/p/v8/issues/detail?id=3056\n\t\tvar test3 = {};\n\t\t'abcdefghijklmnopqrst'.split('').forEach(function (letter) {\n\t\t\ttest3[letter] = letter;\n\t\t});\n\t\tif (Object.keys(Object.assign({}, test3)).join('') !==\n\t\t\t\t'abcdefghijklmnopqrst') {\n\t\t\treturn false;\n\t\t}\n\n\t\treturn true;\n\t} catch (err) {\n\t\t// We don't expect any of the above to throw, but better to be safe.\n\t\treturn false;\n\t}\n}\n\nmodule.exports = shouldUseNative() ? Object.assign : function (target, source) {\n\tvar from;\n\tvar to = toObject(target);\n\tvar symbols;\n\n\tfor (var s = 1; s < arguments.length; s++) {\n\t\tfrom = Object(arguments[s]);\n\n\t\tfor (var key in from) {\n\t\t\tif (hasOwnProperty.call(from, key)) {\n\t\t\t\tto[key] = from[key];\n\t\t\t}\n\t\t}\n\n\t\tif (getOwnPropertySymbols) {\n\t\t\tsymbols = getOwnPropertySymbols(from);\n\t\t\tfor (var i = 0; i < symbols.length; i++) {\n\t\t\t\tif (propIsEnumerable.call(from, symbols[i])) {\n\t\t\t\t\tto[symbols[i]] = from[symbols[i]];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn to;\n};\n", "/** @license React v17.0.2\n * react.production.min.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n'use strict';var l=require(\"object-assign\"),n=60103,p=60106;exports.Fragment=60107;exports.StrictMode=60108;exports.Profiler=60114;var q=60109,r=60110,t=60112;exports.Suspense=60113;var u=60115,v=60116;\nif(\"function\"===typeof Symbol&&Symbol.for){var w=Symbol.for;n=w(\"react.element\");p=w(\"react.portal\");exports.Fragment=w(\"react.fragment\");exports.StrictMode=w(\"react.strict_mode\");exports.Profiler=w(\"react.profiler\");q=w(\"react.provider\");r=w(\"react.context\");t=w(\"react.forward_ref\");exports.Suspense=w(\"react.suspense\");u=w(\"react.memo\");v=w(\"react.lazy\")}var x=\"function\"===typeof Symbol&&Symbol.iterator;\nfunction y(a){if(null===a||\"object\"!==typeof a)return null;a=x&&a[x]||a[\"@@iterator\"];return\"function\"===typeof a?a:null}function z(a){for(var b=\"https://reactjs.org/docs/error-decoder.html?invariant=\"+a,c=1;c=\nE};k=function(){};exports.unstable_forceFrameRate=function(a){0>a||125>>1,e=a[d];if(void 0!==e&&0I(n,c))void 0!==r&&0>I(r,n)?(a[d]=r,a[v]=c,d=v):(a[d]=n,a[m]=c,d=m);else if(void 0!==r&&0>I(r,c))a[d]=r,a[v]=c,d=v;else break a}}return b}return null}function I(a,b){var c=a.sortIndex-b.sortIndex;return 0!==c?c:a.id-b.id}var L=[],M=[],N=1,O=null,P=3,Q=!1,R=!1,S=!1;\nfunction T(a){for(var b=J(M);null!==b;){if(null===b.callback)K(M);else if(b.startTime<=a)K(M),b.sortIndex=b.expirationTime,H(L,b);else break;b=J(M)}}function U(a){S=!1;T(a);if(!R)if(null!==J(L))R=!0,f(V);else{var b=J(M);null!==b&&g(U,b.startTime-a)}}\nfunction V(a,b){R=!1;S&&(S=!1,h());Q=!0;var c=P;try{T(b);for(O=J(L);null!==O&&(!(O.expirationTime>b)||a&&!exports.unstable_shouldYield());){var d=O.callback;if(\"function\"===typeof d){O.callback=null;P=O.priorityLevel;var e=d(O.expirationTime<=b);b=exports.unstable_now();\"function\"===typeof e?O.callback=e:O===J(L)&&K(L);T(b)}else K(L);O=J(L)}if(null!==O)var m=!0;else{var n=J(M);null!==n&&g(U,n.startTime-b);m=!1}return m}finally{O=null,P=c,Q=!1}}var W=k;exports.unstable_IdlePriority=5;\nexports.unstable_ImmediatePriority=1;exports.unstable_LowPriority=4;exports.unstable_NormalPriority=3;exports.unstable_Profiling=null;exports.unstable_UserBlockingPriority=2;exports.unstable_cancelCallback=function(a){a.callback=null};exports.unstable_continueExecution=function(){R||Q||(R=!0,f(V))};exports.unstable_getCurrentPriorityLevel=function(){return P};exports.unstable_getFirstCallbackNode=function(){return J(L)};\nexports.unstable_next=function(a){switch(P){case 1:case 2:case 3:var b=3;break;default:b=P}var c=P;P=b;try{return a()}finally{P=c}};exports.unstable_pauseExecution=function(){};exports.unstable_requestPaint=W;exports.unstable_runWithPriority=function(a,b){switch(a){case 1:case 2:case 3:case 4:case 5:break;default:a=3}var c=P;P=a;try{return b()}finally{P=c}};\nexports.unstable_scheduleCallback=function(a,b,c){var d=exports.unstable_now();\"object\"===typeof c&&null!==c?(c=c.delay,c=\"number\"===typeof c&&0d?(a.sortIndex=c,H(M,a),null===J(L)&&a===J(M)&&(S?h():S=!0,g(U,c-d))):(a.sortIndex=e,H(L,a),R||Q||(R=!0,f(V)));return a};\nexports.unstable_wrapCallback=function(a){var b=P;return function(){var c=P;P=b;try{return a.apply(this,arguments)}finally{P=c}}};\n", "'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('./cjs/scheduler.production.min.js');\n} else {\n module.exports = require('./cjs/scheduler.development.js');\n}\n", "/** @license React v17.0.2\n * react-dom.production.min.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n/*\n Modernizr 3.0.0pre (Custom Build) | MIT\n*/\n'use strict';var aa=require(\"react\"),m=require(\"object-assign\"),r=require(\"scheduler\");function y(a){for(var b=\"https://reactjs.org/docs/error-decoder.html?invariant=\"+a,c=1;cb}return!1}function B(a,b,c,d,e,f,g){this.acceptsBooleans=2===b||3===b||4===b;this.attributeName=d;this.attributeNamespace=e;this.mustUseProperty=c;this.propertyName=a;this.type=b;this.sanitizeURL=f;this.removeEmptyString=g}var D={};\n\"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style\".split(\" \").forEach(function(a){D[a]=new B(a,0,!1,a,null,!1,!1)});[[\"acceptCharset\",\"accept-charset\"],[\"className\",\"class\"],[\"htmlFor\",\"for\"],[\"httpEquiv\",\"http-equiv\"]].forEach(function(a){var b=a[0];D[b]=new B(b,1,!1,a[1],null,!1,!1)});[\"contentEditable\",\"draggable\",\"spellCheck\",\"value\"].forEach(function(a){D[a]=new B(a,2,!1,a.toLowerCase(),null,!1,!1)});\n[\"autoReverse\",\"externalResourcesRequired\",\"focusable\",\"preserveAlpha\"].forEach(function(a){D[a]=new B(a,2,!1,a,null,!1,!1)});\"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope\".split(\" \").forEach(function(a){D[a]=new B(a,3,!1,a.toLowerCase(),null,!1,!1)});\n[\"checked\",\"multiple\",\"muted\",\"selected\"].forEach(function(a){D[a]=new B(a,3,!0,a,null,!1,!1)});[\"capture\",\"download\"].forEach(function(a){D[a]=new B(a,4,!1,a,null,!1,!1)});[\"cols\",\"rows\",\"size\",\"span\"].forEach(function(a){D[a]=new B(a,6,!1,a,null,!1,!1)});[\"rowSpan\",\"start\"].forEach(function(a){D[a]=new B(a,5,!1,a.toLowerCase(),null,!1,!1)});var oa=/[\\-:]([a-z])/g;function pa(a){return a[1].toUpperCase()}\n\"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height\".split(\" \").forEach(function(a){var b=a.replace(oa,\npa);D[b]=new B(b,1,!1,a,null,!1,!1)});\"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type\".split(\" \").forEach(function(a){var b=a.replace(oa,pa);D[b]=new B(b,1,!1,a,\"http://www.w3.org/1999/xlink\",!1,!1)});[\"xml:base\",\"xml:lang\",\"xml:space\"].forEach(function(a){var b=a.replace(oa,pa);D[b]=new B(b,1,!1,a,\"http://www.w3.org/XML/1998/namespace\",!1,!1)});[\"tabIndex\",\"crossOrigin\"].forEach(function(a){D[a]=new B(a,1,!1,a.toLowerCase(),null,!1,!1)});\nD.xlinkHref=new B(\"xlinkHref\",1,!1,\"xlink:href\",\"http://www.w3.org/1999/xlink\",!0,!1);[\"src\",\"href\",\"action\",\"formAction\"].forEach(function(a){D[a]=new B(a,1,!1,a.toLowerCase(),null,!0,!0)});\nfunction qa(a,b,c,d){var e=D.hasOwnProperty(b)?D[b]:null;var f=null!==e?0===e.type:d?!1:!(2h||e[g]!==f[h])return\"\\n\"+e[g].replace(\" at new \",\" at \");while(1<=g&&0<=h)}break}}}finally{Oa=!1,Error.prepareStackTrace=c}return(a=a?a.displayName||a.name:\"\")?Na(a):\"\"}\nfunction Qa(a){switch(a.tag){case 5:return Na(a.type);case 16:return Na(\"Lazy\");case 13:return Na(\"Suspense\");case 19:return Na(\"SuspenseList\");case 0:case 2:case 15:return a=Pa(a.type,!1),a;case 11:return a=Pa(a.type.render,!1),a;case 22:return a=Pa(a.type._render,!1),a;case 1:return a=Pa(a.type,!0),a;default:return\"\"}}\nfunction Ra(a){if(null==a)return null;if(\"function\"===typeof a)return a.displayName||a.name||null;if(\"string\"===typeof a)return a;switch(a){case ua:return\"Fragment\";case ta:return\"Portal\";case xa:return\"Profiler\";case wa:return\"StrictMode\";case Ba:return\"Suspense\";case Ca:return\"SuspenseList\"}if(\"object\"===typeof a)switch(a.$$typeof){case za:return(a.displayName||\"Context\")+\".Consumer\";case ya:return(a._context.displayName||\"Context\")+\".Provider\";case Aa:var b=a.render;b=b.displayName||b.name||\"\";\nreturn a.displayName||(\"\"!==b?\"ForwardRef(\"+b+\")\":\"ForwardRef\");case Da:return Ra(a.type);case Fa:return Ra(a._render);case Ea:b=a._payload;a=a._init;try{return Ra(a(b))}catch(c){}}return null}function Sa(a){switch(typeof a){case \"boolean\":case \"number\":case \"object\":case \"string\":case \"undefined\":return a;default:return\"\"}}function Ta(a){var b=a.type;return(a=a.nodeName)&&\"input\"===a.toLowerCase()&&(\"checkbox\"===b||\"radio\"===b)}\nfunction Ua(a){var b=Ta(a)?\"checked\":\"value\",c=Object.getOwnPropertyDescriptor(a.constructor.prototype,b),d=\"\"+a[b];if(!a.hasOwnProperty(b)&&\"undefined\"!==typeof c&&\"function\"===typeof c.get&&\"function\"===typeof c.set){var e=c.get,f=c.set;Object.defineProperty(a,b,{configurable:!0,get:function(){return e.call(this)},set:function(a){d=\"\"+a;f.call(this,a)}});Object.defineProperty(a,b,{enumerable:c.enumerable});return{getValue:function(){return d},setValue:function(a){d=\"\"+a},stopTracking:function(){a._valueTracker=\nnull;delete a[b]}}}}function Va(a){a._valueTracker||(a._valueTracker=Ua(a))}function Wa(a){if(!a)return!1;var b=a._valueTracker;if(!b)return!0;var c=b.getValue();var d=\"\";a&&(d=Ta(a)?a.checked?\"true\":\"false\":a.value);a=d;return a!==c?(b.setValue(a),!0):!1}function Xa(a){a=a||(\"undefined\"!==typeof document?document:void 0);if(\"undefined\"===typeof a)return null;try{return a.activeElement||a.body}catch(b){return a.body}}\nfunction Ya(a,b){var c=b.checked;return m({},b,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:null!=c?c:a._wrapperState.initialChecked})}function Za(a,b){var c=null==b.defaultValue?\"\":b.defaultValue,d=null!=b.checked?b.checked:b.defaultChecked;c=Sa(null!=b.value?b.value:c);a._wrapperState={initialChecked:d,initialValue:c,controlled:\"checkbox\"===b.type||\"radio\"===b.type?null!=b.checked:null!=b.value}}function $a(a,b){b=b.checked;null!=b&&qa(a,\"checked\",b,!1)}\nfunction ab(a,b){$a(a,b);var c=Sa(b.value),d=b.type;if(null!=c)if(\"number\"===d){if(0===c&&\"\"===a.value||a.value!=c)a.value=\"\"+c}else a.value!==\"\"+c&&(a.value=\"\"+c);else if(\"submit\"===d||\"reset\"===d){a.removeAttribute(\"value\");return}b.hasOwnProperty(\"value\")?bb(a,b.type,c):b.hasOwnProperty(\"defaultValue\")&&bb(a,b.type,Sa(b.defaultValue));null==b.checked&&null!=b.defaultChecked&&(a.defaultChecked=!!b.defaultChecked)}\nfunction cb(a,b,c){if(b.hasOwnProperty(\"value\")||b.hasOwnProperty(\"defaultValue\")){var d=b.type;if(!(\"submit\"!==d&&\"reset\"!==d||void 0!==b.value&&null!==b.value))return;b=\"\"+a._wrapperState.initialValue;c||b===a.value||(a.value=b);a.defaultValue=b}c=a.name;\"\"!==c&&(a.name=\"\");a.defaultChecked=!!a._wrapperState.initialChecked;\"\"!==c&&(a.name=c)}\nfunction bb(a,b,c){if(\"number\"!==b||Xa(a.ownerDocument)!==a)null==c?a.defaultValue=\"\"+a._wrapperState.initialValue:a.defaultValue!==\"\"+c&&(a.defaultValue=\"\"+c)}function db(a){var b=\"\";aa.Children.forEach(a,function(a){null!=a&&(b+=a)});return b}function eb(a,b){a=m({children:void 0},b);if(b=db(b.children))a.children=b;return a}\nfunction fb(a,b,c,d){a=a.options;if(b){b={};for(var e=0;e=c.length))throw Error(y(93));c=c[0]}b=c}null==b&&(b=\"\");c=b}a._wrapperState={initialValue:Sa(c)}}\nfunction ib(a,b){var c=Sa(b.value),d=Sa(b.defaultValue);null!=c&&(c=\"\"+c,c!==a.value&&(a.value=c),null==b.defaultValue&&a.defaultValue!==c&&(a.defaultValue=c));null!=d&&(a.defaultValue=\"\"+d)}function jb(a){var b=a.textContent;b===a._wrapperState.initialValue&&\"\"!==b&&null!==b&&(a.value=b)}var kb={html:\"http://www.w3.org/1999/xhtml\",mathml:\"http://www.w3.org/1998/Math/MathML\",svg:\"http://www.w3.org/2000/svg\"};\nfunction lb(a){switch(a){case \"svg\":return\"http://www.w3.org/2000/svg\";case \"math\":return\"http://www.w3.org/1998/Math/MathML\";default:return\"http://www.w3.org/1999/xhtml\"}}function mb(a,b){return null==a||\"http://www.w3.org/1999/xhtml\"===a?lb(b):\"http://www.w3.org/2000/svg\"===a&&\"foreignObject\"===b?\"http://www.w3.org/1999/xhtml\":a}\nvar nb,ob=function(a){return\"undefined\"!==typeof MSApp&&MSApp.execUnsafeLocalFunction?function(b,c,d,e){MSApp.execUnsafeLocalFunction(function(){return a(b,c,d,e)})}:a}(function(a,b){if(a.namespaceURI!==kb.svg||\"innerHTML\"in a)a.innerHTML=b;else{nb=nb||document.createElement(\"div\");nb.innerHTML=\"\"+b.valueOf().toString()+\"\";for(b=nb.firstChild;a.firstChild;)a.removeChild(a.firstChild);for(;b.firstChild;)a.appendChild(b.firstChild)}});\nfunction pb(a,b){if(b){var c=a.firstChild;if(c&&c===a.lastChild&&3===c.nodeType){c.nodeValue=b;return}}a.textContent=b}\nvar qb={animationIterationCount:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,\nfloodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},rb=[\"Webkit\",\"ms\",\"Moz\",\"O\"];Object.keys(qb).forEach(function(a){rb.forEach(function(b){b=b+a.charAt(0).toUpperCase()+a.substring(1);qb[b]=qb[a]})});function sb(a,b,c){return null==b||\"boolean\"===typeof b||\"\"===b?\"\":c||\"number\"!==typeof b||0===b||qb.hasOwnProperty(a)&&qb[a]?(\"\"+b).trim():b+\"px\"}\nfunction tb(a,b){a=a.style;for(var c in b)if(b.hasOwnProperty(c)){var d=0===c.indexOf(\"--\"),e=sb(c,b[c],d);\"float\"===c&&(c=\"cssFloat\");d?a.setProperty(c,e):a[c]=e}}var ub=m({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});\nfunction vb(a,b){if(b){if(ub[a]&&(null!=b.children||null!=b.dangerouslySetInnerHTML))throw Error(y(137,a));if(null!=b.dangerouslySetInnerHTML){if(null!=b.children)throw Error(y(60));if(!(\"object\"===typeof b.dangerouslySetInnerHTML&&\"__html\"in b.dangerouslySetInnerHTML))throw Error(y(61));}if(null!=b.style&&\"object\"!==typeof b.style)throw Error(y(62));}}\nfunction wb(a,b){if(-1===a.indexOf(\"-\"))return\"string\"===typeof b.is;switch(a){case \"annotation-xml\":case \"color-profile\":case \"font-face\":case \"font-face-src\":case \"font-face-uri\":case \"font-face-format\":case \"font-face-name\":case \"missing-glyph\":return!1;default:return!0}}function xb(a){a=a.target||a.srcElement||window;a.correspondingUseElement&&(a=a.correspondingUseElement);return 3===a.nodeType?a.parentNode:a}var yb=null,zb=null,Ab=null;\nfunction Bb(a){if(a=Cb(a)){if(\"function\"!==typeof yb)throw Error(y(280));var b=a.stateNode;b&&(b=Db(b),yb(a.stateNode,a.type,b))}}function Eb(a){zb?Ab?Ab.push(a):Ab=[a]:zb=a}function Fb(){if(zb){var a=zb,b=Ab;Ab=zb=null;Bb(a);if(b)for(a=0;ad?0:1<c;c++)b.push(a);return b}\nfunction $c(a,b,c){a.pendingLanes|=b;var d=b-1;a.suspendedLanes&=d;a.pingedLanes&=d;a=a.eventTimes;b=31-Vc(b);a[b]=c}var Vc=Math.clz32?Math.clz32:ad,bd=Math.log,cd=Math.LN2;function ad(a){return 0===a?32:31-(bd(a)/cd|0)|0}var dd=r.unstable_UserBlockingPriority,ed=r.unstable_runWithPriority,fd=!0;function gd(a,b,c,d){Kb||Ib();var e=hd,f=Kb;Kb=!0;try{Hb(e,a,b,c,d)}finally{(Kb=f)||Mb()}}function id(a,b,c,d){ed(dd,hd.bind(null,a,b,c,d))}\nfunction hd(a,b,c,d){if(fd){var e;if((e=0===(b&4))&&0=be),ee=String.fromCharCode(32),fe=!1;\nfunction ge(a,b){switch(a){case \"keyup\":return-1!==$d.indexOf(b.keyCode);case \"keydown\":return 229!==b.keyCode;case \"keypress\":case \"mousedown\":case \"focusout\":return!0;default:return!1}}function he(a){a=a.detail;return\"object\"===typeof a&&\"data\"in a?a.data:null}var ie=!1;function je(a,b){switch(a){case \"compositionend\":return he(b);case \"keypress\":if(32!==b.which)return null;fe=!0;return ee;case \"textInput\":return a=b.data,a===ee&&fe?null:a;default:return null}}\nfunction ke(a,b){if(ie)return\"compositionend\"===a||!ae&&ge(a,b)?(a=nd(),md=ld=kd=null,ie=!1,a):null;switch(a){case \"paste\":return null;case \"keypress\":if(!(b.ctrlKey||b.altKey||b.metaKey)||b.ctrlKey&&b.altKey){if(b.char&&1=b)return{node:c,offset:b-a};a=d}a:{for(;c;){if(c.nextSibling){c=c.nextSibling;break a}c=c.parentNode}c=void 0}c=Ke(c)}}function Me(a,b){return a&&b?a===b?!0:a&&3===a.nodeType?!1:b&&3===b.nodeType?Me(a,b.parentNode):\"contains\"in a?a.contains(b):a.compareDocumentPosition?!!(a.compareDocumentPosition(b)&16):!1:!1}\nfunction Ne(){for(var a=window,b=Xa();b instanceof a.HTMLIFrameElement;){try{var c=\"string\"===typeof b.contentWindow.location.href}catch(d){c=!1}if(c)a=b.contentWindow;else break;b=Xa(a.document)}return b}function Oe(a){var b=a&&a.nodeName&&a.nodeName.toLowerCase();return b&&(\"input\"===b&&(\"text\"===a.type||\"search\"===a.type||\"tel\"===a.type||\"url\"===a.type||\"password\"===a.type)||\"textarea\"===b||\"true\"===a.contentEditable)}\nvar Pe=fa&&\"documentMode\"in document&&11>=document.documentMode,Qe=null,Re=null,Se=null,Te=!1;\nfunction Ue(a,b,c){var d=c.window===c?c.document:9===c.nodeType?c:c.ownerDocument;Te||null==Qe||Qe!==Xa(d)||(d=Qe,\"selectionStart\"in d&&Oe(d)?d={start:d.selectionStart,end:d.selectionEnd}:(d=(d.ownerDocument&&d.ownerDocument.defaultView||window).getSelection(),d={anchorNode:d.anchorNode,anchorOffset:d.anchorOffset,focusNode:d.focusNode,focusOffset:d.focusOffset}),Se&&Je(Se,d)||(Se=d,d=oe(Re,\"onSelect\"),0Af||(a.current=zf[Af],zf[Af]=null,Af--)}function I(a,b){Af++;zf[Af]=a.current;a.current=b}var Cf={},M=Bf(Cf),N=Bf(!1),Df=Cf;\nfunction Ef(a,b){var c=a.type.contextTypes;if(!c)return Cf;var d=a.stateNode;if(d&&d.__reactInternalMemoizedUnmaskedChildContext===b)return d.__reactInternalMemoizedMaskedChildContext;var e={},f;for(f in c)e[f]=b[f];d&&(a=a.stateNode,a.__reactInternalMemoizedUnmaskedChildContext=b,a.__reactInternalMemoizedMaskedChildContext=e);return e}function Ff(a){a=a.childContextTypes;return null!==a&&void 0!==a}function Gf(){H(N);H(M)}function Hf(a,b,c){if(M.current!==Cf)throw Error(y(168));I(M,b);I(N,c)}\nfunction If(a,b,c){var d=a.stateNode;a=b.childContextTypes;if(\"function\"!==typeof d.getChildContext)return c;d=d.getChildContext();for(var e in d)if(!(e in a))throw Error(y(108,Ra(b)||\"Unknown\",e));return m({},c,d)}function Jf(a){a=(a=a.stateNode)&&a.__reactInternalMemoizedMergedChildContext||Cf;Df=M.current;I(M,a);I(N,N.current);return!0}function Kf(a,b,c){var d=a.stateNode;if(!d)throw Error(y(169));c?(a=If(a,b,Df),d.__reactInternalMemoizedMergedChildContext=a,H(N),H(M),I(M,a)):H(N);I(N,c)}\nvar Lf=null,Mf=null,Nf=r.unstable_runWithPriority,Of=r.unstable_scheduleCallback,Pf=r.unstable_cancelCallback,Qf=r.unstable_shouldYield,Rf=r.unstable_requestPaint,Sf=r.unstable_now,Tf=r.unstable_getCurrentPriorityLevel,Uf=r.unstable_ImmediatePriority,Vf=r.unstable_UserBlockingPriority,Wf=r.unstable_NormalPriority,Xf=r.unstable_LowPriority,Yf=r.unstable_IdlePriority,Zf={},$f=void 0!==Rf?Rf:function(){},ag=null,bg=null,cg=!1,dg=Sf(),O=1E4>dg?Sf:function(){return Sf()-dg};\nfunction eg(){switch(Tf()){case Uf:return 99;case Vf:return 98;case Wf:return 97;case Xf:return 96;case Yf:return 95;default:throw Error(y(332));}}function fg(a){switch(a){case 99:return Uf;case 98:return Vf;case 97:return Wf;case 96:return Xf;case 95:return Yf;default:throw Error(y(332));}}function gg(a,b){a=fg(a);return Nf(a,b)}function hg(a,b,c){a=fg(a);return Of(a,b,c)}function ig(){if(null!==bg){var a=bg;bg=null;Pf(a)}jg()}\nfunction jg(){if(!cg&&null!==ag){cg=!0;var a=0;try{var b=ag;gg(99,function(){for(;az?(q=u,u=null):q=u.sibling;var n=p(e,u,h[z],k);if(null===n){null===u&&(u=q);break}a&&u&&null===\nn.alternate&&b(e,u);g=f(n,g,z);null===t?l=n:t.sibling=n;t=n;u=q}if(z===h.length)return c(e,u),l;if(null===u){for(;zz?(q=u,u=null):q=u.sibling;var w=p(e,u,n.value,k);if(null===w){null===u&&(u=q);break}a&&u&&null===w.alternate&&b(e,u);g=f(w,g,z);null===t?l=w:t.sibling=w;t=w;u=q}if(n.done)return c(e,u),l;if(null===u){for(;!n.done;z++,n=h.next())n=A(e,n.value,k),null!==n&&(g=f(n,g,z),null===t?l=n:t.sibling=n,t=n);return l}for(u=d(e,u);!n.done;z++,n=h.next())n=C(u,e,z,n.value,k),null!==n&&(a&&null!==n.alternate&&\nu.delete(null===n.key?z:n.key),g=f(n,g,z),null===t?l=n:t.sibling=n,t=n);a&&u.forEach(function(a){return b(e,a)});return l}return function(a,d,f,h){var k=\"object\"===typeof f&&null!==f&&f.type===ua&&null===f.key;k&&(f=f.props.children);var l=\"object\"===typeof f&&null!==f;if(l)switch(f.$$typeof){case sa:a:{l=f.key;for(k=d;null!==k;){if(k.key===l){switch(k.tag){case 7:if(f.type===ua){c(a,k.sibling);d=e(k,f.props.children);d.return=a;a=d;break a}break;default:if(k.elementType===f.type){c(a,k.sibling);\nd=e(k,f.props);d.ref=Qg(a,k,f);d.return=a;a=d;break a}}c(a,k);break}else b(a,k);k=k.sibling}f.type===ua?(d=Xg(f.props.children,a.mode,h,f.key),d.return=a,a=d):(h=Vg(f.type,f.key,f.props,null,a.mode,h),h.ref=Qg(a,d,f),h.return=a,a=h)}return g(a);case ta:a:{for(k=f.key;null!==d;){if(d.key===k)if(4===d.tag&&d.stateNode.containerInfo===f.containerInfo&&d.stateNode.implementation===f.implementation){c(a,d.sibling);d=e(d,f.children||[]);d.return=a;a=d;break a}else{c(a,d);break}else b(a,d);d=d.sibling}d=\nWg(f,a.mode,h);d.return=a;a=d}return g(a)}if(\"string\"===typeof f||\"number\"===typeof f)return f=\"\"+f,null!==d&&6===d.tag?(c(a,d.sibling),d=e(d,f),d.return=a,a=d):(c(a,d),d=Ug(f,a.mode,h),d.return=a,a=d),g(a);if(Pg(f))return x(a,d,f,h);if(La(f))return w(a,d,f,h);l&&Rg(a,f);if(\"undefined\"===typeof f&&!k)switch(a.tag){case 1:case 22:case 0:case 11:case 15:throw Error(y(152,Ra(a.type)||\"Component\"));}return c(a,d)}}var Yg=Sg(!0),Zg=Sg(!1),$g={},ah=Bf($g),bh=Bf($g),ch=Bf($g);\nfunction dh(a){if(a===$g)throw Error(y(174));return a}function eh(a,b){I(ch,b);I(bh,a);I(ah,$g);a=b.nodeType;switch(a){case 9:case 11:b=(b=b.documentElement)?b.namespaceURI:mb(null,\"\");break;default:a=8===a?b.parentNode:b,b=a.namespaceURI||null,a=a.tagName,b=mb(b,a)}H(ah);I(ah,b)}function fh(){H(ah);H(bh);H(ch)}function gh(a){dh(ch.current);var b=dh(ah.current);var c=mb(b,a.type);b!==c&&(I(bh,a),I(ah,c))}function hh(a){bh.current===a&&(H(ah),H(bh))}var P=Bf(0);\nfunction ih(a){for(var b=a;null!==b;){if(13===b.tag){var c=b.memoizedState;if(null!==c&&(c=c.dehydrated,null===c||\"$?\"===c.data||\"$!\"===c.data))return b}else if(19===b.tag&&void 0!==b.memoizedProps.revealOrder){if(0!==(b.flags&64))return b}else if(null!==b.child){b.child.return=b;b=b.child;continue}if(b===a)break;for(;null===b.sibling;){if(null===b.return||b.return===a)return null;b=b.return}b.sibling.return=b.return;b=b.sibling}return null}var jh=null,kh=null,lh=!1;\nfunction mh(a,b){var c=nh(5,null,null,0);c.elementType=\"DELETED\";c.type=\"DELETED\";c.stateNode=b;c.return=a;c.flags=8;null!==a.lastEffect?(a.lastEffect.nextEffect=c,a.lastEffect=c):a.firstEffect=a.lastEffect=c}function oh(a,b){switch(a.tag){case 5:var c=a.type;b=1!==b.nodeType||c.toLowerCase()!==b.nodeName.toLowerCase()?null:b;return null!==b?(a.stateNode=b,!0):!1;case 6:return b=\"\"===a.pendingProps||3!==b.nodeType?null:b,null!==b?(a.stateNode=b,!0):!1;case 13:return!1;default:return!1}}\nfunction ph(a){if(lh){var b=kh;if(b){var c=b;if(!oh(a,b)){b=rf(c.nextSibling);if(!b||!oh(a,b)){a.flags=a.flags&-1025|2;lh=!1;jh=a;return}mh(jh,c)}jh=a;kh=rf(b.firstChild)}else a.flags=a.flags&-1025|2,lh=!1,jh=a}}function qh(a){for(a=a.return;null!==a&&5!==a.tag&&3!==a.tag&&13!==a.tag;)a=a.return;jh=a}\nfunction rh(a){if(a!==jh)return!1;if(!lh)return qh(a),lh=!0,!1;var b=a.type;if(5!==a.tag||\"head\"!==b&&\"body\"!==b&&!nf(b,a.memoizedProps))for(b=kh;b;)mh(a,b),b=rf(b.nextSibling);qh(a);if(13===a.tag){a=a.memoizedState;a=null!==a?a.dehydrated:null;if(!a)throw Error(y(317));a:{a=a.nextSibling;for(b=0;a;){if(8===a.nodeType){var c=a.data;if(\"/$\"===c){if(0===b){kh=rf(a.nextSibling);break a}b--}else\"$\"!==c&&\"$!\"!==c&&\"$?\"!==c||b++}a=a.nextSibling}kh=null}}else kh=jh?rf(a.stateNode.nextSibling):null;return!0}\nfunction sh(){kh=jh=null;lh=!1}var th=[];function uh(){for(var a=0;af))throw Error(y(301));f+=1;T=S=null;b.updateQueue=null;vh.current=Fh;a=c(d,e)}while(zh)}vh.current=Gh;b=null!==S&&null!==S.next;xh=0;T=S=R=null;yh=!1;if(b)throw Error(y(300));return a}function Hh(){var a={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};null===T?R.memoizedState=T=a:T=T.next=a;return T}\nfunction Ih(){if(null===S){var a=R.alternate;a=null!==a?a.memoizedState:null}else a=S.next;var b=null===T?R.memoizedState:T.next;if(null!==b)T=b,S=a;else{if(null===a)throw Error(y(310));S=a;a={memoizedState:S.memoizedState,baseState:S.baseState,baseQueue:S.baseQueue,queue:S.queue,next:null};null===T?R.memoizedState=T=a:T=T.next=a}return T}function Jh(a,b){return\"function\"===typeof b?b(a):b}\nfunction Kh(a){var b=Ih(),c=b.queue;if(null===c)throw Error(y(311));c.lastRenderedReducer=a;var d=S,e=d.baseQueue,f=c.pending;if(null!==f){if(null!==e){var g=e.next;e.next=f.next;f.next=g}d.baseQueue=e=f;c.pending=null}if(null!==e){e=e.next;d=d.baseState;var h=g=f=null,k=e;do{var l=k.lane;if((xh&l)===l)null!==h&&(h=h.next={lane:0,action:k.action,eagerReducer:k.eagerReducer,eagerState:k.eagerState,next:null}),d=k.eagerReducer===a?k.eagerState:a(d,k.action);else{var n={lane:l,action:k.action,eagerReducer:k.eagerReducer,\neagerState:k.eagerState,next:null};null===h?(g=h=n,f=d):h=h.next=n;R.lanes|=l;Dg|=l}k=k.next}while(null!==k&&k!==e);null===h?f=d:h.next=g;He(d,b.memoizedState)||(ug=!0);b.memoizedState=d;b.baseState=f;b.baseQueue=h;c.lastRenderedState=d}return[b.memoizedState,c.dispatch]}\nfunction Lh(a){var b=Ih(),c=b.queue;if(null===c)throw Error(y(311));c.lastRenderedReducer=a;var d=c.dispatch,e=c.pending,f=b.memoizedState;if(null!==e){c.pending=null;var g=e=e.next;do f=a(f,g.action),g=g.next;while(g!==e);He(f,b.memoizedState)||(ug=!0);b.memoizedState=f;null===b.baseQueue&&(b.baseState=f);c.lastRenderedState=f}return[f,d]}\nfunction Mh(a,b,c){var d=b._getVersion;d=d(b._source);var e=b._workInProgressVersionPrimary;if(null!==e)a=e===d;else if(a=a.mutableReadLanes,a=(xh&a)===a)b._workInProgressVersionPrimary=d,th.push(b);if(a)return c(b._source);th.push(b);throw Error(y(350));}\nfunction Nh(a,b,c,d){var e=U;if(null===e)throw Error(y(349));var f=b._getVersion,g=f(b._source),h=vh.current,k=h.useState(function(){return Mh(e,b,c)}),l=k[1],n=k[0];k=T;var A=a.memoizedState,p=A.refs,C=p.getSnapshot,x=A.source;A=A.subscribe;var w=R;a.memoizedState={refs:p,source:b,subscribe:d};h.useEffect(function(){p.getSnapshot=c;p.setSnapshot=l;var a=f(b._source);if(!He(g,a)){a=c(b._source);He(n,a)||(l(a),a=Ig(w),e.mutableReadLanes|=a&e.pendingLanes);a=e.mutableReadLanes;e.entangledLanes|=a;for(var d=\ne.entanglements,h=a;0c?98:c,function(){a(!0)});gg(97\\x3c/script>\",a=a.removeChild(a.firstChild)):\"string\"===typeof d.is?a=g.createElement(c,{is:d.is}):(a=g.createElement(c),\"select\"===c&&(g=a,d.multiple?g.multiple=!0:d.size&&(g.size=d.size))):a=g.createElementNS(a,c);a[wf]=b;a[xf]=d;Bi(a,b,!1,!1);b.stateNode=a;g=wb(c,d);switch(c){case \"dialog\":G(\"cancel\",a);G(\"close\",a);\ne=d;break;case \"iframe\":case \"object\":case \"embed\":G(\"load\",a);e=d;break;case \"video\":case \"audio\":for(e=0;eJi&&(b.flags|=64,f=!0,Fi(d,!1),b.lanes=33554432)}else{if(!f)if(a=ih(g),null!==a){if(b.flags|=64,f=!0,c=a.updateQueue,null!==c&&(b.updateQueue=c,b.flags|=4),Fi(d,!0),null===d.tail&&\"hidden\"===d.tailMode&&!g.alternate&&!lh)return b=b.lastEffect=d.lastEffect,null!==b&&(b.nextEffect=null),null}else 2*O()-d.renderingStartTime>Ji&&1073741824!==c&&(b.flags|=\n64,f=!0,Fi(d,!1),b.lanes=33554432);d.isBackwards?(g.sibling=b.child,b.child=g):(c=d.last,null!==c?c.sibling=g:b.child=g,d.last=g)}return null!==d.tail?(c=d.tail,d.rendering=c,d.tail=c.sibling,d.lastEffect=b.lastEffect,d.renderingStartTime=O(),c.sibling=null,b=P.current,I(P,f?b&1|2:b&1),c):null;case 23:case 24:return Ki(),null!==a&&null!==a.memoizedState!==(null!==b.memoizedState)&&\"unstable-defer-without-hiding\"!==d.mode&&(b.flags|=4),null}throw Error(y(156,b.tag));}\nfunction Li(a){switch(a.tag){case 1:Ff(a.type)&&Gf();var b=a.flags;return b&4096?(a.flags=b&-4097|64,a):null;case 3:fh();H(N);H(M);uh();b=a.flags;if(0!==(b&64))throw Error(y(285));a.flags=b&-4097|64;return a;case 5:return hh(a),null;case 13:return H(P),b=a.flags,b&4096?(a.flags=b&-4097|64,a):null;case 19:return H(P),null;case 4:return fh(),null;case 10:return rg(a),null;case 23:case 24:return Ki(),null;default:return null}}\nfunction Mi(a,b){try{var c=\"\",d=b;do c+=Qa(d),d=d.return;while(d);var e=c}catch(f){e=\"\\nError generating stack: \"+f.message+\"\\n\"+f.stack}return{value:a,source:b,stack:e}}function Ni(a,b){try{console.error(b.value)}catch(c){setTimeout(function(){throw c;})}}var Oi=\"function\"===typeof WeakMap?WeakMap:Map;function Pi(a,b,c){c=zg(-1,c);c.tag=3;c.payload={element:null};var d=b.value;c.callback=function(){Qi||(Qi=!0,Ri=d);Ni(a,b)};return c}\nfunction Si(a,b,c){c=zg(-1,c);c.tag=3;var d=a.type.getDerivedStateFromError;if(\"function\"===typeof d){var e=b.value;c.payload=function(){Ni(a,b);return d(e)}}var f=a.stateNode;null!==f&&\"function\"===typeof f.componentDidCatch&&(c.callback=function(){\"function\"!==typeof d&&(null===Ti?Ti=new Set([this]):Ti.add(this),Ni(a,b));var c=b.stack;this.componentDidCatch(b.value,{componentStack:null!==c?c:\"\"})});return c}var Ui=\"function\"===typeof WeakSet?WeakSet:Set;\nfunction Vi(a){var b=a.ref;if(null!==b)if(\"function\"===typeof b)try{b(null)}catch(c){Wi(a,c)}else b.current=null}function Xi(a,b){switch(b.tag){case 0:case 11:case 15:case 22:return;case 1:if(b.flags&256&&null!==a){var c=a.memoizedProps,d=a.memoizedState;a=b.stateNode;b=a.getSnapshotBeforeUpdate(b.elementType===b.type?c:lg(b.type,c),d);a.__reactInternalSnapshotBeforeUpdate=b}return;case 3:b.flags&256&&qf(b.stateNode.containerInfo);return;case 5:case 6:case 4:case 17:return}throw Error(y(163));}\nfunction Yi(a,b,c){switch(c.tag){case 0:case 11:case 15:case 22:b=c.updateQueue;b=null!==b?b.lastEffect:null;if(null!==b){a=b=b.next;do{if(3===(a.tag&3)){var d=a.create;a.destroy=d()}a=a.next}while(a!==b)}b=c.updateQueue;b=null!==b?b.lastEffect:null;if(null!==b){a=b=b.next;do{var e=a;d=e.next;e=e.tag;0!==(e&4)&&0!==(e&1)&&(Zi(c,a),$i(c,a));a=d}while(a!==b)}return;case 1:a=c.stateNode;c.flags&4&&(null===b?a.componentDidMount():(d=c.elementType===c.type?b.memoizedProps:lg(c.type,b.memoizedProps),a.componentDidUpdate(d,\nb.memoizedState,a.__reactInternalSnapshotBeforeUpdate)));b=c.updateQueue;null!==b&&Eg(c,b,a);return;case 3:b=c.updateQueue;if(null!==b){a=null;if(null!==c.child)switch(c.child.tag){case 5:a=c.child.stateNode;break;case 1:a=c.child.stateNode}Eg(c,b,a)}return;case 5:a=c.stateNode;null===b&&c.flags&4&&mf(c.type,c.memoizedProps)&&a.focus();return;case 6:return;case 4:return;case 12:return;case 13:null===c.memoizedState&&(c=c.alternate,null!==c&&(c=c.memoizedState,null!==c&&(c=c.dehydrated,null!==c&&Cc(c))));\nreturn;case 19:case 17:case 20:case 21:case 23:case 24:return}throw Error(y(163));}\nfunction aj(a,b){for(var c=a;;){if(5===c.tag){var d=c.stateNode;if(b)d=d.style,\"function\"===typeof d.setProperty?d.setProperty(\"display\",\"none\",\"important\"):d.display=\"none\";else{d=c.stateNode;var e=c.memoizedProps.style;e=void 0!==e&&null!==e&&e.hasOwnProperty(\"display\")?e.display:null;d.style.display=sb(\"display\",e)}}else if(6===c.tag)c.stateNode.nodeValue=b?\"\":c.memoizedProps;else if((23!==c.tag&&24!==c.tag||null===c.memoizedState||c===a)&&null!==c.child){c.child.return=c;c=c.child;continue}if(c===\na)break;for(;null===c.sibling;){if(null===c.return||c.return===a)return;c=c.return}c.sibling.return=c.return;c=c.sibling}}\nfunction bj(a,b){if(Mf&&\"function\"===typeof Mf.onCommitFiberUnmount)try{Mf.onCommitFiberUnmount(Lf,b)}catch(f){}switch(b.tag){case 0:case 11:case 14:case 15:case 22:a=b.updateQueue;if(null!==a&&(a=a.lastEffect,null!==a)){var c=a=a.next;do{var d=c,e=d.destroy;d=d.tag;if(void 0!==e)if(0!==(d&4))Zi(b,c);else{d=b;try{e()}catch(f){Wi(d,f)}}c=c.next}while(c!==a)}break;case 1:Vi(b);a=b.stateNode;if(\"function\"===typeof a.componentWillUnmount)try{a.props=b.memoizedProps,a.state=b.memoizedState,a.componentWillUnmount()}catch(f){Wi(b,\nf)}break;case 5:Vi(b);break;case 4:cj(a,b)}}function dj(a){a.alternate=null;a.child=null;a.dependencies=null;a.firstEffect=null;a.lastEffect=null;a.memoizedProps=null;a.memoizedState=null;a.pendingProps=null;a.return=null;a.updateQueue=null}function ej(a){return 5===a.tag||3===a.tag||4===a.tag}\nfunction fj(a){a:{for(var b=a.return;null!==b;){if(ej(b))break a;b=b.return}throw Error(y(160));}var c=b;b=c.stateNode;switch(c.tag){case 5:var d=!1;break;case 3:b=b.containerInfo;d=!0;break;case 4:b=b.containerInfo;d=!0;break;default:throw Error(y(161));}c.flags&16&&(pb(b,\"\"),c.flags&=-17);a:b:for(c=a;;){for(;null===c.sibling;){if(null===c.return||ej(c.return)){c=null;break a}c=c.return}c.sibling.return=c.return;for(c=c.sibling;5!==c.tag&&6!==c.tag&&18!==c.tag;){if(c.flags&2)continue b;if(null===\nc.child||4===c.tag)continue b;else c.child.return=c,c=c.child}if(!(c.flags&2)){c=c.stateNode;break a}}d?gj(a,c,b):hj(a,c,b)}\nfunction gj(a,b,c){var d=a.tag,e=5===d||6===d;if(e)a=e?a.stateNode:a.stateNode.instance,b?8===c.nodeType?c.parentNode.insertBefore(a,b):c.insertBefore(a,b):(8===c.nodeType?(b=c.parentNode,b.insertBefore(a,c)):(b=c,b.appendChild(a)),c=c._reactRootContainer,null!==c&&void 0!==c||null!==b.onclick||(b.onclick=jf));else if(4!==d&&(a=a.child,null!==a))for(gj(a,b,c),a=a.sibling;null!==a;)gj(a,b,c),a=a.sibling}\nfunction hj(a,b,c){var d=a.tag,e=5===d||6===d;if(e)a=e?a.stateNode:a.stateNode.instance,b?c.insertBefore(a,b):c.appendChild(a);else if(4!==d&&(a=a.child,null!==a))for(hj(a,b,c),a=a.sibling;null!==a;)hj(a,b,c),a=a.sibling}\nfunction cj(a,b){for(var c=b,d=!1,e,f;;){if(!d){d=c.return;a:for(;;){if(null===d)throw Error(y(160));e=d.stateNode;switch(d.tag){case 5:f=!1;break a;case 3:e=e.containerInfo;f=!0;break a;case 4:e=e.containerInfo;f=!0;break a}d=d.return}d=!0}if(5===c.tag||6===c.tag){a:for(var g=a,h=c,k=h;;)if(bj(g,k),null!==k.child&&4!==k.tag)k.child.return=k,k=k.child;else{if(k===h)break a;for(;null===k.sibling;){if(null===k.return||k.return===h)break a;k=k.return}k.sibling.return=k.return;k=k.sibling}f?(g=e,h=c.stateNode,\n8===g.nodeType?g.parentNode.removeChild(h):g.removeChild(h)):e.removeChild(c.stateNode)}else if(4===c.tag){if(null!==c.child){e=c.stateNode.containerInfo;f=!0;c.child.return=c;c=c.child;continue}}else if(bj(a,c),null!==c.child){c.child.return=c;c=c.child;continue}if(c===b)break;for(;null===c.sibling;){if(null===c.return||c.return===b)return;c=c.return;4===c.tag&&(d=!1)}c.sibling.return=c.return;c=c.sibling}}\nfunction ij(a,b){switch(b.tag){case 0:case 11:case 14:case 15:case 22:var c=b.updateQueue;c=null!==c?c.lastEffect:null;if(null!==c){var d=c=c.next;do 3===(d.tag&3)&&(a=d.destroy,d.destroy=void 0,void 0!==a&&a()),d=d.next;while(d!==c)}return;case 1:return;case 5:c=b.stateNode;if(null!=c){d=b.memoizedProps;var e=null!==a?a.memoizedProps:d;a=b.type;var f=b.updateQueue;b.updateQueue=null;if(null!==f){c[xf]=d;\"input\"===a&&\"radio\"===d.type&&null!=d.name&&$a(c,d);wb(a,e);b=wb(a,d);for(e=0;ee&&(e=g);c&=~f}c=e;c=O()-c;c=(120>c?120:480>c?480:1080>c?1080:1920>c?1920:3E3>c?3E3:4320>\nc?4320:1960*nj(c/1960))-c;if(10 component higher in the tree to provide a loading indicator or placeholder to display.\")}5!==V&&(V=2);k=Mi(k,h);p=\ng;do{switch(p.tag){case 3:f=k;p.flags|=4096;b&=-b;p.lanes|=b;var J=Pi(p,f,b);Bg(p,J);break a;case 1:f=k;var K=p.type,Q=p.stateNode;if(0===(p.flags&64)&&(\"function\"===typeof K.getDerivedStateFromError||null!==Q&&\"function\"===typeof Q.componentDidCatch&&(null===Ti||!Ti.has(Q)))){p.flags|=4096;b&=-b;p.lanes|=b;var L=Si(p,f,b);Bg(p,L);break a}}p=p.return}while(null!==p)}Zj(c)}catch(va){b=va;Y===c&&null!==c&&(Y=c=c.return);continue}break}while(1)}\nfunction Pj(){var a=oj.current;oj.current=Gh;return null===a?Gh:a}function Tj(a,b){var c=X;X|=16;var d=Pj();U===a&&W===b||Qj(a,b);do try{ak();break}catch(e){Sj(a,e)}while(1);qg();X=c;oj.current=d;if(null!==Y)throw Error(y(261));U=null;W=0;return V}function ak(){for(;null!==Y;)bk(Y)}function Rj(){for(;null!==Y&&!Qf();)bk(Y)}function bk(a){var b=ck(a.alternate,a,qj);a.memoizedProps=a.pendingProps;null===b?Zj(a):Y=b;pj.current=null}\nfunction Zj(a){var b=a;do{var c=b.alternate;a=b.return;if(0===(b.flags&2048)){c=Gi(c,b,qj);if(null!==c){Y=c;return}c=b;if(24!==c.tag&&23!==c.tag||null===c.memoizedState||0!==(qj&1073741824)||0===(c.mode&4)){for(var d=0,e=c.child;null!==e;)d|=e.lanes|e.childLanes,e=e.sibling;c.childLanes=d}null!==a&&0===(a.flags&2048)&&(null===a.firstEffect&&(a.firstEffect=b.firstEffect),null!==b.lastEffect&&(null!==a.lastEffect&&(a.lastEffect.nextEffect=b.firstEffect),a.lastEffect=b.lastEffect),1g&&(h=g,g=J,J=h),h=Le(t,J),f=Le(t,g),h&&f&&(1!==v.rangeCount||v.anchorNode!==h.node||v.anchorOffset!==h.offset||v.focusNode!==f.node||v.focusOffset!==f.offset)&&(q=q.createRange(),q.setStart(h.node,h.offset),v.removeAllRanges(),J>g?(v.addRange(q),v.extend(f.node,f.offset)):(q.setEnd(f.node,f.offset),v.addRange(q))))));q=[];for(v=t;v=v.parentNode;)1===v.nodeType&&q.push({element:v,left:v.scrollLeft,top:v.scrollTop});\"function\"===typeof t.focus&&t.focus();for(t=\n0;tO()-jj?Qj(a,0):uj|=c);Mj(a,b)}function lj(a,b){var c=a.stateNode;null!==c&&c.delete(b);b=0;0===b&&(b=a.mode,0===(b&2)?b=1:0===(b&4)?b=99===eg()?1:2:(0===Gj&&(Gj=tj),b=Yc(62914560&~Gj),0===b&&(b=4194304)));c=Hg();a=Kj(a,b);null!==a&&($c(a,b,c),Mj(a,c))}var ck;\nck=function(a,b,c){var d=b.lanes;if(null!==a)if(a.memoizedProps!==b.pendingProps||N.current)ug=!0;else if(0!==(c&d))ug=0!==(a.flags&16384)?!0:!1;else{ug=!1;switch(b.tag){case 3:ri(b);sh();break;case 5:gh(b);break;case 1:Ff(b.type)&&Jf(b);break;case 4:eh(b,b.stateNode.containerInfo);break;case 10:d=b.memoizedProps.value;var e=b.type._context;I(mg,e._currentValue);e._currentValue=d;break;case 13:if(null!==b.memoizedState){if(0!==(c&b.child.childLanes))return ti(a,b,c);I(P,P.current&1);b=hi(a,b,c);return null!==\nb?b.sibling:null}I(P,P.current&1);break;case 19:d=0!==(c&b.childLanes);if(0!==(a.flags&64)){if(d)return Ai(a,b,c);b.flags|=64}e=b.memoizedState;null!==e&&(e.rendering=null,e.tail=null,e.lastEffect=null);I(P,P.current);if(d)break;else return null;case 23:case 24:return b.lanes=0,mi(a,b,c)}return hi(a,b,c)}else ug=!1;b.lanes=0;switch(b.tag){case 2:d=b.type;null!==a&&(a.alternate=null,b.alternate=null,b.flags|=2);a=b.pendingProps;e=Ef(b,M.current);tg(b,c);e=Ch(null,b,d,a,e,c);b.flags|=1;if(\"object\"===\ntypeof e&&null!==e&&\"function\"===typeof e.render&&void 0===e.$$typeof){b.tag=1;b.memoizedState=null;b.updateQueue=null;if(Ff(d)){var f=!0;Jf(b)}else f=!1;b.memoizedState=null!==e.state&&void 0!==e.state?e.state:null;xg(b);var g=d.getDerivedStateFromProps;\"function\"===typeof g&&Gg(b,d,g,a);e.updater=Kg;b.stateNode=e;e._reactInternals=b;Og(b,d,a,c);b=qi(null,b,d,!0,f,c)}else b.tag=0,fi(null,b,e,c),b=b.child;return b;case 16:e=b.elementType;a:{null!==a&&(a.alternate=null,b.alternate=null,b.flags|=2);\na=b.pendingProps;f=e._init;e=f(e._payload);b.type=e;f=b.tag=hk(e);a=lg(e,a);switch(f){case 0:b=li(null,b,e,a,c);break a;case 1:b=pi(null,b,e,a,c);break a;case 11:b=gi(null,b,e,a,c);break a;case 14:b=ii(null,b,e,lg(e.type,a),d,c);break a}throw Error(y(306,e,\"\"));}return b;case 0:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:lg(d,e),li(a,b,d,e,c);case 1:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:lg(d,e),pi(a,b,d,e,c);case 3:ri(b);d=b.updateQueue;if(null===a||null===d)throw Error(y(282));\nd=b.pendingProps;e=b.memoizedState;e=null!==e?e.element:null;yg(a,b);Cg(b,d,null,c);d=b.memoizedState.element;if(d===e)sh(),b=hi(a,b,c);else{e=b.stateNode;if(f=e.hydrate)kh=rf(b.stateNode.containerInfo.firstChild),jh=b,f=lh=!0;if(f){a=e.mutableSourceEagerHydrationData;if(null!=a)for(e=0;e 2 && arguments[2] !== undefined ? arguments[2] : {\n clone: true\n };\n var output = options.clone ? (0, _extends2.default)({}, target) : target;\n\n if (isPlainObject(target) && isPlainObject(source)) {\n Object.keys(source).forEach(function (key) {\n // Avoid prototype pollution\n if (key === '__proto__') {\n return;\n }\n\n if (isPlainObject(source[key]) && key in target) {\n output[key] = deepmerge(target[key], source[key], options);\n } else {\n output[key] = source[key];\n }\n });\n }\n\n return output;\n}", "/**\n * Copyright (c) 2013-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n'use strict';\n\nvar ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';\n\nmodule.exports = ReactPropTypesSecret;\n", "/**\n * Copyright (c) 2013-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n'use strict';\n\nvar ReactPropTypesSecret = require('./lib/ReactPropTypesSecret');\n\nfunction emptyFunction() {}\nfunction emptyFunctionWithReset() {}\nemptyFunctionWithReset.resetWarningCache = emptyFunction;\n\nmodule.exports = function() {\n function shim(props, propName, componentName, location, propFullName, secret) {\n if (secret === ReactPropTypesSecret) {\n // It is still safe when called from React.\n return;\n }\n var err = new Error(\n 'Calling PropTypes validators directly is not supported by the `prop-types` package. ' +\n 'Use PropTypes.checkPropTypes() to call them. ' +\n 'Read more at http://fb.me/use-check-prop-types'\n );\n err.name = 'Invariant Violation';\n throw err;\n };\n shim.isRequired = shim;\n function getShim() {\n return shim;\n };\n // Important!\n // Keep this list in sync with production version in `./factoryWithTypeCheckers.js`.\n var ReactPropTypes = {\n array: shim,\n bigint: shim,\n bool: shim,\n func: shim,\n number: shim,\n object: shim,\n string: shim,\n symbol: shim,\n\n any: shim,\n arrayOf: getShim,\n element: shim,\n elementType: shim,\n instanceOf: getShim,\n node: shim,\n objectOf: getShim,\n oneOf: getShim,\n oneOfType: getShim,\n shape: getShim,\n exact: getShim,\n\n checkPropTypes: emptyFunctionWithReset,\n resetWarningCache: emptyFunction\n };\n\n ReactPropTypes.PropTypes = ReactPropTypes;\n\n return ReactPropTypes;\n};\n", "/**\n * Copyright (c) 2013-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\nif (process.env.NODE_ENV !== 'production') {\n var ReactIs = require('react-is');\n\n // By explicitly using `prop-types` you are opting into new development behavior.\n // http://fb.me/prop-types-in-prod\n var throwOnDirectAccess = true;\n module.exports = require('./factoryWithTypeCheckers')(ReactIs.isElement, throwOnDirectAccess);\n} else {\n // By explicitly using `prop-types` you are opting into new production behavior.\n // http://fb.me/prop-types-in-prod\n module.exports = require('./factoryWithThrowingShims')();\n}\n", "\"use strict\";\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\");\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nvar _propTypes = _interopRequireDefault(require(\"prop-types\"));\n\nvar _chainPropTypes = _interopRequireDefault(require(\"./chainPropTypes\"));\n\nfunction isClassComponent(elementType) {\n // elementType.prototype?.isReactComponent\n var _elementType$prototyp = elementType.prototype,\n prototype = _elementType$prototyp === void 0 ? {} : _elementType$prototyp;\n return Boolean(prototype.isReactComponent);\n}\n\nfunction acceptingRef(props, propName, componentName, location, propFullName) {\n var element = props[propName];\n var safePropName = propFullName || propName;\n\n if (element == null) {\n return null;\n }\n\n var warningHint;\n var elementType = element.type;\n /**\n * Blacklisting instead of whitelisting\n *\n * Blacklisting will miss some components, such as React.Fragment. Those will at least\n * trigger a warning in React.\n * We can't whitelist because there is no safe way to detect React.forwardRef\n * or class components. \"Safe\" means there's no public API.\n *\n */\n\n if (typeof elementType === 'function' && !isClassComponent(elementType)) {\n warningHint = 'Did you accidentally use a plain function component for an element instead?';\n }\n\n if (warningHint !== undefined) {\n return new Error(\"Invalid \".concat(location, \" `\").concat(safePropName, \"` supplied to `\").concat(componentName, \"`. \") + \"Expected an element that can hold a ref. \".concat(warningHint, \" \") + 'For more information see https://mui.com/r/caveat-with-refs-guide');\n }\n\n return null;\n}\n\nvar elementAcceptingRef = (0, _chainPropTypes.default)(_propTypes.default.element, acceptingRef);\nelementAcceptingRef.isRequired = (0, _chainPropTypes.default)(_propTypes.default.element.isRequired, acceptingRef);\nvar _default = elementAcceptingRef;\nexports.default = _default;", "\"use strict\";\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\");\n\nvar _interopRequireWildcard = require(\"@babel/runtime/helpers/interopRequireWildcard\");\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nvar PropTypes = _interopRequireWildcard(require(\"prop-types\"));\n\nvar _chainPropTypes = _interopRequireDefault(require(\"./chainPropTypes\"));\n\nfunction isClassComponent(elementType) {\n // elementType.prototype?.isReactComponent\n var _elementType$prototyp = elementType.prototype,\n prototype = _elementType$prototyp === void 0 ? {} : _elementType$prototyp;\n return Boolean(prototype.isReactComponent);\n}\n\nfunction elementTypeAcceptingRef(props, propName, componentName, location, propFullName) {\n var propValue = props[propName];\n var safePropName = propFullName || propName;\n\n if (propValue == null) {\n return null;\n }\n\n var warningHint;\n /**\n * Blacklisting instead of whitelisting\n *\n * Blacklisting will miss some components, such as React.Fragment. Those will at least\n * trigger a warning in React.\n * We can't whitelist because there is no safe way to detect React.forwardRef\n * or class components. \"Safe\" means there's no public API.\n *\n */\n\n if (typeof propValue === 'function' && !isClassComponent(propValue)) {\n warningHint = 'Did you accidentally provide a plain function component instead?';\n }\n\n if (warningHint !== undefined) {\n return new Error(\"Invalid \".concat(location, \" `\").concat(safePropName, \"` supplied to `\").concat(componentName, \"`. \") + \"Expected an element type that can hold a ref. \".concat(warningHint, \" \") + 'For more information see https://mui.com/r/caveat-with-refs-guide');\n }\n\n return null;\n}\n\nvar _default = (0, _chainPropTypes.default)(PropTypes.elementType, elementTypeAcceptingRef);\n\nexports.default = _default;", "var _typeof = require(\"./typeof.js\")[\"default\"];\nfunction toPrimitive(t, r) {\n if (\"object\" != _typeof(t) || !t) return t;\n var e = t[Symbol.toPrimitive];\n if (void 0 !== e) {\n var i = e.call(t, r || \"default\");\n if (\"object\" != _typeof(i)) return i;\n throw new TypeError(\"@@toPrimitive must return a primitive value.\");\n }\n return (\"string\" === r ? String : Number)(t);\n}\nmodule.exports = toPrimitive, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;", "var _typeof = require(\"./typeof.js\")[\"default\"];\nvar toPrimitive = require(\"./toPrimitive.js\");\nfunction toPropertyKey(t) {\n var i = toPrimitive(t, \"string\");\n return \"symbol\" == _typeof(i) ? i : i + \"\";\n}\nmodule.exports = toPropertyKey, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;", "var toPropertyKey = require(\"./toPropertyKey.js\");\nfunction _defineProperty(e, r, t) {\n return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {\n value: t,\n enumerable: !0,\n configurable: !0,\n writable: !0\n }) : e[r] = t, e;\n}\nmodule.exports = _defineProperty, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;", "\"use strict\";\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\");\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = exactProp;\nexports.specialProperty = void 0;\n\nvar _defineProperty2 = _interopRequireDefault(require(\"@babel/runtime/helpers/defineProperty\"));\n\nvar _extends3 = _interopRequireDefault(require(\"@babel/runtime/helpers/extends\"));\n\n// This module is based on https://github.com/airbnb/prop-types-exact repository.\n// However, in order to reduce the number of dependencies and to remove some extra safe checks\n// the module was forked.\n// Only exported for test purposes.\nvar specialProperty = \"exact-prop: \\u200B\";\nexports.specialProperty = specialProperty;\n\nfunction exactProp(propTypes) {\n if (process.env.NODE_ENV === 'production') {\n return propTypes;\n }\n\n return (0, _extends3.default)({}, propTypes, (0, _defineProperty2.default)({}, specialProperty, function (props) {\n var unsupportedProps = Object.keys(props).filter(function (prop) {\n return !propTypes.hasOwnProperty(prop);\n });\n\n if (unsupportedProps.length > 0) {\n return new Error(\"The following props are not supported: \".concat(unsupportedProps.map(function (prop) {\n return \"`\".concat(prop, \"`\");\n }).join(', '), \". Please remove them.\"));\n }\n\n return null;\n }));\n}", "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = formatMuiErrorMessage;\n\n/**\n * WARNING: Don't import this directly.\n * Use `MuiError` from `@material-ui/utils/macros/MuiError.macro` instead.\n * @param {number} code\n */\nfunction formatMuiErrorMessage(code) {\n // Apply babel-plugin-transform-template-literals in loose mode\n // loose mode is safe iff we're concatenating primitives\n // see https://babeljs.io/docs/en/babel-plugin-transform-template-literals#loose\n\n /* eslint-disable prefer-template */\n var url = 'https://mui.com/production-error/?code=' + code;\n\n for (var i = 1; i < arguments.length; i += 1) {\n // rest params over-transpile for this case\n // eslint-disable-next-line prefer-rest-params\n url += '&args[]=' + encodeURIComponent(arguments[i]);\n }\n\n return 'Minified Material-UI error #' + code + '; visit ' + url + ' for the full message.';\n /* eslint-enable prefer-template */\n}", "/** @license React v17.0.2\n * react-is.production.min.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n'use strict';var b=60103,c=60106,d=60107,e=60108,f=60114,g=60109,h=60110,k=60112,l=60113,m=60120,n=60115,p=60116,q=60121,r=60122,u=60117,v=60129,w=60131;\nif(\"function\"===typeof Symbol&&Symbol.for){var x=Symbol.for;b=x(\"react.element\");c=x(\"react.portal\");d=x(\"react.fragment\");e=x(\"react.strict_mode\");f=x(\"react.profiler\");g=x(\"react.provider\");h=x(\"react.context\");k=x(\"react.forward_ref\");l=x(\"react.suspense\");m=x(\"react.suspense_list\");n=x(\"react.memo\");p=x(\"react.lazy\");q=x(\"react.block\");r=x(\"react.server.block\");u=x(\"react.fundamental\");v=x(\"react.debug_trace_mode\");w=x(\"react.legacy_hidden\")}\nfunction y(a){if(\"object\"===typeof a&&null!==a){var t=a.$$typeof;switch(t){case b:switch(a=a.type,a){case d:case f:case e:case l:case m:return a;default:switch(a=a&&a.$$typeof,a){case h:case k:case p:case n:case g:return a;default:return t}}case c:return t}}}var z=g,A=b,B=k,C=d,D=p,E=n,F=c,G=f,H=e,I=l;exports.ContextConsumer=h;exports.ContextProvider=z;exports.Element=A;exports.ForwardRef=B;exports.Fragment=C;exports.Lazy=D;exports.Memo=E;exports.Portal=F;exports.Profiler=G;exports.StrictMode=H;\nexports.Suspense=I;exports.isAsyncMode=function(){return!1};exports.isConcurrentMode=function(){return!1};exports.isContextConsumer=function(a){return y(a)===h};exports.isContextProvider=function(a){return y(a)===g};exports.isElement=function(a){return\"object\"===typeof a&&null!==a&&a.$$typeof===b};exports.isForwardRef=function(a){return y(a)===k};exports.isFragment=function(a){return y(a)===d};exports.isLazy=function(a){return y(a)===p};exports.isMemo=function(a){return y(a)===n};\nexports.isPortal=function(a){return y(a)===c};exports.isProfiler=function(a){return y(a)===f};exports.isStrictMode=function(a){return y(a)===e};exports.isSuspense=function(a){return y(a)===l};exports.isValidElementType=function(a){return\"string\"===typeof a||\"function\"===typeof a||a===d||a===f||a===v||a===e||a===l||a===m||a===w||\"object\"===typeof a&&null!==a&&(a.$$typeof===p||a.$$typeof===n||a.$$typeof===g||a.$$typeof===h||a.$$typeof===k||a.$$typeof===u||a.$$typeof===q||a[0]===r)?!0:!1};\nexports.typeOf=y;\n", "'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('./cjs/react-is.production.min.js');\n} else {\n module.exports = require('./cjs/react-is.development.js');\n}\n", "\"use strict\";\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\");\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.getFunctionName = getFunctionName;\nexports.default = getDisplayName;\n\nvar _typeof2 = _interopRequireDefault(require(\"@babel/runtime/helpers/typeof\"));\n\nvar _reactIs = require(\"react-is\");\n\n// Simplified polyfill for IE 11 support\n// https://github.com/JamesMGreene/Function.name/blob/58b314d4a983110c3682f1228f845d39ccca1817/Function.name.js#L3\nvar fnNameMatchRegex = /^\\s*function(?:\\s|\\s*\\/\\*.*\\*\\/\\s*)+([^(\\s/]*)\\s*/;\n\nfunction getFunctionName(fn) {\n var match = \"\".concat(fn).match(fnNameMatchRegex);\n var name = match && match[1];\n return name || '';\n}\n/**\n * @param {function} Component\n * @param {string} fallback\n * @returns {string | undefined}\n */\n\n\nfunction getFunctionComponentName(Component) {\n var fallback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';\n return Component.displayName || Component.name || getFunctionName(Component) || fallback;\n}\n\nfunction getWrappedName(outerType, innerType, wrapperName) {\n var functionName = getFunctionComponentName(innerType);\n return outerType.displayName || (functionName !== '' ? \"\".concat(wrapperName, \"(\").concat(functionName, \")\") : wrapperName);\n}\n/**\n * cherry-pick from\n * https://github.com/facebook/react/blob/769b1f270e1251d9dbdce0fcbd9e92e502d059b8/packages/shared/getComponentName.js\n * originally forked from recompose/getDisplayName with added IE 11 support\n *\n * @param {React.ReactType} Component\n * @returns {string | undefined}\n */\n\n\nfunction getDisplayName(Component) {\n if (Component == null) {\n return undefined;\n }\n\n if (typeof Component === 'string') {\n return Component;\n }\n\n if (typeof Component === 'function') {\n return getFunctionComponentName(Component, 'Component');\n }\n\n if ((0, _typeof2.default)(Component) === 'object') {\n switch (Component.$$typeof) {\n case _reactIs.ForwardRef:\n return getWrappedName(Component, Component.render, 'ForwardRef');\n\n case _reactIs.Memo:\n return getWrappedName(Component, Component.type, 'memo');\n\n default:\n return undefined;\n }\n }\n\n return undefined;\n}", "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = HTMLElementType;\n\nfunction HTMLElementType(props, propName, componentName, location, propFullName) {\n if (process.env.NODE_ENV === 'production') {\n return null;\n }\n\n var propValue = props[propName];\n var safePropName = propFullName || propName;\n\n if (propValue == null) {\n return null;\n }\n\n if (propValue && propValue.nodeType !== 1) {\n return new Error(\"Invalid \".concat(location, \" `\").concat(safePropName, \"` supplied to `\").concat(componentName, \"`. \") + \"Expected an HTMLElement.\");\n }\n\n return null;\n}", "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\n/* eslint-disable */\n// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028\nvar _default = typeof window != 'undefined' && window.Math == Math ? window : typeof self != 'undefined' && self.Math == Math ? self : Function('return this')();\n\nexports.default = _default;", "\"use strict\";\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\");\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nvar _propTypes = _interopRequireDefault(require(\"prop-types\"));\n\nvar refType = _propTypes.default.oneOfType([_propTypes.default.func, _propTypes.default.object]);\n\nvar _default = refType;\nexports.default = _default;", "/** @license Material-UI v4.11.3\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\"use strict\";\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\");\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nObject.defineProperty(exports, \"chainPropTypes\", {\n enumerable: true,\n get: function get() {\n return _chainPropTypes.default;\n }\n});\nObject.defineProperty(exports, \"deepmerge\", {\n enumerable: true,\n get: function get() {\n return _deepmerge.default;\n }\n});\nObject.defineProperty(exports, \"elementAcceptingRef\", {\n enumerable: true,\n get: function get() {\n return _elementAcceptingRef.default;\n }\n});\nObject.defineProperty(exports, \"elementTypeAcceptingRef\", {\n enumerable: true,\n get: function get() {\n return _elementTypeAcceptingRef.default;\n }\n});\nObject.defineProperty(exports, \"exactProp\", {\n enumerable: true,\n get: function get() {\n return _exactProp.default;\n }\n});\nObject.defineProperty(exports, \"formatMuiErrorMessage\", {\n enumerable: true,\n get: function get() {\n return _formatMuiErrorMessage.default;\n }\n});\nObject.defineProperty(exports, \"getDisplayName\", {\n enumerable: true,\n get: function get() {\n return _getDisplayName.default;\n }\n});\nObject.defineProperty(exports, \"HTMLElementType\", {\n enumerable: true,\n get: function get() {\n return _HTMLElementType.default;\n }\n});\nObject.defineProperty(exports, \"ponyfillGlobal\", {\n enumerable: true,\n get: function get() {\n return _ponyfillGlobal.default;\n }\n});\nObject.defineProperty(exports, \"refType\", {\n enumerable: true,\n get: function get() {\n return _refType.default;\n }\n});\n\nvar _chainPropTypes = _interopRequireDefault(require(\"./chainPropTypes\"));\n\nvar _deepmerge = _interopRequireDefault(require(\"./deepmerge\"));\n\nvar _elementAcceptingRef = _interopRequireDefault(require(\"./elementAcceptingRef\"));\n\nvar _elementTypeAcceptingRef = _interopRequireDefault(require(\"./elementTypeAcceptingRef\"));\n\nvar _exactProp = _interopRequireDefault(require(\"./exactProp\"));\n\nvar _formatMuiErrorMessage = _interopRequireDefault(require(\"./formatMuiErrorMessage\"));\n\nvar _getDisplayName = _interopRequireDefault(require(\"./getDisplayName\"));\n\nvar _HTMLElementType = _interopRequireDefault(require(\"./HTMLElementType\"));\n\nvar _ponyfillGlobal = _interopRequireDefault(require(\"./ponyfillGlobal\"));\n\nvar _refType = _interopRequireDefault(require(\"./refType\"));", "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.hexToRgb = hexToRgb;\nexports.rgbToHex = rgbToHex;\nexports.hslToRgb = hslToRgb;\nexports.decomposeColor = decomposeColor;\nexports.recomposeColor = recomposeColor;\nexports.getContrastRatio = getContrastRatio;\nexports.getLuminance = getLuminance;\nexports.emphasize = emphasize;\nexports.fade = fade;\nexports.alpha = alpha;\nexports.darken = darken;\nexports.lighten = lighten;\n\nvar _utils = require(\"@material-ui/utils\");\n\n/* eslint-disable no-use-before-define */\n\n/**\n * Returns a number whose value is limited to the given range.\n *\n * @param {number} value The value to be clamped\n * @param {number} min The lower boundary of the output range\n * @param {number} max The upper boundary of the output range\n * @returns {number} A number in the range [min, max]\n */\nfunction clamp(value) {\n var min = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;\n var max = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;\n\n if (process.env.NODE_ENV !== 'production') {\n if (value < min || value > max) {\n console.error(\"Material-UI: The value provided \".concat(value, \" is out of range [\").concat(min, \", \").concat(max, \"].\"));\n }\n }\n\n return Math.min(Math.max(min, value), max);\n}\n/**\n * Converts a color from CSS hex format to CSS rgb format.\n *\n * @param {string} color - Hex color, i.e. #nnn or #nnnnnn\n * @returns {string} A CSS rgb color string\n */\n\n\nfunction hexToRgb(color) {\n color = color.substr(1);\n var re = new RegExp(\".{1,\".concat(color.length >= 6 ? 2 : 1, \"}\"), 'g');\n var colors = color.match(re);\n\n if (colors && colors[0].length === 1) {\n colors = colors.map(function (n) {\n return n + n;\n });\n }\n\n return colors ? \"rgb\".concat(colors.length === 4 ? 'a' : '', \"(\").concat(colors.map(function (n, index) {\n return index < 3 ? parseInt(n, 16) : Math.round(parseInt(n, 16) / 255 * 1000) / 1000;\n }).join(', '), \")\") : '';\n}\n\nfunction intToHex(int) {\n var hex = int.toString(16);\n return hex.length === 1 ? \"0\".concat(hex) : hex;\n}\n/**\n * Converts a color from CSS rgb format to CSS hex format.\n *\n * @param {string} color - RGB color, i.e. rgb(n, n, n)\n * @returns {string} A CSS rgb color string, i.e. #nnnnnn\n */\n\n\nfunction rgbToHex(color) {\n // Idempotent\n if (color.indexOf('#') === 0) {\n return color;\n }\n\n var _decomposeColor = decomposeColor(color),\n values = _decomposeColor.values;\n\n return \"#\".concat(values.map(function (n) {\n return intToHex(n);\n }).join(''));\n}\n/**\n * Converts a color from hsl format to rgb format.\n *\n * @param {string} color - HSL color values\n * @returns {string} rgb color values\n */\n\n\nfunction hslToRgb(color) {\n color = decomposeColor(color);\n var _color = color,\n values = _color.values;\n var h = values[0];\n var s = values[1] / 100;\n var l = values[2] / 100;\n var a = s * Math.min(l, 1 - l);\n\n var f = function f(n) {\n var k = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : (n + h / 30) % 12;\n return l - a * Math.max(Math.min(k - 3, 9 - k, 1), -1);\n };\n\n var type = 'rgb';\n var rgb = [Math.round(f(0) * 255), Math.round(f(8) * 255), Math.round(f(4) * 255)];\n\n if (color.type === 'hsla') {\n type += 'a';\n rgb.push(values[3]);\n }\n\n return recomposeColor({\n type: type,\n values: rgb\n });\n}\n/**\n * Returns an object with the type and values of a color.\n *\n * Note: Does not support rgb % values.\n *\n * @param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()\n * @returns {object} - A MUI color object: {type: string, values: number[]}\n */\n\n\nfunction decomposeColor(color) {\n // Idempotent\n if (color.type) {\n return color;\n }\n\n if (color.charAt(0) === '#') {\n return decomposeColor(hexToRgb(color));\n }\n\n var marker = color.indexOf('(');\n var type = color.substring(0, marker);\n\n if (['rgb', 'rgba', 'hsl', 'hsla'].indexOf(type) === -1) {\n throw new Error(process.env.NODE_ENV !== \"production\" ? \"Material-UI: Unsupported `\".concat(color, \"` color.\\nWe support the following formats: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla().\") : (0, _utils.formatMuiErrorMessage)(3, color));\n }\n\n var values = color.substring(marker + 1, color.length - 1).split(',');\n values = values.map(function (value) {\n return parseFloat(value);\n });\n return {\n type: type,\n values: values\n };\n}\n/**\n * Converts a color object with type and values to a string.\n *\n * @param {object} color - Decomposed color\n * @param {string} color.type - One of: 'rgb', 'rgba', 'hsl', 'hsla'\n * @param {array} color.values - [n,n,n] or [n,n,n,n]\n * @returns {string} A CSS color string\n */\n\n\nfunction recomposeColor(color) {\n var type = color.type;\n var values = color.values;\n\n if (type.indexOf('rgb') !== -1) {\n // Only convert the first 3 values to int (i.e. not alpha)\n values = values.map(function (n, i) {\n return i < 3 ? parseInt(n, 10) : n;\n });\n } else if (type.indexOf('hsl') !== -1) {\n values[1] = \"\".concat(values[1], \"%\");\n values[2] = \"\".concat(values[2], \"%\");\n }\n\n return \"\".concat(type, \"(\").concat(values.join(', '), \")\");\n}\n/**\n * Calculates the contrast ratio between two colors.\n *\n * Formula: https://www.w3.org/TR/WCAG20-TECHS/G17.html#G17-tests\n *\n * @param {string} foreground - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()\n * @param {string} background - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()\n * @returns {number} A contrast ratio value in the range 0 - 21.\n */\n\n\nfunction getContrastRatio(foreground, background) {\n var lumA = getLuminance(foreground);\n var lumB = getLuminance(background);\n return (Math.max(lumA, lumB) + 0.05) / (Math.min(lumA, lumB) + 0.05);\n}\n/**\n * The relative brightness of any point in a color space,\n * normalized to 0 for darkest black and 1 for lightest white.\n *\n * Formula: https://www.w3.org/TR/WCAG20-TECHS/G17.html#G17-tests\n *\n * @param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()\n * @returns {number} The relative brightness of the color in the range 0 - 1\n */\n\n\nfunction getLuminance(color) {\n color = decomposeColor(color);\n var rgb = color.type === 'hsl' ? decomposeColor(hslToRgb(color)).values : color.values;\n rgb = rgb.map(function (val) {\n val /= 255; // normalized\n\n return val <= 0.03928 ? val / 12.92 : Math.pow((val + 0.055) / 1.055, 2.4);\n }); // Truncate at 3 digits\n\n return Number((0.2126 * rgb[0] + 0.7152 * rgb[1] + 0.0722 * rgb[2]).toFixed(3));\n}\n/**\n * Darken or lighten a color, depending on its luminance.\n * Light colors are darkened, dark colors are lightened.\n *\n * @param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()\n * @param {number} coefficient=0.15 - multiplier in the range 0 - 1\n * @returns {string} A CSS color string. Hex input values are returned as rgb\n */\n\n\nfunction emphasize(color) {\n var coefficient = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0.15;\n return getLuminance(color) > 0.5 ? darken(color, coefficient) : lighten(color, coefficient);\n}\n\nvar warnedOnce = false;\n/**\n * Set the absolute transparency of a color.\n * Any existing alpha values are overwritten.\n *\n * @param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()\n * @param {number} value - value to set the alpha channel to in the range 0 -1\n * @returns {string} A CSS color string. Hex input values are returned as rgb\n *\n * @deprecated\n * Use `import { alpha } from '@material-ui/core/styles'` instead.\n */\n\nfunction fade(color, value) {\n if (process.env.NODE_ENV !== 'production') {\n if (!warnedOnce) {\n warnedOnce = true;\n console.error(['Material-UI: The `fade` color utility was renamed to `alpha` to better describe its functionality.', '', \"You should use `import { alpha } from '@material-ui/core/styles'`\"].join('\\n'));\n }\n }\n\n return alpha(color, value);\n}\n/**\n * Set the absolute transparency of a color.\n * Any existing alpha value is overwritten.\n *\n * @param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()\n * @param {number} value - value to set the alpha channel to in the range 0-1\n * @returns {string} A CSS color string. Hex input values are returned as rgb\n */\n\n\nfunction alpha(color, value) {\n color = decomposeColor(color);\n value = clamp(value);\n\n if (color.type === 'rgb' || color.type === 'hsl') {\n color.type += 'a';\n }\n\n color.values[3] = value;\n return recomposeColor(color);\n}\n/**\n * Darkens a color.\n *\n * @param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()\n * @param {number} coefficient - multiplier in the range 0 - 1\n * @returns {string} A CSS color string. Hex input values are returned as rgb\n */\n\n\nfunction darken(color, coefficient) {\n color = decomposeColor(color);\n coefficient = clamp(coefficient);\n\n if (color.type.indexOf('hsl') !== -1) {\n color.values[2] *= 1 - coefficient;\n } else if (color.type.indexOf('rgb') !== -1) {\n for (var i = 0; i < 3; i += 1) {\n color.values[i] *= 1 - coefficient;\n }\n }\n\n return recomposeColor(color);\n}\n/**\n * Lightens a color.\n *\n * @param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()\n * @param {number} coefficient - multiplier in the range 0 - 1\n * @returns {string} A CSS color string. Hex input values are returned as rgb\n */\n\n\nfunction lighten(color, coefficient) {\n color = decomposeColor(color);\n coefficient = clamp(coefficient);\n\n if (color.type.indexOf('hsl') !== -1) {\n color.values[2] += (100 - color.values[2]) * coefficient;\n } else if (color.type.indexOf('rgb') !== -1) {\n for (var i = 0; i < 3; i += 1) {\n color.values[i] += (255 - color.values[i]) * coefficient;\n }\n }\n\n return recomposeColor(color);\n}", "function _objectWithoutPropertiesLoose(r, e) {\n if (null == r) return {};\n var t = {};\n for (var n in r) if ({}.hasOwnProperty.call(r, n)) {\n if (e.includes(n)) continue;\n t[n] = r[n];\n }\n return t;\n}\nmodule.exports = _objectWithoutPropertiesLoose, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;", "var objectWithoutPropertiesLoose = require(\"./objectWithoutPropertiesLoose.js\");\nfunction _objectWithoutProperties(e, t) {\n if (null == e) return {};\n var o,\n r,\n i = objectWithoutPropertiesLoose(e, t);\n if (Object.getOwnPropertySymbols) {\n var s = Object.getOwnPropertySymbols(e);\n for (r = 0; r < s.length; r++) o = s[r], t.includes(o) || {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]);\n }\n return i;\n}\nmodule.exports = _objectWithoutProperties, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;", "\"use strict\";\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\");\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = createBreakpoints;\nexports.keys = void 0;\n\nvar _extends2 = _interopRequireDefault(require(\"@babel/runtime/helpers/extends\"));\n\nvar _objectWithoutProperties2 = _interopRequireDefault(require(\"@babel/runtime/helpers/objectWithoutProperties\"));\n\n// Sorted ASC by size. That's important.\n// It can't be configured as it's used statically for propTypes.\nvar keys = ['xs', 'sm', 'md', 'lg', 'xl']; // Keep in mind that @media is inclusive by the CSS specification.\n\nexports.keys = keys;\n\nfunction createBreakpoints(breakpoints) {\n var _breakpoints$values = breakpoints.values,\n values = _breakpoints$values === void 0 ? {\n xs: 0,\n sm: 600,\n md: 960,\n lg: 1280,\n xl: 1920\n } : _breakpoints$values,\n _breakpoints$unit = breakpoints.unit,\n unit = _breakpoints$unit === void 0 ? 'px' : _breakpoints$unit,\n _breakpoints$step = breakpoints.step,\n step = _breakpoints$step === void 0 ? 5 : _breakpoints$step,\n other = (0, _objectWithoutProperties2.default)(breakpoints, [\"values\", \"unit\", \"step\"]);\n\n function up(key) {\n var value = typeof values[key] === 'number' ? values[key] : key;\n return \"@media (min-width:\".concat(value).concat(unit, \")\");\n }\n\n function down(key) {\n var endIndex = keys.indexOf(key) + 1;\n var upperbound = values[keys[endIndex]];\n\n if (endIndex === keys.length) {\n // xl down applies to all sizes\n return up('xs');\n }\n\n var value = typeof upperbound === 'number' && endIndex > 0 ? upperbound : key;\n return \"@media (max-width:\".concat(value - step / 100).concat(unit, \")\");\n }\n\n function between(start, end) {\n var endIndex = keys.indexOf(end);\n\n if (endIndex === keys.length - 1) {\n return up(start);\n }\n\n return \"@media (min-width:\".concat(typeof values[start] === 'number' ? values[start] : start).concat(unit, \") and \") + \"(max-width:\".concat((endIndex !== -1 && typeof values[keys[endIndex + 1]] === 'number' ? values[keys[endIndex + 1]] : end) - step / 100).concat(unit, \")\");\n }\n\n function only(key) {\n return between(key, key);\n }\n\n var warnedOnce = false;\n\n function width(key) {\n if (process.env.NODE_ENV !== 'production') {\n if (!warnedOnce) {\n warnedOnce = true;\n console.warn([\"Material-UI: The `theme.breakpoints.width` utility is deprecated because it's redundant.\", 'Use the `theme.breakpoints.values` instead.'].join('\\n'));\n }\n }\n\n return values[key];\n }\n\n return (0, _extends2.default)({\n keys: keys,\n values: values,\n up: up,\n down: down,\n between: between,\n only: only,\n width: width\n }, other);\n}", "\"use strict\";\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\");\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = createMixins;\n\nvar _defineProperty2 = _interopRequireDefault(require(\"@babel/runtime/helpers/defineProperty\"));\n\nvar _extends3 = _interopRequireDefault(require(\"@babel/runtime/helpers/extends\"));\n\nfunction createMixins(breakpoints, spacing, mixins) {\n var _toolbar;\n\n return (0, _extends3.default)({\n gutters: function gutters() {\n var styles = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n console.warn(['Material-UI: theme.mixins.gutters() is deprecated.', 'You can use the source of the mixin directly:', \"\\n paddingLeft: theme.spacing(2),\\n paddingRight: theme.spacing(2),\\n [theme.breakpoints.up('sm')]: {\\n paddingLeft: theme.spacing(3),\\n paddingRight: theme.spacing(3),\\n },\\n \"].join('\\n'));\n return (0, _extends3.default)({\n paddingLeft: spacing(2),\n paddingRight: spacing(2)\n }, styles, (0, _defineProperty2.default)({}, breakpoints.up('sm'), (0, _extends3.default)({\n paddingLeft: spacing(3),\n paddingRight: spacing(3)\n }, styles[breakpoints.up('sm')])));\n },\n toolbar: (_toolbar = {\n minHeight: 56\n }, (0, _defineProperty2.default)(_toolbar, \"\".concat(breakpoints.up('xs'), \" and (orientation: landscape)\"), {\n minHeight: 48\n }), (0, _defineProperty2.default)(_toolbar, breakpoints.up('sm'), {\n minHeight: 64\n }), _toolbar)\n }, mixins);\n}", "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar common = {\n black: '#000',\n white: '#fff'\n};\nvar _default = common;\nexports.default = _default;", "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar grey = {\n 50: '#fafafa',\n 100: '#f5f5f5',\n 200: '#eeeeee',\n 300: '#e0e0e0',\n 400: '#bdbdbd',\n 500: '#9e9e9e',\n 600: '#757575',\n 700: '#616161',\n 800: '#424242',\n 900: '#212121',\n A100: '#d5d5d5',\n A200: '#aaaaaa',\n A400: '#303030',\n A700: '#616161'\n};\nvar _default = grey;\nexports.default = _default;", "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar indigo = {\n 50: '#e8eaf6',\n 100: '#c5cae9',\n 200: '#9fa8da',\n 300: '#7986cb',\n 400: '#5c6bc0',\n 500: '#3f51b5',\n 600: '#3949ab',\n 700: '#303f9f',\n 800: '#283593',\n 900: '#1a237e',\n A100: '#8c9eff',\n A200: '#536dfe',\n A400: '#3d5afe',\n A700: '#304ffe'\n};\nvar _default = indigo;\nexports.default = _default;", "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar pink = {\n 50: '#fce4ec',\n 100: '#f8bbd0',\n 200: '#f48fb1',\n 300: '#f06292',\n 400: '#ec407a',\n 500: '#e91e63',\n 600: '#d81b60',\n 700: '#c2185b',\n 800: '#ad1457',\n 900: '#880e4f',\n A100: '#ff80ab',\n A200: '#ff4081',\n A400: '#f50057',\n A700: '#c51162'\n};\nvar _default = pink;\nexports.default = _default;", "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar red = {\n 50: '#ffebee',\n 100: '#ffcdd2',\n 200: '#ef9a9a',\n 300: '#e57373',\n 400: '#ef5350',\n 500: '#f44336',\n 600: '#e53935',\n 700: '#d32f2f',\n 800: '#c62828',\n 900: '#b71c1c',\n A100: '#ff8a80',\n A200: '#ff5252',\n A400: '#ff1744',\n A700: '#d50000'\n};\nvar _default = red;\nexports.default = _default;", "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar orange = {\n 50: '#fff3e0',\n 100: '#ffe0b2',\n 200: '#ffcc80',\n 300: '#ffb74d',\n 400: '#ffa726',\n 500: '#ff9800',\n 600: '#fb8c00',\n 700: '#f57c00',\n 800: '#ef6c00',\n 900: '#e65100',\n A100: '#ffd180',\n A200: '#ffab40',\n A400: '#ff9100',\n A700: '#ff6d00'\n};\nvar _default = orange;\nexports.default = _default;", "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar blue = {\n 50: '#e3f2fd',\n 100: '#bbdefb',\n 200: '#90caf9',\n 300: '#64b5f6',\n 400: '#42a5f5',\n 500: '#2196f3',\n 600: '#1e88e5',\n 700: '#1976d2',\n 800: '#1565c0',\n 900: '#0d47a1',\n A100: '#82b1ff',\n A200: '#448aff',\n A400: '#2979ff',\n A700: '#2962ff'\n};\nvar _default = blue;\nexports.default = _default;", "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar green = {\n 50: '#e8f5e9',\n 100: '#c8e6c9',\n 200: '#a5d6a7',\n 300: '#81c784',\n 400: '#66bb6a',\n 500: '#4caf50',\n 600: '#43a047',\n 700: '#388e3c',\n 800: '#2e7d32',\n 900: '#1b5e20',\n A100: '#b9f6ca',\n A200: '#69f0ae',\n A400: '#00e676',\n A700: '#00c853'\n};\nvar _default = green;\nexports.default = _default;", "\"use strict\";\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\");\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = createPalette;\nexports.dark = exports.light = void 0;\n\nvar _extends2 = _interopRequireDefault(require(\"@babel/runtime/helpers/extends\"));\n\nvar _objectWithoutProperties2 = _interopRequireDefault(require(\"@babel/runtime/helpers/objectWithoutProperties\"));\n\nvar _utils = require(\"@material-ui/utils\");\n\nvar _common = _interopRequireDefault(require(\"../colors/common\"));\n\nvar _grey = _interopRequireDefault(require(\"../colors/grey\"));\n\nvar _indigo = _interopRequireDefault(require(\"../colors/indigo\"));\n\nvar _pink = _interopRequireDefault(require(\"../colors/pink\"));\n\nvar _red = _interopRequireDefault(require(\"../colors/red\"));\n\nvar _orange = _interopRequireDefault(require(\"../colors/orange\"));\n\nvar _blue = _interopRequireDefault(require(\"../colors/blue\"));\n\nvar _green = _interopRequireDefault(require(\"../colors/green\"));\n\nvar _colorManipulator = require(\"./colorManipulator\");\n\nvar light = {\n // The colors used to style the text.\n text: {\n // The most important text.\n primary: 'rgba(0, 0, 0, 0.87)',\n // Secondary text.\n secondary: 'rgba(0, 0, 0, 0.54)',\n // Disabled text have even lower visual prominence.\n disabled: 'rgba(0, 0, 0, 0.38)',\n // Text hints.\n hint: 'rgba(0, 0, 0, 0.38)'\n },\n // The color used to divide different elements.\n divider: 'rgba(0, 0, 0, 0.12)',\n // The background colors used to style the surfaces.\n // Consistency between these values is important.\n background: {\n paper: _common.default.white,\n default: _grey.default[50]\n },\n // The colors used to style the action elements.\n action: {\n // The color of an active action like an icon button.\n active: 'rgba(0, 0, 0, 0.54)',\n // The color of an hovered action.\n hover: 'rgba(0, 0, 0, 0.04)',\n hoverOpacity: 0.04,\n // The color of a selected action.\n selected: 'rgba(0, 0, 0, 0.08)',\n selectedOpacity: 0.08,\n // The color of a disabled action.\n disabled: 'rgba(0, 0, 0, 0.26)',\n // The background color of a disabled action.\n disabledBackground: 'rgba(0, 0, 0, 0.12)',\n disabledOpacity: 0.38,\n focus: 'rgba(0, 0, 0, 0.12)',\n focusOpacity: 0.12,\n activatedOpacity: 0.12\n }\n};\nexports.light = light;\nvar dark = {\n text: {\n primary: _common.default.white,\n secondary: 'rgba(255, 255, 255, 0.7)',\n disabled: 'rgba(255, 255, 255, 0.5)',\n hint: 'rgba(255, 255, 255, 0.5)',\n icon: 'rgba(255, 255, 255, 0.5)'\n },\n divider: 'rgba(255, 255, 255, 0.12)',\n background: {\n paper: _grey.default[800],\n default: '#303030'\n },\n action: {\n active: _common.default.white,\n hover: 'rgba(255, 255, 255, 0.08)',\n hoverOpacity: 0.08,\n selected: 'rgba(255, 255, 255, 0.16)',\n selectedOpacity: 0.16,\n disabled: 'rgba(255, 255, 255, 0.3)',\n disabledBackground: 'rgba(255, 255, 255, 0.12)',\n disabledOpacity: 0.38,\n focus: 'rgba(255, 255, 255, 0.12)',\n focusOpacity: 0.12,\n activatedOpacity: 0.24\n }\n};\nexports.dark = dark;\n\nfunction addLightOrDark(intent, direction, shade, tonalOffset) {\n var tonalOffsetLight = tonalOffset.light || tonalOffset;\n var tonalOffsetDark = tonalOffset.dark || tonalOffset * 1.5;\n\n if (!intent[direction]) {\n if (intent.hasOwnProperty(shade)) {\n intent[direction] = intent[shade];\n } else if (direction === 'light') {\n intent.light = (0, _colorManipulator.lighten)(intent.main, tonalOffsetLight);\n } else if (direction === 'dark') {\n intent.dark = (0, _colorManipulator.darken)(intent.main, tonalOffsetDark);\n }\n }\n}\n\nfunction createPalette(palette) {\n var _palette$primary = palette.primary,\n primary = _palette$primary === void 0 ? {\n light: _indigo.default[300],\n main: _indigo.default[500],\n dark: _indigo.default[700]\n } : _palette$primary,\n _palette$secondary = palette.secondary,\n secondary = _palette$secondary === void 0 ? {\n light: _pink.default.A200,\n main: _pink.default.A400,\n dark: _pink.default.A700\n } : _palette$secondary,\n _palette$error = palette.error,\n error = _palette$error === void 0 ? {\n light: _red.default[300],\n main: _red.default[500],\n dark: _red.default[700]\n } : _palette$error,\n _palette$warning = palette.warning,\n warning = _palette$warning === void 0 ? {\n light: _orange.default[300],\n main: _orange.default[500],\n dark: _orange.default[700]\n } : _palette$warning,\n _palette$info = palette.info,\n info = _palette$info === void 0 ? {\n light: _blue.default[300],\n main: _blue.default[500],\n dark: _blue.default[700]\n } : _palette$info,\n _palette$success = palette.success,\n success = _palette$success === void 0 ? {\n light: _green.default[300],\n main: _green.default[500],\n dark: _green.default[700]\n } : _palette$success,\n _palette$type = palette.type,\n type = _palette$type === void 0 ? 'light' : _palette$type,\n _palette$contrastThre = palette.contrastThreshold,\n contrastThreshold = _palette$contrastThre === void 0 ? 3 : _palette$contrastThre,\n _palette$tonalOffset = palette.tonalOffset,\n tonalOffset = _palette$tonalOffset === void 0 ? 0.2 : _palette$tonalOffset,\n other = (0, _objectWithoutProperties2.default)(palette, [\"primary\", \"secondary\", \"error\", \"warning\", \"info\", \"success\", \"type\", \"contrastThreshold\", \"tonalOffset\"]); // Use the same logic as\n // Bootstrap: https://github.com/twbs/bootstrap/blob/1d6e3710dd447de1a200f29e8fa521f8a0908f70/scss/_functions.scss#L59\n // and material-components-web https://github.com/material-components/material-components-web/blob/ac46b8863c4dab9fc22c4c662dc6bd1b65dd652f/packages/mdc-theme/_functions.scss#L54\n\n function getContrastText(background) {\n var contrastText = (0, _colorManipulator.getContrastRatio)(background, dark.text.primary) >= contrastThreshold ? dark.text.primary : light.text.primary;\n\n if (process.env.NODE_ENV !== 'production') {\n var contrast = (0, _colorManipulator.getContrastRatio)(background, contrastText);\n\n if (contrast < 3) {\n console.error([\"Material-UI: The contrast ratio of \".concat(contrast, \":1 for \").concat(contrastText, \" on \").concat(background), 'falls below the WCAG recommended absolute minimum contrast ratio of 3:1.', 'https://www.w3.org/TR/2008/REC-WCAG20-20081211/#visual-audio-contrast-contrast'].join('\\n'));\n }\n }\n\n return contrastText;\n }\n\n var augmentColor = function augmentColor(color) {\n var mainShade = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 500;\n var lightShade = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 300;\n var darkShade = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 700;\n color = (0, _extends2.default)({}, color);\n\n if (!color.main && color[mainShade]) {\n color.main = color[mainShade];\n }\n\n if (!color.main) {\n throw new Error(process.env.NODE_ENV !== \"production\" ? \"Material-UI: The color provided to augmentColor(color) is invalid.\\nThe color object needs to have a `main` property or a `\".concat(mainShade, \"` property.\") : (0, _utils.formatMuiErrorMessage)(4, mainShade));\n }\n\n if (typeof color.main !== 'string') {\n throw new Error(process.env.NODE_ENV !== \"production\" ? \"Material-UI: The color provided to augmentColor(color) is invalid.\\n`color.main` should be a string, but `\".concat(JSON.stringify(color.main), \"` was provided instead.\\n\\nDid you intend to use one of the following approaches?\\n\\nimport {\\xA0green } from \\\"@material-ui/core/colors\\\";\\n\\nconst theme1 = createTheme({ palette: {\\n primary: green,\\n} });\\n\\nconst theme2 = createTheme({ palette: {\\n primary: { main: green[500] },\\n} });\") : _formatMuiErrorMessage(5, JSON.stringify(color.main)));\n }\n\n addLightOrDark(color, 'light', lightShade, tonalOffset);\n addLightOrDark(color, 'dark', darkShade, tonalOffset);\n\n if (!color.contrastText) {\n color.contrastText = getContrastText(color.main);\n }\n\n return color;\n };\n\n var types = {\n dark: dark,\n light: light\n };\n\n if (process.env.NODE_ENV !== 'production') {\n if (!types[type]) {\n console.error(\"Material-UI: The palette type `\".concat(type, \"` is not supported.\"));\n }\n }\n\n var paletteOutput = (0, _utils.deepmerge)((0, _extends2.default)({\n // A collection of common colors.\n common: _common.default,\n // The palette type, can be light or dark.\n type: type,\n // The colors used to represent primary interface elements for a user.\n primary: augmentColor(primary),\n // The colors used to represent secondary interface elements for a user.\n secondary: augmentColor(secondary, 'A400', 'A200', 'A700'),\n // The colors used to represent interface elements that the user should be made aware of.\n error: augmentColor(error),\n // The colors used to represent potentially dangerous actions or important messages.\n warning: augmentColor(warning),\n // The colors used to present information to the user that is neutral and not necessarily important.\n info: augmentColor(info),\n // The colors used to indicate the successful completion of an action that user triggered.\n success: augmentColor(success),\n // The grey colors.\n grey: _grey.default,\n // Used by `getContrastText()` to maximize the contrast between\n // the background and the text.\n contrastThreshold: contrastThreshold,\n // Takes a background color and returns the text color that maximizes the contrast.\n getContrastText: getContrastText,\n // Generate a rich color object.\n augmentColor: augmentColor,\n // Used by the functions below to shift a color's luminance by approximately\n // two indexes within its tonal palette.\n // E.g., shift from Red 500 to Red 300 or Red 700.\n tonalOffset: tonalOffset\n }, types[type]), other);\n return paletteOutput;\n}", "\"use strict\";\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\");\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = createTypography;\n\nvar _extends2 = _interopRequireDefault(require(\"@babel/runtime/helpers/extends\"));\n\nvar _objectWithoutProperties2 = _interopRequireDefault(require(\"@babel/runtime/helpers/objectWithoutProperties\"));\n\nvar _utils = require(\"@material-ui/utils\");\n\nfunction round(value) {\n return Math.round(value * 1e5) / 1e5;\n}\n\nvar warnedOnce = false;\n\nfunction roundWithDeprecationWarning(value) {\n if (process.env.NODE_ENV !== 'production') {\n if (!warnedOnce) {\n console.warn(['Material-UI: The `theme.typography.round` helper is deprecated.', 'Head to https://mui.com/r/migration-v4/#theme for a migration path.'].join('\\n'));\n warnedOnce = true;\n }\n }\n\n return round(value);\n}\n\nvar caseAllCaps = {\n textTransform: 'uppercase'\n};\nvar defaultFontFamily = '\"Roboto\", \"Helvetica\", \"Arial\", sans-serif';\n/**\n * @see @link{https://material.io/design/typography/the-type-system.html}\n * @see @link{https://material.io/design/typography/understanding-typography.html}\n */\n\nfunction createTypography(palette, typography) {\n var _ref = typeof typography === 'function' ? typography(palette) : typography,\n _ref$fontFamily = _ref.fontFamily,\n fontFamily = _ref$fontFamily === void 0 ? defaultFontFamily : _ref$fontFamily,\n _ref$fontSize = _ref.fontSize,\n fontSize = _ref$fontSize === void 0 ? 14 : _ref$fontSize,\n _ref$fontWeightLight = _ref.fontWeightLight,\n fontWeightLight = _ref$fontWeightLight === void 0 ? 300 : _ref$fontWeightLight,\n _ref$fontWeightRegula = _ref.fontWeightRegular,\n fontWeightRegular = _ref$fontWeightRegula === void 0 ? 400 : _ref$fontWeightRegula,\n _ref$fontWeightMedium = _ref.fontWeightMedium,\n fontWeightMedium = _ref$fontWeightMedium === void 0 ? 500 : _ref$fontWeightMedium,\n _ref$fontWeightBold = _ref.fontWeightBold,\n fontWeightBold = _ref$fontWeightBold === void 0 ? 700 : _ref$fontWeightBold,\n _ref$htmlFontSize = _ref.htmlFontSize,\n htmlFontSize = _ref$htmlFontSize === void 0 ? 16 : _ref$htmlFontSize,\n allVariants = _ref.allVariants,\n pxToRem2 = _ref.pxToRem,\n other = (0, _objectWithoutProperties2.default)(_ref, [\"fontFamily\", \"fontSize\", \"fontWeightLight\", \"fontWeightRegular\", \"fontWeightMedium\", \"fontWeightBold\", \"htmlFontSize\", \"allVariants\", \"pxToRem\"]);\n\n if (process.env.NODE_ENV !== 'production') {\n if (typeof fontSize !== 'number') {\n console.error('Material-UI: `fontSize` is required to be a number.');\n }\n\n if (typeof htmlFontSize !== 'number') {\n console.error('Material-UI: `htmlFontSize` is required to be a number.');\n }\n }\n\n var coef = fontSize / 14;\n\n var pxToRem = pxToRem2 || function (size) {\n return \"\".concat(size / htmlFontSize * coef, \"rem\");\n };\n\n var buildVariant = function buildVariant(fontWeight, size, lineHeight, letterSpacing, casing) {\n return (0, _extends2.default)({\n fontFamily: fontFamily,\n fontWeight: fontWeight,\n fontSize: pxToRem(size),\n // Unitless following https://meyerweb.com/eric/thoughts/2006/02/08/unitless-line-heights/\n lineHeight: lineHeight\n }, fontFamily === defaultFontFamily ? {\n letterSpacing: \"\".concat(round(letterSpacing / size), \"em\")\n } : {}, casing, allVariants);\n };\n\n var variants = {\n h1: buildVariant(fontWeightLight, 96, 1.167, -1.5),\n h2: buildVariant(fontWeightLight, 60, 1.2, -0.5),\n h3: buildVariant(fontWeightRegular, 48, 1.167, 0),\n h4: buildVariant(fontWeightRegular, 34, 1.235, 0.25),\n h5: buildVariant(fontWeightRegular, 24, 1.334, 0),\n h6: buildVariant(fontWeightMedium, 20, 1.6, 0.15),\n subtitle1: buildVariant(fontWeightRegular, 16, 1.75, 0.15),\n subtitle2: buildVariant(fontWeightMedium, 14, 1.57, 0.1),\n body1: buildVariant(fontWeightRegular, 16, 1.5, 0.15),\n body2: buildVariant(fontWeightRegular, 14, 1.43, 0.15),\n button: buildVariant(fontWeightMedium, 14, 1.75, 0.4, caseAllCaps),\n caption: buildVariant(fontWeightRegular, 12, 1.66, 0.4),\n overline: buildVariant(fontWeightRegular, 12, 2.66, 1, caseAllCaps)\n };\n return (0, _utils.deepmerge)((0, _extends2.default)({\n htmlFontSize: htmlFontSize,\n pxToRem: pxToRem,\n round: roundWithDeprecationWarning,\n // TODO v5: remove\n fontFamily: fontFamily,\n fontSize: fontSize,\n fontWeightLight: fontWeightLight,\n fontWeightRegular: fontWeightRegular,\n fontWeightMedium: fontWeightMedium,\n fontWeightBold: fontWeightBold\n }, variants), other, {\n clone: false // No need to clone deep\n\n });\n}", "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar shadowKeyUmbraOpacity = 0.2;\nvar shadowKeyPenumbraOpacity = 0.14;\nvar shadowAmbientShadowOpacity = 0.12;\n\nfunction createShadow() {\n return [\"\".concat(arguments.length <= 0 ? undefined : arguments[0], \"px \").concat(arguments.length <= 1 ? undefined : arguments[1], \"px \").concat(arguments.length <= 2 ? undefined : arguments[2], \"px \").concat(arguments.length <= 3 ? undefined : arguments[3], \"px rgba(0,0,0,\").concat(shadowKeyUmbraOpacity, \")\"), \"\".concat(arguments.length <= 4 ? undefined : arguments[4], \"px \").concat(arguments.length <= 5 ? undefined : arguments[5], \"px \").concat(arguments.length <= 6 ? undefined : arguments[6], \"px \").concat(arguments.length <= 7 ? undefined : arguments[7], \"px rgba(0,0,0,\").concat(shadowKeyPenumbraOpacity, \")\"), \"\".concat(arguments.length <= 8 ? undefined : arguments[8], \"px \").concat(arguments.length <= 9 ? undefined : arguments[9], \"px \").concat(arguments.length <= 10 ? undefined : arguments[10], \"px \").concat(arguments.length <= 11 ? undefined : arguments[11], \"px rgba(0,0,0,\").concat(shadowAmbientShadowOpacity, \")\")].join(',');\n} // Values from https://github.com/material-components/material-components-web/blob/be8747f94574669cb5e7add1a7c54fa41a89cec7/packages/mdc-elevation/_variables.scss\n\n\nvar shadows = ['none', createShadow(0, 2, 1, -1, 0, 1, 1, 0, 0, 1, 3, 0), createShadow(0, 3, 1, -2, 0, 2, 2, 0, 0, 1, 5, 0), createShadow(0, 3, 3, -2, 0, 3, 4, 0, 0, 1, 8, 0), createShadow(0, 2, 4, -1, 0, 4, 5, 0, 0, 1, 10, 0), createShadow(0, 3, 5, -1, 0, 5, 8, 0, 0, 1, 14, 0), createShadow(0, 3, 5, -1, 0, 6, 10, 0, 0, 1, 18, 0), createShadow(0, 4, 5, -2, 0, 7, 10, 1, 0, 2, 16, 1), createShadow(0, 5, 5, -3, 0, 8, 10, 1, 0, 3, 14, 2), createShadow(0, 5, 6, -3, 0, 9, 12, 1, 0, 3, 16, 2), createShadow(0, 6, 6, -3, 0, 10, 14, 1, 0, 4, 18, 3), createShadow(0, 6, 7, -4, 0, 11, 15, 1, 0, 4, 20, 3), createShadow(0, 7, 8, -4, 0, 12, 17, 2, 0, 5, 22, 4), createShadow(0, 7, 8, -4, 0, 13, 19, 2, 0, 5, 24, 4), createShadow(0, 7, 9, -4, 0, 14, 21, 2, 0, 5, 26, 4), createShadow(0, 8, 9, -5, 0, 15, 22, 2, 0, 6, 28, 5), createShadow(0, 8, 10, -5, 0, 16, 24, 2, 0, 6, 30, 5), createShadow(0, 8, 11, -5, 0, 17, 26, 2, 0, 6, 32, 5), createShadow(0, 9, 11, -5, 0, 18, 28, 2, 0, 7, 34, 6), createShadow(0, 9, 12, -6, 0, 19, 29, 2, 0, 7, 36, 6), createShadow(0, 10, 13, -6, 0, 20, 31, 3, 0, 8, 38, 7), createShadow(0, 10, 13, -6, 0, 21, 33, 3, 0, 8, 40, 7), createShadow(0, 10, 14, -6, 0, 22, 35, 3, 0, 8, 42, 7), createShadow(0, 11, 14, -7, 0, 23, 36, 3, 0, 9, 44, 8), createShadow(0, 11, 15, -7, 0, 24, 38, 3, 0, 9, 46, 8)];\nvar _default = shadows;\nexports.default = _default;", "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar shape = {\n borderRadius: 4\n};\nvar _default = shape;\nexports.default = _default;", "\"use strict\";\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\");\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nvar _propTypes = _interopRequireDefault(require(\"prop-types\"));\n\nvar responsivePropType = process.env.NODE_ENV !== 'production' ? _propTypes.default.oneOfType([_propTypes.default.number, _propTypes.default.string, _propTypes.default.object, _propTypes.default.array]) : {};\nvar _default = responsivePropType;\nexports.default = _default;", "function _arrayLikeToArray(r, a) {\n (null == a || a > r.length) && (a = r.length);\n for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];\n return n;\n}\nmodule.exports = _arrayLikeToArray, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;", "var arrayLikeToArray = require(\"./arrayLikeToArray.js\");\nfunction _arrayWithoutHoles(r) {\n if (Array.isArray(r)) return arrayLikeToArray(r);\n}\nmodule.exports = _arrayWithoutHoles, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;", "function _iterableToArray(r) {\n if (\"undefined\" != typeof Symbol && null != r[Symbol.iterator] || null != r[\"@@iterator\"]) return Array.from(r);\n}\nmodule.exports = _iterableToArray, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;", "var arrayLikeToArray = require(\"./arrayLikeToArray.js\");\nfunction _unsupportedIterableToArray(r, a) {\n if (r) {\n if (\"string\" == typeof r) return arrayLikeToArray(r, a);\n var t = {}.toString.call(r).slice(8, -1);\n return \"Object\" === t && r.constructor && (t = r.constructor.name), \"Map\" === t || \"Set\" === t ? Array.from(r) : \"Arguments\" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? arrayLikeToArray(r, a) : void 0;\n }\n}\nmodule.exports = _unsupportedIterableToArray, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;", "function _nonIterableSpread() {\n throw new TypeError(\"Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\");\n}\nmodule.exports = _nonIterableSpread, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;", "var arrayWithoutHoles = require(\"./arrayWithoutHoles.js\");\nvar iterableToArray = require(\"./iterableToArray.js\");\nvar unsupportedIterableToArray = require(\"./unsupportedIterableToArray.js\");\nvar nonIterableSpread = require(\"./nonIterableSpread.js\");\nfunction _toConsumableArray(r) {\n return arrayWithoutHoles(r) || iterableToArray(r) || unsupportedIterableToArray(r) || nonIterableSpread();\n}\nmodule.exports = _toConsumableArray, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;", "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nvar _utils = require(\"@material-ui/utils\");\n\nfunction merge(acc, item) {\n if (!item) {\n return acc;\n }\n\n return (0, _utils.deepmerge)(acc, item, {\n clone: false // No need to clone deep, it's way faster.\n\n });\n}\n\nvar _default = merge;\nexports.default = _default;", "\"use strict\";\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\");\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.handleBreakpoints = handleBreakpoints;\nexports.default = void 0;\n\nvar _toConsumableArray2 = _interopRequireDefault(require(\"@babel/runtime/helpers/toConsumableArray\"));\n\nvar _extends2 = _interopRequireDefault(require(\"@babel/runtime/helpers/extends\"));\n\nvar _typeof2 = _interopRequireDefault(require(\"@babel/runtime/helpers/typeof\"));\n\nvar _propTypes = _interopRequireDefault(require(\"prop-types\"));\n\nvar _merge = _interopRequireDefault(require(\"./merge\"));\n\n// The breakpoint **start** at this value.\n// For instance with the first breakpoint xs: [xs, sm[.\nvar values = {\n xs: 0,\n sm: 600,\n md: 960,\n lg: 1280,\n xl: 1920\n};\nvar defaultBreakpoints = {\n // Sorted ASC by size. That's important.\n // It can't be configured as it's used statically for propTypes.\n keys: ['xs', 'sm', 'md', 'lg', 'xl'],\n up: function up(key) {\n return \"@media (min-width:\".concat(values[key], \"px)\");\n }\n};\n\nfunction handleBreakpoints(props, propValue, styleFromPropValue) {\n if (process.env.NODE_ENV !== 'production') {\n if (!props.theme) {\n console.error('Material-UI: You are calling a style function without a theme value.');\n }\n }\n\n if (Array.isArray(propValue)) {\n var themeBreakpoints = props.theme.breakpoints || defaultBreakpoints;\n return propValue.reduce(function (acc, item, index) {\n acc[themeBreakpoints.up(themeBreakpoints.keys[index])] = styleFromPropValue(propValue[index]);\n return acc;\n }, {});\n }\n\n if ((0, _typeof2.default)(propValue) === 'object') {\n var _themeBreakpoints = props.theme.breakpoints || defaultBreakpoints;\n\n return Object.keys(propValue).reduce(function (acc, breakpoint) {\n acc[_themeBreakpoints.up(breakpoint)] = styleFromPropValue(propValue[breakpoint]);\n return acc;\n }, {});\n }\n\n var output = styleFromPropValue(propValue);\n return output;\n}\n\nfunction breakpoints(styleFunction) {\n var newStyleFunction = function newStyleFunction(props) {\n var base = styleFunction(props);\n var themeBreakpoints = props.theme.breakpoints || defaultBreakpoints;\n var extended = themeBreakpoints.keys.reduce(function (acc, key) {\n if (props[key]) {\n acc = acc || {};\n acc[themeBreakpoints.up(key)] = styleFunction((0, _extends2.default)({\n theme: props.theme\n }, props[key]));\n }\n\n return acc;\n }, null);\n return (0, _merge.default)(base, extended);\n };\n\n newStyleFunction.propTypes = process.env.NODE_ENV !== 'production' ? (0, _extends2.default)({}, styleFunction.propTypes, {\n xs: _propTypes.default.object,\n sm: _propTypes.default.object,\n md: _propTypes.default.object,\n lg: _propTypes.default.object,\n xl: _propTypes.default.object\n }) : {};\n newStyleFunction.filterProps = ['xs', 'sm', 'md', 'lg', 'xl'].concat((0, _toConsumableArray2.default)(styleFunction.filterProps));\n return newStyleFunction;\n}\n\nvar _default = breakpoints;\nexports.default = _default;", "\"use strict\";\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\");\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nvar _defineProperty2 = _interopRequireDefault(require(\"@babel/runtime/helpers/defineProperty\"));\n\nvar _responsivePropType = _interopRequireDefault(require(\"./responsivePropType\"));\n\nvar _breakpoints = require(\"./breakpoints\");\n\nfunction getPath(obj, path) {\n if (!path || typeof path !== 'string') {\n return null;\n }\n\n return path.split('.').reduce(function (acc, item) {\n return acc && acc[item] ? acc[item] : null;\n }, obj);\n}\n\nfunction style(options) {\n var prop = options.prop,\n _options$cssProperty = options.cssProperty,\n cssProperty = _options$cssProperty === void 0 ? options.prop : _options$cssProperty,\n themeKey = options.themeKey,\n transform = options.transform;\n\n var fn = function fn(props) {\n if (props[prop] == null) {\n return null;\n }\n\n var propValue = props[prop];\n var theme = props.theme;\n var themeMapping = getPath(theme, themeKey) || {};\n\n var styleFromPropValue = function styleFromPropValue(propValueFinal) {\n var value;\n\n if (typeof themeMapping === 'function') {\n value = themeMapping(propValueFinal);\n } else if (Array.isArray(themeMapping)) {\n value = themeMapping[propValueFinal] || propValueFinal;\n } else {\n value = getPath(themeMapping, propValueFinal) || propValueFinal;\n\n if (transform) {\n value = transform(value);\n }\n }\n\n if (cssProperty === false) {\n return value;\n }\n\n return (0, _defineProperty2.default)({}, cssProperty, value);\n };\n\n return (0, _breakpoints.handleBreakpoints)(props, propValue, styleFromPropValue);\n };\n\n fn.propTypes = process.env.NODE_ENV !== 'production' ? (0, _defineProperty2.default)({}, prop, _responsivePropType.default) : {};\n fn.filterProps = [prop];\n return fn;\n}\n\nvar _default = style;\nexports.default = _default;", "\"use strict\";\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\");\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nvar _extends2 = _interopRequireDefault(require(\"@babel/runtime/helpers/extends\"));\n\nvar _merge = _interopRequireDefault(require(\"./merge\"));\n\nfunction compose() {\n for (var _len = arguments.length, styles = new Array(_len), _key = 0; _key < _len; _key++) {\n styles[_key] = arguments[_key];\n }\n\n var fn = function fn(props) {\n return styles.reduce(function (acc, style) {\n var output = style(props);\n\n if (output) {\n return (0, _merge.default)(acc, output);\n }\n\n return acc;\n }, {});\n }; // Alternative approach that doesn't yield any performance gain.\n // const handlers = styles.reduce((acc, style) => {\n // style.filterProps.forEach(prop => {\n // acc[prop] = style;\n // });\n // return acc;\n // }, {});\n // const fn = props => {\n // return Object.keys(props).reduce((acc, prop) => {\n // if (handlers[prop]) {\n // return merge(acc, handlers[prop](props));\n // }\n // return acc;\n // }, {});\n // };\n\n\n fn.propTypes = process.env.NODE_ENV !== 'production' ? styles.reduce(function (acc, style) {\n return (0, _extends2.default)(acc, style.propTypes);\n }, {}) : {};\n fn.filterProps = styles.reduce(function (acc, style) {\n return acc.concat(style.filterProps);\n }, []);\n return fn;\n}\n\nvar _default = compose;\nexports.default = _default;", "\"use strict\";\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\");\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = exports.borderRadius = exports.borderColor = exports.borderLeft = exports.borderBottom = exports.borderRight = exports.borderTop = exports.border = void 0;\n\nvar _style = _interopRequireDefault(require(\"./style\"));\n\nvar _compose = _interopRequireDefault(require(\"./compose\"));\n\nfunction getBorder(value) {\n if (typeof value !== 'number') {\n return value;\n }\n\n return \"\".concat(value, \"px solid\");\n}\n\nvar border = (0, _style.default)({\n prop: 'border',\n themeKey: 'borders',\n transform: getBorder\n});\nexports.border = border;\nvar borderTop = (0, _style.default)({\n prop: 'borderTop',\n themeKey: 'borders',\n transform: getBorder\n});\nexports.borderTop = borderTop;\nvar borderRight = (0, _style.default)({\n prop: 'borderRight',\n themeKey: 'borders',\n transform: getBorder\n});\nexports.borderRight = borderRight;\nvar borderBottom = (0, _style.default)({\n prop: 'borderBottom',\n themeKey: 'borders',\n transform: getBorder\n});\nexports.borderBottom = borderBottom;\nvar borderLeft = (0, _style.default)({\n prop: 'borderLeft',\n themeKey: 'borders',\n transform: getBorder\n});\nexports.borderLeft = borderLeft;\nvar borderColor = (0, _style.default)({\n prop: 'borderColor',\n themeKey: 'palette'\n});\nexports.borderColor = borderColor;\nvar borderRadius = (0, _style.default)({\n prop: 'borderRadius',\n themeKey: 'shape'\n});\nexports.borderRadius = borderRadius;\nvar borders = (0, _compose.default)(border, borderTop, borderRight, borderBottom, borderLeft, borderColor, borderRadius);\nvar _default = borders;\nexports.default = _default;", "\"use strict\";\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\");\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.css = css;\nexports.default = void 0;\n\nvar _toConsumableArray2 = _interopRequireDefault(require(\"@babel/runtime/helpers/toConsumableArray\"));\n\nvar _extends2 = _interopRequireDefault(require(\"@babel/runtime/helpers/extends\"));\n\nvar _propTypes = _interopRequireDefault(require(\"prop-types\"));\n\nvar _utils = require(\"@material-ui/utils\");\n\nvar _merge = _interopRequireDefault(require(\"./merge\"));\n\nfunction omit(input, fields) {\n var output = {};\n Object.keys(input).forEach(function (prop) {\n if (fields.indexOf(prop) === -1) {\n output[prop] = input[prop];\n }\n });\n return output;\n}\n\nvar warnedOnce = false;\n\nfunction styleFunctionSx(styleFunction) {\n var newStyleFunction = function newStyleFunction(props) {\n var output = styleFunction(props);\n\n if (props.css) {\n return (0, _extends2.default)({}, (0, _merge.default)(output, styleFunction((0, _extends2.default)({\n theme: props.theme\n }, props.css))), omit(props.css, [styleFunction.filterProps]));\n }\n\n if (props.sx) {\n return (0, _extends2.default)({}, (0, _merge.default)(output, styleFunction((0, _extends2.default)({\n theme: props.theme\n }, props.sx))), omit(props.sx, [styleFunction.filterProps]));\n }\n\n return output;\n };\n\n newStyleFunction.propTypes = process.env.NODE_ENV !== 'production' ? (0, _extends2.default)({}, styleFunction.propTypes, {\n css: (0, _utils.chainPropTypes)(_propTypes.default.object, function (props) {\n if (!warnedOnce && props.css !== undefined) {\n warnedOnce = true;\n return new Error('Material-UI: The `css` prop is deprecated, please use the `sx` prop instead.');\n }\n\n return null;\n }),\n sx: _propTypes.default.object\n }) : {};\n newStyleFunction.filterProps = ['css', 'sx'].concat((0, _toConsumableArray2.default)(styleFunction.filterProps));\n return newStyleFunction;\n}\n/**\n *\n * @deprecated\n * The css style function is deprecated. Use the `styleFunctionSx` instead.\n */\n\n\nfunction css(styleFunction) {\n if (process.env.NODE_ENV !== 'production') {\n console.warn('Material-UI: The `css` function is deprecated. Use the `styleFunctionSx` instead.');\n }\n\n return styleFunctionSx(styleFunction);\n}\n\nvar _default = styleFunctionSx;\nexports.default = _default;", "\"use strict\";\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\");\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = exports.whiteSpace = exports.visibility = exports.textOverflow = exports.overflow = exports.displayRaw = exports.displayPrint = void 0;\n\nvar _style = _interopRequireDefault(require(\"./style\"));\n\nvar _compose = _interopRequireDefault(require(\"./compose\"));\n\nvar displayPrint = (0, _style.default)({\n prop: 'displayPrint',\n cssProperty: false,\n transform: function transform(value) {\n return {\n '@media print': {\n display: value\n }\n };\n }\n});\nexports.displayPrint = displayPrint;\nvar displayRaw = (0, _style.default)({\n prop: 'display'\n});\nexports.displayRaw = displayRaw;\nvar overflow = (0, _style.default)({\n prop: 'overflow'\n});\nexports.overflow = overflow;\nvar textOverflow = (0, _style.default)({\n prop: 'textOverflow'\n});\nexports.textOverflow = textOverflow;\nvar visibility = (0, _style.default)({\n prop: 'visibility'\n});\nexports.visibility = visibility;\nvar whiteSpace = (0, _style.default)({\n prop: 'whiteSpace'\n});\nexports.whiteSpace = whiteSpace;\n\nvar _default = (0, _compose.default)(displayPrint, displayRaw, overflow, textOverflow, visibility, whiteSpace);\n\nexports.default = _default;", "\"use strict\";\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\");\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = exports.justifySelf = exports.justifyItems = exports.alignSelf = exports.flexShrink = exports.flexGrow = exports.flex = exports.order = exports.alignContent = exports.alignItems = exports.justifyContent = exports.flexWrap = exports.flexDirection = exports.flexBasis = void 0;\n\nvar _style = _interopRequireDefault(require(\"./style\"));\n\nvar _compose = _interopRequireDefault(require(\"./compose\"));\n\nvar flexBasis = (0, _style.default)({\n prop: 'flexBasis'\n});\nexports.flexBasis = flexBasis;\nvar flexDirection = (0, _style.default)({\n prop: 'flexDirection'\n});\nexports.flexDirection = flexDirection;\nvar flexWrap = (0, _style.default)({\n prop: 'flexWrap'\n});\nexports.flexWrap = flexWrap;\nvar justifyContent = (0, _style.default)({\n prop: 'justifyContent'\n});\nexports.justifyContent = justifyContent;\nvar alignItems = (0, _style.default)({\n prop: 'alignItems'\n});\nexports.alignItems = alignItems;\nvar alignContent = (0, _style.default)({\n prop: 'alignContent'\n});\nexports.alignContent = alignContent;\nvar order = (0, _style.default)({\n prop: 'order'\n});\nexports.order = order;\nvar flex = (0, _style.default)({\n prop: 'flex'\n});\nexports.flex = flex;\nvar flexGrow = (0, _style.default)({\n prop: 'flexGrow'\n});\nexports.flexGrow = flexGrow;\nvar flexShrink = (0, _style.default)({\n prop: 'flexShrink'\n});\nexports.flexShrink = flexShrink;\nvar alignSelf = (0, _style.default)({\n prop: 'alignSelf'\n});\nexports.alignSelf = alignSelf;\nvar justifyItems = (0, _style.default)({\n prop: 'justifyItems'\n});\nexports.justifyItems = justifyItems;\nvar justifySelf = (0, _style.default)({\n prop: 'justifySelf'\n});\nexports.justifySelf = justifySelf;\nvar flexbox = (0, _compose.default)(flexBasis, flexDirection, flexWrap, justifyContent, alignItems, alignContent, order, flex, flexGrow, flexShrink, alignSelf, justifyItems, justifySelf);\nvar _default = flexbox;\nexports.default = _default;", "\"use strict\";\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\");\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = exports.gridArea = exports.gridTemplateAreas = exports.gridTemplateRows = exports.gridTemplateColumns = exports.gridAutoRows = exports.gridAutoColumns = exports.gridAutoFlow = exports.gridRow = exports.gridColumn = exports.gridRowGap = exports.gridColumnGap = exports.gridGap = void 0;\n\nvar _style = _interopRequireDefault(require(\"./style\"));\n\nvar _compose = _interopRequireDefault(require(\"./compose\"));\n\nvar gridGap = (0, _style.default)({\n prop: 'gridGap'\n});\nexports.gridGap = gridGap;\nvar gridColumnGap = (0, _style.default)({\n prop: 'gridColumnGap'\n});\nexports.gridColumnGap = gridColumnGap;\nvar gridRowGap = (0, _style.default)({\n prop: 'gridRowGap'\n});\nexports.gridRowGap = gridRowGap;\nvar gridColumn = (0, _style.default)({\n prop: 'gridColumn'\n});\nexports.gridColumn = gridColumn;\nvar gridRow = (0, _style.default)({\n prop: 'gridRow'\n});\nexports.gridRow = gridRow;\nvar gridAutoFlow = (0, _style.default)({\n prop: 'gridAutoFlow'\n});\nexports.gridAutoFlow = gridAutoFlow;\nvar gridAutoColumns = (0, _style.default)({\n prop: 'gridAutoColumns'\n});\nexports.gridAutoColumns = gridAutoColumns;\nvar gridAutoRows = (0, _style.default)({\n prop: 'gridAutoRows'\n});\nexports.gridAutoRows = gridAutoRows;\nvar gridTemplateColumns = (0, _style.default)({\n prop: 'gridTemplateColumns'\n});\nexports.gridTemplateColumns = gridTemplateColumns;\nvar gridTemplateRows = (0, _style.default)({\n prop: 'gridTemplateRows'\n});\nexports.gridTemplateRows = gridTemplateRows;\nvar gridTemplateAreas = (0, _style.default)({\n prop: 'gridTemplateAreas'\n});\nexports.gridTemplateAreas = gridTemplateAreas;\nvar gridArea = (0, _style.default)({\n prop: 'gridArea'\n});\nexports.gridArea = gridArea;\nvar grid = (0, _compose.default)(gridGap, gridColumnGap, gridRowGap, gridColumn, gridRow, gridAutoFlow, gridAutoColumns, gridAutoRows, gridTemplateColumns, gridTemplateRows, gridTemplateAreas, gridArea);\nvar _default = grid;\nexports.default = _default;", "\"use strict\";\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\");\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = exports.bgcolor = exports.color = void 0;\n\nvar _style = _interopRequireDefault(require(\"./style\"));\n\nvar _compose = _interopRequireDefault(require(\"./compose\"));\n\nvar color = (0, _style.default)({\n prop: 'color',\n themeKey: 'palette'\n});\nexports.color = color;\nvar bgcolor = (0, _style.default)({\n prop: 'bgcolor',\n cssProperty: 'backgroundColor',\n themeKey: 'palette'\n});\nexports.bgcolor = bgcolor;\nvar palette = (0, _compose.default)(color, bgcolor);\nvar _default = palette;\nexports.default = _default;", "\"use strict\";\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\");\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = exports.left = exports.bottom = exports.right = exports.top = exports.zIndex = exports.position = void 0;\n\nvar _style = _interopRequireDefault(require(\"./style\"));\n\nvar _compose = _interopRequireDefault(require(\"./compose\"));\n\nvar position = (0, _style.default)({\n prop: 'position'\n});\nexports.position = position;\nvar zIndex = (0, _style.default)({\n prop: 'zIndex',\n themeKey: 'zIndex'\n});\nexports.zIndex = zIndex;\nvar top = (0, _style.default)({\n prop: 'top'\n});\nexports.top = top;\nvar right = (0, _style.default)({\n prop: 'right'\n});\nexports.right = right;\nvar bottom = (0, _style.default)({\n prop: 'bottom'\n});\nexports.bottom = bottom;\nvar left = (0, _style.default)({\n prop: 'left'\n});\nexports.left = left;\n\nvar _default = (0, _compose.default)(position, zIndex, top, right, bottom, left);\n\nexports.default = _default;", "\"use strict\";\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\");\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nvar _style = _interopRequireDefault(require(\"./style\"));\n\nvar boxShadow = (0, _style.default)({\n prop: 'boxShadow',\n themeKey: 'shadows'\n});\nvar _default = boxShadow;\nexports.default = _default;", "\"use strict\";\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\");\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = exports.boxSizing = exports.sizeHeight = exports.sizeWidth = exports.minHeight = exports.maxHeight = exports.height = exports.minWidth = exports.maxWidth = exports.width = void 0;\n\nvar _style = _interopRequireDefault(require(\"./style\"));\n\nvar _compose = _interopRequireDefault(require(\"./compose\"));\n\nfunction transform(value) {\n return value <= 1 ? \"\".concat(value * 100, \"%\") : value;\n}\n\nvar width = (0, _style.default)({\n prop: 'width',\n transform: transform\n});\nexports.width = width;\nvar maxWidth = (0, _style.default)({\n prop: 'maxWidth',\n transform: transform\n});\nexports.maxWidth = maxWidth;\nvar minWidth = (0, _style.default)({\n prop: 'minWidth',\n transform: transform\n});\nexports.minWidth = minWidth;\nvar height = (0, _style.default)({\n prop: 'height',\n transform: transform\n});\nexports.height = height;\nvar maxHeight = (0, _style.default)({\n prop: 'maxHeight',\n transform: transform\n});\nexports.maxHeight = maxHeight;\nvar minHeight = (0, _style.default)({\n prop: 'minHeight',\n transform: transform\n});\nexports.minHeight = minHeight;\nvar sizeWidth = (0, _style.default)({\n prop: 'size',\n cssProperty: 'width',\n transform: transform\n});\nexports.sizeWidth = sizeWidth;\nvar sizeHeight = (0, _style.default)({\n prop: 'size',\n cssProperty: 'height',\n transform: transform\n});\nexports.sizeHeight = sizeHeight;\nvar boxSizing = (0, _style.default)({\n prop: 'boxSizing'\n});\nexports.boxSizing = boxSizing;\nvar sizing = (0, _compose.default)(width, maxWidth, minWidth, height, maxHeight, minHeight, boxSizing);\nvar _default = sizing;\nexports.default = _default;", "function _arrayWithHoles(r) {\n if (Array.isArray(r)) return r;\n}\nmodule.exports = _arrayWithHoles, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;", "function _iterableToArrayLimit(r, l) {\n var t = null == r ? null : \"undefined\" != typeof Symbol && r[Symbol.iterator] || r[\"@@iterator\"];\n if (null != t) {\n var e,\n n,\n i,\n u,\n a = [],\n f = !0,\n o = !1;\n try {\n if (i = (t = t.call(r)).next, 0 === l) {\n if (Object(t) !== t) return;\n f = !1;\n } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0);\n } catch (r) {\n o = !0, n = r;\n } finally {\n try {\n if (!f && null != t[\"return\"] && (u = t[\"return\"](), Object(u) !== u)) return;\n } finally {\n if (o) throw n;\n }\n }\n return a;\n }\n}\nmodule.exports = _iterableToArrayLimit, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;", "function _nonIterableRest() {\n throw new TypeError(\"Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\");\n}\nmodule.exports = _nonIterableRest, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;", "var arrayWithHoles = require(\"./arrayWithHoles.js\");\nvar iterableToArrayLimit = require(\"./iterableToArrayLimit.js\");\nvar unsupportedIterableToArray = require(\"./unsupportedIterableToArray.js\");\nvar nonIterableRest = require(\"./nonIterableRest.js\");\nfunction _slicedToArray(r, e) {\n return arrayWithHoles(r) || iterableToArrayLimit(r, e) || unsupportedIterableToArray(r, e) || nonIterableRest();\n}\nmodule.exports = _slicedToArray, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;", "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = memoize;\n\nfunction memoize(fn) {\n var cache = {};\n return function (arg) {\n if (cache[arg] === undefined) {\n cache[arg] = fn(arg);\n }\n\n return cache[arg];\n };\n}", "\"use strict\";\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\");\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.createUnarySpacing = createUnarySpacing;\nexports.default = void 0;\n\nvar _slicedToArray2 = _interopRequireDefault(require(\"@babel/runtime/helpers/slicedToArray\"));\n\nvar _responsivePropType = _interopRequireDefault(require(\"./responsivePropType\"));\n\nvar _breakpoints = require(\"./breakpoints\");\n\nvar _merge = _interopRequireDefault(require(\"./merge\"));\n\nvar _memoize = _interopRequireDefault(require(\"./memoize\"));\n\nvar properties = {\n m: 'margin',\n p: 'padding'\n};\nvar directions = {\n t: 'Top',\n r: 'Right',\n b: 'Bottom',\n l: 'Left',\n x: ['Left', 'Right'],\n y: ['Top', 'Bottom']\n};\nvar aliases = {\n marginX: 'mx',\n marginY: 'my',\n paddingX: 'px',\n paddingY: 'py'\n}; // memoize() impact:\n// From 300,000 ops/sec\n// To 350,000 ops/sec\n\nvar getCssProperties = (0, _memoize.default)(function (prop) {\n // It's not a shorthand notation.\n if (prop.length > 2) {\n if (aliases[prop]) {\n prop = aliases[prop];\n } else {\n return [prop];\n }\n }\n\n var _prop$split = prop.split(''),\n _prop$split2 = (0, _slicedToArray2.default)(_prop$split, 2),\n a = _prop$split2[0],\n b = _prop$split2[1];\n\n var property = properties[a];\n var direction = directions[b] || '';\n return Array.isArray(direction) ? direction.map(function (dir) {\n return property + dir;\n }) : [property + direction];\n});\nvar spacingKeys = ['m', 'mt', 'mr', 'mb', 'ml', 'mx', 'my', 'p', 'pt', 'pr', 'pb', 'pl', 'px', 'py', 'margin', 'marginTop', 'marginRight', 'marginBottom', 'marginLeft', 'marginX', 'marginY', 'padding', 'paddingTop', 'paddingRight', 'paddingBottom', 'paddingLeft', 'paddingX', 'paddingY'];\n\nfunction createUnarySpacing(theme) {\n var themeSpacing = theme.spacing || 8;\n\n if (typeof themeSpacing === 'number') {\n return function (abs) {\n if (process.env.NODE_ENV !== 'production') {\n if (typeof abs !== 'number') {\n console.error(\"Material-UI: Expected spacing argument to be a number, got \".concat(abs, \".\"));\n }\n }\n\n return themeSpacing * abs;\n };\n }\n\n if (Array.isArray(themeSpacing)) {\n return function (abs) {\n if (process.env.NODE_ENV !== 'production') {\n if (abs > themeSpacing.length - 1) {\n console.error([\"Material-UI: The value provided (\".concat(abs, \") overflows.\"), \"The supported values are: \".concat(JSON.stringify(themeSpacing), \".\"), \"\".concat(abs, \" > \").concat(themeSpacing.length - 1, \", you need to add the missing values.\")].join('\\n'));\n }\n }\n\n return themeSpacing[abs];\n };\n }\n\n if (typeof themeSpacing === 'function') {\n return themeSpacing;\n }\n\n if (process.env.NODE_ENV !== 'production') {\n console.error([\"Material-UI: The `theme.spacing` value (\".concat(themeSpacing, \") is invalid.\"), 'It should be a number, an array or a function.'].join('\\n'));\n }\n\n return function () {\n return undefined;\n };\n}\n\nfunction getValue(transformer, propValue) {\n if (typeof propValue === 'string' || propValue == null) {\n return propValue;\n }\n\n var abs = Math.abs(propValue);\n var transformed = transformer(abs);\n\n if (propValue >= 0) {\n return transformed;\n }\n\n if (typeof transformed === 'number') {\n return -transformed;\n }\n\n return \"-\".concat(transformed);\n}\n\nfunction getStyleFromPropValue(cssProperties, transformer) {\n return function (propValue) {\n return cssProperties.reduce(function (acc, cssProperty) {\n acc[cssProperty] = getValue(transformer, propValue);\n return acc;\n }, {});\n };\n}\n\nfunction spacing(props) {\n var theme = props.theme;\n var transformer = createUnarySpacing(theme);\n return Object.keys(props).map(function (prop) {\n // Using a hash computation over an array iteration could be faster, but with only 28 items,\n // it's doesn't worth the bundle size.\n if (spacingKeys.indexOf(prop) === -1) {\n return null;\n }\n\n var cssProperties = getCssProperties(prop);\n var styleFromPropValue = getStyleFromPropValue(cssProperties, transformer);\n var propValue = props[prop];\n return (0, _breakpoints.handleBreakpoints)(props, propValue, styleFromPropValue);\n }).reduce(_merge.default, {});\n}\n\nspacing.propTypes = process.env.NODE_ENV !== 'production' ? spacingKeys.reduce(function (obj, key) {\n obj[key] = _responsivePropType.default;\n return obj;\n}, {}) : {};\nspacing.filterProps = spacingKeys;\nvar _default = spacing;\nexports.default = _default;", "\"use strict\";\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\");\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = exports.textAlign = exports.lineHeight = exports.letterSpacing = exports.fontWeight = exports.fontStyle = exports.fontSize = exports.fontFamily = void 0;\n\nvar _style = _interopRequireDefault(require(\"./style\"));\n\nvar _compose = _interopRequireDefault(require(\"./compose\"));\n\nvar fontFamily = (0, _style.default)({\n prop: 'fontFamily',\n themeKey: 'typography'\n});\nexports.fontFamily = fontFamily;\nvar fontSize = (0, _style.default)({\n prop: 'fontSize',\n themeKey: 'typography'\n});\nexports.fontSize = fontSize;\nvar fontStyle = (0, _style.default)({\n prop: 'fontStyle',\n themeKey: 'typography'\n});\nexports.fontStyle = fontStyle;\nvar fontWeight = (0, _style.default)({\n prop: 'fontWeight',\n themeKey: 'typography'\n});\nexports.fontWeight = fontWeight;\nvar letterSpacing = (0, _style.default)({\n prop: 'letterSpacing'\n});\nexports.letterSpacing = letterSpacing;\nvar lineHeight = (0, _style.default)({\n prop: 'lineHeight'\n});\nexports.lineHeight = lineHeight;\nvar textAlign = (0, _style.default)({\n prop: 'textAlign'\n});\nexports.textAlign = textAlign;\nvar typography = (0, _compose.default)(fontFamily, fontSize, fontStyle, fontWeight, letterSpacing, lineHeight, textAlign);\nvar _default = typography;\nexports.default = _default;", "/** @license Material-UI v4.12.2\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\"use strict\";\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\");\n\nvar _interopRequireWildcard = require(\"@babel/runtime/helpers/interopRequireWildcard\");\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nvar _exportNames = {\n borders: true,\n breakpoints: true,\n compose: true,\n styleFunctionSx: true,\n display: true,\n flexbox: true,\n grid: true,\n palette: true,\n positions: true,\n shadows: true,\n sizing: true,\n spacing: true,\n style: true,\n typography: true\n};\nObject.defineProperty(exports, \"borders\", {\n enumerable: true,\n get: function get() {\n return _borders.default;\n }\n});\nObject.defineProperty(exports, \"breakpoints\", {\n enumerable: true,\n get: function get() {\n return _breakpoints.default;\n }\n});\nObject.defineProperty(exports, \"compose\", {\n enumerable: true,\n get: function get() {\n return _compose.default;\n }\n});\nObject.defineProperty(exports, \"styleFunctionSx\", {\n enumerable: true,\n get: function get() {\n return _styleFunctionSx.default;\n }\n});\nObject.defineProperty(exports, \"display\", {\n enumerable: true,\n get: function get() {\n return _display.default;\n }\n});\nObject.defineProperty(exports, \"flexbox\", {\n enumerable: true,\n get: function get() {\n return _flexbox.default;\n }\n});\nObject.defineProperty(exports, \"grid\", {\n enumerable: true,\n get: function get() {\n return _grid.default;\n }\n});\nObject.defineProperty(exports, \"palette\", {\n enumerable: true,\n get: function get() {\n return _palette.default;\n }\n});\nObject.defineProperty(exports, \"positions\", {\n enumerable: true,\n get: function get() {\n return _positions.default;\n }\n});\nObject.defineProperty(exports, \"shadows\", {\n enumerable: true,\n get: function get() {\n return _shadows.default;\n }\n});\nObject.defineProperty(exports, \"sizing\", {\n enumerable: true,\n get: function get() {\n return _sizing.default;\n }\n});\nObject.defineProperty(exports, \"spacing\", {\n enumerable: true,\n get: function get() {\n return _spacing.default;\n }\n});\nObject.defineProperty(exports, \"style\", {\n enumerable: true,\n get: function get() {\n return _style.default;\n }\n});\nObject.defineProperty(exports, \"typography\", {\n enumerable: true,\n get: function get() {\n return _typography.default;\n }\n});\n\nvar _borders = _interopRequireWildcard(require(\"./borders\"));\n\nObject.keys(_borders).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _borders[key];\n }\n });\n});\n\nvar _breakpoints = _interopRequireDefault(require(\"./breakpoints\"));\n\nvar _compose = _interopRequireDefault(require(\"./compose\"));\n\nvar _styleFunctionSx = _interopRequireWildcard(require(\"./styleFunctionSx\"));\n\nObject.keys(_styleFunctionSx).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _styleFunctionSx[key];\n }\n });\n});\n\nvar _display = _interopRequireDefault(require(\"./display\"));\n\nvar _flexbox = _interopRequireWildcard(require(\"./flexbox\"));\n\nObject.keys(_flexbox).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _flexbox[key];\n }\n });\n});\n\nvar _grid = _interopRequireWildcard(require(\"./grid\"));\n\nObject.keys(_grid).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _grid[key];\n }\n });\n});\n\nvar _palette = _interopRequireWildcard(require(\"./palette\"));\n\nObject.keys(_palette).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _palette[key];\n }\n });\n});\n\nvar _positions = _interopRequireWildcard(require(\"./positions\"));\n\nObject.keys(_positions).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _positions[key];\n }\n });\n});\n\nvar _shadows = _interopRequireDefault(require(\"./shadows\"));\n\nvar _sizing = _interopRequireWildcard(require(\"./sizing\"));\n\nObject.keys(_sizing).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _sizing[key];\n }\n });\n});\n\nvar _spacing = _interopRequireWildcard(require(\"./spacing\"));\n\nObject.keys(_spacing).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _spacing[key];\n }\n });\n});\n\nvar _style = _interopRequireDefault(require(\"./style\"));\n\nvar _typography = _interopRequireWildcard(require(\"./typography\"));\n\nObject.keys(_typography).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _typography[key];\n }\n });\n});", "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = createSpacing;\n\nvar _system = require(\"@material-ui/system\");\n\nvar warnOnce;\n\nfunction createSpacing() {\n var spacingInput = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 8;\n\n // Already transformed.\n if (spacingInput.mui) {\n return spacingInput;\n } // Material Design layouts are visually balanced. Most measurements align to an 8dp grid applied, which aligns both spacing and the overall layout.\n // Smaller components, such as icons and type, can align to a 4dp grid.\n // https://material.io/design/layout/understanding-layout.html#usage\n\n\n var transform = (0, _system.createUnarySpacing)({\n spacing: spacingInput\n });\n\n var spacing = function spacing() {\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n if (process.env.NODE_ENV !== 'production') {\n if (!(args.length <= 4)) {\n console.error(\"Material-UI: Too many arguments provided, expected between 0 and 4, got \".concat(args.length));\n }\n }\n\n if (args.length === 0) {\n return transform(1);\n }\n\n if (args.length === 1) {\n return transform(args[0]);\n }\n\n return args.map(function (argument) {\n if (typeof argument === 'string') {\n return argument;\n }\n\n var output = transform(argument);\n return typeof output === 'number' ? \"\".concat(output, \"px\") : output;\n }).join(' ');\n }; // Backward compatibility, to remove in v5.\n\n\n Object.defineProperty(spacing, 'unit', {\n get: function get() {\n if (process.env.NODE_ENV !== 'production') {\n if (!warnOnce || process.env.NODE_ENV === 'test') {\n console.error(['Material-UI: theme.spacing.unit usage has been deprecated.', 'It will be removed in v5.', 'You can replace `theme.spacing.unit * y` with `theme.spacing(y)`.', '', 'You can use the `https://github.com/mui-org/material-ui/tree/master/packages/material-ui-codemod/README.md#theme-spacing-api` migration helper to make the process smoother.'].join('\\n'));\n }\n\n warnOnce = true;\n }\n\n return spacingInput;\n }\n });\n spacing.mui = true;\n return spacing;\n}", "\"use strict\";\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\");\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = exports.duration = exports.easing = void 0;\n\nvar _objectWithoutProperties2 = _interopRequireDefault(require(\"@babel/runtime/helpers/objectWithoutProperties\"));\n\n// Follow https://material.google.com/motion/duration-easing.html#duration-easing-natural-easing-curves\n// to learn the context in which each easing should be used.\nvar easing = {\n // This is the most common easing curve.\n easeInOut: 'cubic-bezier(0.4, 0, 0.2, 1)',\n // Objects enter the screen at full velocity from off-screen and\n // slowly decelerate to a resting point.\n easeOut: 'cubic-bezier(0.0, 0, 0.2, 1)',\n // Objects leave the screen at full velocity. They do not decelerate when off-screen.\n easeIn: 'cubic-bezier(0.4, 0, 1, 1)',\n // The sharp curve is used by objects that may return to the screen at any time.\n sharp: 'cubic-bezier(0.4, 0, 0.6, 1)'\n}; // Follow https://material.io/guidelines/motion/duration-easing.html#duration-easing-common-durations\n// to learn when use what timing\n\nexports.easing = easing;\nvar duration = {\n shortest: 150,\n shorter: 200,\n short: 250,\n // most basic recommended timing\n standard: 300,\n // this is to be used in complex animations\n complex: 375,\n // recommended when something is entering screen\n enteringScreen: 225,\n // recommended when something is leaving screen\n leavingScreen: 195\n};\nexports.duration = duration;\n\nfunction formatMs(milliseconds) {\n return \"\".concat(Math.round(milliseconds), \"ms\");\n}\n/**\n * @param {string|Array} props\n * @param {object} param\n * @param {string} param.prop\n * @param {number} param.duration\n * @param {string} param.easing\n * @param {number} param.delay\n */\n\n\nvar _default = {\n easing: easing,\n duration: duration,\n create: function create() {\n var props = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ['all'];\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n var _options$duration = options.duration,\n durationOption = _options$duration === void 0 ? duration.standard : _options$duration,\n _options$easing = options.easing,\n easingOption = _options$easing === void 0 ? easing.easeInOut : _options$easing,\n _options$delay = options.delay,\n delay = _options$delay === void 0 ? 0 : _options$delay,\n other = (0, _objectWithoutProperties2.default)(options, [\"duration\", \"easing\", \"delay\"]);\n\n if (process.env.NODE_ENV !== 'production') {\n var isString = function isString(value) {\n return typeof value === 'string';\n };\n\n var isNumber = function isNumber(value) {\n return !isNaN(parseFloat(value));\n };\n\n if (!isString(props) && !Array.isArray(props)) {\n console.error('Material-UI: Argument \"props\" must be a string or Array.');\n }\n\n if (!isNumber(durationOption) && !isString(durationOption)) {\n console.error(\"Material-UI: Argument \\\"duration\\\" must be a number or a string but found \".concat(durationOption, \".\"));\n }\n\n if (!isString(easingOption)) {\n console.error('Material-UI: Argument \"easing\" must be a string.');\n }\n\n if (!isNumber(delay) && !isString(delay)) {\n console.error('Material-UI: Argument \"delay\" must be a number or a string.');\n }\n\n if (Object.keys(other).length !== 0) {\n console.error(\"Material-UI: Unrecognized argument(s) [\".concat(Object.keys(other).join(','), \"].\"));\n }\n }\n\n return (Array.isArray(props) ? props : [props]).map(function (animatedProp) {\n return \"\".concat(animatedProp, \" \").concat(typeof durationOption === 'string' ? durationOption : formatMs(durationOption), \" \").concat(easingOption, \" \").concat(typeof delay === 'string' ? delay : formatMs(delay));\n }).join(',');\n },\n getAutoHeightDuration: function getAutoHeightDuration(height) {\n if (!height) {\n return 0;\n }\n\n var constant = height / 36; // https://www.wolframalpha.com/input/?i=(4+%2B+15+*+(x+%2F+36+)+**+0.25+%2B+(x+%2F+36)+%2F+5)+*+10\n\n return Math.round((4 + 15 * Math.pow(constant, 0.25) + constant / 5) * 10);\n }\n};\nexports.default = _default;", "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n// We need to centralize the zIndex definitions as they work\n// like global values in the browser.\nvar zIndex = {\n mobileStepper: 1000,\n speedDial: 1050,\n appBar: 1100,\n drawer: 1200,\n modal: 1300,\n snackbar: 1400,\n tooltip: 1500\n};\nvar _default = zIndex;\nexports.default = _default;", "\"use strict\";\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\");\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.createMuiTheme = createMuiTheme;\nexports.default = void 0;\n\nvar _defineProperty2 = _interopRequireDefault(require(\"@babel/runtime/helpers/defineProperty\"));\n\nvar _objectWithoutProperties2 = _interopRequireDefault(require(\"@babel/runtime/helpers/objectWithoutProperties\"));\n\nvar _utils = require(\"@material-ui/utils\");\n\nvar _createBreakpoints = _interopRequireDefault(require(\"./createBreakpoints\"));\n\nvar _createMixins = _interopRequireDefault(require(\"./createMixins\"));\n\nvar _createPalette = _interopRequireDefault(require(\"./createPalette\"));\n\nvar _createTypography = _interopRequireDefault(require(\"./createTypography\"));\n\nvar _shadows = _interopRequireDefault(require(\"./shadows\"));\n\nvar _shape = _interopRequireDefault(require(\"./shape\"));\n\nvar _createSpacing = _interopRequireDefault(require(\"./createSpacing\"));\n\nvar _transitions = _interopRequireDefault(require(\"./transitions\"));\n\nvar _zIndex = _interopRequireDefault(require(\"./zIndex\"));\n\nfunction createTheme() {\n var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n var _options$breakpoints = options.breakpoints,\n breakpointsInput = _options$breakpoints === void 0 ? {} : _options$breakpoints,\n _options$mixins = options.mixins,\n mixinsInput = _options$mixins === void 0 ? {} : _options$mixins,\n _options$palette = options.palette,\n paletteInput = _options$palette === void 0 ? {} : _options$palette,\n spacingInput = options.spacing,\n _options$typography = options.typography,\n typographyInput = _options$typography === void 0 ? {} : _options$typography,\n other = (0, _objectWithoutProperties2.default)(options, [\"breakpoints\", \"mixins\", \"palette\", \"spacing\", \"typography\"]);\n var palette = (0, _createPalette.default)(paletteInput);\n var breakpoints = (0, _createBreakpoints.default)(breakpointsInput);\n var spacing = (0, _createSpacing.default)(spacingInput);\n var muiTheme = (0, _utils.deepmerge)({\n breakpoints: breakpoints,\n direction: 'ltr',\n mixins: (0, _createMixins.default)(breakpoints, spacing, mixinsInput),\n overrides: {},\n // Inject custom styles\n palette: palette,\n props: {},\n // Provide default props\n shadows: _shadows.default,\n typography: (0, _createTypography.default)(palette, typographyInput),\n spacing: spacing,\n shape: _shape.default,\n transitions: _transitions.default,\n zIndex: _zIndex.default\n }, other);\n\n for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n args[_key - 1] = arguments[_key];\n }\n\n muiTheme = args.reduce(function (acc, argument) {\n return (0, _utils.deepmerge)(acc, argument);\n }, muiTheme);\n\n if (process.env.NODE_ENV !== 'production') {\n var pseudoClasses = ['checked', 'disabled', 'error', 'focused', 'focusVisible', 'required', 'expanded', 'selected'];\n\n var traverse = function traverse(node, parentKey) {\n var depth = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;\n var key; // eslint-disable-next-line guard-for-in, no-restricted-syntax\n\n for (key in node) {\n var child = node[key];\n\n if (depth === 1) {\n if (key.indexOf('Mui') === 0 && child) {\n traverse(child, key, depth + 1);\n }\n } else if (pseudoClasses.indexOf(key) !== -1 && Object.keys(child).length > 0) {\n if (process.env.NODE_ENV !== 'production') {\n console.error([\"Material-UI: The `\".concat(parentKey, \"` component increases \") + \"the CSS specificity of the `\".concat(key, \"` internal state.\"), 'You can not override it like this: ', JSON.stringify(node, null, 2), '', 'Instead, you need to use the $ruleName syntax:', JSON.stringify({\n root: (0, _defineProperty2.default)({}, \"&$\".concat(key), child)\n }, null, 2), '', 'https://mui.com/r/pseudo-classes-guide'].join('\\n'));\n } // Remove the style to prevent global conflicts.\n\n\n node[key] = {};\n }\n }\n };\n\n traverse(muiTheme.overrides);\n }\n\n return muiTheme;\n}\n\nvar warnedOnce = false;\n\nfunction createMuiTheme() {\n if (process.env.NODE_ENV !== 'production') {\n if (!warnedOnce) {\n warnedOnce = true;\n console.error(['Material-UI: the createMuiTheme function was renamed to createTheme.', '', \"You should use `import { createTheme } from '@material-ui/core/styles'`\"].join('\\n'));\n }\n }\n\n return createTheme.apply(void 0, arguments);\n}\n\nvar _default = createTheme;\nexports.default = _default;", "\"use strict\";\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\");\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = createMuiStrictModeTheme;\n\nvar _utils = require(\"@material-ui/utils\");\n\nvar _createTheme = _interopRequireDefault(require(\"./createTheme\"));\n\nfunction createMuiStrictModeTheme(options) {\n for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n args[_key - 1] = arguments[_key];\n }\n\n return _createTheme.default.apply(void 0, [(0, _utils.deepmerge)({\n unstable_strictMode: true\n }, options)].concat(args));\n}", "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar hasSymbol = typeof Symbol === 'function' && Symbol.for;\n\nvar _default = hasSymbol ? Symbol.for('mui.nested') : '__THEME_NESTED__';\n\nexports.default = _default;", "\"use strict\";\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\");\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = createGenerateClassName;\n\nvar _nested = _interopRequireDefault(require(\"../ThemeProvider/nested\"));\n\n/**\n * This is the list of the style rule name we use as drop in replacement for the built-in\n * pseudo classes (:checked, :disabled, :focused, etc.).\n *\n * Why do they exist in the first place?\n * These classes are used at a specificity of 2.\n * It allows them to override previously definied styles as well as\n * being untouched by simple user overrides.\n */\nvar pseudoClasses = ['checked', 'disabled', 'error', 'focused', 'focusVisible', 'required', 'expanded', 'selected']; // Returns a function which generates unique class names based on counters.\n// When new generator function is created, rule counter is reset.\n// We need to reset the rule counter for SSR for each request.\n//\n// It's inspired by\n// https://github.com/cssinjs/jss/blob/4e6a05dd3f7b6572fdd3ab216861d9e446c20331/src/utils/createGenerateClassName.js\n\nfunction createGenerateClassName() {\n var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n var _options$disableGloba = options.disableGlobal,\n disableGlobal = _options$disableGloba === void 0 ? false : _options$disableGloba,\n _options$productionPr = options.productionPrefix,\n productionPrefix = _options$productionPr === void 0 ? 'jss' : _options$productionPr,\n _options$seed = options.seed,\n seed = _options$seed === void 0 ? '' : _options$seed;\n var seedPrefix = seed === '' ? '' : \"\".concat(seed, \"-\");\n var ruleCounter = 0;\n\n var getNextCounterId = function getNextCounterId() {\n ruleCounter += 1;\n\n if (process.env.NODE_ENV !== 'production') {\n if (ruleCounter >= 1e10) {\n console.warn(['Material-UI: You might have a memory leak.', 'The ruleCounter is not supposed to grow that much.'].join(''));\n }\n }\n\n return ruleCounter;\n };\n\n return function (rule, styleSheet) {\n var name = styleSheet.options.name; // Is a global static MUI style?\n\n if (name && name.indexOf('Mui') === 0 && !styleSheet.options.link && !disableGlobal) {\n // We can use a shorthand class name, we never use the keys to style the components.\n if (pseudoClasses.indexOf(rule.key) !== -1) {\n return \"Mui-\".concat(rule.key);\n }\n\n var prefix = \"\".concat(seedPrefix).concat(name, \"-\").concat(rule.key);\n\n if (!styleSheet.options.theme[_nested.default] || seed !== '') {\n return prefix;\n }\n\n return \"\".concat(prefix, \"-\").concat(getNextCounterId());\n }\n\n if (process.env.NODE_ENV === 'production') {\n return \"\".concat(seedPrefix).concat(productionPrefix).concat(getNextCounterId());\n }\n\n var suffix = \"\".concat(rule.key, \"-\").concat(getNextCounterId()); // Help with debuggability.\n\n if (styleSheet.options.classNamePrefix) {\n return \"\".concat(seedPrefix).concat(styleSheet.options.classNamePrefix, \"-\").concat(suffix);\n }\n\n return \"\".concat(seedPrefix).concat(suffix);\n };\n}", "\"use strict\";\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\");\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nObject.defineProperty(exports, \"default\", {\n enumerable: true,\n get: function get() {\n return _createGenerateClassName.default;\n }\n});\n\nvar _createGenerateClassName = _interopRequireDefault(require(\"./createGenerateClassName\"));", "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = createStyles;\n\nfunction createStyles(styles) {\n return styles;\n}", "\"use strict\";\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\");\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nObject.defineProperty(exports, \"default\", {\n enumerable: true,\n get: function get() {\n return _createStyles.default;\n }\n});\n\nvar _createStyles = _interopRequireDefault(require(\"./createStyles\"));", "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = getThemeProps;\n\n/* eslint-disable no-restricted-syntax */\nfunction getThemeProps(params) {\n var theme = params.theme,\n name = params.name,\n props = params.props;\n\n if (!theme || !theme.props || !theme.props[name]) {\n return props;\n } // Resolve default props, code borrow from React source.\n // https://github.com/facebook/react/blob/15a8f031838a553e41c0b66eb1bcf1da8448104d/packages/react/src/ReactElement.js#L221\n\n\n var defaultProps = theme.props[name];\n var propName;\n\n for (propName in defaultProps) {\n if (props[propName] === undefined) {\n props[propName] = defaultProps[propName];\n }\n }\n\n return props;\n}", "\"use strict\";\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\");\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nObject.defineProperty(exports, \"default\", {\n enumerable: true,\n get: function get() {\n return _getThemeProps.default;\n }\n});\n\nvar _getThemeProps = _interopRequireDefault(require(\"./getThemeProps\"));", "'use strict';\n\nvar isProduction = process.env.NODE_ENV === 'production';\nfunction warning(condition, message) {\n if (!isProduction) {\n if (condition) {\n return;\n }\n\n var text = \"Warning: \" + message;\n\n if (typeof console !== 'undefined') {\n console.warn(text);\n }\n\n try {\n throw Error(text);\n } catch (x) {}\n }\n}\n\nmodule.exports = warning;\n", "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\n\nvar _typeof = typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; };\n\nvar isBrowser = exports.isBrowser = (typeof window === \"undefined\" ? \"undefined\" : _typeof(window)) === \"object\" && (typeof document === \"undefined\" ? \"undefined\" : _typeof(document)) === 'object' && document.nodeType === 9;\n\nexports.default = isBrowser;", "var toPropertyKey = require(\"./toPropertyKey.js\");\nfunction _defineProperties(e, r) {\n for (var t = 0; t < r.length; t++) {\n var o = r[t];\n o.enumerable = o.enumerable || !1, o.configurable = !0, \"value\" in o && (o.writable = !0), Object.defineProperty(e, toPropertyKey(o.key), o);\n }\n}\nfunction _createClass(e, r, t) {\n return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, \"prototype\", {\n writable: !1\n }), e;\n}\nmodule.exports = _createClass, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;", "function _setPrototypeOf(t, e) {\n return module.exports = _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) {\n return t.__proto__ = e, t;\n }, module.exports.__esModule = true, module.exports[\"default\"] = module.exports, _setPrototypeOf(t, e);\n}\nmodule.exports = _setPrototypeOf, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;", "var setPrototypeOf = require(\"./setPrototypeOf.js\");\nfunction _inheritsLoose(t, o) {\n t.prototype = Object.create(o.prototype), t.prototype.constructor = t, setPrototypeOf(t, o);\n}\nmodule.exports = _inheritsLoose, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;", "function _assertThisInitialized(e) {\n if (void 0 === e) throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");\n return e;\n}\nmodule.exports = _assertThisInitialized, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;", "'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nvar _extends = require('@babel/runtime/helpers/extends');\nvar isInBrowser = require('is-in-browser');\nvar warning = require('tiny-warning');\nvar _createClass = require('@babel/runtime/helpers/createClass');\nvar _inheritsLoose = require('@babel/runtime/helpers/inheritsLoose');\nvar _assertThisInitialized = require('@babel/runtime/helpers/assertThisInitialized');\nvar _objectWithoutPropertiesLoose = require('@babel/runtime/helpers/objectWithoutPropertiesLoose');\n\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\n\nvar _extends__default = /*#__PURE__*/_interopDefaultLegacy(_extends);\nvar isInBrowser__default = /*#__PURE__*/_interopDefaultLegacy(isInBrowser);\nvar warning__default = /*#__PURE__*/_interopDefaultLegacy(warning);\nvar _createClass__default = /*#__PURE__*/_interopDefaultLegacy(_createClass);\nvar _inheritsLoose__default = /*#__PURE__*/_interopDefaultLegacy(_inheritsLoose);\nvar _assertThisInitialized__default = /*#__PURE__*/_interopDefaultLegacy(_assertThisInitialized);\nvar _objectWithoutPropertiesLoose__default = /*#__PURE__*/_interopDefaultLegacy(_objectWithoutPropertiesLoose);\n\nvar plainObjectConstrurctor = {}.constructor;\nfunction cloneStyle(style) {\n if (style == null || typeof style !== 'object') return style;\n if (Array.isArray(style)) return style.map(cloneStyle);\n if (style.constructor !== plainObjectConstrurctor) return style;\n var newStyle = {};\n\n for (var name in style) {\n newStyle[name] = cloneStyle(style[name]);\n }\n\n return newStyle;\n}\n\n/**\n * Create a rule instance.\n */\n\nfunction createRule(name, decl, options) {\n if (name === void 0) {\n name = 'unnamed';\n }\n\n var jss = options.jss;\n var declCopy = cloneStyle(decl);\n var rule = jss.plugins.onCreateRule(name, declCopy, options);\n if (rule) return rule; // It is an at-rule and it has no instance.\n\n if (name[0] === '@') {\n process.env.NODE_ENV !== \"production\" ? warning__default['default'](false, \"[JSS] Unknown rule \" + name) : void 0;\n }\n\n return null;\n}\n\nvar join = function join(value, by) {\n var result = '';\n\n for (var i = 0; i < value.length; i++) {\n // Remove !important from the value, it will be readded later.\n if (value[i] === '!important') break;\n if (result) result += by;\n result += value[i];\n }\n\n return result;\n};\n/**\n * Converts JSS array value to a CSS string.\n *\n * `margin: [['5px', '10px']]` > `margin: 5px 10px;`\n * `border: ['1px', '2px']` > `border: 1px, 2px;`\n * `margin: [['5px', '10px'], '!important']` > `margin: 5px 10px !important;`\n * `color: ['red', !important]` > `color: red !important;`\n */\n\n\nvar toCssValue = function toCssValue(value) {\n if (!Array.isArray(value)) return value;\n var cssValue = ''; // Support space separated values via `[['5px', '10px']]`.\n\n if (Array.isArray(value[0])) {\n for (var i = 0; i < value.length; i++) {\n if (value[i] === '!important') break;\n if (cssValue) cssValue += ', ';\n cssValue += join(value[i], ' ');\n }\n } else cssValue = join(value, ', '); // Add !important, because it was ignored.\n\n\n if (value[value.length - 1] === '!important') {\n cssValue += ' !important';\n }\n\n return cssValue;\n};\n\nfunction getWhitespaceSymbols(options) {\n if (options && options.format === false) {\n return {\n linebreak: '',\n space: ''\n };\n }\n\n return {\n linebreak: '\\n',\n space: ' '\n };\n}\n\n/**\n * Indent a string.\n * http://jsperf.com/array-join-vs-for\n */\n\nfunction indentStr(str, indent) {\n var result = '';\n\n for (var index = 0; index < indent; index++) {\n result += ' ';\n }\n\n return result + str;\n}\n/**\n * Converts a Rule to CSS string.\n */\n\n\nfunction toCss(selector, style, options) {\n if (options === void 0) {\n options = {};\n }\n\n var result = '';\n if (!style) return result;\n var _options = options,\n _options$indent = _options.indent,\n indent = _options$indent === void 0 ? 0 : _options$indent;\n var fallbacks = style.fallbacks;\n\n if (options.format === false) {\n indent = -Infinity;\n }\n\n var _getWhitespaceSymbols = getWhitespaceSymbols(options),\n linebreak = _getWhitespaceSymbols.linebreak,\n space = _getWhitespaceSymbols.space;\n\n if (selector) indent++; // Apply fallbacks first.\n\n if (fallbacks) {\n // Array syntax {fallbacks: [{prop: value}]}\n if (Array.isArray(fallbacks)) {\n for (var index = 0; index < fallbacks.length; index++) {\n var fallback = fallbacks[index];\n\n for (var prop in fallback) {\n var value = fallback[prop];\n\n if (value != null) {\n if (result) result += linebreak;\n result += indentStr(prop + \":\" + space + toCssValue(value) + \";\", indent);\n }\n }\n }\n } else {\n // Object syntax {fallbacks: {prop: value}}\n for (var _prop in fallbacks) {\n var _value = fallbacks[_prop];\n\n if (_value != null) {\n if (result) result += linebreak;\n result += indentStr(_prop + \":\" + space + toCssValue(_value) + \";\", indent);\n }\n }\n }\n }\n\n for (var _prop2 in style) {\n var _value2 = style[_prop2];\n\n if (_value2 != null && _prop2 !== 'fallbacks') {\n if (result) result += linebreak;\n result += indentStr(_prop2 + \":\" + space + toCssValue(_value2) + \";\", indent);\n }\n } // Allow empty style in this case, because properties will be added dynamically.\n\n\n if (!result && !options.allowEmpty) return result; // When rule is being stringified before selector was defined.\n\n if (!selector) return result;\n indent--;\n if (result) result = \"\" + linebreak + result + linebreak;\n return indentStr(\"\" + selector + space + \"{\" + result, indent) + indentStr('}', indent);\n}\n\nvar escapeRegex = /([[\\].#*$><+~=|^:(),\"'`\\s])/g;\nvar nativeEscape = typeof CSS !== 'undefined' && CSS.escape;\nvar escape = (function (str) {\n return nativeEscape ? nativeEscape(str) : str.replace(escapeRegex, '\\\\$1');\n});\n\nvar BaseStyleRule =\n/*#__PURE__*/\nfunction () {\n function BaseStyleRule(key, style, options) {\n this.type = 'style';\n this.isProcessed = false;\n var sheet = options.sheet,\n Renderer = options.Renderer;\n this.key = key;\n this.options = options;\n this.style = style;\n if (sheet) this.renderer = sheet.renderer;else if (Renderer) this.renderer = new Renderer();\n }\n /**\n * Get or set a style property.\n */\n\n\n var _proto = BaseStyleRule.prototype;\n\n _proto.prop = function prop(name, value, options) {\n // It's a getter.\n if (value === undefined) return this.style[name]; // Don't do anything if the value has not changed.\n\n var force = options ? options.force : false;\n if (!force && this.style[name] === value) return this;\n var newValue = value;\n\n if (!options || options.process !== false) {\n newValue = this.options.jss.plugins.onChangeValue(value, name, this);\n }\n\n var isEmpty = newValue == null || newValue === false;\n var isDefined = name in this.style; // Value is empty and wasn't defined before.\n\n if (isEmpty && !isDefined && !force) return this; // We are going to remove this value.\n\n var remove = isEmpty && isDefined;\n if (remove) delete this.style[name];else this.style[name] = newValue; // Renderable is defined if StyleSheet option `link` is true.\n\n if (this.renderable && this.renderer) {\n if (remove) this.renderer.removeProperty(this.renderable, name);else this.renderer.setProperty(this.renderable, name, newValue);\n return this;\n }\n\n var sheet = this.options.sheet;\n\n if (sheet && sheet.attached) {\n process.env.NODE_ENV !== \"production\" ? warning__default['default'](false, '[JSS] Rule is not linked. Missing sheet option \"link: true\".') : void 0;\n }\n\n return this;\n };\n\n return BaseStyleRule;\n}();\nvar StyleRule =\n/*#__PURE__*/\nfunction (_BaseStyleRule) {\n _inheritsLoose__default['default'](StyleRule, _BaseStyleRule);\n\n function StyleRule(key, style, options) {\n var _this;\n\n _this = _BaseStyleRule.call(this, key, style, options) || this;\n var selector = options.selector,\n scoped = options.scoped,\n sheet = options.sheet,\n generateId = options.generateId;\n\n if (selector) {\n _this.selectorText = selector;\n } else if (scoped !== false) {\n _this.id = generateId(_assertThisInitialized__default['default'](_assertThisInitialized__default['default'](_this)), sheet);\n _this.selectorText = \".\" + escape(_this.id);\n }\n\n return _this;\n }\n /**\n * Set selector string.\n * Attention: use this with caution. Most browsers didn't implement\n * selectorText setter, so this may result in rerendering of entire Style Sheet.\n */\n\n\n var _proto2 = StyleRule.prototype;\n\n /**\n * Apply rule to an element inline.\n */\n _proto2.applyTo = function applyTo(renderable) {\n var renderer = this.renderer;\n\n if (renderer) {\n var json = this.toJSON();\n\n for (var prop in json) {\n renderer.setProperty(renderable, prop, json[prop]);\n }\n }\n\n return this;\n }\n /**\n * Returns JSON representation of the rule.\n * Fallbacks are not supported.\n * Useful for inline styles.\n */\n ;\n\n _proto2.toJSON = function toJSON() {\n var json = {};\n\n for (var prop in this.style) {\n var value = this.style[prop];\n if (typeof value !== 'object') json[prop] = value;else if (Array.isArray(value)) json[prop] = toCssValue(value);\n }\n\n return json;\n }\n /**\n * Generates a CSS string.\n */\n ;\n\n _proto2.toString = function toString(options) {\n var sheet = this.options.sheet;\n var link = sheet ? sheet.options.link : false;\n var opts = link ? _extends__default['default']({}, options, {\n allowEmpty: true\n }) : options;\n return toCss(this.selectorText, this.style, opts);\n };\n\n _createClass__default['default'](StyleRule, [{\n key: \"selector\",\n set: function set(selector) {\n if (selector === this.selectorText) return;\n this.selectorText = selector;\n var renderer = this.renderer,\n renderable = this.renderable;\n if (!renderable || !renderer) return;\n var hasChanged = renderer.setSelector(renderable, selector); // If selector setter is not implemented, rerender the rule.\n\n if (!hasChanged) {\n renderer.replaceRule(renderable, this);\n }\n }\n /**\n * Get selector string.\n */\n ,\n get: function get() {\n return this.selectorText;\n }\n }]);\n\n return StyleRule;\n}(BaseStyleRule);\nvar pluginStyleRule = {\n onCreateRule: function onCreateRule(key, style, options) {\n if (key[0] === '@' || options.parent && options.parent.type === 'keyframes') {\n return null;\n }\n\n return new StyleRule(key, style, options);\n }\n};\n\nvar defaultToStringOptions = {\n indent: 1,\n children: true\n};\nvar atRegExp = /@([\\w-]+)/;\n/**\n * Conditional rule for @media, @supports\n */\n\nvar ConditionalRule =\n/*#__PURE__*/\nfunction () {\n function ConditionalRule(key, styles, options) {\n this.type = 'conditional';\n this.isProcessed = false;\n this.key = key;\n var atMatch = key.match(atRegExp);\n this.at = atMatch ? atMatch[1] : 'unknown'; // Key might contain a unique suffix in case the `name` passed by user was duplicate.\n\n this.query = options.name || \"@\" + this.at;\n this.options = options;\n this.rules = new RuleList(_extends__default['default']({}, options, {\n parent: this\n }));\n\n for (var name in styles) {\n this.rules.add(name, styles[name]);\n }\n\n this.rules.process();\n }\n /**\n * Get a rule.\n */\n\n\n var _proto = ConditionalRule.prototype;\n\n _proto.getRule = function getRule(name) {\n return this.rules.get(name);\n }\n /**\n * Get index of a rule.\n */\n ;\n\n _proto.indexOf = function indexOf(rule) {\n return this.rules.indexOf(rule);\n }\n /**\n * Create and register rule, run plugins.\n */\n ;\n\n _proto.addRule = function addRule(name, style, options) {\n var rule = this.rules.add(name, style, options);\n if (!rule) return null;\n this.options.jss.plugins.onProcessRule(rule);\n return rule;\n }\n /**\n * Replace rule, run plugins.\n */\n ;\n\n _proto.replaceRule = function replaceRule(name, style, options) {\n var newRule = this.rules.replace(name, style, options);\n if (newRule) this.options.jss.plugins.onProcessRule(newRule);\n return newRule;\n }\n /**\n * Generates a CSS string.\n */\n ;\n\n _proto.toString = function toString(options) {\n if (options === void 0) {\n options = defaultToStringOptions;\n }\n\n var _getWhitespaceSymbols = getWhitespaceSymbols(options),\n linebreak = _getWhitespaceSymbols.linebreak;\n\n if (options.indent == null) options.indent = defaultToStringOptions.indent;\n if (options.children == null) options.children = defaultToStringOptions.children;\n\n if (options.children === false) {\n return this.query + \" {}\";\n }\n\n var children = this.rules.toString(options);\n return children ? this.query + \" {\" + linebreak + children + linebreak + \"}\" : '';\n };\n\n return ConditionalRule;\n}();\nvar keyRegExp = /@container|@media|@supports\\s+/;\nvar pluginConditionalRule = {\n onCreateRule: function onCreateRule(key, styles, options) {\n return keyRegExp.test(key) ? new ConditionalRule(key, styles, options) : null;\n }\n};\n\nvar defaultToStringOptions$1 = {\n indent: 1,\n children: true\n};\nvar nameRegExp = /@keyframes\\s+([\\w-]+)/;\n/**\n * Rule for @keyframes\n */\n\nvar KeyframesRule =\n/*#__PURE__*/\nfunction () {\n function KeyframesRule(key, frames, options) {\n this.type = 'keyframes';\n this.at = '@keyframes';\n this.isProcessed = false;\n var nameMatch = key.match(nameRegExp);\n\n if (nameMatch && nameMatch[1]) {\n this.name = nameMatch[1];\n } else {\n this.name = 'noname';\n process.env.NODE_ENV !== \"production\" ? warning__default['default'](false, \"[JSS] Bad keyframes name \" + key) : void 0;\n }\n\n this.key = this.type + \"-\" + this.name;\n this.options = options;\n var scoped = options.scoped,\n sheet = options.sheet,\n generateId = options.generateId;\n this.id = scoped === false ? this.name : escape(generateId(this, sheet));\n this.rules = new RuleList(_extends__default['default']({}, options, {\n parent: this\n }));\n\n for (var name in frames) {\n this.rules.add(name, frames[name], _extends__default['default']({}, options, {\n parent: this\n }));\n }\n\n this.rules.process();\n }\n /**\n * Generates a CSS string.\n */\n\n\n var _proto = KeyframesRule.prototype;\n\n _proto.toString = function toString(options) {\n if (options === void 0) {\n options = defaultToStringOptions$1;\n }\n\n var _getWhitespaceSymbols = getWhitespaceSymbols(options),\n linebreak = _getWhitespaceSymbols.linebreak;\n\n if (options.indent == null) options.indent = defaultToStringOptions$1.indent;\n if (options.children == null) options.children = defaultToStringOptions$1.children;\n\n if (options.children === false) {\n return this.at + \" \" + this.id + \" {}\";\n }\n\n var children = this.rules.toString(options);\n if (children) children = \"\" + linebreak + children + linebreak;\n return this.at + \" \" + this.id + \" {\" + children + \"}\";\n };\n\n return KeyframesRule;\n}();\nvar keyRegExp$1 = /@keyframes\\s+/;\nvar refRegExp = /\\$([\\w-]+)/g;\n\nvar findReferencedKeyframe = function findReferencedKeyframe(val, keyframes) {\n if (typeof val === 'string') {\n return val.replace(refRegExp, function (match, name) {\n if (name in keyframes) {\n return keyframes[name];\n }\n\n process.env.NODE_ENV !== \"production\" ? warning__default['default'](false, \"[JSS] Referenced keyframes rule \\\"\" + name + \"\\\" is not defined.\") : void 0;\n return match;\n });\n }\n\n return val;\n};\n/**\n * Replace the reference for a animation name.\n */\n\n\nvar replaceRef = function replaceRef(style, prop, keyframes) {\n var value = style[prop];\n var refKeyframe = findReferencedKeyframe(value, keyframes);\n\n if (refKeyframe !== value) {\n style[prop] = refKeyframe;\n }\n};\n\nvar pluginKeyframesRule = {\n onCreateRule: function onCreateRule(key, frames, options) {\n return typeof key === 'string' && keyRegExp$1.test(key) ? new KeyframesRule(key, frames, options) : null;\n },\n // Animation name ref replacer.\n onProcessStyle: function onProcessStyle(style, rule, sheet) {\n if (rule.type !== 'style' || !sheet) return style;\n if ('animation-name' in style) replaceRef(style, 'animation-name', sheet.keyframes);\n if ('animation' in style) replaceRef(style, 'animation', sheet.keyframes);\n return style;\n },\n onChangeValue: function onChangeValue(val, prop, rule) {\n var sheet = rule.options.sheet;\n\n if (!sheet) {\n return val;\n }\n\n switch (prop) {\n case 'animation':\n return findReferencedKeyframe(val, sheet.keyframes);\n\n case 'animation-name':\n return findReferencedKeyframe(val, sheet.keyframes);\n\n default:\n return val;\n }\n }\n};\n\nvar KeyframeRule =\n/*#__PURE__*/\nfunction (_BaseStyleRule) {\n _inheritsLoose__default['default'](KeyframeRule, _BaseStyleRule);\n\n function KeyframeRule() {\n return _BaseStyleRule.apply(this, arguments) || this;\n }\n\n var _proto = KeyframeRule.prototype;\n\n /**\n * Generates a CSS string.\n */\n _proto.toString = function toString(options) {\n var sheet = this.options.sheet;\n var link = sheet ? sheet.options.link : false;\n var opts = link ? _extends__default['default']({}, options, {\n allowEmpty: true\n }) : options;\n return toCss(this.key, this.style, opts);\n };\n\n return KeyframeRule;\n}(BaseStyleRule);\nvar pluginKeyframeRule = {\n onCreateRule: function onCreateRule(key, style, options) {\n if (options.parent && options.parent.type === 'keyframes') {\n return new KeyframeRule(key, style, options);\n }\n\n return null;\n }\n};\n\nvar FontFaceRule =\n/*#__PURE__*/\nfunction () {\n function FontFaceRule(key, style, options) {\n this.type = 'font-face';\n this.at = '@font-face';\n this.isProcessed = false;\n this.key = key;\n this.style = style;\n this.options = options;\n }\n /**\n * Generates a CSS string.\n */\n\n\n var _proto = FontFaceRule.prototype;\n\n _proto.toString = function toString(options) {\n var _getWhitespaceSymbols = getWhitespaceSymbols(options),\n linebreak = _getWhitespaceSymbols.linebreak;\n\n if (Array.isArray(this.style)) {\n var str = '';\n\n for (var index = 0; index < this.style.length; index++) {\n str += toCss(this.at, this.style[index]);\n if (this.style[index + 1]) str += linebreak;\n }\n\n return str;\n }\n\n return toCss(this.at, this.style, options);\n };\n\n return FontFaceRule;\n}();\nvar keyRegExp$2 = /@font-face/;\nvar pluginFontFaceRule = {\n onCreateRule: function onCreateRule(key, style, options) {\n return keyRegExp$2.test(key) ? new FontFaceRule(key, style, options) : null;\n }\n};\n\nvar ViewportRule =\n/*#__PURE__*/\nfunction () {\n function ViewportRule(key, style, options) {\n this.type = 'viewport';\n this.at = '@viewport';\n this.isProcessed = false;\n this.key = key;\n this.style = style;\n this.options = options;\n }\n /**\n * Generates a CSS string.\n */\n\n\n var _proto = ViewportRule.prototype;\n\n _proto.toString = function toString(options) {\n return toCss(this.key, this.style, options);\n };\n\n return ViewportRule;\n}();\nvar pluginViewportRule = {\n onCreateRule: function onCreateRule(key, style, options) {\n return key === '@viewport' || key === '@-ms-viewport' ? new ViewportRule(key, style, options) : null;\n }\n};\n\nvar SimpleRule =\n/*#__PURE__*/\nfunction () {\n function SimpleRule(key, value, options) {\n this.type = 'simple';\n this.isProcessed = false;\n this.key = key;\n this.value = value;\n this.options = options;\n }\n /**\n * Generates a CSS string.\n */\n // eslint-disable-next-line no-unused-vars\n\n\n var _proto = SimpleRule.prototype;\n\n _proto.toString = function toString(options) {\n if (Array.isArray(this.value)) {\n var str = '';\n\n for (var index = 0; index < this.value.length; index++) {\n str += this.key + \" \" + this.value[index] + \";\";\n if (this.value[index + 1]) str += '\\n';\n }\n\n return str;\n }\n\n return this.key + \" \" + this.value + \";\";\n };\n\n return SimpleRule;\n}();\nvar keysMap = {\n '@charset': true,\n '@import': true,\n '@namespace': true\n};\nvar pluginSimpleRule = {\n onCreateRule: function onCreateRule(key, value, options) {\n return key in keysMap ? new SimpleRule(key, value, options) : null;\n }\n};\n\nvar plugins = [pluginStyleRule, pluginConditionalRule, pluginKeyframesRule, pluginKeyframeRule, pluginFontFaceRule, pluginViewportRule, pluginSimpleRule];\n\nvar defaultUpdateOptions = {\n process: true\n};\nvar forceUpdateOptions = {\n force: true,\n process: true\n /**\n * Contains rules objects and allows adding/removing etc.\n * Is used for e.g. by `StyleSheet` or `ConditionalRule`.\n */\n\n};\n\nvar RuleList =\n/*#__PURE__*/\nfunction () {\n // Rules registry for access by .get() method.\n // It contains the same rule registered by name and by selector.\n // Original styles object.\n // Used to ensure correct rules order.\n function RuleList(options) {\n this.map = {};\n this.raw = {};\n this.index = [];\n this.counter = 0;\n this.options = options;\n this.classes = options.classes;\n this.keyframes = options.keyframes;\n }\n /**\n * Create and register rule.\n *\n * Will not render after Style Sheet was rendered the first time.\n */\n\n\n var _proto = RuleList.prototype;\n\n _proto.add = function add(name, decl, ruleOptions) {\n var _this$options = this.options,\n parent = _this$options.parent,\n sheet = _this$options.sheet,\n jss = _this$options.jss,\n Renderer = _this$options.Renderer,\n generateId = _this$options.generateId,\n scoped = _this$options.scoped;\n\n var options = _extends__default['default']({\n classes: this.classes,\n parent: parent,\n sheet: sheet,\n jss: jss,\n Renderer: Renderer,\n generateId: generateId,\n scoped: scoped,\n name: name,\n keyframes: this.keyframes,\n selector: undefined\n }, ruleOptions); // When user uses .createStyleSheet(), duplicate names are not possible, but\n // `sheet.addRule()` opens the door for any duplicate rule name. When this happens\n // we need to make the key unique within this RuleList instance scope.\n\n\n var key = name;\n\n if (name in this.raw) {\n key = name + \"-d\" + this.counter++;\n } // We need to save the original decl before creating the rule\n // because cache plugin needs to use it as a key to return a cached rule.\n\n\n this.raw[key] = decl;\n\n if (key in this.classes) {\n // E.g. rules inside of @media container\n options.selector = \".\" + escape(this.classes[key]);\n }\n\n var rule = createRule(key, decl, options);\n if (!rule) return null;\n this.register(rule);\n var index = options.index === undefined ? this.index.length : options.index;\n this.index.splice(index, 0, rule);\n return rule;\n }\n /**\n * Replace rule.\n * Create a new rule and remove old one instead of overwriting\n * because we want to invoke onCreateRule hook to make plugins work.\n */\n ;\n\n _proto.replace = function replace(name, decl, ruleOptions) {\n var oldRule = this.get(name);\n var oldIndex = this.index.indexOf(oldRule);\n\n if (oldRule) {\n this.remove(oldRule);\n }\n\n var options = ruleOptions;\n if (oldIndex !== -1) options = _extends__default['default']({}, ruleOptions, {\n index: oldIndex\n });\n return this.add(name, decl, options);\n }\n /**\n * Get a rule by name or selector.\n */\n ;\n\n _proto.get = function get(nameOrSelector) {\n return this.map[nameOrSelector];\n }\n /**\n * Delete a rule.\n */\n ;\n\n _proto.remove = function remove(rule) {\n this.unregister(rule);\n delete this.raw[rule.key];\n this.index.splice(this.index.indexOf(rule), 1);\n }\n /**\n * Get index of a rule.\n */\n ;\n\n _proto.indexOf = function indexOf(rule) {\n return this.index.indexOf(rule);\n }\n /**\n * Run `onProcessRule()` plugins on every rule.\n */\n ;\n\n _proto.process = function process() {\n var plugins = this.options.jss.plugins; // We need to clone array because if we modify the index somewhere else during a loop\n // we end up with very hard-to-track-down side effects.\n\n this.index.slice(0).forEach(plugins.onProcessRule, plugins);\n }\n /**\n * Register a rule in `.map`, `.classes` and `.keyframes` maps.\n */\n ;\n\n _proto.register = function register(rule) {\n this.map[rule.key] = rule;\n\n if (rule instanceof StyleRule) {\n this.map[rule.selector] = rule;\n if (rule.id) this.classes[rule.key] = rule.id;\n } else if (rule instanceof KeyframesRule && this.keyframes) {\n this.keyframes[rule.name] = rule.id;\n }\n }\n /**\n * Unregister a rule.\n */\n ;\n\n _proto.unregister = function unregister(rule) {\n delete this.map[rule.key];\n\n if (rule instanceof StyleRule) {\n delete this.map[rule.selector];\n delete this.classes[rule.key];\n } else if (rule instanceof KeyframesRule) {\n delete this.keyframes[rule.name];\n }\n }\n /**\n * Update the function values with a new data.\n */\n ;\n\n _proto.update = function update() {\n var name;\n var data;\n var options;\n\n if (typeof (arguments.length <= 0 ? undefined : arguments[0]) === 'string') {\n name = arguments.length <= 0 ? undefined : arguments[0];\n data = arguments.length <= 1 ? undefined : arguments[1];\n options = arguments.length <= 2 ? undefined : arguments[2];\n } else {\n data = arguments.length <= 0 ? undefined : arguments[0];\n options = arguments.length <= 1 ? undefined : arguments[1];\n name = null;\n }\n\n if (name) {\n this.updateOne(this.get(name), data, options);\n } else {\n for (var index = 0; index < this.index.length; index++) {\n this.updateOne(this.index[index], data, options);\n }\n }\n }\n /**\n * Execute plugins, update rule props.\n */\n ;\n\n _proto.updateOne = function updateOne(rule, data, options) {\n if (options === void 0) {\n options = defaultUpdateOptions;\n }\n\n var _this$options2 = this.options,\n plugins = _this$options2.jss.plugins,\n sheet = _this$options2.sheet; // It is a rules container like for e.g. ConditionalRule.\n\n if (rule.rules instanceof RuleList) {\n rule.rules.update(data, options);\n return;\n }\n\n var style = rule.style;\n plugins.onUpdate(data, rule, sheet, options); // We rely on a new `style` ref in case it was mutated during onUpdate hook.\n\n if (options.process && style && style !== rule.style) {\n // We need to run the plugins in case new `style` relies on syntax plugins.\n plugins.onProcessStyle(rule.style, rule, sheet); // Update and add props.\n\n for (var prop in rule.style) {\n var nextValue = rule.style[prop];\n var prevValue = style[prop]; // We need to use `force: true` because `rule.style` has been updated during onUpdate hook, so `rule.prop()` will not update the CSSOM rule.\n // We do this comparison to avoid unneeded `rule.prop()` calls, since we have the old `style` object here.\n\n if (nextValue !== prevValue) {\n rule.prop(prop, nextValue, forceUpdateOptions);\n }\n } // Remove props.\n\n\n for (var _prop in style) {\n var _nextValue = rule.style[_prop];\n var _prevValue = style[_prop]; // We need to use `force: true` because `rule.style` has been updated during onUpdate hook, so `rule.prop()` will not update the CSSOM rule.\n // We do this comparison to avoid unneeded `rule.prop()` calls, since we have the old `style` object here.\n\n if (_nextValue == null && _nextValue !== _prevValue) {\n rule.prop(_prop, null, forceUpdateOptions);\n }\n }\n }\n }\n /**\n * Convert rules to a CSS string.\n */\n ;\n\n _proto.toString = function toString(options) {\n var str = '';\n var sheet = this.options.sheet;\n var link = sheet ? sheet.options.link : false;\n\n var _getWhitespaceSymbols = getWhitespaceSymbols(options),\n linebreak = _getWhitespaceSymbols.linebreak;\n\n for (var index = 0; index < this.index.length; index++) {\n var rule = this.index[index];\n var css = rule.toString(options); // No need to render an empty rule.\n\n if (!css && !link) continue;\n if (str) str += linebreak;\n str += css;\n }\n\n return str;\n };\n\n return RuleList;\n}();\n\nvar StyleSheet =\n/*#__PURE__*/\nfunction () {\n function StyleSheet(styles, options) {\n this.attached = false;\n this.deployed = false;\n this.classes = {};\n this.keyframes = {};\n this.options = _extends__default['default']({}, options, {\n sheet: this,\n parent: this,\n classes: this.classes,\n keyframes: this.keyframes\n });\n\n if (options.Renderer) {\n this.renderer = new options.Renderer(this);\n }\n\n this.rules = new RuleList(this.options);\n\n for (var name in styles) {\n this.rules.add(name, styles[name]);\n }\n\n this.rules.process();\n }\n /**\n * Attach renderable to the render tree.\n */\n\n\n var _proto = StyleSheet.prototype;\n\n _proto.attach = function attach() {\n if (this.attached) return this;\n if (this.renderer) this.renderer.attach();\n this.attached = true; // Order is important, because we can't use insertRule API if style element is not attached.\n\n if (!this.deployed) this.deploy();\n return this;\n }\n /**\n * Remove renderable from render tree.\n */\n ;\n\n _proto.detach = function detach() {\n if (!this.attached) return this;\n if (this.renderer) this.renderer.detach();\n this.attached = false;\n return this;\n }\n /**\n * Add a rule to the current stylesheet.\n * Will insert a rule also after the stylesheet has been rendered first time.\n */\n ;\n\n _proto.addRule = function addRule(name, decl, options) {\n var queue = this.queue; // Plugins can create rules.\n // In order to preserve the right order, we need to queue all `.addRule` calls,\n // which happen after the first `rules.add()` call.\n\n if (this.attached && !queue) this.queue = [];\n var rule = this.rules.add(name, decl, options);\n if (!rule) return null;\n this.options.jss.plugins.onProcessRule(rule);\n\n if (this.attached) {\n if (!this.deployed) return rule; // Don't insert rule directly if there is no stringified version yet.\n // It will be inserted all together when .attach is called.\n\n if (queue) queue.push(rule);else {\n this.insertRule(rule);\n\n if (this.queue) {\n this.queue.forEach(this.insertRule, this);\n this.queue = undefined;\n }\n }\n return rule;\n } // We can't add rules to a detached style node.\n // We will redeploy the sheet once user will attach it.\n\n\n this.deployed = false;\n return rule;\n }\n /**\n * Replace a rule in the current stylesheet.\n */\n ;\n\n _proto.replaceRule = function replaceRule(nameOrSelector, decl, options) {\n var oldRule = this.rules.get(nameOrSelector);\n if (!oldRule) return this.addRule(nameOrSelector, decl, options);\n var newRule = this.rules.replace(nameOrSelector, decl, options);\n\n if (newRule) {\n this.options.jss.plugins.onProcessRule(newRule);\n }\n\n if (this.attached) {\n if (!this.deployed) return newRule; // Don't replace / delete rule directly if there is no stringified version yet.\n // It will be inserted all together when .attach is called.\n\n if (this.renderer) {\n if (!newRule) {\n this.renderer.deleteRule(oldRule);\n } else if (oldRule.renderable) {\n this.renderer.replaceRule(oldRule.renderable, newRule);\n }\n }\n\n return newRule;\n } // We can't replace rules to a detached style node.\n // We will redeploy the sheet once user will attach it.\n\n\n this.deployed = false;\n return newRule;\n }\n /**\n * Insert rule into the StyleSheet\n */\n ;\n\n _proto.insertRule = function insertRule(rule) {\n if (this.renderer) {\n this.renderer.insertRule(rule);\n }\n }\n /**\n * Create and add rules.\n * Will render also after Style Sheet was rendered the first time.\n */\n ;\n\n _proto.addRules = function addRules(styles, options) {\n var added = [];\n\n for (var name in styles) {\n var rule = this.addRule(name, styles[name], options);\n if (rule) added.push(rule);\n }\n\n return added;\n }\n /**\n * Get a rule by name or selector.\n */\n ;\n\n _proto.getRule = function getRule(nameOrSelector) {\n return this.rules.get(nameOrSelector);\n }\n /**\n * Delete a rule by name.\n * Returns `true`: if rule has been deleted from the DOM.\n */\n ;\n\n _proto.deleteRule = function deleteRule(name) {\n var rule = typeof name === 'object' ? name : this.rules.get(name);\n\n if (!rule || // Style sheet was created without link: true and attached, in this case we\n // won't be able to remove the CSS rule from the DOM.\n this.attached && !rule.renderable) {\n return false;\n }\n\n this.rules.remove(rule);\n\n if (this.attached && rule.renderable && this.renderer) {\n return this.renderer.deleteRule(rule.renderable);\n }\n\n return true;\n }\n /**\n * Get index of a rule.\n */\n ;\n\n _proto.indexOf = function indexOf(rule) {\n return this.rules.indexOf(rule);\n }\n /**\n * Deploy pure CSS string to a renderable.\n */\n ;\n\n _proto.deploy = function deploy() {\n if (this.renderer) this.renderer.deploy();\n this.deployed = true;\n return this;\n }\n /**\n * Update the function values with a new data.\n */\n ;\n\n _proto.update = function update() {\n var _this$rules;\n\n (_this$rules = this.rules).update.apply(_this$rules, arguments);\n\n return this;\n }\n /**\n * Updates a single rule.\n */\n ;\n\n _proto.updateOne = function updateOne(rule, data, options) {\n this.rules.updateOne(rule, data, options);\n return this;\n }\n /**\n * Convert rules to a CSS string.\n */\n ;\n\n _proto.toString = function toString(options) {\n return this.rules.toString(options);\n };\n\n return StyleSheet;\n}();\n\nvar PluginsRegistry =\n/*#__PURE__*/\nfunction () {\n function PluginsRegistry() {\n this.plugins = {\n internal: [],\n external: []\n };\n this.registry = {};\n }\n\n var _proto = PluginsRegistry.prototype;\n\n /**\n * Call `onCreateRule` hooks and return an object if returned by a hook.\n */\n _proto.onCreateRule = function onCreateRule(name, decl, options) {\n for (var i = 0; i < this.registry.onCreateRule.length; i++) {\n var rule = this.registry.onCreateRule[i](name, decl, options);\n if (rule) return rule;\n }\n\n return null;\n }\n /**\n * Call `onProcessRule` hooks.\n */\n ;\n\n _proto.onProcessRule = function onProcessRule(rule) {\n if (rule.isProcessed) return;\n var sheet = rule.options.sheet;\n\n for (var i = 0; i < this.registry.onProcessRule.length; i++) {\n this.registry.onProcessRule[i](rule, sheet);\n }\n\n if (rule.style) this.onProcessStyle(rule.style, rule, sheet);\n rule.isProcessed = true;\n }\n /**\n * Call `onProcessStyle` hooks.\n */\n ;\n\n _proto.onProcessStyle = function onProcessStyle(style, rule, sheet) {\n for (var i = 0; i < this.registry.onProcessStyle.length; i++) {\n rule.style = this.registry.onProcessStyle[i](rule.style, rule, sheet);\n }\n }\n /**\n * Call `onProcessSheet` hooks.\n */\n ;\n\n _proto.onProcessSheet = function onProcessSheet(sheet) {\n for (var i = 0; i < this.registry.onProcessSheet.length; i++) {\n this.registry.onProcessSheet[i](sheet);\n }\n }\n /**\n * Call `onUpdate` hooks.\n */\n ;\n\n _proto.onUpdate = function onUpdate(data, rule, sheet, options) {\n for (var i = 0; i < this.registry.onUpdate.length; i++) {\n this.registry.onUpdate[i](data, rule, sheet, options);\n }\n }\n /**\n * Call `onChangeValue` hooks.\n */\n ;\n\n _proto.onChangeValue = function onChangeValue(value, prop, rule) {\n var processedValue = value;\n\n for (var i = 0; i < this.registry.onChangeValue.length; i++) {\n processedValue = this.registry.onChangeValue[i](processedValue, prop, rule);\n }\n\n return processedValue;\n }\n /**\n * Register a plugin.\n */\n ;\n\n _proto.use = function use(newPlugin, options) {\n if (options === void 0) {\n options = {\n queue: 'external'\n };\n }\n\n var plugins = this.plugins[options.queue]; // Avoids applying same plugin twice, at least based on ref.\n\n if (plugins.indexOf(newPlugin) !== -1) {\n return;\n }\n\n plugins.push(newPlugin);\n this.registry = [].concat(this.plugins.external, this.plugins.internal).reduce(function (registry, plugin) {\n for (var name in plugin) {\n if (name in registry) {\n registry[name].push(plugin[name]);\n } else {\n process.env.NODE_ENV !== \"production\" ? warning__default['default'](false, \"[JSS] Unknown hook \\\"\" + name + \"\\\".\") : void 0;\n }\n }\n\n return registry;\n }, {\n onCreateRule: [],\n onProcessRule: [],\n onProcessStyle: [],\n onProcessSheet: [],\n onChangeValue: [],\n onUpdate: []\n });\n };\n\n return PluginsRegistry;\n}();\n\n/**\n * Sheets registry to access all instances in one place.\n */\n\nvar SheetsRegistry =\n/*#__PURE__*/\nfunction () {\n function SheetsRegistry() {\n this.registry = [];\n }\n\n var _proto = SheetsRegistry.prototype;\n\n /**\n * Register a Style Sheet.\n */\n _proto.add = function add(sheet) {\n var registry = this.registry;\n var index = sheet.options.index;\n if (registry.indexOf(sheet) !== -1) return;\n\n if (registry.length === 0 || index >= this.index) {\n registry.push(sheet);\n return;\n } // Find a position.\n\n\n for (var i = 0; i < registry.length; i++) {\n if (registry[i].options.index > index) {\n registry.splice(i, 0, sheet);\n return;\n }\n }\n }\n /**\n * Reset the registry.\n */\n ;\n\n _proto.reset = function reset() {\n this.registry = [];\n }\n /**\n * Remove a Style Sheet.\n */\n ;\n\n _proto.remove = function remove(sheet) {\n var index = this.registry.indexOf(sheet);\n this.registry.splice(index, 1);\n }\n /**\n * Convert all attached sheets to a CSS string.\n */\n ;\n\n _proto.toString = function toString(_temp) {\n var _ref = _temp === void 0 ? {} : _temp,\n attached = _ref.attached,\n options = _objectWithoutPropertiesLoose__default['default'](_ref, [\"attached\"]);\n\n var _getWhitespaceSymbols = getWhitespaceSymbols(options),\n linebreak = _getWhitespaceSymbols.linebreak;\n\n var css = '';\n\n for (var i = 0; i < this.registry.length; i++) {\n var sheet = this.registry[i];\n\n if (attached != null && sheet.attached !== attached) {\n continue;\n }\n\n if (css) css += linebreak;\n css += sheet.toString(options);\n }\n\n return css;\n };\n\n _createClass__default['default'](SheetsRegistry, [{\n key: \"index\",\n\n /**\n * Current highest index number.\n */\n get: function get() {\n return this.registry.length === 0 ? 0 : this.registry[this.registry.length - 1].options.index;\n }\n }]);\n\n return SheetsRegistry;\n}();\n\n/**\n * This is a global sheets registry. Only DomRenderer will add sheets to it.\n * On the server one should use an own SheetsRegistry instance and add the\n * sheets to it, because you need to make sure to create a new registry for\n * each request in order to not leak sheets across requests.\n */\n\nvar sheets = new SheetsRegistry();\n\n/* eslint-disable */\n\n/**\n * Now that `globalThis` is available on most platforms\n * (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis#browser_compatibility)\n * we check for `globalThis` first. `globalThis` is necessary for jss\n * to run in Agoric's secure version of JavaScript (SES). Under SES,\n * `globalThis` exists, but `window`, `self`, and `Function('return\n * this')()` are all undefined for security reasons.\n *\n * https://github.com/zloirock/core-js/issues/86#issuecomment-115759028\n */\nvar globalThis$1 = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' && window.Math === Math ? window : typeof self !== 'undefined' && self.Math === Math ? self : Function('return this')();\n\nvar ns = '2f1acc6c3a606b082e5eef5e54414ffb';\nif (globalThis$1[ns] == null) globalThis$1[ns] = 0; // Bundle may contain multiple JSS versions at the same time. In order to identify\n// the current version with just one short number and use it for classes generation\n// we use a counter. Also it is more accurate, because user can manually reevaluate\n// the module.\n\nvar moduleId = globalThis$1[ns]++;\n\nvar maxRules = 1e10;\n/**\n * Returns a function which generates unique class names based on counters.\n * When new generator function is created, rule counter is reseted.\n * We need to reset the rule counter for SSR for each request.\n */\n\nvar createGenerateId = function createGenerateId(options) {\n if (options === void 0) {\n options = {};\n }\n\n var ruleCounter = 0;\n\n var generateId = function generateId(rule, sheet) {\n ruleCounter += 1;\n\n if (ruleCounter > maxRules) {\n process.env.NODE_ENV !== \"production\" ? warning__default['default'](false, \"[JSS] You might have a memory leak. Rule counter is at \" + ruleCounter + \".\") : void 0;\n }\n\n var jssId = '';\n var prefix = '';\n\n if (sheet) {\n if (sheet.options.classNamePrefix) {\n prefix = sheet.options.classNamePrefix;\n }\n\n if (sheet.options.jss.id != null) {\n jssId = String(sheet.options.jss.id);\n }\n }\n\n if (options.minify) {\n // Using \"c\" because a number can't be the first char in a class name.\n return \"\" + (prefix || 'c') + moduleId + jssId + ruleCounter;\n }\n\n return prefix + rule.key + \"-\" + moduleId + (jssId ? \"-\" + jssId : '') + \"-\" + ruleCounter;\n };\n\n return generateId;\n};\n\n/**\n * Cache the value from the first time a function is called.\n */\n\nvar memoize = function memoize(fn) {\n var value;\n return function () {\n if (!value) value = fn();\n return value;\n };\n};\n/**\n * Get a style property value.\n */\n\n\nvar getPropertyValue = function getPropertyValue(cssRule, prop) {\n try {\n // Support CSSTOM.\n if (cssRule.attributeStyleMap) {\n return cssRule.attributeStyleMap.get(prop);\n }\n\n return cssRule.style.getPropertyValue(prop);\n } catch (err) {\n // IE may throw if property is unknown.\n return '';\n }\n};\n/**\n * Set a style property.\n */\n\n\nvar setProperty = function setProperty(cssRule, prop, value) {\n try {\n var cssValue = value;\n\n if (Array.isArray(value)) {\n cssValue = toCssValue(value);\n } // Support CSSTOM.\n\n\n if (cssRule.attributeStyleMap) {\n cssRule.attributeStyleMap.set(prop, cssValue);\n } else {\n var indexOfImportantFlag = cssValue ? cssValue.indexOf('!important') : -1;\n var cssValueWithoutImportantFlag = indexOfImportantFlag > -1 ? cssValue.substr(0, indexOfImportantFlag - 1) : cssValue;\n cssRule.style.setProperty(prop, cssValueWithoutImportantFlag, indexOfImportantFlag > -1 ? 'important' : '');\n }\n } catch (err) {\n // IE may throw if property is unknown.\n return false;\n }\n\n return true;\n};\n/**\n * Remove a style property.\n */\n\n\nvar removeProperty = function removeProperty(cssRule, prop) {\n try {\n // Support CSSTOM.\n if (cssRule.attributeStyleMap) {\n cssRule.attributeStyleMap.delete(prop);\n } else {\n cssRule.style.removeProperty(prop);\n }\n } catch (err) {\n process.env.NODE_ENV !== \"production\" ? warning__default['default'](false, \"[JSS] DOMException \\\"\" + err.message + \"\\\" was thrown. Tried to remove property \\\"\" + prop + \"\\\".\") : void 0;\n }\n};\n/**\n * Set the selector.\n */\n\n\nvar setSelector = function setSelector(cssRule, selectorText) {\n cssRule.selectorText = selectorText; // Return false if setter was not successful.\n // Currently works in chrome only.\n\n return cssRule.selectorText === selectorText;\n};\n/**\n * Gets the `head` element upon the first call and caches it.\n * We assume it can't be null.\n */\n\n\nvar getHead = memoize(function () {\n return document.querySelector('head');\n});\n/**\n * Find attached sheet with an index higher than the passed one.\n */\n\nfunction findHigherSheet(registry, options) {\n for (var i = 0; i < registry.length; i++) {\n var sheet = registry[i];\n\n if (sheet.attached && sheet.options.index > options.index && sheet.options.insertionPoint === options.insertionPoint) {\n return sheet;\n }\n }\n\n return null;\n}\n/**\n * Find attached sheet with the highest index.\n */\n\n\nfunction findHighestSheet(registry, options) {\n for (var i = registry.length - 1; i >= 0; i--) {\n var sheet = registry[i];\n\n if (sheet.attached && sheet.options.insertionPoint === options.insertionPoint) {\n return sheet;\n }\n }\n\n return null;\n}\n/**\n * Find a comment with \"jss\" inside.\n */\n\n\nfunction findCommentNode(text) {\n var head = getHead();\n\n for (var i = 0; i < head.childNodes.length; i++) {\n var node = head.childNodes[i];\n\n if (node.nodeType === 8 && node.nodeValue.trim() === text) {\n return node;\n }\n }\n\n return null;\n}\n/**\n * Find a node before which we can insert the sheet.\n */\n\n\nfunction findPrevNode(options) {\n var registry = sheets.registry;\n\n if (registry.length > 0) {\n // Try to insert before the next higher sheet.\n var sheet = findHigherSheet(registry, options);\n\n if (sheet && sheet.renderer) {\n return {\n parent: sheet.renderer.element.parentNode,\n node: sheet.renderer.element\n };\n } // Otherwise insert after the last attached.\n\n\n sheet = findHighestSheet(registry, options);\n\n if (sheet && sheet.renderer) {\n return {\n parent: sheet.renderer.element.parentNode,\n node: sheet.renderer.element.nextSibling\n };\n }\n } // Try to find a comment placeholder if registry is empty.\n\n\n var insertionPoint = options.insertionPoint;\n\n if (insertionPoint && typeof insertionPoint === 'string') {\n var comment = findCommentNode(insertionPoint);\n\n if (comment) {\n return {\n parent: comment.parentNode,\n node: comment.nextSibling\n };\n } // If user specifies an insertion point and it can't be found in the document -\n // bad specificity issues may appear.\n\n\n process.env.NODE_ENV !== \"production\" ? warning__default['default'](false, \"[JSS] Insertion point \\\"\" + insertionPoint + \"\\\" not found.\") : void 0;\n }\n\n return false;\n}\n/**\n * Insert style element into the DOM.\n */\n\n\nfunction insertStyle(style, options) {\n var insertionPoint = options.insertionPoint;\n var nextNode = findPrevNode(options);\n\n if (nextNode !== false && nextNode.parent) {\n nextNode.parent.insertBefore(style, nextNode.node);\n return;\n } // Works with iframes and any node types.\n\n\n if (insertionPoint && typeof insertionPoint.nodeType === 'number') {\n var insertionPointElement = insertionPoint;\n var parentNode = insertionPointElement.parentNode;\n if (parentNode) parentNode.insertBefore(style, insertionPointElement.nextSibling);else process.env.NODE_ENV !== \"production\" ? warning__default['default'](false, '[JSS] Insertion point is not in the DOM.') : void 0;\n return;\n }\n\n getHead().appendChild(style);\n}\n/**\n * Read jss nonce setting from the page if the user has set it.\n */\n\n\nvar getNonce = memoize(function () {\n var node = document.querySelector('meta[property=\"csp-nonce\"]');\n return node ? node.getAttribute('content') : null;\n});\n\nvar _insertRule = function insertRule(container, rule, index) {\n try {\n if ('insertRule' in container) {\n container.insertRule(rule, index);\n } // Keyframes rule.\n else if ('appendRule' in container) {\n container.appendRule(rule);\n }\n } catch (err) {\n process.env.NODE_ENV !== \"production\" ? warning__default['default'](false, \"[JSS] \" + err.message) : void 0;\n return false;\n }\n\n return container.cssRules[index];\n};\n\nvar getValidRuleInsertionIndex = function getValidRuleInsertionIndex(container, index) {\n var maxIndex = container.cssRules.length; // In case previous insertion fails, passed index might be wrong\n\n if (index === undefined || index > maxIndex) {\n // eslint-disable-next-line no-param-reassign\n return maxIndex;\n }\n\n return index;\n};\n\nvar createStyle = function createStyle() {\n var el = document.createElement('style'); // Without it, IE will have a broken source order specificity if we\n // insert rules after we insert the style tag.\n // It seems to kick-off the source order specificity algorithm.\n\n el.textContent = '\\n';\n return el;\n};\n\nvar DomRenderer =\n/*#__PURE__*/\nfunction () {\n // Will be empty if link: true option is not set, because\n // it is only for use together with insertRule API.\n function DomRenderer(sheet) {\n this.getPropertyValue = getPropertyValue;\n this.setProperty = setProperty;\n this.removeProperty = removeProperty;\n this.setSelector = setSelector;\n this.hasInsertedRules = false;\n this.cssRules = [];\n // There is no sheet when the renderer is used from a standalone StyleRule.\n if (sheet) sheets.add(sheet);\n this.sheet = sheet;\n\n var _ref = this.sheet ? this.sheet.options : {},\n media = _ref.media,\n meta = _ref.meta,\n element = _ref.element;\n\n this.element = element || createStyle();\n this.element.setAttribute('data-jss', '');\n if (media) this.element.setAttribute('media', media);\n if (meta) this.element.setAttribute('data-meta', meta);\n var nonce = getNonce();\n if (nonce) this.element.setAttribute('nonce', nonce);\n }\n /**\n * Insert style element into render tree.\n */\n\n\n var _proto = DomRenderer.prototype;\n\n _proto.attach = function attach() {\n // In the case the element node is external and it is already in the DOM.\n if (this.element.parentNode || !this.sheet) return;\n insertStyle(this.element, this.sheet.options); // When rules are inserted using `insertRule` API, after `sheet.detach().attach()`\n // most browsers create a new CSSStyleSheet, except of all IEs.\n\n var deployed = Boolean(this.sheet && this.sheet.deployed);\n\n if (this.hasInsertedRules && deployed) {\n this.hasInsertedRules = false;\n this.deploy();\n }\n }\n /**\n * Remove style element from render tree.\n */\n ;\n\n _proto.detach = function detach() {\n if (!this.sheet) return;\n var parentNode = this.element.parentNode;\n if (parentNode) parentNode.removeChild(this.element); // In the most browsers, rules inserted using insertRule() API will be lost when style element is removed.\n // Though IE will keep them and we need a consistent behavior.\n\n if (this.sheet.options.link) {\n this.cssRules = [];\n this.element.textContent = '\\n';\n }\n }\n /**\n * Inject CSS string into element.\n */\n ;\n\n _proto.deploy = function deploy() {\n var sheet = this.sheet;\n if (!sheet) return;\n\n if (sheet.options.link) {\n this.insertRules(sheet.rules);\n return;\n }\n\n this.element.textContent = \"\\n\" + sheet.toString() + \"\\n\";\n }\n /**\n * Insert RuleList into an element.\n */\n ;\n\n _proto.insertRules = function insertRules(rules, nativeParent) {\n for (var i = 0; i < rules.index.length; i++) {\n this.insertRule(rules.index[i], i, nativeParent);\n }\n }\n /**\n * Insert a rule into element.\n */\n ;\n\n _proto.insertRule = function insertRule(rule, index, nativeParent) {\n if (nativeParent === void 0) {\n nativeParent = this.element.sheet;\n }\n\n if (rule.rules) {\n var parent = rule;\n var latestNativeParent = nativeParent;\n\n if (rule.type === 'conditional' || rule.type === 'keyframes') {\n var _insertionIndex = getValidRuleInsertionIndex(nativeParent, index); // We need to render the container without children first.\n\n\n latestNativeParent = _insertRule(nativeParent, parent.toString({\n children: false\n }), _insertionIndex);\n\n if (latestNativeParent === false) {\n return false;\n }\n\n this.refCssRule(rule, _insertionIndex, latestNativeParent);\n }\n\n this.insertRules(parent.rules, latestNativeParent);\n return latestNativeParent;\n }\n\n var ruleStr = rule.toString();\n if (!ruleStr) return false;\n var insertionIndex = getValidRuleInsertionIndex(nativeParent, index);\n\n var nativeRule = _insertRule(nativeParent, ruleStr, insertionIndex);\n\n if (nativeRule === false) {\n return false;\n }\n\n this.hasInsertedRules = true;\n this.refCssRule(rule, insertionIndex, nativeRule);\n return nativeRule;\n };\n\n _proto.refCssRule = function refCssRule(rule, index, cssRule) {\n rule.renderable = cssRule; // We only want to reference the top level rules, deleteRule API doesn't support removing nested rules\n // like rules inside media queries or keyframes\n\n if (rule.options.parent instanceof StyleSheet) {\n this.cssRules.splice(index, 0, cssRule);\n }\n }\n /**\n * Delete a rule.\n */\n ;\n\n _proto.deleteRule = function deleteRule(cssRule) {\n var sheet = this.element.sheet;\n var index = this.indexOf(cssRule);\n if (index === -1) return false;\n sheet.deleteRule(index);\n this.cssRules.splice(index, 1);\n return true;\n }\n /**\n * Get index of a CSS Rule.\n */\n ;\n\n _proto.indexOf = function indexOf(cssRule) {\n return this.cssRules.indexOf(cssRule);\n }\n /**\n * Generate a new CSS rule and replace the existing one.\n */\n ;\n\n _proto.replaceRule = function replaceRule(cssRule, rule) {\n var index = this.indexOf(cssRule);\n if (index === -1) return false;\n this.element.sheet.deleteRule(index);\n this.cssRules.splice(index, 1);\n return this.insertRule(rule, index);\n }\n /**\n * Get all rules elements.\n */\n ;\n\n _proto.getRules = function getRules() {\n return this.element.sheet.cssRules;\n };\n\n return DomRenderer;\n}();\n\nvar instanceCounter = 0;\n\nvar Jss =\n/*#__PURE__*/\nfunction () {\n function Jss(options) {\n this.id = instanceCounter++;\n this.version = \"10.10.0\";\n this.plugins = new PluginsRegistry();\n this.options = {\n id: {\n minify: false\n },\n createGenerateId: createGenerateId,\n Renderer: isInBrowser__default['default'] ? DomRenderer : null,\n plugins: []\n };\n this.generateId = createGenerateId({\n minify: false\n });\n\n for (var i = 0; i < plugins.length; i++) {\n this.plugins.use(plugins[i], {\n queue: 'internal'\n });\n }\n\n this.setup(options);\n }\n /**\n * Prepares various options, applies plugins.\n * Should not be used twice on the same instance, because there is no plugins\n * deduplication logic.\n */\n\n\n var _proto = Jss.prototype;\n\n _proto.setup = function setup(options) {\n if (options === void 0) {\n options = {};\n }\n\n if (options.createGenerateId) {\n this.options.createGenerateId = options.createGenerateId;\n }\n\n if (options.id) {\n this.options.id = _extends__default['default']({}, this.options.id, options.id);\n }\n\n if (options.createGenerateId || options.id) {\n this.generateId = this.options.createGenerateId(this.options.id);\n }\n\n if (options.insertionPoint != null) this.options.insertionPoint = options.insertionPoint;\n\n if ('Renderer' in options) {\n this.options.Renderer = options.Renderer;\n } // eslint-disable-next-line prefer-spread\n\n\n if (options.plugins) this.use.apply(this, options.plugins);\n return this;\n }\n /**\n * Create a Style Sheet.\n */\n ;\n\n _proto.createStyleSheet = function createStyleSheet(styles, options) {\n if (options === void 0) {\n options = {};\n }\n\n var _options = options,\n index = _options.index;\n\n if (typeof index !== 'number') {\n index = sheets.index === 0 ? 0 : sheets.index + 1;\n }\n\n var sheet = new StyleSheet(styles, _extends__default['default']({}, options, {\n jss: this,\n generateId: options.generateId || this.generateId,\n insertionPoint: this.options.insertionPoint,\n Renderer: this.options.Renderer,\n index: index\n }));\n this.plugins.onProcessSheet(sheet);\n return sheet;\n }\n /**\n * Detach the Style Sheet and remove it from the registry.\n */\n ;\n\n _proto.removeStyleSheet = function removeStyleSheet(sheet) {\n sheet.detach();\n sheets.remove(sheet);\n return this;\n }\n /**\n * Create a rule without a Style Sheet.\n * [Deprecated] will be removed in the next major version.\n */\n ;\n\n _proto.createRule = function createRule$1(name, style, options) {\n if (style === void 0) {\n style = {};\n }\n\n if (options === void 0) {\n options = {};\n }\n\n // Enable rule without name for inline styles.\n if (typeof name === 'object') {\n return this.createRule(undefined, name, style);\n }\n\n var ruleOptions = _extends__default['default']({}, options, {\n name: name,\n jss: this,\n Renderer: this.options.Renderer\n });\n\n if (!ruleOptions.generateId) ruleOptions.generateId = this.generateId;\n if (!ruleOptions.classes) ruleOptions.classes = {};\n if (!ruleOptions.keyframes) ruleOptions.keyframes = {};\n\n var rule = createRule(name, style, ruleOptions);\n\n if (rule) this.plugins.onProcessRule(rule);\n return rule;\n }\n /**\n * Register plugin. Passed function will be invoked with a rule instance.\n */\n ;\n\n _proto.use = function use() {\n var _this = this;\n\n for (var _len = arguments.length, plugins = new Array(_len), _key = 0; _key < _len; _key++) {\n plugins[_key] = arguments[_key];\n }\n\n plugins.forEach(function (plugin) {\n _this.plugins.use(plugin);\n });\n return this;\n };\n\n return Jss;\n}();\n\nvar createJss = function createJss(options) {\n return new Jss(options);\n};\n\n/**\n * SheetsManager is like a WeakMap which is designed to count StyleSheet\n * instances and attach/detach automatically.\n * Used in react-jss.\n */\n\nvar SheetsManager =\n/*#__PURE__*/\nfunction () {\n function SheetsManager() {\n this.length = 0;\n this.sheets = new WeakMap();\n }\n\n var _proto = SheetsManager.prototype;\n\n _proto.get = function get(key) {\n var entry = this.sheets.get(key);\n return entry && entry.sheet;\n };\n\n _proto.add = function add(key, sheet) {\n if (this.sheets.has(key)) return;\n this.length++;\n this.sheets.set(key, {\n sheet: sheet,\n refs: 0\n });\n };\n\n _proto.manage = function manage(key) {\n var entry = this.sheets.get(key);\n\n if (entry) {\n if (entry.refs === 0) {\n entry.sheet.attach();\n }\n\n entry.refs++;\n return entry.sheet;\n }\n\n warning__default['default'](false, \"[JSS] SheetsManager: can't find sheet to manage\");\n return undefined;\n };\n\n _proto.unmanage = function unmanage(key) {\n var entry = this.sheets.get(key);\n\n if (entry) {\n if (entry.refs > 0) {\n entry.refs--;\n if (entry.refs === 0) entry.sheet.detach();\n }\n } else {\n warning__default['default'](false, \"SheetsManager: can't find sheet to unmanage\");\n }\n };\n\n _createClass__default['default'](SheetsManager, [{\n key: \"size\",\n get: function get() {\n return this.length;\n }\n }]);\n\n return SheetsManager;\n}();\n\n/**\n* Export a constant indicating if this browser has CSSTOM support.\n* https://developers.google.com/web/updates/2018/03/cssom\n*/\nvar hasCSSTOMSupport = typeof CSS === 'object' && CSS != null && 'number' in CSS;\n\n/**\n * Extracts a styles object with only props that contain function values.\n */\nfunction getDynamicStyles(styles) {\n var to = null;\n\n for (var key in styles) {\n var value = styles[key];\n var type = typeof value;\n\n if (type === 'function') {\n if (!to) to = {};\n to[key] = value;\n } else if (type === 'object' && value !== null && !Array.isArray(value)) {\n var extracted = getDynamicStyles(value);\n\n if (extracted) {\n if (!to) to = {};\n to[key] = extracted;\n }\n }\n }\n\n return to;\n}\n\n/**\n * A better abstraction over CSS.\n *\n * @copyright Oleg Isonen (Slobodskoi) / Isonen 2014-present\n * @website https://github.com/cssinjs/jss\n * @license MIT\n */\nvar index = createJss();\n\nexports.RuleList = RuleList;\nexports.SheetsManager = SheetsManager;\nexports.SheetsRegistry = SheetsRegistry;\nexports.create = createJss;\nexports.createGenerateId = createGenerateId;\nexports.createRule = createRule;\nexports.default = index;\nexports.getDynamicStyles = getDynamicStyles;\nexports.hasCSSTOMSupport = hasCSSTOMSupport;\nexports.sheets = sheets;\nexports.toCssValue = toCssValue;\n", "'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nvar warning = require('tiny-warning');\nvar jss = require('jss');\n\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\n\nvar warning__default = /*#__PURE__*/_interopDefaultLegacy(warning);\n\nvar now = Date.now();\nvar fnValuesNs = \"fnValues\" + now;\nvar fnRuleNs = \"fnStyle\" + ++now;\n\nvar functionPlugin = function functionPlugin() {\n return {\n onCreateRule: function onCreateRule(name, decl, options) {\n if (typeof decl !== 'function') return null;\n var rule = jss.createRule(name, {}, options);\n rule[fnRuleNs] = decl;\n return rule;\n },\n onProcessStyle: function onProcessStyle(style, rule) {\n // We need to extract function values from the declaration, so that we can keep core unaware of them.\n // We need to do that only once.\n // We don't need to extract functions on each style update, since this can happen only once.\n // We don't support function values inside of function rules.\n if (fnValuesNs in rule || fnRuleNs in rule) return style;\n var fnValues = {};\n\n for (var prop in style) {\n var value = style[prop];\n if (typeof value !== 'function') continue;\n delete style[prop];\n fnValues[prop] = value;\n }\n\n rule[fnValuesNs] = fnValues;\n return style;\n },\n onUpdate: function onUpdate(data, rule, sheet, options) {\n var styleRule = rule;\n var fnRule = styleRule[fnRuleNs]; // If we have a style function, the entire rule is dynamic and style object\n // will be returned from that function.\n\n if (fnRule) {\n // Empty object will remove all currently defined props\n // in case function rule returns a falsy value.\n styleRule.style = fnRule(data) || {};\n\n if (process.env.NODE_ENV === 'development') {\n for (var prop in styleRule.style) {\n if (typeof styleRule.style[prop] === 'function') {\n process.env.NODE_ENV !== \"production\" ? warning__default['default'](false, '[JSS] Function values inside function rules are not supported.') : void 0;\n break;\n }\n }\n }\n }\n\n var fnValues = styleRule[fnValuesNs]; // If we have a fn values map, it is a rule with function values.\n\n if (fnValues) {\n for (var _prop in fnValues) {\n styleRule.prop(_prop, fnValues[_prop](data), options);\n }\n }\n }\n };\n};\n\nexports.default = functionPlugin;\n", "'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nvar _extends = require('@babel/runtime/helpers/extends');\nvar jss = require('jss');\n\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\n\nvar _extends__default = /*#__PURE__*/_interopDefaultLegacy(_extends);\n\nvar at = '@global';\nvar atPrefix = '@global ';\n\nvar GlobalContainerRule =\n/*#__PURE__*/\nfunction () {\n function GlobalContainerRule(key, styles, options) {\n this.type = 'global';\n this.at = at;\n this.isProcessed = false;\n this.key = key;\n this.options = options;\n this.rules = new jss.RuleList(_extends__default['default']({}, options, {\n parent: this\n }));\n\n for (var selector in styles) {\n this.rules.add(selector, styles[selector]);\n }\n\n this.rules.process();\n }\n /**\n * Get a rule.\n */\n\n\n var _proto = GlobalContainerRule.prototype;\n\n _proto.getRule = function getRule(name) {\n return this.rules.get(name);\n }\n /**\n * Create and register rule, run plugins.\n */\n ;\n\n _proto.addRule = function addRule(name, style, options) {\n var rule = this.rules.add(name, style, options);\n if (rule) this.options.jss.plugins.onProcessRule(rule);\n return rule;\n }\n /**\n * Replace rule, run plugins.\n */\n ;\n\n _proto.replaceRule = function replaceRule(name, style, options) {\n var newRule = this.rules.replace(name, style, options);\n if (newRule) this.options.jss.plugins.onProcessRule(newRule);\n return newRule;\n }\n /**\n * Get index of a rule.\n */\n ;\n\n _proto.indexOf = function indexOf(rule) {\n return this.rules.indexOf(rule);\n }\n /**\n * Generates a CSS string.\n */\n ;\n\n _proto.toString = function toString(options) {\n return this.rules.toString(options);\n };\n\n return GlobalContainerRule;\n}();\n\nvar GlobalPrefixedRule =\n/*#__PURE__*/\nfunction () {\n function GlobalPrefixedRule(key, style, options) {\n this.type = 'global';\n this.at = at;\n this.isProcessed = false;\n this.key = key;\n this.options = options;\n var selector = key.substr(atPrefix.length);\n this.rule = options.jss.createRule(selector, style, _extends__default['default']({}, options, {\n parent: this\n }));\n }\n\n var _proto2 = GlobalPrefixedRule.prototype;\n\n _proto2.toString = function toString(options) {\n return this.rule ? this.rule.toString(options) : '';\n };\n\n return GlobalPrefixedRule;\n}();\n\nvar separatorRegExp = /\\s*,\\s*/g;\n\nfunction addScope(selector, scope) {\n var parts = selector.split(separatorRegExp);\n var scoped = '';\n\n for (var i = 0; i < parts.length; i++) {\n scoped += scope + \" \" + parts[i].trim();\n if (parts[i + 1]) scoped += ', ';\n }\n\n return scoped;\n}\n\nfunction handleNestedGlobalContainerRule(rule, sheet) {\n var options = rule.options,\n style = rule.style;\n var rules = style ? style[at] : null;\n if (!rules) return;\n\n for (var name in rules) {\n sheet.addRule(name, rules[name], _extends__default['default']({}, options, {\n selector: addScope(name, rule.selector)\n }));\n }\n\n delete style[at];\n}\n\nfunction handlePrefixedGlobalRule(rule, sheet) {\n var options = rule.options,\n style = rule.style;\n\n for (var prop in style) {\n if (prop[0] !== '@' || prop.substr(0, at.length) !== at) continue;\n var selector = addScope(prop.substr(at.length), rule.selector);\n sheet.addRule(selector, style[prop], _extends__default['default']({}, options, {\n selector: selector\n }));\n delete style[prop];\n }\n}\n/**\n * Convert nested rules to separate, remove them from original styles.\n */\n\n\nfunction jssGlobal() {\n function onCreateRule(name, styles, options) {\n if (!name) return null;\n\n if (name === at) {\n return new GlobalContainerRule(name, styles, options);\n }\n\n if (name[0] === '@' && name.substr(0, atPrefix.length) === atPrefix) {\n return new GlobalPrefixedRule(name, styles, options);\n }\n\n var parent = options.parent;\n\n if (parent) {\n if (parent.type === 'global' || parent.options.parent && parent.options.parent.type === 'global') {\n options.scoped = false;\n }\n }\n\n if (!options.selector && options.scoped === false) {\n options.selector = name;\n }\n\n return null;\n }\n\n function onProcessRule(rule, sheet) {\n if (rule.type !== 'style' || !sheet) return;\n handleNestedGlobalContainerRule(rule, sheet);\n handlePrefixedGlobalRule(rule, sheet);\n }\n\n return {\n onCreateRule: onCreateRule,\n onProcessRule: onProcessRule\n };\n}\n\nexports.default = jssGlobal;\n", "'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nvar _extends = require('@babel/runtime/helpers/extends');\nvar warning = require('tiny-warning');\n\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\n\nvar _extends__default = /*#__PURE__*/_interopDefaultLegacy(_extends);\nvar warning__default = /*#__PURE__*/_interopDefaultLegacy(warning);\n\nvar separatorRegExp = /\\s*,\\s*/g;\nvar parentRegExp = /&/g;\nvar refRegExp = /\\$([\\w-]+)/g;\n/**\n * Convert nested rules to separate, remove them from original styles.\n */\n\nfunction jssNested() {\n // Get a function to be used for $ref replacement.\n function getReplaceRef(container, sheet) {\n return function (match, key) {\n var rule = container.getRule(key) || sheet && sheet.getRule(key);\n\n if (rule) {\n return rule.selector;\n }\n\n process.env.NODE_ENV !== \"production\" ? warning__default['default'](false, \"[JSS] Could not find the referenced rule \\\"\" + key + \"\\\" in \\\"\" + (container.options.meta || container.toString()) + \"\\\".\") : void 0;\n return key;\n };\n }\n\n function replaceParentRefs(nestedProp, parentProp) {\n var parentSelectors = parentProp.split(separatorRegExp);\n var nestedSelectors = nestedProp.split(separatorRegExp);\n var result = '';\n\n for (var i = 0; i < parentSelectors.length; i++) {\n var parent = parentSelectors[i];\n\n for (var j = 0; j < nestedSelectors.length; j++) {\n var nested = nestedSelectors[j];\n if (result) result += ', '; // Replace all & by the parent or prefix & with the parent.\n\n result += nested.indexOf('&') !== -1 ? nested.replace(parentRegExp, parent) : parent + \" \" + nested;\n }\n }\n\n return result;\n }\n\n function getOptions(rule, container, prevOptions) {\n // Options has been already created, now we only increase index.\n if (prevOptions) return _extends__default['default']({}, prevOptions, {\n index: prevOptions.index + 1\n });\n var nestingLevel = rule.options.nestingLevel;\n nestingLevel = nestingLevel === undefined ? 1 : nestingLevel + 1;\n\n var options = _extends__default['default']({}, rule.options, {\n nestingLevel: nestingLevel,\n index: container.indexOf(rule) + 1 // We don't need the parent name to be set options for chlid.\n\n });\n\n delete options.name;\n return options;\n }\n\n function onProcessStyle(style, rule, sheet) {\n if (rule.type !== 'style') return style;\n var styleRule = rule;\n var container = styleRule.options.parent;\n var options;\n var replaceRef;\n\n for (var prop in style) {\n var isNested = prop.indexOf('&') !== -1;\n var isNestedConditional = prop[0] === '@';\n if (!isNested && !isNestedConditional) continue;\n options = getOptions(styleRule, container, options);\n\n if (isNested) {\n var selector = replaceParentRefs(prop, styleRule.selector); // Lazily create the ref replacer function just once for\n // all nested rules within the sheet.\n\n if (!replaceRef) replaceRef = getReplaceRef(container, sheet); // Replace all $refs.\n\n selector = selector.replace(refRegExp, replaceRef);\n var name = styleRule.key + \"-\" + prop;\n\n if ('replaceRule' in container) {\n // for backward compatibility\n container.replaceRule(name, style[prop], _extends__default['default']({}, options, {\n selector: selector\n }));\n } else {\n container.addRule(name, style[prop], _extends__default['default']({}, options, {\n selector: selector\n }));\n }\n } else if (isNestedConditional) {\n // Place conditional right after the parent rule to ensure right ordering.\n container.addRule(prop, {}, options).addRule(styleRule.key, style[prop], {\n selector: styleRule.selector\n });\n }\n\n delete style[prop];\n }\n\n return style;\n }\n\n return {\n onProcessStyle: onProcessStyle\n };\n}\n\nexports.default = jssNested;\n", "'use strict';\n\n/* eslint-disable no-var, prefer-template */\nvar uppercasePattern = /[A-Z]/g;\nvar msPattern = /^ms-/;\nvar cache = {};\n\nfunction toHyphenLower(match) {\n return '-' + match.toLowerCase()\n}\n\nfunction hyphenateStyleName(name) {\n if (cache.hasOwnProperty(name)) {\n return cache[name]\n }\n\n var hName = name.replace(uppercasePattern, toHyphenLower);\n return (cache[name] = msPattern.test(hName) ? '-' + hName : hName)\n}\n\nmodule.exports = hyphenateStyleName;\n", "'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nvar hyphenate = require('hyphenate-style-name');\n\nfunction _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }\n\nvar hyphenate__default = /*#__PURE__*/_interopDefaultLegacy(hyphenate);\n\n/**\n * Convert camel cased property names to dash separated.\n */\n\nfunction convertCase(style) {\n var converted = {};\n\n for (var prop in style) {\n var key = prop.indexOf('--') === 0 ? prop : hyphenate__default['default'](prop);\n converted[key] = style[prop];\n }\n\n if (style.fallbacks) {\n if (Array.isArray(style.fallbacks)) converted.fallbacks = style.fallbacks.map(convertCase);else converted.fallbacks = convertCase(style.fallbacks);\n }\n\n return converted;\n}\n/**\n * Allow camel cased property names by converting them back to dasherized.\n */\n\n\nfunction camelCase() {\n function onProcessStyle(style) {\n if (Array.isArray(style)) {\n // Handle rules like @font-face, which can have multiple styles in an array\n for (var index = 0; index < style.length; index++) {\n style[index] = convertCase(style[index]);\n }\n\n return style;\n }\n\n return convertCase(style);\n }\n\n function onChangeValue(value, prop, rule) {\n if (prop.indexOf('--') === 0) {\n return value;\n }\n\n var hyphenatedProp = hyphenate__default['default'](prop); // There was no camel case in place\n\n if (prop === hyphenatedProp) return value;\n rule.prop(hyphenatedProp, value); // Core will ignore that property value we set the proper one above.\n\n return null;\n }\n\n return {\n onProcessStyle: onProcessStyle,\n onChangeValue: onChangeValue\n };\n}\n\nexports.default = camelCase;\n", "'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nvar jss = require('jss');\n\nvar px = jss.hasCSSTOMSupport && CSS ? CSS.px : 'px';\nvar ms = jss.hasCSSTOMSupport && CSS ? CSS.ms : 'ms';\nvar percent = jss.hasCSSTOMSupport && CSS ? CSS.percent : '%';\n/**\n * Generated jss-plugin-default-unit CSS property units\n */\n\nvar defaultUnits = {\n // Animation properties\n 'animation-delay': ms,\n 'animation-duration': ms,\n // Background properties\n 'background-position': px,\n 'background-position-x': px,\n 'background-position-y': px,\n 'background-size': px,\n // Border Properties\n border: px,\n 'border-bottom': px,\n 'border-bottom-left-radius': px,\n 'border-bottom-right-radius': px,\n 'border-bottom-width': px,\n 'border-left': px,\n 'border-left-width': px,\n 'border-radius': px,\n 'border-right': px,\n 'border-right-width': px,\n 'border-top': px,\n 'border-top-left-radius': px,\n 'border-top-right-radius': px,\n 'border-top-width': px,\n 'border-width': px,\n 'border-block': px,\n 'border-block-end': px,\n 'border-block-end-width': px,\n 'border-block-start': px,\n 'border-block-start-width': px,\n 'border-block-width': px,\n 'border-inline': px,\n 'border-inline-end': px,\n 'border-inline-end-width': px,\n 'border-inline-start': px,\n 'border-inline-start-width': px,\n 'border-inline-width': px,\n 'border-start-start-radius': px,\n 'border-start-end-radius': px,\n 'border-end-start-radius': px,\n 'border-end-end-radius': px,\n // Margin properties\n margin: px,\n 'margin-bottom': px,\n 'margin-left': px,\n 'margin-right': px,\n 'margin-top': px,\n 'margin-block': px,\n 'margin-block-end': px,\n 'margin-block-start': px,\n 'margin-inline': px,\n 'margin-inline-end': px,\n 'margin-inline-start': px,\n // Padding properties\n padding: px,\n 'padding-bottom': px,\n 'padding-left': px,\n 'padding-right': px,\n 'padding-top': px,\n 'padding-block': px,\n 'padding-block-end': px,\n 'padding-block-start': px,\n 'padding-inline': px,\n 'padding-inline-end': px,\n 'padding-inline-start': px,\n // Mask properties\n 'mask-position-x': px,\n 'mask-position-y': px,\n 'mask-size': px,\n // Width and height properties\n height: px,\n width: px,\n 'min-height': px,\n 'max-height': px,\n 'min-width': px,\n 'max-width': px,\n // Position properties\n bottom: px,\n left: px,\n top: px,\n right: px,\n inset: px,\n 'inset-block': px,\n 'inset-block-end': px,\n 'inset-block-start': px,\n 'inset-inline': px,\n 'inset-inline-end': px,\n 'inset-inline-start': px,\n // Shadow properties\n 'box-shadow': px,\n 'text-shadow': px,\n // Column properties\n 'column-gap': px,\n 'column-rule': px,\n 'column-rule-width': px,\n 'column-width': px,\n // Font and text properties\n 'font-size': px,\n 'font-size-delta': px,\n 'letter-spacing': px,\n 'text-decoration-thickness': px,\n 'text-indent': px,\n 'text-stroke': px,\n 'text-stroke-width': px,\n 'word-spacing': px,\n // Motion properties\n motion: px,\n 'motion-offset': px,\n // Outline properties\n outline: px,\n 'outline-offset': px,\n 'outline-width': px,\n // Perspective properties\n perspective: px,\n 'perspective-origin-x': percent,\n 'perspective-origin-y': percent,\n // Transform properties\n 'transform-origin': percent,\n 'transform-origin-x': percent,\n 'transform-origin-y': percent,\n 'transform-origin-z': percent,\n // Transition properties\n 'transition-delay': ms,\n 'transition-duration': ms,\n // Alignment properties\n 'vertical-align': px,\n 'flex-basis': px,\n // Some random properties\n 'shape-margin': px,\n size: px,\n gap: px,\n // Grid properties\n grid: px,\n 'grid-gap': px,\n 'row-gap': px,\n 'grid-row-gap': px,\n 'grid-column-gap': px,\n 'grid-template-rows': px,\n 'grid-template-columns': px,\n 'grid-auto-rows': px,\n 'grid-auto-columns': px,\n // Not existing properties.\n // Used to avoid issues with jss-plugin-expand integration.\n 'box-shadow-x': px,\n 'box-shadow-y': px,\n 'box-shadow-blur': px,\n 'box-shadow-spread': px,\n 'font-line-height': px,\n 'text-shadow-x': px,\n 'text-shadow-y': px,\n 'text-shadow-blur': px\n};\n\n/**\n * Clones the object and adds a camel cased property version.\n */\n\nfunction addCamelCasedVersion(obj) {\n var regExp = /(-[a-z])/g;\n\n var replace = function replace(str) {\n return str[1].toUpperCase();\n };\n\n var newObj = {};\n\n for (var key in obj) {\n newObj[key] = obj[key];\n newObj[key.replace(regExp, replace)] = obj[key];\n }\n\n return newObj;\n}\n\nvar units = addCamelCasedVersion(defaultUnits);\n/**\n * Recursive deep style passing function\n */\n\nfunction iterate(prop, value, options) {\n if (value == null) return value;\n\n if (Array.isArray(value)) {\n for (var i = 0; i < value.length; i++) {\n value[i] = iterate(prop, value[i], options);\n }\n } else if (typeof value === 'object') {\n if (prop === 'fallbacks') {\n for (var innerProp in value) {\n value[innerProp] = iterate(innerProp, value[innerProp], options);\n }\n } else {\n for (var _innerProp in value) {\n value[_innerProp] = iterate(prop + \"-\" + _innerProp, value[_innerProp], options);\n }\n } // eslint-disable-next-line no-restricted-globals\n\n } else if (typeof value === 'number' && isNaN(value) === false) {\n var unit = options[prop] || units[prop]; // Add the unit if available, except for the special case of 0px.\n\n if (unit && !(value === 0 && unit === px)) {\n return typeof unit === 'function' ? unit(value).toString() : \"\" + value + unit;\n }\n\n return value.toString();\n }\n\n return value;\n}\n/**\n * Add unit to numeric values.\n */\n\n\nfunction defaultUnit(options) {\n if (options === void 0) {\n options = {};\n }\n\n var camelCasedOptions = addCamelCasedVersion(options);\n\n function onProcessStyle(style, rule) {\n if (rule.type !== 'style') return style;\n\n for (var prop in style) {\n style[prop] = iterate(prop, style[prop], camelCasedOptions);\n }\n\n return style;\n }\n\n function onChangeValue(value, prop) {\n return iterate(prop, value, camelCasedOptions);\n }\n\n return {\n onProcessStyle: onProcessStyle,\n onChangeValue: onChangeValue\n };\n}\n\nexports.default = defaultUnit;\n", "'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nfunction _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }\n\nvar isInBrowser = _interopDefault(require('is-in-browser'));\nvar _toConsumableArray = _interopDefault(require('@babel/runtime/helpers/toConsumableArray'));\n\n// Export javascript style and css style vendor prefixes.\nvar js = '';\nvar css = '';\nvar vendor = '';\nvar browser = '';\nvar isTouch = isInBrowser && 'ontouchstart' in document.documentElement; // We should not do anything if required serverside.\n\nif (isInBrowser) {\n // Order matters. We need to check Webkit the last one because\n // other vendors use to add Webkit prefixes to some properties\n var jsCssMap = {\n Moz: '-moz-',\n ms: '-ms-',\n O: '-o-',\n Webkit: '-webkit-'\n };\n\n var _document$createEleme = document.createElement('p'),\n style = _document$createEleme.style;\n\n var testProp = 'Transform';\n\n for (var key in jsCssMap) {\n if (key + testProp in style) {\n js = key;\n css = jsCssMap[key];\n break;\n }\n } // Correctly detect the Edge browser.\n\n\n if (js === 'Webkit' && 'msHyphens' in style) {\n js = 'ms';\n css = jsCssMap.ms;\n browser = 'edge';\n } // Correctly detect the Safari browser.\n\n\n if (js === 'Webkit' && '-apple-trailing-word' in style) {\n vendor = 'apple';\n }\n}\n/**\n * Vendor prefix string for the current browser.\n *\n * @type {{js: String, css: String, vendor: String, browser: String}}\n * @api public\n */\n\n\nvar prefix = {\n js: js,\n css: css,\n vendor: vendor,\n browser: browser,\n isTouch: isTouch\n};\n\n/**\n * Test if a keyframe at-rule should be prefixed or not\n *\n * @param {String} vendor prefix string for the current browser.\n * @return {String}\n * @api public\n */\n\nfunction supportedKeyframes(key) {\n // Keyframes is already prefixed. e.g. key = '@-webkit-keyframes a'\n if (key[1] === '-') return key; // No need to prefix IE/Edge. Older browsers will ignore unsupported rules.\n // https://caniuse.com/#search=keyframes\n\n if (prefix.js === 'ms') return key;\n return \"@\" + prefix.css + \"keyframes\" + key.substr(10);\n}\n\n// https://caniuse.com/#search=appearance\n\nvar appearence = {\n noPrefill: ['appearance'],\n supportedProperty: function supportedProperty(prop) {\n if (prop !== 'appearance') return false;\n if (prefix.js === 'ms') return \"-webkit-\" + prop;\n return prefix.css + prop;\n }\n};\n\n// https://caniuse.com/#search=color-adjust\n\nvar colorAdjust = {\n noPrefill: ['color-adjust'],\n supportedProperty: function supportedProperty(prop) {\n if (prop !== 'color-adjust') return false;\n if (prefix.js === 'Webkit') return prefix.css + \"print-\" + prop;\n return prop;\n }\n};\n\nvar regExp = /[-\\s]+(.)?/g;\n/**\n * Replaces the letter with the capital letter\n *\n * @param {String} match\n * @param {String} c\n * @return {String}\n * @api private\n */\n\nfunction toUpper(match, c) {\n return c ? c.toUpperCase() : '';\n}\n/**\n * Convert dash separated strings to camel-cased.\n *\n * @param {String} str\n * @return {String}\n * @api private\n */\n\n\nfunction camelize(str) {\n return str.replace(regExp, toUpper);\n}\n\n/**\n * Convert dash separated strings to pascal cased.\n *\n * @param {String} str\n * @return {String}\n * @api private\n */\n\nfunction pascalize(str) {\n return camelize(\"-\" + str);\n}\n\n// but we can use a longhand property instead.\n// https://caniuse.com/#search=mask\n\nvar mask = {\n noPrefill: ['mask'],\n supportedProperty: function supportedProperty(prop, style) {\n if (!/^mask/.test(prop)) return false;\n\n if (prefix.js === 'Webkit') {\n var longhand = 'mask-image';\n\n if (camelize(longhand) in style) {\n return prop;\n }\n\n if (prefix.js + pascalize(longhand) in style) {\n return prefix.css + prop;\n }\n }\n\n return prop;\n }\n};\n\n// https://caniuse.com/#search=text-orientation\n\nvar textOrientation = {\n noPrefill: ['text-orientation'],\n supportedProperty: function supportedProperty(prop) {\n if (prop !== 'text-orientation') return false;\n\n if (prefix.vendor === 'apple' && !prefix.isTouch) {\n return prefix.css + prop;\n }\n\n return prop;\n }\n};\n\n// https://caniuse.com/#search=transform\n\nvar transform = {\n noPrefill: ['transform'],\n supportedProperty: function supportedProperty(prop, style, options) {\n if (prop !== 'transform') return false;\n\n if (options.transform) {\n return prop;\n }\n\n return prefix.css + prop;\n }\n};\n\n// https://caniuse.com/#search=transition\n\nvar transition = {\n noPrefill: ['transition'],\n supportedProperty: function supportedProperty(prop, style, options) {\n if (prop !== 'transition') return false;\n\n if (options.transition) {\n return prop;\n }\n\n return prefix.css + prop;\n }\n};\n\n// https://caniuse.com/#search=writing-mode\n\nvar writingMode = {\n noPrefill: ['writing-mode'],\n supportedProperty: function supportedProperty(prop) {\n if (prop !== 'writing-mode') return false;\n\n if (prefix.js === 'Webkit' || prefix.js === 'ms' && prefix.browser !== 'edge') {\n return prefix.css + prop;\n }\n\n return prop;\n }\n};\n\n// https://caniuse.com/#search=user-select\n\nvar userSelect = {\n noPrefill: ['user-select'],\n supportedProperty: function supportedProperty(prop) {\n if (prop !== 'user-select') return false;\n\n if (prefix.js === 'Moz' || prefix.js === 'ms' || prefix.vendor === 'apple') {\n return prefix.css + prop;\n }\n\n return prop;\n }\n};\n\n// https://caniuse.com/#search=multicolumn\n// https://github.com/postcss/autoprefixer/issues/491\n// https://github.com/postcss/autoprefixer/issues/177\n\nvar breakPropsOld = {\n supportedProperty: function supportedProperty(prop, style) {\n if (!/^break-/.test(prop)) return false;\n\n if (prefix.js === 'Webkit') {\n var jsProp = \"WebkitColumn\" + pascalize(prop);\n return jsProp in style ? prefix.css + \"column-\" + prop : false;\n }\n\n if (prefix.js === 'Moz') {\n var _jsProp = \"page\" + pascalize(prop);\n\n return _jsProp in style ? \"page-\" + prop : false;\n }\n\n return false;\n }\n};\n\n// See https://github.com/postcss/autoprefixer/issues/324.\n\nvar inlineLogicalOld = {\n supportedProperty: function supportedProperty(prop, style) {\n if (!/^(border|margin|padding)-inline/.test(prop)) return false;\n if (prefix.js === 'Moz') return prop;\n var newProp = prop.replace('-inline', '');\n return prefix.js + pascalize(newProp) in style ? prefix.css + newProp : false;\n }\n};\n\n// Camelization is required because we can't test using.\n// CSS syntax for e.g. in FF.\n\nvar unprefixed = {\n supportedProperty: function supportedProperty(prop, style) {\n return camelize(prop) in style ? prop : false;\n }\n};\n\nvar prefixed = {\n supportedProperty: function supportedProperty(prop, style) {\n var pascalized = pascalize(prop); // Return custom CSS variable without prefixing.\n\n if (prop[0] === '-') return prop; // Return already prefixed value without prefixing.\n\n if (prop[0] === '-' && prop[1] === '-') return prop;\n if (prefix.js + pascalized in style) return prefix.css + prop; // Try webkit fallback.\n\n if (prefix.js !== 'Webkit' && \"Webkit\" + pascalized in style) return \"-webkit-\" + prop;\n return false;\n }\n};\n\n// https://caniuse.com/#search=scroll-snap\n\nvar scrollSnap = {\n supportedProperty: function supportedProperty(prop) {\n if (prop.substring(0, 11) !== 'scroll-snap') return false;\n\n if (prefix.js === 'ms') {\n return \"\" + prefix.css + prop;\n }\n\n return prop;\n }\n};\n\n// https://caniuse.com/#search=overscroll-behavior\n\nvar overscrollBehavior = {\n supportedProperty: function supportedProperty(prop) {\n if (prop !== 'overscroll-behavior') return false;\n\n if (prefix.js === 'ms') {\n return prefix.css + \"scroll-chaining\";\n }\n\n return prop;\n }\n};\n\nvar propMap = {\n 'flex-grow': 'flex-positive',\n 'flex-shrink': 'flex-negative',\n 'flex-basis': 'flex-preferred-size',\n 'justify-content': 'flex-pack',\n order: 'flex-order',\n 'align-items': 'flex-align',\n 'align-content': 'flex-line-pack' // 'align-self' is handled by 'align-self' plugin.\n\n}; // Support old flex spec from 2012.\n\nvar flex2012 = {\n supportedProperty: function supportedProperty(prop, style) {\n var newProp = propMap[prop];\n if (!newProp) return false;\n return prefix.js + pascalize(newProp) in style ? prefix.css + newProp : false;\n }\n};\n\nvar propMap$1 = {\n flex: 'box-flex',\n 'flex-grow': 'box-flex',\n 'flex-direction': ['box-orient', 'box-direction'],\n order: 'box-ordinal-group',\n 'align-items': 'box-align',\n 'flex-flow': ['box-orient', 'box-direction'],\n 'justify-content': 'box-pack'\n};\nvar propKeys = Object.keys(propMap$1);\n\nvar prefixCss = function prefixCss(p) {\n return prefix.css + p;\n}; // Support old flex spec from 2009.\n\n\nvar flex2009 = {\n supportedProperty: function supportedProperty(prop, style, _ref) {\n var multiple = _ref.multiple;\n\n if (propKeys.indexOf(prop) > -1) {\n var newProp = propMap$1[prop];\n\n if (!Array.isArray(newProp)) {\n return prefix.js + pascalize(newProp) in style ? prefix.css + newProp : false;\n }\n\n if (!multiple) return false;\n\n for (var i = 0; i < newProp.length; i++) {\n if (!(prefix.js + pascalize(newProp[0]) in style)) {\n return false;\n }\n }\n\n return newProp.map(prefixCss);\n }\n\n return false;\n }\n};\n\n// plugins = [\n// ...plugins,\n// breakPropsOld,\n// inlineLogicalOld,\n// unprefixed,\n// prefixed,\n// scrollSnap,\n// flex2012,\n// flex2009\n// ]\n// Plugins without 'noPrefill' value, going last.\n// 'flex-*' plugins should be at the bottom.\n// 'flex2009' going after 'flex2012'.\n// 'prefixed' going after 'unprefixed'\n\nvar plugins = [appearence, colorAdjust, mask, textOrientation, transform, transition, writingMode, userSelect, breakPropsOld, inlineLogicalOld, unprefixed, prefixed, scrollSnap, overscrollBehavior, flex2012, flex2009];\nvar propertyDetectors = plugins.filter(function (p) {\n return p.supportedProperty;\n}).map(function (p) {\n return p.supportedProperty;\n});\nvar noPrefill = plugins.filter(function (p) {\n return p.noPrefill;\n}).reduce(function (a, p) {\n a.push.apply(a, _toConsumableArray(p.noPrefill));\n return a;\n}, []);\n\nvar el;\nvar cache = {};\n\nif (isInBrowser) {\n el = document.createElement('p'); // We test every property on vendor prefix requirement.\n // Once tested, result is cached. It gives us up to 70% perf boost.\n // http://jsperf.com/element-style-object-access-vs-plain-object\n //\n // Prefill cache with known css properties to reduce amount of\n // properties we need to feature test at runtime.\n // http://davidwalsh.name/vendor-prefix\n\n var computed = window.getComputedStyle(document.documentElement, '');\n\n for (var key$1 in computed) {\n // eslint-disable-next-line no-restricted-globals\n if (!isNaN(key$1)) cache[computed[key$1]] = computed[key$1];\n } // Properties that cannot be correctly detected using the\n // cache prefill method.\n\n\n noPrefill.forEach(function (x) {\n return delete cache[x];\n });\n}\n/**\n * Test if a property is supported, returns supported property with vendor\n * prefix if required. Returns `false` if not supported.\n *\n * @param {String} prop dash separated\n * @param {Object} [options]\n * @return {String|Boolean}\n * @api public\n */\n\n\nfunction supportedProperty(prop, options) {\n if (options === void 0) {\n options = {};\n }\n\n // For server-side rendering.\n if (!el) return prop; // Remove cache for benchmark tests or return property from the cache.\n\n if (process.env.NODE_ENV !== 'benchmark' && cache[prop] != null) {\n return cache[prop];\n } // Check if 'transition' or 'transform' natively supported in browser.\n\n\n if (prop === 'transition' || prop === 'transform') {\n options[prop] = prop in el.style;\n } // Find a plugin for current prefix property.\n\n\n for (var i = 0; i < propertyDetectors.length; i++) {\n cache[prop] = propertyDetectors[i](prop, el.style, options); // Break loop, if value found.\n\n if (cache[prop]) break;\n } // Reset styles for current property.\n // Firefox can even throw an error for invalid properties, e.g., \"0\".\n\n\n try {\n el.style[prop] = '';\n } catch (err) {\n return false;\n }\n\n return cache[prop];\n}\n\nvar cache$1 = {};\nvar transitionProperties = {\n transition: 1,\n 'transition-property': 1,\n '-webkit-transition': 1,\n '-webkit-transition-property': 1\n};\nvar transPropsRegExp = /(^\\s*[\\w-]+)|, (\\s*[\\w-]+)(?![^()]*\\))/g;\nvar el$1;\n/**\n * Returns prefixed value transition/transform if needed.\n *\n * @param {String} match\n * @param {String} p1\n * @param {String} p2\n * @return {String}\n * @api private\n */\n\nfunction prefixTransitionCallback(match, p1, p2) {\n if (p1 === 'var') return 'var';\n if (p1 === 'all') return 'all';\n if (p2 === 'all') return ', all';\n var prefixedValue = p1 ? supportedProperty(p1) : \", \" + supportedProperty(p2);\n if (!prefixedValue) return p1 || p2;\n return prefixedValue;\n}\n\nif (isInBrowser) el$1 = document.createElement('p');\n/**\n * Returns prefixed value if needed. Returns `false` if value is not supported.\n *\n * @param {String} property\n * @param {String} value\n * @return {String|Boolean}\n * @api public\n */\n\nfunction supportedValue(property, value) {\n // For server-side rendering.\n var prefixedValue = value;\n if (!el$1 || property === 'content') return value; // It is a string or a number as a string like '1'.\n // We want only prefixable values here.\n // eslint-disable-next-line no-restricted-globals\n\n if (typeof prefixedValue !== 'string' || !isNaN(parseInt(prefixedValue, 10))) {\n return prefixedValue;\n } // Create cache key for current value.\n\n\n var cacheKey = property + prefixedValue; // Remove cache for benchmark tests or return value from cache.\n\n if (process.env.NODE_ENV !== 'benchmark' && cache$1[cacheKey] != null) {\n return cache$1[cacheKey];\n } // IE can even throw an error in some cases, for e.g. style.content = 'bar'.\n\n\n try {\n // Test value as it is.\n el$1.style[property] = prefixedValue;\n } catch (err) {\n // Return false if value not supported.\n cache$1[cacheKey] = false;\n return false;\n } // If 'transition' or 'transition-property' property.\n\n\n if (transitionProperties[property]) {\n prefixedValue = prefixedValue.replace(transPropsRegExp, prefixTransitionCallback);\n } else if (el$1.style[property] === '') {\n // Value with a vendor prefix.\n prefixedValue = prefix.css + prefixedValue; // Hardcode test to convert \"flex\" to \"-ms-flexbox\" for IE10.\n\n if (prefixedValue === '-ms-flex') el$1.style[property] = '-ms-flexbox'; // Test prefixed value.\n\n el$1.style[property] = prefixedValue; // Return false if value not supported.\n\n if (el$1.style[property] === '') {\n cache$1[cacheKey] = false;\n return false;\n }\n } // Reset styles for current property.\n\n\n el$1.style[property] = ''; // Write current value to cache.\n\n cache$1[cacheKey] = prefixedValue;\n return cache$1[cacheKey];\n}\n\nexports.prefix = prefix;\nexports.supportedKeyframes = supportedKeyframes;\nexports.supportedProperty = supportedProperty;\nexports.supportedValue = supportedValue;\n", "'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nvar vendor = require('css-vendor');\nvar jss = require('jss');\n\n/**\n * Add vendor prefix to a property name when needed.\n */\n\nfunction jssVendorPrefixer() {\n function onProcessRule(rule) {\n if (rule.type === 'keyframes') {\n var atRule = rule;\n atRule.at = vendor.supportedKeyframes(atRule.at);\n }\n }\n\n function prefixStyle(style) {\n for (var prop in style) {\n var value = style[prop];\n\n if (prop === 'fallbacks' && Array.isArray(value)) {\n style[prop] = value.map(prefixStyle);\n continue;\n }\n\n var changeProp = false;\n var supportedProp = vendor.supportedProperty(prop);\n if (supportedProp && supportedProp !== prop) changeProp = true;\n var changeValue = false;\n var supportedValue = vendor.supportedValue(supportedProp, jss.toCssValue(value));\n if (supportedValue && supportedValue !== value) changeValue = true;\n\n if (changeProp || changeValue) {\n if (changeProp) delete style[prop];\n style[supportedProp || prop] = supportedValue || value;\n }\n }\n\n return style;\n }\n\n function onProcessStyle(style, rule) {\n if (rule.type !== 'style') return style;\n return prefixStyle(style);\n }\n\n function onChangeValue(value, prop) {\n return vendor.supportedValue(prop, jss.toCssValue(value)) || value;\n }\n\n return {\n onProcessRule: onProcessRule,\n onProcessStyle: onProcessStyle,\n onChangeValue: onChangeValue\n };\n}\n\nexports.default = jssVendorPrefixer;\n", "'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\n/**\n * Sort props by length.\n */\nfunction jssPropsSort() {\n var sort = function sort(prop0, prop1) {\n if (prop0.length === prop1.length) {\n return prop0 > prop1 ? 1 : -1;\n }\n\n return prop0.length - prop1.length;\n };\n\n return {\n onProcessStyle: function onProcessStyle(style, rule) {\n if (rule.type !== 'style') return style;\n var newStyle = {};\n var props = Object.keys(style).sort(sort);\n\n for (var i = 0; i < props.length; i++) {\n newStyle[props[i]] = style[props[i]];\n }\n\n return newStyle;\n }\n };\n}\n\nexports.default = jssPropsSort;\n", "\"use strict\";\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\");\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = jssPreset;\n\nvar _jssPluginRuleValueFunction = _interopRequireDefault(require(\"jss-plugin-rule-value-function\"));\n\nvar _jssPluginGlobal = _interopRequireDefault(require(\"jss-plugin-global\"));\n\nvar _jssPluginNested = _interopRequireDefault(require(\"jss-plugin-nested\"));\n\nvar _jssPluginCamelCase = _interopRequireDefault(require(\"jss-plugin-camel-case\"));\n\nvar _jssPluginDefaultUnit = _interopRequireDefault(require(\"jss-plugin-default-unit\"));\n\nvar _jssPluginVendorPrefixer = _interopRequireDefault(require(\"jss-plugin-vendor-prefixer\"));\n\nvar _jssPluginPropsSort = _interopRequireDefault(require(\"jss-plugin-props-sort\"));\n\n// Subset of jss-preset-default with only the plugins the Material-UI components are using.\nfunction jssPreset() {\n return {\n plugins: [(0, _jssPluginRuleValueFunction.default)(), (0, _jssPluginGlobal.default)(), (0, _jssPluginNested.default)(), (0, _jssPluginCamelCase.default)(), (0, _jssPluginDefaultUnit.default)(), // Disable the vendor prefixer server-side, it does nothing.\n // This way, we can get a performance boost.\n // In the documentation, we are using `autoprefixer` to solve this problem.\n typeof window === 'undefined' ? null : (0, _jssPluginVendorPrefixer.default)(), (0, _jssPluginPropsSort.default)()]\n };\n}", "\"use strict\";\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\");\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nObject.defineProperty(exports, \"default\", {\n enumerable: true,\n get: function get() {\n return _jssPreset.default;\n }\n});\n\nvar _jssPreset = _interopRequireDefault(require(\"./jssPreset\"));", "\"use strict\";\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\");\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = mergeClasses;\n\nvar _extends2 = _interopRequireDefault(require(\"@babel/runtime/helpers/extends\"));\n\nvar _utils = require(\"@material-ui/utils\");\n\nfunction mergeClasses() {\n var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n var baseClasses = options.baseClasses,\n newClasses = options.newClasses,\n Component = options.Component;\n\n if (!newClasses) {\n return baseClasses;\n }\n\n var nextClasses = (0, _extends2.default)({}, baseClasses);\n\n if (process.env.NODE_ENV !== 'production') {\n if (typeof newClasses === 'string') {\n console.error([\"Material-UI: The value `\".concat(newClasses, \"` \") + \"provided to the classes prop of \".concat((0, _utils.getDisplayName)(Component), \" is incorrect.\"), 'You might want to use the className prop instead.'].join('\\n'));\n return baseClasses;\n }\n }\n\n Object.keys(newClasses).forEach(function (key) {\n if (process.env.NODE_ENV !== 'production') {\n if (!baseClasses[key] && newClasses[key]) {\n console.error([\"Material-UI: The key `\".concat(key, \"` \") + \"provided to the classes prop is not implemented in \".concat((0, _utils.getDisplayName)(Component), \".\"), \"You can only override one of the following: \".concat(Object.keys(baseClasses).join(','), \".\")].join('\\n'));\n }\n\n if (newClasses[key] && typeof newClasses[key] !== 'string') {\n console.error([\"Material-UI: The key `\".concat(key, \"` \") + \"provided to the classes prop is not valid for \".concat((0, _utils.getDisplayName)(Component), \".\"), \"You need to provide a non empty string instead of: \".concat(newClasses[key], \".\")].join('\\n'));\n }\n }\n\n if (newClasses[key]) {\n nextClasses[key] = \"\".concat(baseClasses[key], \" \").concat(newClasses[key]);\n }\n });\n return nextClasses;\n}", "\"use strict\";\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\");\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nObject.defineProperty(exports, \"default\", {\n enumerable: true,\n get: function get() {\n return _mergeClasses.default;\n }\n});\n\nvar _mergeClasses = _interopRequireDefault(require(\"./mergeClasses\"));", "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n// Used https://github.com/thinkloop/multi-key-cache as inspiration\nvar multiKeyStore = {\n set: function set(cache, key1, key2, value) {\n var subCache = cache.get(key1);\n\n if (!subCache) {\n subCache = new Map();\n cache.set(key1, subCache);\n }\n\n subCache.set(key2, value);\n },\n get: function get(cache, key1, key2) {\n var subCache = cache.get(key1);\n return subCache ? subCache.get(key2) : undefined;\n },\n delete: function _delete(cache, key1, key2) {\n var subCache = cache.get(key1);\n subCache.delete(key2);\n }\n};\nvar _default = multiKeyStore;\nexports.default = _default;", "\"use strict\";\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\");\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nvar _react = _interopRequireDefault(require(\"react\"));\n\nvar ThemeContext = _react.default.createContext(null);\n\nif (process.env.NODE_ENV !== 'production') {\n ThemeContext.displayName = 'ThemeContext';\n}\n\nvar _default = ThemeContext;\nexports.default = _default;", "\"use strict\";\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\");\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = useTheme;\n\nvar _react = _interopRequireDefault(require(\"react\"));\n\nvar _ThemeContext = _interopRequireDefault(require(\"./ThemeContext\"));\n\nfunction useTheme() {\n var theme = _react.default.useContext(_ThemeContext.default);\n\n if (process.env.NODE_ENV !== 'production') {\n // eslint-disable-next-line react-hooks/rules-of-hooks\n _react.default.useDebugValue(theme);\n }\n\n return theme;\n}", "\"use strict\";\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\");\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nObject.defineProperty(exports, \"default\", {\n enumerable: true,\n get: function get() {\n return _useTheme.default;\n }\n});\n\nvar _useTheme = _interopRequireDefault(require(\"./useTheme\"));", "\"use strict\";\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\");\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = StylesProvider;\nexports.StylesContext = exports.sheetsManager = void 0;\n\nvar _extends2 = _interopRequireDefault(require(\"@babel/runtime/helpers/extends\"));\n\nvar _objectWithoutProperties2 = _interopRequireDefault(require(\"@babel/runtime/helpers/objectWithoutProperties\"));\n\nvar _react = _interopRequireDefault(require(\"react\"));\n\nvar _propTypes = _interopRequireDefault(require(\"prop-types\"));\n\nvar _utils = require(\"@material-ui/utils\");\n\nvar _createGenerateClassName = _interopRequireDefault(require(\"../createGenerateClassName\"));\n\nvar _jss = require(\"jss\");\n\nvar _jssPreset = _interopRequireDefault(require(\"../jssPreset\"));\n\n// Default JSS instance.\nvar jss = (0, _jss.create)((0, _jssPreset.default)()); // Use a singleton or the provided one by the context.\n//\n// The counter-based approach doesn't tolerate any mistake.\n// It's much safer to use the same counter everywhere.\n\nvar generateClassName = (0, _createGenerateClassName.default)(); // Exported for test purposes\n\nvar sheetsManager = new Map();\nexports.sheetsManager = sheetsManager;\nvar defaultOptions = {\n disableGeneration: false,\n generateClassName: generateClassName,\n jss: jss,\n sheetsCache: null,\n sheetsManager: sheetsManager,\n sheetsRegistry: null\n};\n\nvar StylesContext = _react.default.createContext(defaultOptions);\n\nexports.StylesContext = StylesContext;\n\nif (process.env.NODE_ENV !== 'production') {\n StylesContext.displayName = 'StylesContext';\n}\n\nvar injectFirstNode;\n\nfunction StylesProvider(props) {\n var children = props.children,\n _props$injectFirst = props.injectFirst,\n injectFirst = _props$injectFirst === void 0 ? false : _props$injectFirst,\n _props$disableGenerat = props.disableGeneration,\n disableGeneration = _props$disableGenerat === void 0 ? false : _props$disableGenerat,\n localOptions = (0, _objectWithoutProperties2.default)(props, [\"children\", \"injectFirst\", \"disableGeneration\"]);\n\n var outerOptions = _react.default.useContext(StylesContext);\n\n var context = (0, _extends2.default)({}, outerOptions, {\n disableGeneration: disableGeneration\n }, localOptions);\n\n if (process.env.NODE_ENV !== 'production') {\n if (typeof window === 'undefined' && !context.sheetsManager) {\n console.error('Material-UI: You need to use the ServerStyleSheets API when rendering on the server.');\n }\n }\n\n if (process.env.NODE_ENV !== 'production') {\n if (context.jss.options.insertionPoint && injectFirst) {\n console.error('Material-UI: You cannot use a custom insertionPoint and at the same time.');\n }\n }\n\n if (process.env.NODE_ENV !== 'production') {\n if (injectFirst && localOptions.jss) {\n console.error('Material-UI: You cannot use the jss and injectFirst props at the same time.');\n }\n }\n\n if (!context.jss.options.insertionPoint && injectFirst && typeof window !== 'undefined') {\n if (!injectFirstNode) {\n var head = document.head;\n injectFirstNode = document.createComment('mui-inject-first');\n head.insertBefore(injectFirstNode, head.firstChild);\n }\n\n context.jss = (0, _jss.create)({\n plugins: (0, _jssPreset.default)().plugins,\n insertionPoint: injectFirstNode\n });\n }\n\n return /*#__PURE__*/_react.default.createElement(StylesContext.Provider, {\n value: context\n }, children);\n}\n\nprocess.env.NODE_ENV !== \"production\" ? StylesProvider.propTypes = {\n /**\n * Your component tree.\n */\n children: _propTypes.default.node.isRequired,\n\n /**\n * You can disable the generation of the styles with this option.\n * It can be useful when traversing the React tree outside of the HTML\n * rendering step on the server.\n * Let's say you are using react-apollo to extract all\n * the queries made by the interface server-side - you can significantly speed up the traversal with this prop.\n */\n disableGeneration: _propTypes.default.bool,\n\n /**\n * JSS's class name generator.\n */\n generateClassName: _propTypes.default.func,\n\n /**\n * By default, the styles are injected last in the element of the page.\n * As a result, they gain more specificity than any other style sheet.\n * If you want to override Material-UI's styles, set this prop.\n */\n injectFirst: _propTypes.default.bool,\n\n /**\n * JSS's instance.\n */\n jss: _propTypes.default.object,\n\n /**\n * @ignore\n */\n serverGenerateClassName: _propTypes.default.func,\n\n /**\n * @ignore\n *\n * Beta feature.\n *\n * Cache for the sheets.\n */\n sheetsCache: _propTypes.default.object,\n\n /**\n * @ignore\n *\n * The sheetsManager is used to deduplicate style sheet injection in the page.\n * It's deduplicating using the (theme, styles) couple.\n * On the server, you should provide a new instance for each request.\n */\n sheetsManager: _propTypes.default.object,\n\n /**\n * @ignore\n *\n * Collect the sheets.\n */\n sheetsRegistry: _propTypes.default.object\n} : void 0;\n\nif (process.env.NODE_ENV !== 'production') {\n process.env.NODE_ENV !== \"production\" ? StylesProvider.propTypes = (0, _utils.exactProp)(StylesProvider.propTypes) : void 0;\n}", "\"use strict\";\n\nvar _interopRequireWildcard = require(\"@babel/runtime/helpers/interopRequireWildcard\");\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nvar _exportNames = {};\nObject.defineProperty(exports, \"default\", {\n enumerable: true,\n get: function get() {\n return _StylesProvider.default;\n }\n});\n\nvar _StylesProvider = _interopRequireWildcard(require(\"./StylesProvider\"));\n\nObject.keys(_StylesProvider).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _StylesProvider[key];\n }\n });\n});", "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.increment = increment;\n\n/* eslint-disable import/prefer-default-export */\n// Global index counter to preserve source order.\n// We create the style sheet during the creation of the component,\n// children are handled after the parents, so the order of style elements would be parent->child.\n// It is a problem though when a parent passes a className\n// which needs to override any child's styles.\n// StyleSheet of the child has a higher specificity, because of the source order.\n// So our solution is to render sheets them in the reverse order child->sheet, so\n// that parent has a higher specificity.\nvar indexCounter = -1e9;\n\nfunction increment() {\n indexCounter += 1;\n\n if (process.env.NODE_ENV !== 'production') {\n if (indexCounter >= 0) {\n console.warn(['Material-UI: You might have a memory leak.', 'The indexCounter is not supposed to grow that much.'].join('\\n'));\n }\n }\n\n return indexCounter;\n}", "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n// We use the same empty object to ref count the styles that don't need a theme object.\nvar noopTheme = {};\nvar _default = noopTheme;\nexports.default = _default;", "\"use strict\";\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\");\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = getStylesCreator;\n\nvar _extends2 = _interopRequireDefault(require(\"@babel/runtime/helpers/extends\"));\n\nvar _typeof2 = _interopRequireDefault(require(\"@babel/runtime/helpers/typeof\"));\n\nvar _utils = require(\"@material-ui/utils\");\n\nvar _noopTheme = _interopRequireDefault(require(\"./noopTheme\"));\n\nfunction getStylesCreator(stylesOrCreator) {\n var themingEnabled = typeof stylesOrCreator === 'function';\n\n if (process.env.NODE_ENV !== 'production') {\n if ((0, _typeof2.default)(stylesOrCreator) !== 'object' && !themingEnabled) {\n console.error(['Material-UI: The `styles` argument provided is invalid.', 'You need to provide a function generating the styles or a styles object.'].join('\\n'));\n }\n }\n\n return {\n create: function create(theme, name) {\n var styles;\n\n try {\n styles = themingEnabled ? stylesOrCreator(theme) : stylesOrCreator;\n } catch (err) {\n if (process.env.NODE_ENV !== 'production') {\n if (themingEnabled === true && theme === _noopTheme.default) {\n // TODO: prepend error message/name instead\n console.error(['Material-UI: The `styles` argument provided is invalid.', 'You are providing a function without a theme in the context.', 'One of the parent elements needs to use a ThemeProvider.'].join('\\n'));\n }\n }\n\n throw err;\n }\n\n if (!name || !theme.overrides || !theme.overrides[name]) {\n return styles;\n }\n\n var overrides = theme.overrides[name];\n var stylesWithOverrides = (0, _extends2.default)({}, styles);\n Object.keys(overrides).forEach(function (key) {\n if (process.env.NODE_ENV !== 'production') {\n if (!stylesWithOverrides[key]) {\n console.warn(['Material-UI: You are trying to override a style that does not exist.', \"Fix the `\".concat(key, \"` key of `theme.overrides.\").concat(name, \"`.\")].join('\\n'));\n }\n }\n\n stylesWithOverrides[key] = (0, _utils.deepmerge)(stylesWithOverrides[key], overrides[key]);\n });\n return stylesWithOverrides;\n },\n options: {}\n };\n}", "\"use strict\";\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\");\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nObject.defineProperty(exports, \"default\", {\n enumerable: true,\n get: function get() {\n return _getStylesCreator.default;\n }\n});\n\nvar _getStylesCreator = _interopRequireDefault(require(\"./getStylesCreator\"));", "\"use strict\";\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\");\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = makeStyles;\n\nvar _objectWithoutProperties2 = _interopRequireDefault(require(\"@babel/runtime/helpers/objectWithoutProperties\"));\n\nvar _extends2 = _interopRequireDefault(require(\"@babel/runtime/helpers/extends\"));\n\nvar _react = _interopRequireDefault(require(\"react\"));\n\nvar _jss = require(\"jss\");\n\nvar _mergeClasses = _interopRequireDefault(require(\"../mergeClasses\"));\n\nvar _multiKeyStore = _interopRequireDefault(require(\"./multiKeyStore\"));\n\nvar _useTheme = _interopRequireDefault(require(\"../useTheme\"));\n\nvar _StylesProvider = require(\"../StylesProvider\");\n\nvar _indexCounter = require(\"./indexCounter\");\n\nvar _getStylesCreator = _interopRequireDefault(require(\"../getStylesCreator\"));\n\nvar _noopTheme = _interopRequireDefault(require(\"../getStylesCreator/noopTheme\"));\n\nfunction getClasses(_ref, classes, Component) {\n var state = _ref.state,\n stylesOptions = _ref.stylesOptions;\n\n if (stylesOptions.disableGeneration) {\n return classes || {};\n }\n\n if (!state.cacheClasses) {\n state.cacheClasses = {\n // Cache for the finalized classes value.\n value: null,\n // Cache for the last used classes prop pointer.\n lastProp: null,\n // Cache for the last used rendered classes pointer.\n lastJSS: {}\n };\n } // Tracks if either the rendered classes or classes prop has changed,\n // requiring the generation of a new finalized classes object.\n\n\n var generate = false;\n\n if (state.classes !== state.cacheClasses.lastJSS) {\n state.cacheClasses.lastJSS = state.classes;\n generate = true;\n }\n\n if (classes !== state.cacheClasses.lastProp) {\n state.cacheClasses.lastProp = classes;\n generate = true;\n }\n\n if (generate) {\n state.cacheClasses.value = (0, _mergeClasses.default)({\n baseClasses: state.cacheClasses.lastJSS,\n newClasses: classes,\n Component: Component\n });\n }\n\n return state.cacheClasses.value;\n}\n\nfunction attach(_ref2, props) {\n var state = _ref2.state,\n theme = _ref2.theme,\n stylesOptions = _ref2.stylesOptions,\n stylesCreator = _ref2.stylesCreator,\n name = _ref2.name;\n\n if (stylesOptions.disableGeneration) {\n return;\n }\n\n var sheetManager = _multiKeyStore.default.get(stylesOptions.sheetsManager, stylesCreator, theme);\n\n if (!sheetManager) {\n sheetManager = {\n refs: 0,\n staticSheet: null,\n dynamicStyles: null\n };\n\n _multiKeyStore.default.set(stylesOptions.sheetsManager, stylesCreator, theme, sheetManager);\n }\n\n var options = (0, _extends2.default)({}, stylesCreator.options, stylesOptions, {\n theme: theme,\n flip: typeof stylesOptions.flip === 'boolean' ? stylesOptions.flip : theme.direction === 'rtl'\n });\n options.generateId = options.serverGenerateClassName || options.generateClassName;\n var sheetsRegistry = stylesOptions.sheetsRegistry;\n\n if (sheetManager.refs === 0) {\n var staticSheet;\n\n if (stylesOptions.sheetsCache) {\n staticSheet = _multiKeyStore.default.get(stylesOptions.sheetsCache, stylesCreator, theme);\n }\n\n var styles = stylesCreator.create(theme, name);\n\n if (!staticSheet) {\n staticSheet = stylesOptions.jss.createStyleSheet(styles, (0, _extends2.default)({\n link: false\n }, options));\n staticSheet.attach();\n\n if (stylesOptions.sheetsCache) {\n _multiKeyStore.default.set(stylesOptions.sheetsCache, stylesCreator, theme, staticSheet);\n }\n }\n\n if (sheetsRegistry) {\n sheetsRegistry.add(staticSheet);\n }\n\n sheetManager.staticSheet = staticSheet;\n sheetManager.dynamicStyles = (0, _jss.getDynamicStyles)(styles);\n }\n\n if (sheetManager.dynamicStyles) {\n var dynamicSheet = stylesOptions.jss.createStyleSheet(sheetManager.dynamicStyles, (0, _extends2.default)({\n link: true\n }, options));\n dynamicSheet.update(props);\n dynamicSheet.attach();\n state.dynamicSheet = dynamicSheet;\n state.classes = (0, _mergeClasses.default)({\n baseClasses: sheetManager.staticSheet.classes,\n newClasses: dynamicSheet.classes\n });\n\n if (sheetsRegistry) {\n sheetsRegistry.add(dynamicSheet);\n }\n } else {\n state.classes = sheetManager.staticSheet.classes;\n }\n\n sheetManager.refs += 1;\n}\n\nfunction update(_ref3, props) {\n var state = _ref3.state;\n\n if (state.dynamicSheet) {\n state.dynamicSheet.update(props);\n }\n}\n\nfunction detach(_ref4) {\n var state = _ref4.state,\n theme = _ref4.theme,\n stylesOptions = _ref4.stylesOptions,\n stylesCreator = _ref4.stylesCreator;\n\n if (stylesOptions.disableGeneration) {\n return;\n }\n\n var sheetManager = _multiKeyStore.default.get(stylesOptions.sheetsManager, stylesCreator, theme);\n\n sheetManager.refs -= 1;\n var sheetsRegistry = stylesOptions.sheetsRegistry;\n\n if (sheetManager.refs === 0) {\n _multiKeyStore.default.delete(stylesOptions.sheetsManager, stylesCreator, theme);\n\n stylesOptions.jss.removeStyleSheet(sheetManager.staticSheet);\n\n if (sheetsRegistry) {\n sheetsRegistry.remove(sheetManager.staticSheet);\n }\n }\n\n if (state.dynamicSheet) {\n stylesOptions.jss.removeStyleSheet(state.dynamicSheet);\n\n if (sheetsRegistry) {\n sheetsRegistry.remove(state.dynamicSheet);\n }\n }\n}\n\nfunction useSynchronousEffect(func, values) {\n var key = _react.default.useRef([]);\n\n var output; // Store \"generation\" key. Just returns a new object every time\n\n var currentKey = _react.default.useMemo(function () {\n return {};\n }, values); // eslint-disable-line react-hooks/exhaustive-deps\n // \"the first render\", or \"memo dropped the value\"\n\n\n if (key.current !== currentKey) {\n key.current = currentKey;\n output = func();\n }\n\n _react.default.useEffect(function () {\n return function () {\n if (output) {\n output();\n }\n };\n }, [currentKey] // eslint-disable-line react-hooks/exhaustive-deps\n );\n}\n\nfunction makeStyles(stylesOrCreator) {\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n var name = options.name,\n classNamePrefixOption = options.classNamePrefix,\n Component = options.Component,\n _options$defaultTheme = options.defaultTheme,\n defaultTheme = _options$defaultTheme === void 0 ? _noopTheme.default : _options$defaultTheme,\n stylesOptions2 = (0, _objectWithoutProperties2.default)(options, [\"name\", \"classNamePrefix\", \"Component\", \"defaultTheme\"]);\n var stylesCreator = (0, _getStylesCreator.default)(stylesOrCreator);\n var classNamePrefix = name || classNamePrefixOption || 'makeStyles';\n stylesCreator.options = {\n index: (0, _indexCounter.increment)(),\n name: name,\n meta: classNamePrefix,\n classNamePrefix: classNamePrefix\n };\n\n var useStyles = function useStyles() {\n var props = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n var theme = (0, _useTheme.default)() || defaultTheme;\n var stylesOptions = (0, _extends2.default)({}, _react.default.useContext(_StylesProvider.StylesContext), stylesOptions2);\n\n var instance = _react.default.useRef();\n\n var shouldUpdate = _react.default.useRef();\n\n useSynchronousEffect(function () {\n var current = {\n name: name,\n state: {},\n stylesCreator: stylesCreator,\n stylesOptions: stylesOptions,\n theme: theme\n };\n attach(current, props);\n shouldUpdate.current = false;\n instance.current = current;\n return function () {\n detach(current);\n };\n }, [theme, stylesCreator]);\n\n _react.default.useEffect(function () {\n if (shouldUpdate.current) {\n update(instance.current, props);\n }\n\n shouldUpdate.current = true;\n });\n\n var classes = getClasses(instance.current, props.classes, Component);\n\n if (process.env.NODE_ENV !== 'production') {\n // eslint-disable-next-line react-hooks/rules-of-hooks\n _react.default.useDebugValue(classes);\n }\n\n return classes;\n };\n\n return useStyles;\n}", "\"use strict\";\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\");\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nObject.defineProperty(exports, \"default\", {\n enumerable: true,\n get: function get() {\n return _makeStyles.default;\n }\n});\n\nvar _makeStyles = _interopRequireDefault(require(\"./makeStyles\"));", "function _classCallCheck(a, n) {\n if (!(a instanceof n)) throw new TypeError(\"Cannot call a class as a function\");\n}\nmodule.exports = _classCallCheck, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;", "\"use strict\";\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\");\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nvar _extends2 = _interopRequireDefault(require(\"@babel/runtime/helpers/extends\"));\n\nvar _classCallCheck2 = _interopRequireDefault(require(\"@babel/runtime/helpers/classCallCheck\"));\n\nvar _createClass2 = _interopRequireDefault(require(\"@babel/runtime/helpers/createClass\"));\n\nvar _react = _interopRequireDefault(require(\"react\"));\n\nvar _jss = require(\"jss\");\n\nvar _StylesProvider = _interopRequireDefault(require(\"../StylesProvider\"));\n\nvar _createGenerateClassName = _interopRequireDefault(require(\"../createGenerateClassName\"));\n\nvar ServerStyleSheets = /*#__PURE__*/function () {\n function ServerStyleSheets() {\n var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n (0, _classCallCheck2.default)(this, ServerStyleSheets);\n this.options = options;\n }\n\n (0, _createClass2.default)(ServerStyleSheets, [{\n key: \"collect\",\n value: function collect(children) {\n // This is needed in order to deduplicate the injection of CSS in the page.\n var sheetsManager = new Map(); // This is needed in order to inject the critical CSS.\n\n this.sheetsRegistry = new _jss.SheetsRegistry(); // A new class name generator\n\n var generateClassName = (0, _createGenerateClassName.default)();\n return /*#__PURE__*/_react.default.createElement(_StylesProvider.default, (0, _extends2.default)({\n sheetsManager: sheetsManager,\n serverGenerateClassName: generateClassName,\n sheetsRegistry: this.sheetsRegistry\n }, this.options), children);\n }\n }, {\n key: \"toString\",\n value: function toString() {\n return this.sheetsRegistry ? this.sheetsRegistry.toString() : '';\n }\n }, {\n key: \"getStyleElement\",\n value: function getStyleElement(props) {\n return /*#__PURE__*/_react.default.createElement('style', (0, _extends2.default)({\n id: 'jss-server-side',\n key: 'jss-server-side',\n dangerouslySetInnerHTML: {\n __html: this.toString()\n }\n }, props));\n }\n }]);\n return ServerStyleSheets;\n}();\n\nexports.default = ServerStyleSheets;", "\"use strict\";\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\");\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nObject.defineProperty(exports, \"default\", {\n enumerable: true,\n get: function get() {\n return _ServerStyleSheets.default;\n }\n});\n\nvar _ServerStyleSheets = _interopRequireDefault(require(\"./ServerStyleSheets\"));", "function e(r){var o,t,f=\"\";if(\"string\"==typeof r||\"number\"==typeof r)f+=r;else if(\"object\"==typeof r)if(Array.isArray(r))for(o=0;o 1 && arguments[1] !== undefined ? arguments[1] : {};\n var name = options.name,\n stylesOptions = (0, _objectWithoutProperties2.default)(options, [\"name\"]);\n\n if (process.env.NODE_ENV !== 'production' && Component === undefined) {\n throw new Error(['You are calling styled(Component)(style) with an undefined component.', 'You may have forgotten to import it.'].join('\\n'));\n }\n\n var classNamePrefix = name;\n\n if (process.env.NODE_ENV !== 'production') {\n if (!name) {\n // Provide a better DX outside production.\n var displayName = (0, _utils.getDisplayName)(Component);\n\n if (displayName !== undefined) {\n classNamePrefix = displayName;\n }\n }\n }\n\n var stylesOrCreator = typeof style === 'function' ? function (theme) {\n return {\n root: function root(props) {\n return style((0, _extends2.default)({\n theme: theme\n }, props));\n }\n };\n } : {\n root: style\n };\n var useStyles = (0, _makeStyles.default)(stylesOrCreator, (0, _extends2.default)({\n Component: Component,\n name: name || Component.displayName,\n classNamePrefix: classNamePrefix\n }, stylesOptions));\n var filterProps;\n var propTypes = {};\n\n if (style.filterProps) {\n filterProps = style.filterProps;\n delete style.filterProps;\n }\n /* eslint-disable react/forbid-foreign-prop-types */\n\n\n if (style.propTypes) {\n propTypes = style.propTypes;\n delete style.propTypes;\n }\n /* eslint-enable react/forbid-foreign-prop-types */\n\n\n var StyledComponent = /*#__PURE__*/_react.default.forwardRef(function StyledComponent(props, ref) {\n var children = props.children,\n classNameProp = props.className,\n clone = props.clone,\n ComponentProp = props.component,\n other = (0, _objectWithoutProperties2.default)(props, [\"children\", \"className\", \"clone\", \"component\"]);\n var classes = useStyles(props);\n var className = (0, _clsx.default)(classes.root, classNameProp);\n var spread = other;\n\n if (filterProps) {\n spread = omit(spread, filterProps);\n }\n\n if (clone) {\n return /*#__PURE__*/_react.default.cloneElement(children, (0, _extends2.default)({\n className: (0, _clsx.default)(children.props.className, className)\n }, spread));\n }\n\n if (typeof children === 'function') {\n return children((0, _extends2.default)({\n className: className\n }, spread));\n }\n\n var FinalComponent = ComponentProp || Component;\n return /*#__PURE__*/_react.default.createElement(FinalComponent, (0, _extends2.default)({\n ref: ref,\n className: className\n }, spread), children);\n });\n\n process.env.NODE_ENV !== \"production\" ? StyledComponent.propTypes = (0, _extends2.default)({\n /**\n * A render function or node.\n */\n children: _propTypes.default.oneOfType([_propTypes.default.node, _propTypes.default.func]),\n\n /**\n * @ignore\n */\n className: _propTypes.default.string,\n\n /**\n * If `true`, the component will recycle it's children HTML element.\n * It's using `React.cloneElement` internally.\n *\n * This prop will be deprecated and removed in v5\n */\n clone: (0, _utils.chainPropTypes)(_propTypes.default.bool, function (props) {\n if (props.clone && props.component) {\n return new Error('You can not use the clone and component prop at the same time.');\n }\n\n return null;\n }),\n\n /**\n * The component used for the root node.\n * Either a string to use a HTML element or a component.\n */\n component: _propTypes.default\n /* @typescript-to-proptypes-ignore */\n .elementType\n }, propTypes) : void 0;\n\n if (process.env.NODE_ENV !== 'production') {\n StyledComponent.displayName = \"Styled(\".concat(classNamePrefix, \")\");\n }\n\n (0, _hoistNonReactStatics.default)(StyledComponent, Component);\n return StyledComponent;\n };\n\n return componentCreator;\n}", "\"use strict\";\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\");\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nObject.defineProperty(exports, \"default\", {\n enumerable: true,\n get: function get() {\n return _styled.default;\n }\n});\n\nvar _styled = _interopRequireDefault(require(\"./styled\"));", "\"use strict\";\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\");\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nvar _extends2 = _interopRequireDefault(require(\"@babel/runtime/helpers/extends\"));\n\nvar _react = _interopRequireDefault(require(\"react\"));\n\nvar _propTypes = _interopRequireDefault(require(\"prop-types\"));\n\nvar _utils = require(\"@material-ui/utils\");\n\nvar _ThemeContext = _interopRequireDefault(require(\"../useTheme/ThemeContext\"));\n\nvar _useTheme = _interopRequireDefault(require(\"../useTheme\"));\n\nvar _nested = _interopRequireDefault(require(\"./nested\"));\n\n// To support composition of theme.\nfunction mergeOuterLocalTheme(outerTheme, localTheme) {\n if (typeof localTheme === 'function') {\n var mergedTheme = localTheme(outerTheme);\n\n if (process.env.NODE_ENV !== 'production') {\n if (!mergedTheme) {\n console.error(['Material-UI: You should return an object from your theme function, i.e.', ' ({})} />'].join('\\n'));\n }\n }\n\n return mergedTheme;\n }\n\n return (0, _extends2.default)({}, outerTheme, localTheme);\n}\n/**\n * This component takes a `theme` prop.\n * It makes the `theme` available down the React tree thanks to React context.\n * This component should preferably be used at **the root of your component tree**.\n */\n\n\nfunction ThemeProvider(props) {\n var children = props.children,\n localTheme = props.theme;\n var outerTheme = (0, _useTheme.default)();\n\n if (process.env.NODE_ENV !== 'production') {\n if (outerTheme === null && typeof localTheme === 'function') {\n console.error(['Material-UI: You are providing a theme function prop to the ThemeProvider component:', ' outerTheme} />', '', 'However, no outer theme is present.', 'Make sure a theme is already injected higher in the React tree ' + 'or provide a theme object.'].join('\\n'));\n }\n }\n\n var theme = _react.default.useMemo(function () {\n var output = outerTheme === null ? localTheme : mergeOuterLocalTheme(outerTheme, localTheme);\n\n if (output != null) {\n output[_nested.default] = outerTheme !== null;\n }\n\n return output;\n }, [localTheme, outerTheme]);\n\n return /*#__PURE__*/_react.default.createElement(_ThemeContext.default.Provider, {\n value: theme\n }, children);\n}\n\nprocess.env.NODE_ENV !== \"production\" ? ThemeProvider.propTypes = {\n /**\n * Your component tree.\n */\n children: _propTypes.default.node.isRequired,\n\n /**\n * A theme object. You can provide a function to extend the outer theme.\n */\n theme: _propTypes.default.oneOfType([_propTypes.default.object, _propTypes.default.func]).isRequired\n} : void 0;\n\nif (process.env.NODE_ENV !== 'production') {\n process.env.NODE_ENV !== \"production\" ? ThemeProvider.propTypes = (0, _utils.exactProp)(ThemeProvider.propTypes) : void 0;\n}\n\nvar _default = ThemeProvider;\nexports.default = _default;", "\"use strict\";\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\");\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nObject.defineProperty(exports, \"default\", {\n enumerable: true,\n get: function get() {\n return _ThemeProvider.default;\n }\n});\n\nvar _ThemeProvider = _interopRequireDefault(require(\"./ThemeProvider\"));", "\"use strict\";\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\");\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nvar _extends2 = _interopRequireDefault(require(\"@babel/runtime/helpers/extends\"));\n\nvar _objectWithoutProperties2 = _interopRequireDefault(require(\"@babel/runtime/helpers/objectWithoutProperties\"));\n\nvar _react = _interopRequireDefault(require(\"react\"));\n\nvar _propTypes = _interopRequireDefault(require(\"prop-types\"));\n\nvar _hoistNonReactStatics = _interopRequireDefault(require(\"hoist-non-react-statics\"));\n\nvar _utils = require(\"@material-ui/utils\");\n\nvar _makeStyles = _interopRequireDefault(require(\"../makeStyles\"));\n\nvar _getThemeProps = _interopRequireDefault(require(\"../getThemeProps\"));\n\nvar _useTheme = _interopRequireDefault(require(\"../useTheme\"));\n\n// Link a style sheet with a component.\n// It does not modify the component passed to it;\n// instead, it returns a new component, with a `classes` property.\nvar withStyles = function withStyles(stylesOrCreator) {\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n return function (Component) {\n var defaultTheme = options.defaultTheme,\n _options$withTheme = options.withTheme,\n withTheme = _options$withTheme === void 0 ? false : _options$withTheme,\n name = options.name,\n stylesOptions = (0, _objectWithoutProperties2.default)(options, [\"defaultTheme\", \"withTheme\", \"name\"]);\n\n if (process.env.NODE_ENV !== 'production') {\n if (Component === undefined) {\n throw new Error(['You are calling withStyles(styles)(Component) with an undefined component.', 'You may have forgotten to import it.'].join('\\n'));\n }\n }\n\n var classNamePrefix = name;\n\n if (process.env.NODE_ENV !== 'production') {\n if (!name) {\n // Provide a better DX outside production.\n var displayName = (0, _utils.getDisplayName)(Component);\n\n if (displayName !== undefined) {\n classNamePrefix = displayName;\n }\n }\n }\n\n var useStyles = (0, _makeStyles.default)(stylesOrCreator, (0, _extends2.default)({\n defaultTheme: defaultTheme,\n Component: Component,\n name: name || Component.displayName,\n classNamePrefix: classNamePrefix\n }, stylesOptions));\n\n var WithStyles = /*#__PURE__*/_react.default.forwardRef(function WithStyles(props, ref) {\n var classesProp = props.classes,\n innerRef = props.innerRef,\n other = (0, _objectWithoutProperties2.default)(props, [\"classes\", \"innerRef\"]); // The wrapper receives only user supplied props, which could be a subset of\n // the actual props Component might receive due to merging with defaultProps.\n // So copying it here would give us the same result in the wrapper as well.\n\n var classes = useStyles((0, _extends2.default)({}, Component.defaultProps, props));\n var theme;\n var more = other;\n\n if (typeof name === 'string' || withTheme) {\n // name and withTheme are invariant in the outer scope\n // eslint-disable-next-line react-hooks/rules-of-hooks\n theme = (0, _useTheme.default)() || defaultTheme;\n\n if (name) {\n more = (0, _getThemeProps.default)({\n theme: theme,\n name: name,\n props: other\n });\n } // Provide the theme to the wrapped component.\n // So we don't have to use the `withTheme()` Higher-order Component.\n\n\n if (withTheme && !more.theme) {\n more.theme = theme;\n }\n }\n\n return /*#__PURE__*/_react.default.createElement(Component, (0, _extends2.default)({\n ref: innerRef || ref,\n classes: classes\n }, more));\n });\n\n process.env.NODE_ENV !== \"production\" ? WithStyles.propTypes = {\n /**\n * Override or extend the styles applied to the component.\n */\n classes: _propTypes.default.object,\n\n /**\n * Use that prop to pass a ref to the decorated component.\n * @deprecated\n */\n innerRef: (0, _utils.chainPropTypes)(_propTypes.default.oneOfType([_propTypes.default.func, _propTypes.default.object]), function (props) {\n if (props.innerRef == null) {\n return null;\n }\n\n return null; // return new Error(\n // 'Material-UI: The `innerRef` prop is deprecated and will be removed in v5. ' +\n // 'Refs are now automatically forwarded to the inner component.',\n // );\n })\n } : void 0;\n\n if (process.env.NODE_ENV !== 'production') {\n WithStyles.displayName = \"WithStyles(\".concat((0, _utils.getDisplayName)(Component), \")\");\n }\n\n (0, _hoistNonReactStatics.default)(WithStyles, Component);\n\n if (process.env.NODE_ENV !== 'production') {\n // Exposed for test purposes.\n WithStyles.Naked = Component;\n WithStyles.options = options;\n WithStyles.useStyles = useStyles;\n }\n\n return WithStyles;\n };\n};\n\nvar _default = withStyles;\nexports.default = _default;", "\"use strict\";\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\");\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nObject.defineProperty(exports, \"default\", {\n enumerable: true,\n get: function get() {\n return _withStyles.default;\n }\n});\n\nvar _withStyles = _interopRequireDefault(require(\"./withStyles\"));", "\"use strict\";\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\");\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.withThemeCreator = withThemeCreator;\nexports.default = void 0;\n\nvar _extends2 = _interopRequireDefault(require(\"@babel/runtime/helpers/extends\"));\n\nvar _objectWithoutProperties2 = _interopRequireDefault(require(\"@babel/runtime/helpers/objectWithoutProperties\"));\n\nvar _react = _interopRequireDefault(require(\"react\"));\n\nvar _propTypes = _interopRequireDefault(require(\"prop-types\"));\n\nvar _hoistNonReactStatics = _interopRequireDefault(require(\"hoist-non-react-statics\"));\n\nvar _utils = require(\"@material-ui/utils\");\n\nvar _useTheme = _interopRequireDefault(require(\"../useTheme\"));\n\nfunction withThemeCreator() {\n var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n var defaultTheme = options.defaultTheme;\n\n var withTheme = function withTheme(Component) {\n if (process.env.NODE_ENV !== 'production') {\n if (Component === undefined) {\n throw new Error(['You are calling withTheme(Component) with an undefined component.', 'You may have forgotten to import it.'].join('\\n'));\n }\n }\n\n var WithTheme = /*#__PURE__*/_react.default.forwardRef(function WithTheme(props, ref) {\n var innerRef = props.innerRef,\n other = (0, _objectWithoutProperties2.default)(props, [\"innerRef\"]);\n var theme = (0, _useTheme.default)() || defaultTheme;\n return /*#__PURE__*/_react.default.createElement(Component, (0, _extends2.default)({\n theme: theme,\n ref: innerRef || ref\n }, other));\n });\n\n process.env.NODE_ENV !== \"production\" ? WithTheme.propTypes = {\n /**\n * Use that prop to pass a ref to the decorated component.\n * @deprecated\n */\n innerRef: (0, _utils.chainPropTypes)(_propTypes.default.oneOfType([_propTypes.default.func, _propTypes.default.object]), function (props) {\n if (props.innerRef == null) {\n return null;\n }\n\n return new Error('Material-UI: The `innerRef` prop is deprecated and will be removed in v5. ' + 'Refs are now automatically forwarded to the inner component.');\n })\n } : void 0;\n\n if (process.env.NODE_ENV !== 'production') {\n WithTheme.displayName = \"WithTheme(\".concat((0, _utils.getDisplayName)(Component), \")\");\n }\n\n (0, _hoistNonReactStatics.default)(WithTheme, Component);\n\n if (process.env.NODE_ENV !== 'production') {\n // Exposed for test purposes.\n WithTheme.Naked = Component;\n }\n\n return WithTheme;\n };\n\n return withTheme;\n} // Provide the theme object as a prop to the input component.\n// It's an alternative API to useTheme().\n// We encourage the usage of useTheme() where possible.\n\n\nvar withTheme = withThemeCreator();\nvar _default = withTheme;\nexports.default = _default;", "\"use strict\";\n\nvar _interopRequireWildcard = require(\"@babel/runtime/helpers/interopRequireWildcard\");\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nvar _exportNames = {};\nObject.defineProperty(exports, \"default\", {\n enumerable: true,\n get: function get() {\n return _withTheme.default;\n }\n});\n\nvar _withTheme = _interopRequireWildcard(require(\"./withTheme\"));\n\nObject.keys(_withTheme).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _withTheme[key];\n }\n });\n});", "/** @license Material-UI v4.11.5\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\"use strict\";\n\nvar _interopRequireWildcard = require(\"@babel/runtime/helpers/interopRequireWildcard\");\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nvar _exportNames = {\n createGenerateClassName: true,\n createStyles: true,\n getThemeProps: true,\n jssPreset: true,\n makeStyles: true,\n mergeClasses: true,\n ServerStyleSheets: true,\n styled: true,\n StylesProvider: true,\n ThemeProvider: true,\n useTheme: true,\n withStyles: true,\n withTheme: true\n};\nObject.defineProperty(exports, \"createGenerateClassName\", {\n enumerable: true,\n get: function get() {\n return _createGenerateClassName.default;\n }\n});\nObject.defineProperty(exports, \"createStyles\", {\n enumerable: true,\n get: function get() {\n return _createStyles.default;\n }\n});\nObject.defineProperty(exports, \"getThemeProps\", {\n enumerable: true,\n get: function get() {\n return _getThemeProps.default;\n }\n});\nObject.defineProperty(exports, \"jssPreset\", {\n enumerable: true,\n get: function get() {\n return _jssPreset.default;\n }\n});\nObject.defineProperty(exports, \"makeStyles\", {\n enumerable: true,\n get: function get() {\n return _makeStyles.default;\n }\n});\nObject.defineProperty(exports, \"mergeClasses\", {\n enumerable: true,\n get: function get() {\n return _mergeClasses.default;\n }\n});\nObject.defineProperty(exports, \"ServerStyleSheets\", {\n enumerable: true,\n get: function get() {\n return _ServerStyleSheets.default;\n }\n});\nObject.defineProperty(exports, \"styled\", {\n enumerable: true,\n get: function get() {\n return _styled.default;\n }\n});\nObject.defineProperty(exports, \"StylesProvider\", {\n enumerable: true,\n get: function get() {\n return _StylesProvider.default;\n }\n});\nObject.defineProperty(exports, \"ThemeProvider\", {\n enumerable: true,\n get: function get() {\n return _ThemeProvider.default;\n }\n});\nObject.defineProperty(exports, \"useTheme\", {\n enumerable: true,\n get: function get() {\n return _useTheme.default;\n }\n});\nObject.defineProperty(exports, \"withStyles\", {\n enumerable: true,\n get: function get() {\n return _withStyles.default;\n }\n});\nObject.defineProperty(exports, \"withTheme\", {\n enumerable: true,\n get: function get() {\n return _withTheme.default;\n }\n});\n\nvar _utils = require(\"@material-ui/utils\");\n\nvar _createGenerateClassName = _interopRequireWildcard(require(\"./createGenerateClassName\"));\n\nObject.keys(_createGenerateClassName).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _createGenerateClassName[key];\n }\n });\n});\n\nvar _createStyles = _interopRequireWildcard(require(\"./createStyles\"));\n\nObject.keys(_createStyles).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _createStyles[key];\n }\n });\n});\n\nvar _getThemeProps = _interopRequireWildcard(require(\"./getThemeProps\"));\n\nObject.keys(_getThemeProps).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _getThemeProps[key];\n }\n });\n});\n\nvar _jssPreset = _interopRequireWildcard(require(\"./jssPreset\"));\n\nObject.keys(_jssPreset).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _jssPreset[key];\n }\n });\n});\n\nvar _makeStyles = _interopRequireWildcard(require(\"./makeStyles\"));\n\nObject.keys(_makeStyles).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _makeStyles[key];\n }\n });\n});\n\nvar _mergeClasses = _interopRequireWildcard(require(\"./mergeClasses\"));\n\nObject.keys(_mergeClasses).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _mergeClasses[key];\n }\n });\n});\n\nvar _ServerStyleSheets = _interopRequireWildcard(require(\"./ServerStyleSheets\"));\n\nObject.keys(_ServerStyleSheets).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _ServerStyleSheets[key];\n }\n });\n});\n\nvar _styled = _interopRequireWildcard(require(\"./styled\"));\n\nObject.keys(_styled).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _styled[key];\n }\n });\n});\n\nvar _StylesProvider = _interopRequireWildcard(require(\"./StylesProvider\"));\n\nObject.keys(_StylesProvider).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _StylesProvider[key];\n }\n });\n});\n\nvar _ThemeProvider = _interopRequireWildcard(require(\"./ThemeProvider\"));\n\nObject.keys(_ThemeProvider).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _ThemeProvider[key];\n }\n });\n});\n\nvar _useTheme = _interopRequireWildcard(require(\"./useTheme\"));\n\nObject.keys(_useTheme).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _useTheme[key];\n }\n });\n});\n\nvar _withStyles = _interopRequireWildcard(require(\"./withStyles\"));\n\nObject.keys(_withStyles).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _withStyles[key];\n }\n });\n});\n\nvar _withTheme = _interopRequireWildcard(require(\"./withTheme\"));\n\nObject.keys(_withTheme).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _withTheme[key];\n }\n });\n});\n\n/* eslint-disable import/export */\n\n/* Warning if there are several instances of @material-ui/styles */\nif (process.env.NODE_ENV !== 'production' && process.env.NODE_ENV !== 'test' && typeof window !== 'undefined') {\n _utils.ponyfillGlobal['__@material-ui/styles-init__'] = _utils.ponyfillGlobal['__@material-ui/styles-init__'] || 0;\n\n if (_utils.ponyfillGlobal['__@material-ui/styles-init__'] === 1) {\n console.warn(['It looks like there are several instances of `@material-ui/styles` initialized in this application.', 'This may cause theme propagation issues, broken class names, ' + 'specificity issues, and makes your application bigger without a good reason.', '', 'See https://mui.com/r/styles-instance-warning for more info.'].join('\\n'));\n }\n\n _utils.ponyfillGlobal['__@material-ui/styles-init__'] += 1;\n}", "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = createStyles;\n\nvar _styles = require(\"@material-ui/styles\");\n\n// let warnOnce = false;\n// To remove in v5\nfunction createStyles(styles) {\n // warning(\n // warnOnce,\n // [\n // 'Material-UI: createStyles from @material-ui/core/styles is deprecated.',\n // 'Please use @material-ui/styles/createStyles',\n // ].join('\\n'),\n // );\n // warnOnce = true;\n return (0, _styles.createStyles)(styles);\n}", "\"use strict\";\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\");\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nvar _createTheme = _interopRequireDefault(require(\"./createTheme\"));\n\nvar defaultTheme = (0, _createTheme.default)();\nvar _default = defaultTheme;\nexports.default = _default;", "\"use strict\";\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\");\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nvar _extends2 = _interopRequireDefault(require(\"@babel/runtime/helpers/extends\"));\n\nvar _styles = require(\"@material-ui/styles\");\n\nvar _defaultTheme = _interopRequireDefault(require(\"./defaultTheme\"));\n\nfunction makeStyles(stylesOrCreator) {\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n return (0, _styles.makeStyles)(stylesOrCreator, (0, _extends2.default)({\n defaultTheme: _defaultTheme.default\n }, options));\n}\n\nvar _default = makeStyles;\nexports.default = _default;", "\"use strict\";\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\");\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.isUnitless = isUnitless;\nexports.getUnit = getUnit;\nexports.toUnitless = toUnitless;\nexports.convertLength = convertLength;\nexports.alignProperty = alignProperty;\nexports.fontGrid = fontGrid;\nexports.responsiveProperty = responsiveProperty;\n\nvar _defineProperty2 = _interopRequireDefault(require(\"@babel/runtime/helpers/defineProperty\"));\n\nfunction isUnitless(value) {\n return String(parseFloat(value)).length === String(value).length;\n} // Ported from Compass\n// https://github.com/Compass/compass/blob/master/core/stylesheets/compass/typography/_units.scss\n// Emulate the sass function \"unit\"\n\n\nfunction getUnit(input) {\n return String(input).match(/[\\d.\\-+]*\\s*(.*)/)[1] || '';\n} // Emulate the sass function \"unitless\"\n\n\nfunction toUnitless(length) {\n return parseFloat(length);\n} // Convert any CSS or value to any another.\n// From https://github.com/KyleAMathews/convert-css-length\n\n\nfunction convertLength(baseFontSize) {\n return function (length, toUnit) {\n var fromUnit = getUnit(length); // Optimize for cases where `from` and `to` units are accidentally the same.\n\n if (fromUnit === toUnit) {\n return length;\n } // Convert input length to pixels.\n\n\n var pxLength = toUnitless(length);\n\n if (fromUnit !== 'px') {\n if (fromUnit === 'em') {\n pxLength = toUnitless(length) * toUnitless(baseFontSize);\n } else if (fromUnit === 'rem') {\n pxLength = toUnitless(length) * toUnitless(baseFontSize);\n return length;\n }\n } // Convert length in pixels to the output unit\n\n\n var outputLength = pxLength;\n\n if (toUnit !== 'px') {\n if (toUnit === 'em') {\n outputLength = pxLength / toUnitless(baseFontSize);\n } else if (toUnit === 'rem') {\n outputLength = pxLength / toUnitless(baseFontSize);\n } else {\n return length;\n }\n }\n\n return parseFloat(outputLength.toFixed(5)) + toUnit;\n };\n}\n\nfunction alignProperty(_ref) {\n var size = _ref.size,\n grid = _ref.grid;\n var sizeBelow = size - size % grid;\n var sizeAbove = sizeBelow + grid;\n return size - sizeBelow < sizeAbove - size ? sizeBelow : sizeAbove;\n} // fontGrid finds a minimal grid (in rem) for the fontSize values so that the\n// lineHeight falls under a x pixels grid, 4px in the case of Material Design,\n// without changing the relative line height\n\n\nfunction fontGrid(_ref2) {\n var lineHeight = _ref2.lineHeight,\n pixels = _ref2.pixels,\n htmlFontSize = _ref2.htmlFontSize;\n return pixels / (lineHeight * htmlFontSize);\n}\n/**\n * generate a responsive version of a given CSS property\n * @example\n * responsiveProperty({\n * cssProperty: 'fontSize',\n * min: 15,\n * max: 20,\n * unit: 'px',\n * breakpoints: [300, 600],\n * })\n *\n * // this returns\n *\n * {\n * fontSize: '15px',\n * '@media (min-width:300px)': {\n * fontSize: '17.5px',\n * },\n * '@media (min-width:600px)': {\n * fontSize: '20px',\n * },\n * }\n *\n * @param {Object} params\n * @param {string} params.cssProperty - The CSS property to be made responsive\n * @param {number} params.min - The smallest value of the CSS property\n * @param {number} params.max - The largest value of the CSS property\n * @param {string} [params.unit] - The unit to be used for the CSS property\n * @param {Array.number} [params.breakpoints] - An array of breakpoints\n * @param {number} [params.alignStep] - Round scaled value to fall under this grid\n * @returns {Object} responsive styles for {params.cssProperty}\n */\n\n\nfunction responsiveProperty(_ref3) {\n var cssProperty = _ref3.cssProperty,\n min = _ref3.min,\n max = _ref3.max,\n _ref3$unit = _ref3.unit,\n unit = _ref3$unit === void 0 ? 'rem' : _ref3$unit,\n _ref3$breakpoints = _ref3.breakpoints,\n breakpoints = _ref3$breakpoints === void 0 ? [600, 960, 1280] : _ref3$breakpoints,\n _ref3$transform = _ref3.transform,\n transform = _ref3$transform === void 0 ? null : _ref3$transform;\n var output = (0, _defineProperty2.default)({}, cssProperty, \"\".concat(min).concat(unit));\n var factor = (max - min) / breakpoints[breakpoints.length - 1];\n breakpoints.forEach(function (breakpoint) {\n var value = min + factor * breakpoint;\n\n if (transform !== null) {\n value = transform(value);\n }\n\n output[\"@media (min-width:\".concat(breakpoint, \"px)\")] = (0, _defineProperty2.default)({}, cssProperty, \"\".concat(Math.round(value * 10000) / 10000).concat(unit));\n });\n return output;\n}", "\"use strict\";\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\");\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = responsiveFontSizes;\n\nvar _extends2 = _interopRequireDefault(require(\"@babel/runtime/helpers/extends\"));\n\nvar _utils = require(\"@material-ui/utils\");\n\nvar _cssUtils = require(\"./cssUtils\");\n\nfunction responsiveFontSizes(themeInput) {\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n var _options$breakpoints = options.breakpoints,\n breakpoints = _options$breakpoints === void 0 ? ['sm', 'md', 'lg'] : _options$breakpoints,\n _options$disableAlign = options.disableAlign,\n disableAlign = _options$disableAlign === void 0 ? false : _options$disableAlign,\n _options$factor = options.factor,\n factor = _options$factor === void 0 ? 2 : _options$factor,\n _options$variants = options.variants,\n variants = _options$variants === void 0 ? ['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'subtitle1', 'subtitle2', 'body1', 'body2', 'caption', 'button', 'overline'] : _options$variants;\n var theme = (0, _extends2.default)({}, themeInput);\n theme.typography = (0, _extends2.default)({}, theme.typography);\n var typography = theme.typography; // Convert between css lengths e.g. em->px or px->rem\n // Set the baseFontSize for your project. Defaults to 16px (also the browser default).\n\n var convert = (0, _cssUtils.convertLength)(typography.htmlFontSize);\n var breakpointValues = breakpoints.map(function (x) {\n return theme.breakpoints.values[x];\n });\n variants.forEach(function (variant) {\n var style = typography[variant];\n var remFontSize = parseFloat(convert(style.fontSize, 'rem'));\n\n if (remFontSize <= 1) {\n return;\n }\n\n var maxFontSize = remFontSize;\n var minFontSize = 1 + (maxFontSize - 1) / factor;\n var lineHeight = style.lineHeight;\n\n if (!(0, _cssUtils.isUnitless)(lineHeight) && !disableAlign) {\n throw new Error(process.env.NODE_ENV !== \"production\" ? \"Material-UI: Unsupported non-unitless line height with grid alignment.\\nUse unitless line heights instead.\" : (0, _utils.formatMuiErrorMessage)(6));\n }\n\n if (!(0, _cssUtils.isUnitless)(lineHeight)) {\n // make it unitless\n lineHeight = parseFloat(convert(lineHeight, 'rem')) / parseFloat(remFontSize);\n }\n\n var transform = null;\n\n if (!disableAlign) {\n transform = function transform(value) {\n return (0, _cssUtils.alignProperty)({\n size: value,\n grid: (0, _cssUtils.fontGrid)({\n pixels: 4,\n lineHeight: lineHeight,\n htmlFontSize: typography.htmlFontSize\n })\n });\n };\n }\n\n typography[variant] = (0, _extends2.default)({}, style, (0, _cssUtils.responsiveProperty)({\n cssProperty: 'fontSize',\n min: minFontSize,\n max: maxFontSize,\n unit: 'rem',\n breakpoints: breakpointValues,\n transform: transform\n }));\n });\n return theme;\n}", "\"use strict\";\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\");\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nvar _extends2 = _interopRequireDefault(require(\"@babel/runtime/helpers/extends\"));\n\nvar _styles = require(\"@material-ui/styles\");\n\nvar _defaultTheme = _interopRequireDefault(require(\"./defaultTheme\"));\n\nvar styled = function styled(Component) {\n var componentCreator = (0, _styles.styled)(Component);\n return function (style, options) {\n return componentCreator(style, (0, _extends2.default)({\n defaultTheme: _defaultTheme.default\n }, options));\n };\n};\n\nvar _default = styled;\nexports.default = _default;", "\"use strict\";\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\");\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = useTheme;\n\nvar _styles = require(\"@material-ui/styles\");\n\nvar _react = _interopRequireDefault(require(\"react\"));\n\nvar _defaultTheme = _interopRequireDefault(require(\"./defaultTheme\"));\n\nfunction useTheme() {\n var theme = (0, _styles.useTheme)() || _defaultTheme.default;\n\n if (process.env.NODE_ENV !== 'production') {\n // eslint-disable-next-line react-hooks/rules-of-hooks\n _react.default.useDebugValue(theme);\n }\n\n return theme;\n}", "\"use strict\";\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\");\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nvar _extends2 = _interopRequireDefault(require(\"@babel/runtime/helpers/extends\"));\n\nvar _styles = require(\"@material-ui/styles\");\n\nvar _defaultTheme = _interopRequireDefault(require(\"./defaultTheme\"));\n\nfunction withStyles(stylesOrCreator, options) {\n return (0, _styles.withStyles)(stylesOrCreator, (0, _extends2.default)({\n defaultTheme: _defaultTheme.default\n }, options));\n}\n\nvar _default = withStyles;\nexports.default = _default;", "\"use strict\";\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\");\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nvar _styles = require(\"@material-ui/styles\");\n\nvar _defaultTheme = _interopRequireDefault(require(\"./defaultTheme\"));\n\nvar withTheme = (0, _styles.withThemeCreator)({\n defaultTheme: _defaultTheme.default\n});\nvar _default = withTheme;\nexports.default = _default;", "\"use strict\";\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\");\n\nvar _interopRequireWildcard = require(\"@babel/runtime/helpers/interopRequireWildcard\");\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nvar _exportNames = {\n createTheme: true,\n createMuiTheme: true,\n unstable_createMuiStrictModeTheme: true,\n createStyles: true,\n makeStyles: true,\n responsiveFontSizes: true,\n styled: true,\n useTheme: true,\n withStyles: true,\n withTheme: true,\n createGenerateClassName: true,\n jssPreset: true,\n ServerStyleSheets: true,\n StylesProvider: true,\n MuiThemeProvider: true,\n ThemeProvider: true\n};\nObject.defineProperty(exports, \"createTheme\", {\n enumerable: true,\n get: function get() {\n return _createTheme.default;\n }\n});\nObject.defineProperty(exports, \"createMuiTheme\", {\n enumerable: true,\n get: function get() {\n return _createTheme.createMuiTheme;\n }\n});\nObject.defineProperty(exports, \"unstable_createMuiStrictModeTheme\", {\n enumerable: true,\n get: function get() {\n return _createMuiStrictModeTheme.default;\n }\n});\nObject.defineProperty(exports, \"createStyles\", {\n enumerable: true,\n get: function get() {\n return _createStyles.default;\n }\n});\nObject.defineProperty(exports, \"makeStyles\", {\n enumerable: true,\n get: function get() {\n return _makeStyles.default;\n }\n});\nObject.defineProperty(exports, \"responsiveFontSizes\", {\n enumerable: true,\n get: function get() {\n return _responsiveFontSizes.default;\n }\n});\nObject.defineProperty(exports, \"styled\", {\n enumerable: true,\n get: function get() {\n return _styled.default;\n }\n});\nObject.defineProperty(exports, \"useTheme\", {\n enumerable: true,\n get: function get() {\n return _useTheme.default;\n }\n});\nObject.defineProperty(exports, \"withStyles\", {\n enumerable: true,\n get: function get() {\n return _withStyles.default;\n }\n});\nObject.defineProperty(exports, \"withTheme\", {\n enumerable: true,\n get: function get() {\n return _withTheme.default;\n }\n});\nObject.defineProperty(exports, \"createGenerateClassName\", {\n enumerable: true,\n get: function get() {\n return _styles.createGenerateClassName;\n }\n});\nObject.defineProperty(exports, \"jssPreset\", {\n enumerable: true,\n get: function get() {\n return _styles.jssPreset;\n }\n});\nObject.defineProperty(exports, \"ServerStyleSheets\", {\n enumerable: true,\n get: function get() {\n return _styles.ServerStyleSheets;\n }\n});\nObject.defineProperty(exports, \"StylesProvider\", {\n enumerable: true,\n get: function get() {\n return _styles.StylesProvider;\n }\n});\nObject.defineProperty(exports, \"MuiThemeProvider\", {\n enumerable: true,\n get: function get() {\n return _styles.ThemeProvider;\n }\n});\nObject.defineProperty(exports, \"ThemeProvider\", {\n enumerable: true,\n get: function get() {\n return _styles.ThemeProvider;\n }\n});\n\nvar _colorManipulator = require(\"./colorManipulator\");\n\nObject.keys(_colorManipulator).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _colorManipulator[key];\n }\n });\n});\n\nvar _createTheme = _interopRequireWildcard(require(\"./createTheme\"));\n\nvar _createMuiStrictModeTheme = _interopRequireDefault(require(\"./createMuiStrictModeTheme\"));\n\nvar _createStyles = _interopRequireDefault(require(\"./createStyles\"));\n\nvar _makeStyles = _interopRequireDefault(require(\"./makeStyles\"));\n\nvar _responsiveFontSizes = _interopRequireDefault(require(\"./responsiveFontSizes\"));\n\nvar _styled = _interopRequireDefault(require(\"./styled\"));\n\nvar _transitions = require(\"./transitions\");\n\nObject.keys(_transitions).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _transitions[key];\n }\n });\n});\n\nvar _useTheme = _interopRequireDefault(require(\"./useTheme\"));\n\nvar _withStyles = _interopRequireDefault(require(\"./withStyles\"));\n\nvar _withTheme = _interopRequireDefault(require(\"./withTheme\"));\n\nvar _styles = require(\"@material-ui/styles\");", "import { createTheme } from '@material-ui/core/styles';\n\nimport orange from '@material-ui/core/colors/orange';\n\nconst step = (16 - 5) / 23 / 100;\n\n/**\n * Convert hex color in the format '#rrggbb' or '#rgb' to an RGB object.\n * @param {string} hex\n * @returns {{r: number, g: number, b: number}}\n */\nfunction toInt(hex) {\n const rgb = {\n r: 0,\n g: 0,\n b: 0,\n };\n\n if (hex.length === 7) {\n rgb.r = parseInt(hex.substr(1, 2), 16);\n rgb.g = parseInt(hex.substr(3, 2), 16);\n rgb.b = parseInt(hex.substr(5, 2), 16);\n } else if (hex.length === 4) {\n const r = hex.substr(1, 1);\n const g = hex.substr(2, 1);\n const b = hex.substr(3, 1);\n\n rgb.r = parseInt(r + r, 16);\n rgb.g = parseInt(g + g, 16);\n rgb.b = parseInt(b + b, 16);\n }\n\n return rgb;\n}\n\n/**\n * Convert an RGB object to a hex color string in the format '#rrggbb'.\n * @param {{r: number, g: number, b: number}} int\n * @returns {string}\n */\nfunction toHex(int) {\n return `#${Math.round(int.r).toString(16)}${Math.round(int.g).toString(16)}${Math.round(int.b).toString(16)}`;\n}\n\n/**\n * @param {string} color color in the format '#rrggbb' or '#rgb'\n * @param {string} overlayColor overlay color in the format '#rrggbb' or '#rgb'\n * @param {number} elevation elevation as an integer starting with 1\n * @returns {string} the hex color string in the format '#rrggbb'\n */\nfunction getElevation(color, overlayColor, elevation) {\n const rgb = toInt(color);\n const overlay = toInt(overlayColor);\n\n rgb.r += overlay.r * (0.05 + step * (elevation - 1));\n rgb.g += overlay.g * (0.05 + step * (elevation - 1));\n rgb.b += overlay.b * (0.05 + step * (elevation - 1));\n\n return toHex(rgb);\n}\n\n/**\n * Get all 24 elevations of the given color and overlay.\n * @param {string} color color in the format '#rrggbb' or '#rgb'\n * @param {string} overlay overlay color in the format '#rrggbb' or '#rgb'\n * @returns {import('@material-ui/core/styles/withStyles').CSSProperties}\n */\nfunction getElevations(color, overlay) {\n /** @type {import('@material-ui/core/styles/withStyles').CSSProperties} */\n const elevations = {};\n\n for (let i = 1; i <= 24; i++) {\n elevations[`elevation${i}`] = {\n backgroundColor: getElevation(color, overlay, i),\n };\n }\n\n return elevations;\n}\n\n/**\n * The theme creation factory function.\n * @param {string} type\n * @returns {import('./types').Theme}\n */\nconst Theme = type => {\n let theme;\n if (type === 'dark') {\n theme = {\n name: type,\n palette: {\n type: 'dark',\n background: {\n paper: '#121212',\n default: '#121212'\n },\n primary: {\n main: '#4dabf5'\n },\n secondary: {\n main: '#436a93'\n },\n expert: '#14bb00',\n text: {\n primary: '#ffffff',\n secondary: '#ffffff'\n }\n },\n overrides: {\n MuiAppBar: {\n colorDefault: {\n backgroundColor: '#272727'\n }\n },\n MuiLink: {\n root: {\n textTransform: 'uppercase',\n transition: 'color .3s ease',\n color: orange[200],\n '&:hover': {\n color: orange[100]\n }\n }\n },\n MuiPaper: getElevations('#121212', '#fff')\n }\n };\n } else if (type === 'blue') {\n theme = {\n name: type,\n palette: {\n type: 'dark',\n background: {\n paper: '#151d21',\n default: '#151d21'\n },\n primary: {\n main: '#4dabf5'\n },\n secondary: {\n main: '#436a93'\n },\n expert: '#14bb00',\n text: {\n primary: '#ffffff',\n secondary: '#ffffff'\n }\n },\n overrides: {\n MuiAppBar: {\n colorDefault: {\n backgroundColor: '#2a3135'\n }\n },\n MuiLink: {\n root: {\n textTransform: 'uppercase',\n transition: 'color .3s ease',\n color: orange[200],\n '&:hover': {\n color: orange[100]\n }\n }\n },\n MuiPaper: getElevations('#151d21', '#fff')\n }\n };\n } else if (type === 'colored') {\n theme = {\n name: type,\n palette: {\n type: 'light',\n primary: {\n main: '#3399CC'\n },\n secondary: {\n main: '#164477'\n },\n expert: '#96fc96'\n },\n overrides: {\n MuiAppBar: {\n colorDefault: {\n backgroundColor: '#3399CC'\n }\n },\n MuiLink: {\n root: {\n textTransform: 'uppercase',\n transition: 'color .3s ease',\n color: orange[400],\n '&:hover': {\n color: orange[300]\n }\n }\n }\n }\n };\n } else if (type === 'PT') {\n theme = {\n name: type,\n palette: {\n type: 'light',\n primary: {\n main: '#0F99DE'\n },\n secondary: {\n main: '#88A536'\n },\n expert: '#BD1B24'\n },\n overrides: {\n MuiAppBar: {\n colorDefault: {\n backgroundColor: '#0F99DE'\n }\n },\n MuiLink: {\n root: {\n textTransform: 'uppercase',\n transition: 'color .3s ease',\n color: orange[400],\n '&:hover': {\n color: orange[300]\n }\n }\n }\n }\n };\n } else if (type === 'DX') {\n theme = {\n name: type,\n palette: {\n type: 'light',\n primary: {\n main: '#F5F5F7'\n },\n secondary: {\n main: '#a9a9a9'\n },\n expert: '#BD1B24',\n text: {\n primary: '#007AFE',\n secondary: '#007AFE',\n disabled: '#007AFEAA',\n }\n },\n overrides: {\n MuiAppBar: {\n colorDefault: {\n backgroundColor: '#a9a9a9'\n }\n },\n MuiLink: {\n root: {\n textTransform: 'uppercase',\n transition: 'color .3s ease',\n color: orange[400],\n '&:hover': {\n color: orange[300]\n }\n }\n }\n }\n };\n } else {\n theme = {\n name: type,\n palette: {\n type: 'light',\n primary: {\n main: '#3399CC'\n },\n secondary: {\n main: '#164477'\n },\n expert: '#14bb00'\n },\n overrides: {\n MuiLink: {\n root: {\n textTransform: 'uppercase',\n transition: 'color .3s ease',\n color: orange[400],\n '&:hover': {\n color: orange[300]\n }\n }\n }\n }\n };\n }\n\n theme.toolbar = {\n height: 48\n };\n\n // add save toolbar\n theme.saveToolbar = {\n background: theme.palette.primary.main,\n button: {\n borderRadius: 3,\n height: 32\n }\n };\n\n return createTheme(theme);\n};\n\nexport default Theme;\n", "/***\n * Copyright 2018-2022 bluefox \n *\n * MIT License\n *\n ***/\n\n /**\n * Translation string management.\n */\nclass I18n {\n /**\n * List of all languages with their translations.\n * @type {{ [lang in ioBroker.Languages]?: Record; }}\n */\n static translations = {};\n\n /**\n * The currently displayed language.\n * @type {ioBroker.Languages}\n */\n static lang = window.sysLang || 'en';\n\n static _disableWarning = false;\n\n /**\n * Set the language to display.\n * @param {ioBroker.Languages} lang\n */\n static setLanguage(lang) {\n if (lang) {\n I18n.lang = lang;\n }\n }\n\n /**\n * Add translations\n * User can provide two types of structures:\n * - {\"word1\": \"translated word1\", \"word2\": \"translated word2\"}, but in this case the lang must be provided\n * - {\"word1\": {\"en\": \"translated en word1\", \"de\": \"translated de word1\"}, \"word2\": {\"en\": \"translated en word2\", \"de\": \"translated de word2\"}}, but no lang must be provided\n * @param {object} words additional words for specific language\n * @param {ioBroker.Languages} lang\n */\n static extendTranslations(words, lang) {\n try {\n if (!lang) {\n Object.keys(words).forEach(word => {\n Object.keys(words[word]).forEach(lang => {\n if (!I18n.translations[lang]) {\n console.warn(`Used unknown language: ${lang}`);\n }\n if (!I18n.translations[lang][word]) {\n I18n.translations[lang][word] = words[word][lang];\n } else if (I18n.translations[lang][word] !== words[word][lang]) {\n console.warn(`Translation for word \"${word}\" in \"${lang}\" was ignored: existing = \"${I18n.translations[lang][word]}\", new = ${words[word][lang]}`);\n }\n });\n });\n } else {\n if (!I18n.translations[lang]) {\n console.warn(`Used unknown language: ${lang}`);\n }\n I18n.translations[lang] = I18n.translations[lang] || {};\n Object.keys(words)\n .forEach(word => {\n if (!I18n.translations[lang][word]) {\n I18n.translations[lang][word] = words[word];\n } else if (I18n.translations[lang][word] !== words[word]) {\n console.warn(`Translation for word \"${word}\" in \"${lang}\" was ignored: existing = \"${I18n.translations[lang][word]}\", new = ${words[word]}`);\n }\n });\n }\n } catch (e) {\n console.error(`Cannot apply translations: ${e}`);\n }\n }\n\n /**\n * Sets all translations (in all languages).\n * @param {{ [lang in ioBroker.Languages]?: Record; }} translations\n */\n static setTranslations(translations) {\n if (translations) {\n I18n.translations = translations;\n }\n }\n\n /**\n * Get the currently chosen language.\n * @returns {ioBroker.Languages} The current language.\n */\n static getLanguage() {\n return I18n.lang;\n }\n\n /**\n * Translate the given string to the selected language.\n * @param {string} word The (key) word to look up the string.\n * @param {string[]} args Optional arguments which will replace the first (second, third, ...) occurrences of %s\n */\n static t(word, ...args) {\n const translation = I18n.translations[I18n.lang];\n if (translation) {\n const w = translation[word];\n if (w) {\n word = w;\n } else {\n I18n._disableWarning && console.log(`Translate: ${word}`);\n }\n }\n for (const arg of args) {\n word = word.replace('%s', arg);\n }\n return word;\n }\n\n /**\n * Disable warning about non-translated words\n * Required during development\n * @param {boolean} disable Do the warning should be disabled\n */\n static disableWarning(disable) {\n I18n._disableWarning = !!disable;\n }\n}\n\n/*I18n.translations = {\n 'en': require('./i18n/en'),\n 'ru': require('./i18n/ru'),\n 'de': require('./i18n/de'),\n};\nI18n.fallbacks = true;\nI18n.t = function () {};*/\n\nexport default I18n;", "/**\r\n * Copyright 2018-2022 bluefox \r\n *\r\n * MIT License\r\n *\r\n **/\r\nimport React from 'react';\r\nimport I18n from '../i18n';\r\n\r\nconst NAMESPACE = 'material';\r\nconst days = ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'];\r\nconst months = ['Jan', 'Feb', 'Mar', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];\r\nconst QUALITY_BITS = {\r\n 0x00: '0x00 - good',\r\n\r\n 0x01: '0x01 - general problem',\r\n 0x02: '0x02 - no connection problem',\r\n\r\n 0x10: '0x10 - substitute value from controller',\r\n 0x20: '0x20 - substitute initial value',\r\n 0x40: '0x40 - substitute value from device or instance',\r\n 0x80: '0x80 - substitute value from sensor',\r\n\r\n 0x11: '0x11 - general problem by instance',\r\n 0x41: '0x41 - general problem by device',\r\n 0x81: '0x81 - general problem by sensor',\r\n\r\n 0x12: '0x12 - instance not connected',\r\n 0x42: '0x42 - device not connected',\r\n 0x82: '0x82 - sensor not connected',\r\n\r\n 0x44: '0x44 - device reports error',\r\n 0x84: '0x84 - sensor reports error',\r\n};\r\n\r\nclass Utils {\r\n static namespace = NAMESPACE;\r\n static INSTANCES = 'instances';\r\n static dateFormat = ['DD', 'MM'];\r\n static FORBIDDEN_CHARS = /[^._\\-/ :!#$%&()+=@^{}|~\\p{Ll}\\p{Lu}\\p{Nd}]+/gu;\r\n\r\n /**\r\n * Capitalize words.\r\n * @param {string | undefined} name\r\n * @returns {string}\r\n */\r\n static CapitalWords(name) {\r\n return (name || '').split(/[\\s_]/)\r\n .filter(item => item)\r\n .map(word => word ? word[0].toUpperCase() + word.substring(1).toLowerCase() : '')\r\n .join(' ');\r\n }\r\n\r\n static formatSeconds(seconds) {\r\n const days = Math.floor(seconds / (3600 * 24));\r\n seconds %= 3600 * 24;\r\n let hours = Math.floor(seconds / 3600);\r\n if (hours < 10) {\r\n hours = '0' + hours;\r\n }\r\n seconds %= 3600;\r\n let minutes = Math.floor(seconds / 60);\r\n if (minutes < 10) {\r\n minutes = '0' + minutes;\r\n }\r\n seconds %= 60;\r\n seconds = Math.floor(seconds);\r\n if (seconds < 10) {\r\n seconds = '0' + seconds;\r\n }\r\n let text = '';\r\n if (days) {\r\n text += `${days} ${I18n.t('ra_daysShortText')} `;\r\n }\r\n text += `${hours}:${minutes}:${seconds}`;\r\n\r\n return text;\r\n }\r\n\r\n /**\r\n * Get the name of the object by id from the name or description.\r\n * @param {Record} objects\r\n * @param {string} id\r\n * @param {{ name: any; } | ioBroker.Languages | null} settings\r\n * @param {{ language?: ioBroker.Languages; }} options\r\n * @param {boolean} [isDesc] Set to true to get the description.\r\n * @returns {string}\r\n */\r\n static getObjectName(objects, id, settings, options, isDesc) {\r\n let item = objects[id];\r\n let text = id;\r\n const attr = isDesc ? 'desc' : 'name';\r\n\r\n if (typeof settings === 'string' && !options) {\r\n options = {language: settings};\r\n settings = null;\r\n }\r\n\r\n options = options || {};\r\n if (!options.language) {\r\n options.language = (objects['system.config'] && objects['system.config'].common && objects['system.config'].common.language) || window.sysLang || 'en';\r\n }\r\n if (settings && settings.name) {\r\n text = settings.name;\r\n if (typeof text === 'object') {\r\n text = text[options.language] || text.en;\r\n }\r\n } else\r\n if (item && item.common && item.common[attr]) {\r\n text = item.common[attr];\r\n if (attr !== 'desc' && !text && item.common.desc) {\r\n text = item.common.desc;\r\n }\r\n if (typeof text === 'object') {\r\n text = text[options.language] || text.en || text.de || text.ru || '';\r\n }\r\n text = (text || '').toString().replace(/[_.]/g, ' ');\r\n\r\n if (text === text.toUpperCase()) {\r\n text = text[0] + text.substring(1).toLowerCase();\r\n }\r\n } else {\r\n let pos = id.lastIndexOf('.');\r\n text = id.substring(pos + 1).replace(/[_.]/g, ' ');\r\n text = Utils.CapitalWords(text);\r\n }\r\n\r\n return text.trim();\r\n }\r\n\r\n /**\r\n * Get the name of the object from the name or description.\r\n * @param {ioBroker.PartialObject} obj\r\n * @param {{ name: any; } | ioBroker.Languages | null } settings or language\r\n * @param {{ language?: ioBroker.Languages; } } options\r\n * @param {boolean} [isDesc] Set to true to get the description.\r\n * @returns {string}\r\n */\r\n static getObjectNameFromObj(obj, settings, options, isDesc) {\r\n let item = obj;\r\n let text = (obj && obj._id) || '';\r\n const attr = isDesc ? 'desc' : 'name';\r\n\r\n if (typeof settings === 'string' && !options) {\r\n options = {language: settings};\r\n settings = null;\r\n }\r\n\r\n options = options || {};\r\n\r\n if (settings && settings.name) {\r\n text = settings.name;\r\n if (typeof text === 'object') {\r\n text = text[options.language] || text.en;\r\n }\r\n } else\r\n if (item && item.common && item.common[attr]) {\r\n text = item.common[attr];\r\n if (attr !== 'desc' && !text && item.common.desc) {\r\n text = item.common.desc;\r\n }\r\n if (typeof text === 'object') {\r\n text = text[options.language] || text.en;\r\n }\r\n text = (text || '').toString().replace(/[_.]/g, ' ');\r\n\r\n if (text === text.toUpperCase()) {\r\n text = text[0] + text.substring(1).toLowerCase();\r\n }\r\n }\r\n return text.trim();\r\n }\r\n\r\n /**\r\n * @param {ioBroker.PartialObject | ioBroker.ObjectCommon} obj\r\n * @param {string} forEnumId\r\n * @param {{ user: string; }} options\r\n * @returns {string | null}\r\n */\r\n static getSettingsOrder(obj, forEnumId, options) {\r\n if (obj && obj.hasOwnProperty('common')) {\r\n obj = obj.common;\r\n }\r\n let settings;\r\n if (obj && obj.custom) {\r\n settings = (obj.custom || {})[NAMESPACE];\r\n const user = options.user || 'admin';\r\n if (settings && settings[user]) {\r\n if (forEnumId) {\r\n if (settings[user].subOrder && settings[user].subOrder[forEnumId]) {\r\n return JSON.parse(JSON.stringify(settings[user].subOrder[forEnumId]));\r\n }\r\n } else {\r\n if (settings[user].order) {\r\n return JSON.parse(JSON.stringify(settings[user].order));\r\n }\r\n }\r\n }\r\n }\r\n return null;\r\n }\r\n\r\n /**\r\n * @param {ioBroker.PartialObject | ioBroker.ObjectCommon} obj\r\n * @param {string} forEnumId\r\n * @param {{ user: string; }} options\r\n */\r\n static getSettingsCustomURLs(obj, forEnumId, options) {\r\n if (obj && obj.hasOwnProperty('common')) {\r\n obj = obj.common;\r\n }\r\n let settings;\r\n if (obj && obj.custom) {\r\n settings = (obj.custom || {})[NAMESPACE];\r\n const user = options.user || 'admin';\r\n if (settings && settings[user]) {\r\n if (forEnumId) {\r\n if (settings[user].subURLs && settings[user].subURLs[forEnumId]) {\r\n return JSON.parse(JSON.stringify(settings[user].subURLs[forEnumId]));\r\n }\r\n } else {\r\n if (settings[user].URLs) {\r\n return JSON.parse(JSON.stringify(settings[user].URLs));\r\n }\r\n }\r\n }\r\n }\r\n return null;\r\n }\r\n\r\n /**\r\n * Reorder the array items in list between source and dest.\r\n * @param {Iterable | ArrayLike} list\r\n * @param {number} source\r\n * @param {number} dest\r\n */\r\n static reorder(list, source, dest) {\r\n const result = Array.from(list);\r\n const [removed] = result.splice(source, 1);\r\n result.splice(dest, 0, removed);\r\n return result;\r\n };\r\n\r\n /**\r\n * @param {any} obj\r\n * @param {{ id: any; user: any; name: any; icon: any; color: any; language: ioBroker.Languages; }} options\r\n * @param {boolean} [defaultEnabling]\r\n */\r\n static getSettings(obj, options, defaultEnabling) {\r\n let settings;\r\n const id = (obj && obj._id) || (options && options.id);\r\n if (obj && obj.hasOwnProperty('common')) {\r\n obj = obj.common;\r\n }\r\n if (obj && obj.custom) {\r\n settings = obj.custom || {};\r\n settings = settings[NAMESPACE] && settings[NAMESPACE][options.user || 'admin'] ? JSON.parse(JSON.stringify(settings[NAMESPACE][options.user || 'admin'])) : {enabled: true};\r\n } else {\r\n settings = {enabled: defaultEnabling === undefined ? true : defaultEnabling, useCustom: false};\r\n }\r\n\r\n if (!settings.hasOwnProperty('enabled')) {\r\n settings.enabled = defaultEnabling === undefined ? true : defaultEnabling;\r\n }\r\n\r\n if (false && settings.useCommon) {\r\n if (obj.color) settings.color = obj.color;\r\n if (obj.icon) settings.icon = obj.icon;\r\n if (obj.name) settings.name = obj.name;\r\n } else {\r\n if (options) {\r\n if (!settings.name && options.name) settings.name = options.name;\r\n if (!settings.icon && options.icon) settings.icon = options.icon;\r\n if (!settings.color && options.color) settings.color = options.color;\r\n }\r\n\r\n if (obj) {\r\n if (!settings.color && obj.color) settings.color = obj.color;\r\n if (!settings.icon && obj.icon) settings.icon = obj.icon;\r\n if (!settings.name && obj.name) settings.name = obj.name;\r\n }\r\n }\r\n\r\n if (typeof settings.name === 'object') {\r\n settings.name = settings.name[options.language] || settings.name.en;\r\n\r\n settings.name = (settings.name || '').toString().replace(/_/g, ' ');\r\n\r\n if (settings.name === settings.name.toUpperCase()) {\r\n settings.name = settings.name[0] + settings.name.substring(1).toLowerCase();\r\n }\r\n }\r\n if (!settings.name && id) {\r\n let pos = id.lastIndexOf('.');\r\n settings.name = id.substring(pos + 1).replace(/[_.]/g, ' ');\r\n settings.name = (settings.name || '').toString().replace(/_/g, ' ');\r\n settings.name = Utils.CapitalWords(settings.name);\r\n }\r\n\r\n return settings;\r\n }\r\n\r\n /**\r\n * @param {any} obj\r\n * @param {any} settings\r\n * @param {{ user: any; language: ioBroker.Languages; }} options\r\n */\r\n static setSettings(obj, settings, options) {\r\n if (obj) {\r\n obj.common = obj.common || {};\r\n obj.common.custom = obj.common.custom || {};\r\n obj.common.custom[NAMESPACE] = obj.common.custom[NAMESPACE] || {};\r\n obj.common.custom[NAMESPACE][options.user || 'admin'] = settings;\r\n const s = obj.common.custom[NAMESPACE][options.user || 'admin'];\r\n if (s.useCommon) {\r\n if (s.color !== undefined) {\r\n obj.common.color = s.color;\r\n delete s.color;\r\n }\r\n if (s.icon !== undefined) {\r\n obj.common.icon = s.icon;\r\n delete s.icon;\r\n }\r\n if (s.name !== undefined) {\r\n if (typeof obj.common.name !== 'object') {\r\n obj.common.name = {};\r\n obj.common.name[options.language] = s.name;\r\n } else{\r\n obj.common.name[options.language] = s.name;\r\n }\r\n delete s.name;\r\n }\r\n }\r\n\r\n return true;\r\n } else {\r\n return false;\r\n }\r\n }\r\n\r\n /**\r\n * Get the icon for the given settings.\r\n * @param {{ icon: string | undefined; name: string | undefined; prefix: string | undefined}} settings\r\n * @param {any} style\r\n * @returns {JSX.Element | null}\r\n */\r\n static getIcon(settings, style) {\r\n if (settings && settings.icon) {\r\n // If UTF-8 icon\r\n if (settings.icon.length <= 2) {\r\n return {settings.icon};\r\n } else\r\n if (settings.icon.startsWith('data:image')) {\r\n return {settings.name};\r\n } else { // may be later some changes for second type\r\n return {settings.name};\r\n }\r\n }\r\n return null;\r\n }\r\n\r\n /**\r\n * Get the icon for the given object.\r\n * @param {string} id\r\n * @param {{ common: { icon: any; }; }} obj\r\n * @returns {string | null}\r\n */\r\n static getObjectIcon(id, obj) {\r\n // If id is Object\r\n if (typeof id === 'object') {\r\n obj = id;\r\n id = obj._id;\r\n }\r\n\r\n if (obj && obj.common && obj.common.icon) {\r\n let icon = obj.common.icon;\r\n // If UTF-8 icon\r\n if (typeof icon === 'string' && icon.length <= 2) {\r\n return icon;\r\n } else\r\n if (icon.startsWith('data:image')) {\r\n return icon;\r\n } else {\r\n const parts = id.split('.');\r\n if (parts[0] === 'system') {\r\n icon = 'adapter/' + parts[2] + (icon.startsWith('/') ? '' : '/') + icon;\r\n } else {\r\n icon = 'adapter/' + parts[0] + (icon.startsWith('/') ? '' : '/') + icon;\r\n }\r\n\r\n if (window.location.pathname.match(/adapter\\/[^/]+\\/[^/]+\\.html/)) {\r\n icon = '../../' + icon;\r\n } else if (window.location.pathname.match(/material\\/[.\\d]+/)) {\r\n icon = '../../' + icon;\r\n } else\r\n if (window.location.pathname.match(/material\\//)) {\r\n icon = '../' + icon;\r\n }\r\n return icon;\r\n }\r\n } else {\r\n return null;\r\n }\r\n }\r\n\r\n /**\r\n * Splits CamelCase into words.\r\n * @param {string | undefined} text\r\n * @returns {string}\r\n */\r\n static splitCamelCase(text) {\r\n if (false && text !== text.toUpperCase()) {\r\n const words = text.split(/\\s+/);\r\n for (let i = 0; i < words.length; i++) {\r\n let word = words[i];\r\n if (word.toLowerCase() !== word && word.toUpperCase() !== word) {\r\n let z = 0;\r\n const ww = [];\r\n let start = 0;\r\n while (z < word.length) {\r\n if (word[z].match(/[A-ZÜÄÖА-Я]/)) {\r\n ww.push(word.substring(start, z));\r\n start = z;\r\n }\r\n z++;\r\n }\r\n if (start !== z) {\r\n ww.push(word.substring(start, z));\r\n }\r\n for (let k = 0; k < ww.length; k++) {\r\n words.splice(i + k, 0, ww[k]);\r\n }\r\n i += ww.length;\r\n }\r\n }\r\n\r\n return words.map(w => {\r\n w = w.trim();\r\n if (w) {\r\n return w[0].toUpperCase() + w.substring(1).toLowerCase();\r\n }\r\n return '';\r\n }).join(' ');\r\n } else {\r\n return Utils.CapitalWords(text);\r\n }\r\n }\r\n\r\n /**\r\n * Check if the given color is bright.\r\n * https://stackoverflow.com/questions/35969656/how-can-i-generate-the-opposite-color-according-to-current-color\r\n * @param {string | null | undefined} color\r\n * @param {boolean} [defaultValue]\r\n * @returns {boolean}\r\n */\r\n static isUseBright(color, defaultValue) {\r\n if (color === null || color === undefined || color === '') {\r\n return defaultValue === undefined ? true : defaultValue;\r\n }\r\n color = color.toString();\r\n if (color.indexOf('#') === 0) {\r\n color = color.slice(1);\r\n }\r\n let r;\r\n let g;\r\n let b;\r\n\r\n const rgb = color.match(/^rgba?[\\s+]?\\([\\s+]?(\\d+)[\\s+]?,[\\s+]?(\\d+)[\\s+]?,[\\s+]?(\\d+)[\\s+]?/i);\r\n if (rgb && rgb.length === 4) {\r\n r = parseInt(rgb[1], 10);\r\n g = parseInt(rgb[2], 10);\r\n b = parseInt(rgb[3], 10);\r\n } else {\r\n // convert 3-digit hex to 6-digits.\r\n if (color.length === 3) {\r\n color = color[0] + color[0] + color[1] + color[1] + color[2] + color[2];\r\n }\r\n if (color.length !== 6) {\r\n return false;\r\n }\r\n\r\n r = parseInt(color.slice(0, 2), 16);\r\n g = parseInt(color.slice(2, 4), 16);\r\n b = parseInt(color.slice(4, 6), 16);\r\n }\r\n\r\n // http://stackoverflow.com/a/3943023/112731\r\n return (r * 0.299 + g * 0.587 + b * 0.114) <= 186;\r\n };\r\n\r\n /**\r\n * Get the time string in the format 00:00.\r\n * @param {string | number} seconds\r\n */\r\n static getTimeString(seconds) {\r\n seconds = parseFloat(seconds);\r\n if (isNaN(seconds)) {\r\n return '--:--';\r\n }\r\n const hours = Math.floor(seconds / 3600);\r\n let minutes = Math.floor((seconds % 3600) / 60);\r\n let secs = seconds % 60;\r\n if (hours) {\r\n if (minutes < 10) minutes = '0' + minutes;\r\n if (secs < 10) secs = '0' + secs;\r\n return hours + ':' + minutes + ':' + secs;\r\n } else {\r\n if (secs < 10) secs = '0' + secs;\r\n return minutes + ':' + secs;\r\n }\r\n }\r\n\r\n /**\r\n * Gets the wind direction with the given angle (degrees).\r\n * @param {number} angle in degrees.\r\n * @returns {string | undefined}\r\n */\r\n static getWindDirection(angle) {\r\n if (angle >= 0 && angle < 11.25) {\r\n return 'N'\r\n } else if (angle >= 11.25 && angle < 33.75) {\r\n return 'NNE'\r\n } else if (angle >= 33.75 && angle < 56.25) {\r\n return 'NE'\r\n } else if (angle >= 56.25 && angle < 78.75) {\r\n return 'ENE'\r\n } else if (angle >= 78.75 && angle < 101.25) {\r\n return 'E'\r\n } else if (angle >= 101.25 && angle < 123.75) {\r\n return 'ESE'\r\n } else if (angle >= 123.75 && angle < 146.25) {\r\n return 'SE'\r\n } else if (angle >= 146.25 && angle < 168.75) {\r\n return 'SSE'\r\n } else if (angle >= 168.75 && angle < 191.25) {\r\n return 'S'\r\n } else if (angle >= 191.25 && angle < 213.75) {\r\n return 'SSW'\r\n } else if (angle >= 213.75 && angle < 236.25) {\r\n return 'SW'\r\n } else if (angle >= 236.25 && angle < 258.75) {\r\n return 'WSW'\r\n } else if (angle >= 258.75 && angle < 281.25) {\r\n return 'W'\r\n } else if (angle >= 281.25 && angle < 303.75) {\r\n return 'WNW'\r\n } else if (angle >= 303.75 && angle < 326.25) {\r\n return 'NW'\r\n } else if (angle >= 326.25 && angle < 348.75) {\r\n return 'NNW'\r\n } else if (angle >= 348.75) {\r\n return 'N'\r\n }\r\n }\r\n\r\n /**\r\n * Pad the given number with a zero if its not 2 digits long.\r\n * @param {string | number} num\r\n */\r\n static padding(num) {\r\n if (typeof num === 'string') {\r\n if (num.length < 2) {\r\n return '0' + num;\r\n } else {\r\n return num;\r\n }\r\n } else if (num < 10) {\r\n return '0' + num;\r\n } else {\r\n return num;\r\n }\r\n }\r\n\r\n /**\r\n * Sets the date format.\r\n * @param {string} format\r\n */\r\n static setDataFormat(format) {\r\n if (format) {\r\n Utils.dateFormat = format.toUpperCase().split(/[.-/]/);\r\n Utils.dateFormat.splice(Utils.dateFormat.indexOf('YYYY'), 1);\r\n }\r\n }\r\n\r\n /**\r\n * Converts the date to a string.\r\n * @param {string | number | Date} now\r\n * @returns {string}\r\n */\r\n static date2string(now) {\r\n if (typeof now === 'string') {\r\n now = now.trim();\r\n if (!now) return '';\r\n // only letters\r\n if (now.match(/^[\\w\\s]+$/)) {\r\n // Day of week\r\n return now;\r\n }\r\n let m = now.match(/(\\d{1,4})[-./](\\d{1,2})[-./](\\d{1,4})/);\r\n if (m) {\r\n let a = [parseInt(m[1], 10), parseInt(m[2], 10), parseInt(m[3], 10)];\r\n let year = a.find(y => y > 31);\r\n a.splice(a.indexOf(year), 1);\r\n let day = a.find(m => m > 12);\r\n if (day) {\r\n a.splice(a.indexOf(day), 1);\r\n now = new Date(year, a[0] - 1, day);\r\n } else {\r\n // MM DD\r\n if (Utils.dateFormat[0][0] === 'M' && Utils.dateFormat[1][0] === 'D') {\r\n now = new Date(year, a[0] - 1, a[1]);\r\n if (Math.abs(now.getTime - Date.now()) > 3600000 * 24 * 10) {\r\n now = new Date(year, a[1] - 1, a[0]);\r\n }\r\n } else\r\n // DD MM\r\n if (Utils.dateFormat[0][0] === 'D' && Utils.dateFormat[1][0] === 'M') {\r\n now = new Date(year, a[1] - 1, a[0]);\r\n if (Math.abs(now.getTime - Date.now()) > 3600000 * 24 * 10) {\r\n now = new Date(year, a[0] - 1, a[1]);\r\n }\r\n } else {\r\n now = new Date(now);\r\n }\r\n }\r\n } else {\r\n now = new Date(now);\r\n }\r\n } else {\r\n now = new Date(now);\r\n }\r\n\r\n let date = I18n.t('ra_dow_' + days[now.getDay()]).replace('ra_dow_', '');\r\n date += '. ' + now.getDate() + ' ' + I18n.t('ra_month_' + months[now.getMonth()]).replace('ra_month_', '');\r\n return date;\r\n }\r\n\r\n /**\r\n * Render a text as a link.\r\n * @param {string} text\r\n * @returns {string | JSX.Element[]}\r\n */\r\n static renderTextWithA(text) {\r\n let m = text.match(/|/);\r\n if (m) {\r\n const result = [];\r\n let key = 1;\r\n do {\r\n const p = text.split(m[0]);\r\n p[0] && result.push({p[0]});\r\n\r\n if (m[0].startsWith(');\r\n } else {\r\n let href = m[0].match(/href=\"([^\"]+)\"/) || m[0].match(/href='([^']+)'/);\r\n let target = m[0].match(/target=\"([^\"]+)\"/) || m[0].match(/target='([^']+)'/);\r\n let rel = m[0].match(/rel=\"([^\"]+)\"/) || m[0].match(/rel='([^']+)'/);\r\n const title = m[0].match(/>([^<]*){title ? title[1] : ''});\r\n }\r\n\r\n text = p[1];\r\n\r\n m = text && text.match(/|/);\r\n if (!m) {\r\n p[1] && result.push({p[1]});\r\n }\r\n } while (m);\r\n\r\n return result;\r\n } else {\r\n return text;\r\n }\r\n }\r\n\r\n /**\r\n * Get the smart name of the given state.\r\n * @param {Record | ioBroker.StateObject} states\r\n * @param {string} id\r\n * @param {string} instanceId\r\n * @param {boolean} [noCommon]\r\n */\r\n static getSmartName(states, id, instanceId, noCommon) {\r\n if (!id) {\r\n if (!noCommon) {\r\n if (!states.common) {\r\n return states.smartName;\r\n } else {\r\n if (states && !states.common) {\r\n return states.smartName;\r\n } else {\r\n return states.common.smartName;\r\n }\r\n }\r\n } else {\r\n if (states && !states.common) {\r\n return states.smartName;\r\n } else {\r\n return (states &&\r\n states.common &&\r\n states.common.custom &&\r\n states.common.custom[instanceId]) ?\r\n states.common.custom[instanceId].smartName : undefined;\r\n }\r\n }\r\n } else\r\n if (!noCommon) {\r\n return states[id].common.smartName;\r\n } else {\r\n return (states[id] &&\r\n states[id].common &&\r\n states[id].common.custom &&\r\n states[id].common.custom[instanceId]) ?\r\n states[id].common.custom[instanceId].smartName || null : null;\r\n }\r\n }\r\n\r\n /**\r\n * Get the smart name from a state.\r\n * @param {ioBroker.StateObject} obj\r\n * @param {string} instanceId\r\n * @param {boolean} [noCommon]\r\n */\r\n static getSmartNameFromObj(obj, instanceId, noCommon) {\r\n if (!noCommon) {\r\n if (!obj.common) {\r\n return obj.smartName;\r\n } else {\r\n if (obj && !obj.common) {\r\n return obj.smartName;\r\n } else {\r\n return obj.common.smartName;\r\n }\r\n }\r\n } else {\r\n if (obj && !obj.common) {\r\n return obj.smartName;\r\n } else {\r\n return (obj &&\r\n obj.common &&\r\n obj.common.custom &&\r\n obj.common.custom[instanceId]) ?\r\n obj.common.custom[instanceId].smartName : undefined;\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Enable smart name for a state.\r\n * @param {ioBroker.StateObject} obj\r\n * @param {string} instanceId\r\n * @param {boolean} [noCommon]\r\n */\r\n static enableSmartName(obj, instanceId, noCommon) {\r\n if (noCommon) {\r\n obj.common.custom = obj.common.custom || {};\r\n obj.common.custom[instanceId] = obj.common.custom[instanceId] || {};\r\n obj.common.custom[instanceId].smartName = {};\r\n } else {\r\n obj.common.smartName = {};\r\n }\r\n }\r\n\r\n /**\r\n * Completely remove smart name from a state.\r\n * @param {ioBroker.StateObject} obj\r\n * @param {string | number} instanceId\r\n * @param {boolean} [noCommon]\r\n */\r\n static removeSmartName(obj, instanceId, noCommon) {\r\n if (noCommon) {\r\n if (obj.common && obj.common.custom && obj.common.custom[instanceId]) {\r\n obj.common.custom[instanceId] = null;\r\n }\r\n } else {\r\n obj.common.smartName = null;\r\n }\r\n }\r\n\r\n /**\r\n * Update the smartname of a state.\r\n * @param {ioBroker.StateObject} obj\r\n * @param {string} newSmartName\r\n * @param {string | undefined} byON\r\n * @param {string | undefined} smartType\r\n * @param {string} instanceId\r\n * @param {boolean} [noCommon]\r\n */\r\n static updateSmartName(obj, newSmartName, byON, smartType, instanceId, noCommon) {\r\n const language = I18n.getLanguage();\r\n\r\n // convert Old format\r\n if (typeof obj.common.smartName === 'string') {\r\n const nnn = obj.common.smartName;\r\n obj.common.smartName = {};\r\n obj.common.smartName[language] = nnn;\r\n }\r\n\r\n // convert old settings\r\n if (obj.native && obj.native.byON) {\r\n delete obj.native.byON;\r\n let _smartName = obj.common.smartName;\r\n\r\n if (!_smartName || typeof _smartName !== 'object') {\r\n _smartName = {en: _smartName};\r\n _smartName[language] = _smartName.en;\r\n }\r\n obj.common.smartName = _smartName;\r\n }\r\n if (smartType !== undefined) {\r\n if (noCommon) {\r\n obj.common.custom = obj.common.custom || {};\r\n obj.common.custom[instanceId] = obj.common.custom[instanceId] || {};\r\n obj.common.custom[instanceId].smartName = obj.common.custom[instanceId].smartName || {};\r\n if (!smartType) {\r\n delete obj.common.custom[instanceId].smartName.smartType;\r\n } else {\r\n obj.common.custom[instanceId].smartName.smartType = smartType;\r\n }\r\n } else {\r\n obj.common.smartName = obj.common.smartName || {};\r\n if (!smartType) {\r\n delete obj.common.smartName.smartType;\r\n } else {\r\n obj.common.smartName.smartType = smartType;\r\n }\r\n\r\n }\r\n }\r\n if (byON !== undefined) {\r\n if (noCommon) {\r\n obj.common.custom = obj.common.custom || {};\r\n obj.common.custom[instanceId] = obj.common.custom[instanceId] || {};\r\n obj.common.custom[instanceId].smartName = obj.common.custom[instanceId].smartName || {};\r\n obj.common.custom[instanceId].smartName.byON = byON;\r\n } else {\r\n obj.common.smartName = obj.common.smartName || {};\r\n obj.common.smartName.byON = byON;\r\n }\r\n }\r\n if (newSmartName !== undefined) {\r\n let smartName;\r\n if (noCommon) {\r\n obj.common.custom = obj.common.custom || {};\r\n obj.common.custom[instanceId] = obj.common.custom[instanceId] || {};\r\n obj.common.custom[instanceId].smartName = obj.common.custom[instanceId].smartName || {};\r\n smartName = obj.common.custom[instanceId].smartName;\r\n } else {\r\n obj.common.smartName = obj.common.smartName || {};\r\n smartName = obj.common.smartName;\r\n }\r\n smartName[language] = newSmartName;\r\n\r\n // If smart name deleted\r\n if (smartName && (!smartName[language] ||\r\n (smartName[language] === obj.common.name &&\r\n (!obj.common.role || obj.common.role.indexOf('button') >= 0)))) {\r\n delete smartName[language];\r\n let empty = true;\r\n // Check if structure has any definitions\r\n for (const key in smartName) {\r\n if (smartName.hasOwnProperty(key)) {\r\n empty = false;\r\n break;\r\n }\r\n }\r\n // If empty => delete smartName completely\r\n if (empty) {\r\n if (noCommon) {\r\n if (obj.common.custom[instanceId].smartName.byON === undefined) {\r\n delete obj.common.custom[instanceId];\r\n } else {\r\n delete obj.common.custom[instanceId].en;\r\n delete obj.common.custom[instanceId].de;\r\n delete obj.common.custom[instanceId].ru;\r\n delete obj.common.custom[instanceId].nl;\r\n delete obj.common.custom[instanceId].pl;\r\n delete obj.common.custom[instanceId].it;\r\n delete obj.common.custom[instanceId].fr;\r\n delete obj.common.custom[instanceId].pt;\r\n delete obj.common.custom[instanceId].es;\r\n delete obj.common.custom[instanceId]['zh-cn'];\r\n }\r\n } else {\r\n if (obj.common.smartName.byON !== undefined) {\r\n delete obj.common.smartName.en;\r\n delete obj.common.smartName.de;\r\n delete obj.common.smartName.ru;\r\n delete obj.common.smartName.nl;\r\n delete obj.common.smartName.pl;\r\n delete obj.common.smartName.it;\r\n delete obj.common.smartName.fr;\r\n delete obj.common.smartName.pt;\r\n delete obj.common.smartName.es;\r\n delete obj.common.smartName['zh-cn'];\r\n } else {\r\n obj.common.smartName = null;\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Disable the smart name of a state.\r\n * @param {ioBroker.StateObject} obj\r\n * @param {string} instanceId\r\n * @param {boolean} [noCommon]\r\n */\r\n static disableSmartName(obj, instanceId, noCommon) {\r\n if (noCommon) {\r\n obj.common.custom = obj.common.custom || {};\r\n obj.common.custom[instanceId] = obj.common.custom[instanceId] || {};\r\n obj.common.custom[instanceId].smartName = false;\r\n } else {\r\n obj.common.smartName = false;\r\n }\r\n }\r\n\r\n /**\r\n * Copy text to the clipboard.\r\n * @param {string} text\r\n * @param {Event} [e]\r\n */\r\n static copyToClipboard(text, e) {\r\n const el = window.document.createElement('textarea');\r\n el.value = text;\r\n window.document.body.appendChild(el);\r\n el.select();\r\n window.document.execCommand('copy');\r\n window.document.body.removeChild(el);\r\n console.log(text);\r\n e && e.stopPropagation();\r\n e && e.preventDefault();\r\n }\r\n\r\n /**\r\n * Gets the extension of a file name.\r\n * @param {string | null} [fileName] the file name.\r\n * @returns {string | null} The extension in lower case.\r\n */\r\n static getFileExtension(fileName) {\r\n const pos = (fileName || '').lastIndexOf('.');\r\n if (pos !== -1) {\r\n return fileName.substring(pos + 1).toLowerCase();\r\n } else {\r\n return null;\r\n }\r\n }\r\n\r\n /**\r\n * Format number of bytes as a string with B, KB, MB or GB.\r\n * The base for all calculations is 1024.\r\n * @param {number} bytes The number of bytes.\r\n * @returns {string} The formatted string (e.g. '723.5 KB')\r\n */\r\n static formatBytes(bytes) {\r\n if (Math.abs(bytes) < 1024) {\r\n return bytes + ' B';\r\n }\r\n\r\n const units = ['KB','MB','GB'];\r\n //const units = ['KiB','MiB','GiB','TiB','PiB','EiB','ZiB','YiB'];\r\n let u = -1;\r\n\r\n do {\r\n bytes /= 1024;\r\n ++u;\r\n } while (Math.abs(bytes) >= 1024 && u < units.length - 1);\r\n\r\n return bytes.toFixed(1) + ' ' + units[u];\r\n }\r\n\r\n /**\r\n * Invert the given color according to theme type to get the inverted text color for background\r\n * @param {string} color Color in the format '#rrggbb' or '#rgb' (or without hash)\r\n * @param {string} themeType theme type\r\n * @param {string} invert dark theme has light color in control or light theme has light color in control\r\n * @returns {string}\r\n */\r\n static getInvertedColor(color, themeType, invert) {\r\n if (!color) {\r\n return undefined;\r\n } else {\r\n const invertedColor = Utils.invertColor(color, true);\r\n if (invertedColor === '#FFFFFF' && (themeType === 'dark' || (invert && themeType === 'light'))) {\r\n return '#DDD';\r\n } else\r\n if (invertedColor === '#000000' && (themeType === 'light' || (invert && themeType === 'dark'))) {\r\n return '#222';\r\n } else {\r\n return undefined;\r\n }\r\n }\r\n }\r\n\r\n // Big thanks to: https://stackoverflow.com/questions/35969656/how-can-i-generate-the-opposite-color-according-to-current-color\r\n /**\r\n * Invert the given color\r\n * @param {string} hex Color in the format '#rrggbb' or '#rgb' (or without hash)\r\n * @param {boolean} bw Set to black or white.\r\n * @returns {string}\r\n */\r\n static invertColor(hex, bw) {\r\n if (hex === undefined || hex === null || hex === '' || typeof hex !== 'string') {\r\n return '';\r\n }\r\n if (hex.startsWith('rgba')) {\r\n const m = hex.match(/rgba?\\((\\d+),\\s*(\\d+),\\s*(\\d+),\\s*([.\\d]+)\\)/);\r\n if (m) {\r\n hex = parseInt(m[1], 10).toString(16).padStart(2, '0') +\r\n parseInt(m[2], 10).toString(16).padStart(2, '0') +\r\n parseInt(m[2], 10).toString(16).padStart(2, '0');\r\n }\r\n } else if (hex.startsWith('rgba')) {\r\n const m = hex.match(/rgb?\\((\\d+),\\s*(\\d+),\\s*(\\d+)\\)/);\r\n if (m) {\r\n hex = parseInt(m[1], 10).toString(16).padStart(2, '0') +\r\n parseInt(m[2], 10).toString(16).padStart(2, '0') +\r\n parseInt(m[2], 10).toString(16).padStart(2, '0');\r\n }\r\n } else\r\n if (hex.startsWith('#')) {\r\n hex = hex.slice(1);\r\n }\r\n // convert 3-digit hex to 6-digits.\r\n if (hex.length === 3) {\r\n hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2];\r\n }\r\n if (hex.length !== 6) {\r\n console.warn('Cannot invert color: ' + hex);\r\n return hex;\r\n }\r\n let r = parseInt(hex.slice(0, 2), 16);\r\n let g = parseInt(hex.slice(2, 4), 16);\r\n let b = parseInt(hex.slice(4, 6), 16);\r\n\r\n if (bw) {\r\n // http://stackoverflow.com/a/3943023/112731\r\n return (r * 0.299 + g * 0.587 + b * 0.114) > 186\r\n ? '#000000'\r\n : '#FFFFFF';\r\n }\r\n // invert color components\r\n r = (255 - r).toString(16);\r\n g = (255 - g).toString(16);\r\n b = (255 - b).toString(16);\r\n // pad each with zeros and return\r\n return '#' + r.padStart(2, '0') + g.padStart(2, '0') + b.padStart(2, '0');\r\n }\r\n\r\n // https://github.com/lukeed/clsx/blob/master/src/index.js\r\n // License\r\n // MIT © Luke Edwards\r\n /**\r\n * @private\r\n * @param {any} mix\r\n * @returns {string}\r\n */\r\n static _toVal(mix) {\r\n let k, y, str='';\r\n\r\n if (typeof mix === 'string' || typeof mix === 'number') {\r\n str += mix;\r\n } else if (typeof mix === 'object') {\r\n if (Array.isArray(mix)) {\r\n for (k=0; k < mix.length; k++) {\r\n if (mix[k]) {\r\n if ((y = Utils._toVal(mix[k]))) {\r\n str && (str += ' ');\r\n str += y;\r\n }\r\n }\r\n }\r\n } else {\r\n for (k in mix) {\r\n if (mix[k]) {\r\n str && (str += ' ');\r\n str += k;\r\n }\r\n }\r\n }\r\n }\r\n\r\n return str;\r\n }\r\n\r\n // https://github.com/lukeed/clsx/blob/master/src/index.js\r\n // License\r\n // MIT © Luke Edwards\r\n /**\r\n * Convert any object to a string with its values.\r\n * @returns {string}\r\n */\r\n static clsx () {\r\n let i = 0;\r\n let tmp;\r\n let x;\r\n let str = '';\r\n while (i < arguments.length) {\r\n if ((tmp = arguments[i++])) {\r\n if ((x = Utils._toVal(tmp))) {\r\n str && (str += ' ');\r\n str += x\r\n }\r\n }\r\n }\r\n return str;\r\n }\r\n\r\n /**\r\n * Get the current theme name (either from local storage or the browser settings).\r\n * @param {string} [themeName]\r\n * @returns {string}\r\n */\r\n static getThemeName(themeName = '') {\r\n if (window.vendorPrefix && window.vendorPrefix !== '@@vendorPrefix@@') {\r\n return window.vendorPrefix;\r\n }\r\n\r\n return themeName ? themeName : window.localStorage && window.localStorage.getItem('App.themeName') ?\r\n window.localStorage.getItem('App.themeName') : window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'colored';\r\n }\r\n\r\n /**\r\n * Get the type of theme.\r\n * @param {string} [themeName]\r\n * @returns {'dark' | 'light'}\r\n */\r\n static getThemeType(themeName = '') {\r\n if (window.vendorPrefix && window.vendorPrefix !== '@@vendorPrefix@@') {\r\n return 'light';\r\n }\r\n\r\n themeName = themeName || (window.localStorage && window.localStorage.getItem('App.themeName'));\r\n return themeName === 'dark' || themeName === 'blue' ? 'dark' : 'light';\r\n }\r\n\r\n /**\r\n * Set the theme name and theme type.\r\n * @param {string} themeName\r\n */\r\n static setThemeName(themeName) {\r\n if (window.vendorPrefix && window.vendorPrefix !== '@@vendorPrefix@@') {\r\n return; // ignore\r\n }\r\n window.localStorage.setItem('App.themeName', themeName);\r\n window.localStorage.setItem('App.theme', themeName === 'dark' || themeName === 'blue' ? 'dark' : 'light');\r\n }\r\n\r\n /**\r\n * Toggle the theme name between 'dark' and 'colored'.\r\n * @param {string | null} themeName\r\n * @returns {string} the new theme name.\r\n */\r\n static toggleTheme(themeName) {\r\n if (window.vendorPrefix && window.vendorPrefix !== '@@vendorPrefix@@') {\r\n return window.vendorPrefix;\r\n }\r\n themeName = themeName || (window.localStorage && window.localStorage.getItem('App.themeName'));\r\n\r\n // dark => blue => colored => light => dark\r\n const themes = Utils.getThemeNames();\r\n const pos = themes.indexOf(themeName);\r\n let newTheme;\r\n if (pos !== -1) {\r\n newTheme = themes[(pos + 1) % themes.length];\r\n } else {\r\n newTheme = themes[0];\r\n }\r\n Utils.setThemeName(newTheme);\r\n\r\n return newTheme;\r\n }\r\n\r\n /**\r\n * Get the list of themes\r\n * @returns {array} list of possible themes\r\n */\r\n static getThemeNames() {\r\n if (window.vendorPrefix && window.vendorPrefix !== '@@vendorPrefix@@') {\r\n return [window.vendorPrefix];\r\n }\r\n\r\n return ['light', 'dark', 'blue', 'colored'];\r\n }\r\n\r\n /**\r\n * Parse a query string into its parts.\r\n * @param {string} query\r\n * @returns {Record}\r\n */\r\n static parseQuery(query) {\r\n query = (query || '').toString().replace(/^\\?/, '');\r\n /** @type {Record} */\r\n const result = {};\r\n query.split('&').forEach(part => {\r\n part = part.trim();\r\n if (part) {\r\n const parts = part.split('=');\r\n const attr = decodeURIComponent(parts[0]).trim();\r\n if (parts.length > 1) {\r\n result[attr] = decodeURIComponent(parts[1]);\r\n if (result[attr] === 'true') {\r\n result[attr] = true;\r\n } else if (result[attr] === 'false') {\r\n result[attr] = false;\r\n } else {\r\n const f = parseFloat(result[attr]);\r\n if (f.toString() === result[attr]) {\r\n result[attr] = f;\r\n }\r\n }\r\n } else {\r\n result[attr] = true;\r\n }\r\n }\r\n });\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns parent ID.\r\n * @param {string} id\r\n * @returns {string | null} parent ID or null if no parent\r\n */\r\n static getParentId(id) {\r\n const p = (id || '').toString().split('.');\r\n if (p.length > 1) {\r\n p.pop();\r\n return p.join('.');\r\n } else {\r\n return null;\r\n }\r\n }\r\n\r\n static formatDate(dateObj, dateFormat) {\r\n // format could be DD.MM.YYYY, YYYY.MM.DD or MM/DD/YYYY\r\n\r\n if (!dateObj) {\r\n return '';\r\n }\r\n\r\n let text;\r\n let mm = dateObj.getMonth() + 1;\r\n if (mm < 10) {\r\n mm = '0' + mm;\r\n }\r\n\r\n let dd = dateObj.getDate();\r\n if (dd < 10) {\r\n dd = '0' + dd;\r\n }\r\n\r\n if (dateFormat === 'MM/DD/YYYY') {\r\n text = mm + '/' + dd + '/' + dateObj.getFullYear();\r\n } else {\r\n text = dateObj.getFullYear() + '-' + mm + '-' + dd;\r\n }\r\n\r\n // time\r\n let v = dateObj.getHours();\r\n if (v < 10) {\r\n text += ' 0' + v;\r\n } else {\r\n text += ' ' + v;\r\n }\r\n v = dateObj.getMinutes();\r\n if (v < 10) {\r\n text += ':0' + v;\r\n } else {\r\n text += ':' + v;\r\n }\r\n\r\n v = dateObj.getSeconds();\r\n if (v < 10) {\r\n text += ':0' + v;\r\n } else {\r\n text += ':' + v;\r\n }\r\n\r\n v = dateObj.getMilliseconds();\r\n if (v < 10) {\r\n text += '.00' + v;\r\n } else if (v < 100) {\r\n text += '.0' + v;\r\n } else {\r\n text += '.' + v;\r\n }\r\n\r\n return text;\r\n }\r\n\r\n static formatTime(seconds) {\r\n if (seconds) {\r\n seconds = Math.round(seconds);\r\n const d = Math.floor(seconds / (3600 * 24));\r\n const h = Math.floor((seconds % (3600 * 24)) / 3600);\r\n const m = Math.floor((seconds % 3600) / 60);\r\n const s = seconds % 60;\r\n if (d) {\r\n return `${d}.${h.toString().padStart(2, '0')}:${m.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}`;\r\n } else if (h) {\r\n return `${h}:${m.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}`;\r\n } else {\r\n return `0:${m.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}`;\r\n }\r\n } else {\r\n return '0:00:00';\r\n }\r\n }\r\n\r\n static MDtext2link(text) {\r\n const m = text.match(/\\d+\\.\\)\\s/);\r\n if (m) {\r\n text = text.replace(m[0], m[0].replace(/\\s/, ' '));\r\n }\r\n\r\n return text.replace(/[^a-zA-Zа-яА-Я0-9]/g, '').trim().replace(/\\s/g, '').toLowerCase();\r\n }\r\n\r\n static openLink(url, target) {\r\n // replace IPv6 Address with [ipv6]:port\r\n url = url.replace(/\\/\\/([0-9a-f]*:[0-9a-f]*:[0-9a-f]*:[0-9a-f]*:[0-9a-f]*:[0-9a-f]*)(:\\d+)?\\//i, '//[$1]$2/');\r\n\r\n if (target === 'this') {\r\n window.location = url;\r\n } else {\r\n window.open(url, target || '_blank');\r\n }\r\n }\r\n\r\n static MDgetTitle(text) {\r\n let {body, header} = Utils.extractHeader(text);\r\n if (!header.title) {\r\n // remove {docsify-bla}\r\n body = body.replace(/{[^}]*}/g, '');\r\n body = body.trim();\r\n const lines = body.replace(/\\r/g, '').split('\\n');\r\n for (let i = 0; i < lines.length; i++) {\r\n if (lines[i].startsWith('# ')) {\r\n return lines[i].substring(2).trim();\r\n }\r\n }\r\n return '';\r\n } else {\r\n return header.title;\r\n }\r\n }\r\n\r\n static MDextractHeader(text) {\r\n const attrs = {};\r\n if (text.substring(0, 3) === '---') {\r\n const pos = text.substring(3).indexOf('\\n---');\r\n if (pos !== -1) {\r\n const _header = text.substring(3, pos + 3);\r\n const lines = _header.replace(/\\r/g, '').split('\\n');\r\n lines.forEach(line => {\r\n if (!line.trim()) {\r\n return;\r\n }\r\n const pos = line.indexOf(':');\r\n if (pos !== -1) {\r\n const attr = line.substring(0, pos).trim();\r\n attrs[attr] = line.substring(pos + 1).trim();\r\n attrs[attr] = attrs[attr].replace(/^['\"]|['\"]$/g, '');\r\n if (attrs[attr] === 'true') {\r\n attrs[attr] = true;\r\n } else if (attrs[attr] === 'false') {\r\n attrs[attr] = false;\r\n } else if (parseFloat(attrs[attr]).toString() === attrs[attr]) {\r\n attrs[attr] = parseFloat(attrs[attr]);\r\n }\r\n } else {\r\n attrs[line.trim()] = true;\r\n }\r\n });\r\n text = text.substring(pos + 7);\r\n }\r\n }\r\n return {header: attrs, body: text};\r\n }\r\n\r\n static MDremoveDocsify(text) {\r\n const m = text.match(/{docsify-[^}]*}/g);\r\n if (m) {\r\n m.forEach(doc => text = text.replace(doc, ''));\r\n }\r\n return text;\r\n }\r\n\r\n /**\r\n * Generate the json file on the file for download.\r\n * @param {string} filename file name\r\n * @returns {object} json structure (not stringified)\r\n */\r\n static generateFile(filename, json) {\r\n let el = document.createElement('a');\r\n el.setAttribute('href', 'data:application/json;charset=utf-8,' + encodeURIComponent(JSON.stringify(json, null, 2)));\r\n el.setAttribute('download', filename);\r\n\r\n el.style.display = 'none';\r\n document.body.appendChild(el);\r\n\r\n el.click();\r\n\r\n document.body.removeChild(el);\r\n }\r\n\r\n /**\r\n * Convert quality code into text\r\n * @param {number} quality code\r\n * @returns {array} lines that decode qulity\r\n */\r\n static quality2text(quality) {\r\n const custom = quality & 0xFFFF0000;\r\n const text = QUALITY_BITS[quality];\r\n let result;\r\n if (text) {\r\n result = [text];\r\n } else if (quality & 0x01) {\r\n result = [QUALITY_BITS[0x01], '0x' + (quality & (0xFFFF & ~1)).toString(16)];\r\n } else if (quality & 0x02) {\r\n result = [QUALITY_BITS[0x02], '0x' + (quality & (0xFFFF & ~2)).toString(16)];\r\n } else {\r\n result = ['0x' + quality.toString(16)];\r\n }\r\n if (custom) {\r\n result.push('0x' + (custom >> 16).toString(16).toUpperCase());\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Deep copy object\r\n * @param {object} object\r\n * @returns {object}\r\n */\r\n static clone(object) {\r\n return JSON.parse(JSON.stringify(object));\r\n }\r\n\r\n /**\r\n * Get states of object\r\n * @param {object} obj\r\n * @returns {object} states as an object in form {\"value1\": \"label1\", \"value2\": \"label2\"} or null\r\n */\r\n static getStates(obj) {\r\n let states = obj?.common?.states;\r\n if (states) {\r\n if (typeof states === 'string' && states[0] === '{') {\r\n try {\r\n states = JSON.parse(states);\r\n } catch (ex) {\r\n console.error(`Cannot parse states: ${states}`);\r\n states = null;\r\n }\r\n } else\r\n // if old format val1:text1;val2:text2\r\n if (typeof states === 'string') {\r\n const parts = states.split(';');\r\n states = {};\r\n for (let p = 0; p < parts.length; p++) {\r\n const s = parts[p].split(':');\r\n states[s[0]] = s[1];\r\n }\r\n } else if (Array.isArray(states)) {\r\n const result = {};\r\n states.forEach((value, key) => result[key] = value);\r\n return result;\r\n }\r\n }\r\n return states;\r\n }\r\n\r\n /**\r\n * Get svg file as text\r\n * @param {string} url URL of SVG file\r\n * @returns {object} Promise with \"data:image...\"\r\n */\r\n static getSvg(url) {\r\n return fetch(url)\r\n .then(response => response.blob())\r\n .then(blob => {\r\n return new Promise(resolve => {\r\n const reader = new FileReader();\r\n reader.onload = function() { // do not optimize this function. \"this\" is important.\r\n resolve(this.result);\r\n };\r\n reader.readAsDataURL(blob);\r\n });\r\n });\r\n }\r\n}\r\n\r\nexport default Utils;\r\n", "function _getPrototypeOf(t) {\n return module.exports = _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) {\n return t.__proto__ || Object.getPrototypeOf(t);\n }, module.exports.__esModule = true, module.exports[\"default\"] = module.exports, _getPrototypeOf(t);\n}\nmodule.exports = _getPrototypeOf, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;", "var getPrototypeOf = require(\"./getPrototypeOf.js\");\nfunction _superPropBase(t, o) {\n for (; !{}.hasOwnProperty.call(t, o) && null !== (t = getPrototypeOf(t)););\n return t;\n}\nmodule.exports = _superPropBase, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;", "var superPropBase = require(\"./superPropBase.js\");\nfunction _get() {\n return module.exports = _get = \"undefined\" != typeof Reflect && Reflect.get ? Reflect.get.bind() : function (e, t, r) {\n var p = superPropBase(e, t);\n if (p) {\n var n = Object.getOwnPropertyDescriptor(p, t);\n return n.get ? n.get.call(arguments.length < 3 ? e : r) : n.value;\n }\n }, module.exports.__esModule = true, module.exports[\"default\"] = module.exports, _get.apply(null, arguments);\n}\nmodule.exports = _get, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;", "var setPrototypeOf = require(\"./setPrototypeOf.js\");\nfunction _inherits(t, e) {\n if (\"function\" != typeof e && null !== e) throw new TypeError(\"Super expression must either be null or a function\");\n t.prototype = Object.create(e && e.prototype, {\n constructor: {\n value: t,\n writable: !0,\n configurable: !0\n }\n }), Object.defineProperty(t, \"prototype\", {\n writable: !1\n }), e && setPrototypeOf(t, e);\n}\nmodule.exports = _inherits, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;", "var _typeof = require(\"./typeof.js\")[\"default\"];\nvar assertThisInitialized = require(\"./assertThisInitialized.js\");\nfunction _possibleConstructorReturn(t, e) {\n if (e && (\"object\" == _typeof(e) || \"function\" == typeof e)) return e;\n if (void 0 !== e) throw new TypeError(\"Derived constructors may only return object or undefined\");\n return assertThisInitialized(t);\n}\nmodule.exports = _possibleConstructorReturn, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;", "/**\r\n * Copyright 2020-2022, bluefox \r\n *\r\n * MIT License\r\n *\r\n **/\r\nimport PropTypes from 'prop-types';\r\n\r\n/** Possible progress states. */\r\nexport const PROGRESS = {\r\n /** The socket is connecting. */\r\n CONNECTING: 0,\r\n /** The socket is successfully connected. */\r\n CONNECTED: 1,\r\n /** All objects are loaded. */\r\n OBJECTS_LOADED: 2,\r\n /** The socket is ready for use. */\r\n READY: 3\r\n};\r\n\r\nconst PERMISSION_ERROR = 'permissionError';\r\nconst NOT_CONNECTED = 'notConnectedError';\r\nconst TIMEOUT_FOR_ADMIN4 = 1300;\r\n\r\nexport const ERRORS = {\r\n PERMISSION_ERROR,\r\n NOT_CONNECTED\r\n};\r\n\r\nfunction fixAdminUI(obj) {\r\n if (obj && obj.common && !obj.common.adminUI) {\r\n if (obj.common.noConfig) {\r\n obj.common.adminUI = obj.common.adminUI || {};\r\n obj.common.adminUI.config = 'none';\r\n } else if (obj.common.jsonConfig) {\r\n obj.common.adminUI = obj.common.adminUI || {};\r\n obj.common.adminUI.config = 'json';\r\n } else if (obj.common.materialize) {\r\n obj.common.adminUI = obj.common.adminUI || {};\r\n obj.common.adminUI.config = 'materialize';\r\n } else {\r\n obj.common.adminUI = obj.common.adminUI || {};\r\n obj.common.adminUI.config = 'html';\r\n }\r\n\r\n if (obj.common.jsonCustom) {\r\n obj.common.adminUI = obj.common.adminUI || {};\r\n obj.common.adminUI.custom = 'json';\r\n } else if (obj.common.supportCustoms) {\r\n obj.common.adminUI = obj.common.adminUI || {};\r\n obj.common.adminUI.custom = 'json';\r\n }\r\n\r\n if (obj.common.materializeTab && obj.common.adminTab) {\r\n obj.common.adminUI = obj.common.adminUI || {};\r\n obj.common.adminUI.tab = 'materialize';\r\n } else if (obj.common.adminTab) {\r\n obj.common.adminUI = obj.common.adminUI || {};\r\n obj.common.adminUI.tab = 'html';\r\n }\r\n\r\n obj.common.adminUI && console.debug(`Please add to \"${obj._id.replace(/\\.\\d+$/, '')}\" common.adminUI=${JSON.stringify(obj.common.adminUI)}`);\r\n }\r\n return obj;\r\n}\r\n\r\nclass Connection {\r\n /**\r\n * @param {import('./types').ConnectionProps} props\r\n */\r\n constructor(props) {\r\n props = props || { protocol: window.location.protocol, host: window.location.hostname };\r\n this.props = props;\r\n\r\n this.autoSubscribes = this.props.autoSubscribes || [];\r\n this.autoSubscribeLog = this.props.autoSubscribeLog;\r\n\r\n this.props.protocol = this.props.protocol || window.location.protocol;\r\n this.props.host = this.props.host || window.location.hostname;\r\n this.props.port = this.props.port || (window.location.port === '3000' ? (Connection.isWeb() ? 8082 : 8081) : window.location.port);\r\n this.props.ioTimeout = Math.max(this.props.ioTimeout || 20000, 20000);\r\n this.props.cmdTimeout = Math.max(this.props.cmdTimeout || 5000, 5000);\r\n\r\n // breaking change. Do not load all objects by default is true\r\n this.doNotLoadAllObjects = this.props.doNotLoadAllObjects === undefined ? true : this.props.doNotLoadAllObjects;\r\n this.doNotLoadACL = this.props.doNotLoadACL === undefined ? true : this.props.doNotLoadACL;\r\n\r\n /** @type {Record} */\r\n this.states = {};\r\n this.objects = null;\r\n this.acl = null;\r\n this.firstConnect = true;\r\n this.waitForRestart = false;\r\n /** @type {ioBroker.Languages} */\r\n this.systemLang = 'en';\r\n this.connected = false;\r\n this._waitForFirstConnection = new Promise(resolve => { this._waitForFirstConnectionResolve = resolve });\r\n\r\n /** @type {Record} */\r\n this.statesSubscribes = {}; // subscribe for states\r\n\r\n /** @type {Record} */\r\n this.objectsSubscribes = {}; // subscribe for objects\r\n this.onProgress = this.props.onProgress || function () { };\r\n this.onError = this.props.onError || function (err) { console.error(err); };\r\n this.loaded = false;\r\n this.loadTimer = null;\r\n this.loadCounter = 0;\r\n this.admin5only = this.props.admin5only || false;\r\n\r\n /** @type {((connected: boolean) => void)[]} */\r\n this.onConnectionHandlers = [];\r\n /** @type {((message: string) => void)[]} */\r\n this.onLogHandlers = [];\r\n\r\n /** @type {Record>} */\r\n this._promises = {};\r\n\r\n this.log.error = text => this.log(text, 'error');\r\n this.log.warn = text => this.log(text, 'warn');\r\n this.log.info = text => this.log(text, 'info');\r\n this.log.debug = text => this.log(text, 'debug');\r\n this.log.silly = text => this.log(text, 'silly');\r\n\r\n this.startSocket();\r\n }\r\n\r\n /**\r\n * Checks if this connection is running in a web adapter and not in an admin.\r\n * @returns {boolean} True if running in a web adapter or in a socketio adapter.\r\n */\r\n static isWeb() {\r\n return window.adapterName === 'material' ||\r\n window.adapterName === 'vis' ||\r\n window.adapterName === 'echarts-show' ||\r\n window.socketUrl !== undefined;\r\n }\r\n\r\n /**\r\n * Starts the socket.io connection.\r\n * @returns {void}\r\n */\r\n startSocket() {\r\n // if socket io is not yet loaded\r\n if (typeof window.io === 'undefined') {\r\n // if in index.html the onLoad function not defined\r\n if (typeof window.registerSocketOnLoad !== 'function') {\r\n // poll if loaded\r\n this.scriptLoadCounter = this.scriptLoadCounter || 0;\r\n this.scriptLoadCounter++;\r\n\r\n if (this.scriptLoadCounter < 30) {\r\n // wait till the script loaded\r\n setTimeout(() => this.startSocket(), 100);\r\n return;\r\n } else {\r\n window.alert('Cannot load socket.io.js!');\r\n }\r\n } else {\r\n // register on load\r\n window.registerSocketOnLoad(() => this.startSocket());\r\n }\r\n return;\r\n } else {\r\n // socket was initialized, do not repeat\r\n if (this._socket) {\r\n return;\r\n }\r\n }\r\n\r\n let host = this.props.host;\r\n let port = this.props.port;\r\n let protocol = this.props.protocol.replace(':', '');\r\n let path = window.location.pathname;\r\n\r\n if (\r\n window.location.hostname === 'iobroker.net' ||\r\n window.location.hostname === 'iobroker.pro'\r\n ) {\r\n path = '';\r\n } else {\r\n // if web adapter, socket io could be on other port or even host\r\n if (window.socketUrl) {\r\n let parts = window.socketUrl.split(':');\r\n host = parts[0] || host;\r\n port = parts[1] || port;\r\n if (host.includes('://')) {\r\n parts = host.split('://');\r\n protocol = parts[0];\r\n host = parts[1];\r\n }\r\n }\r\n // get current path\r\n const pos = path.lastIndexOf('/');\r\n if (pos !== -1) {\r\n path = path.substring(0, pos + 1);\r\n }\r\n\r\n if (Connection.isWeb()) {\r\n // remove one level, like echarts, vis, .... We have here: '/echarts/'\r\n const parts = path.split('/');\r\n if (parts.length > 2) {\r\n parts.pop();\r\n parts.pop();\r\n path = parts.join('/');\r\n if (!path.endsWith('/')) {\r\n path += '/';\r\n }\r\n }\r\n }\r\n }\r\n\r\n const url = port ? `${protocol}://${host}:${port}${path}` : `${protocol}://${host}${path}`;\r\n\r\n this._socket = window.io.connect(\r\n url,\r\n {\r\n path: path.endsWith('/') ? path + 'socket.io' : path + '/socket.io',\r\n query: 'ws=true',\r\n name: this.props.name,\r\n timeout: this.props.ioTimeout\r\n }\r\n );\r\n\r\n this._socket.on('connect', noTimeout => {\r\n // If the user is not admin it takes some time to install the handlers, because all rights must be checked\r\n if (noTimeout !== true) {\r\n setTimeout(() =>\r\n this.getVersion()\r\n .then(info => {\r\n const [major, minor, patch] = info.version.split('.');\r\n const v = parseInt(major, 10) * 10000 + parseInt(minor, 10) * 100 + parseInt(patch, 10);\r\n if (v < 40102) {\r\n this._authTimer = null;\r\n // possible this is old version of admin\r\n this.onPreConnect(false, false);\r\n } else {\r\n this._socket.emit('authenticate', (isOk, isSecure) => this.onPreConnect(isOk, isSecure));\r\n }\r\n }), 500);\r\n } else {\r\n // iobroker websocket waits, till all handlers are installed\r\n this._socket.emit('authenticate', (isOk, isSecure) => this.onPreConnect(isOk, isSecure));\r\n }\r\n });\r\n\r\n this._socket.on('reconnect', () => {\r\n this.onProgress(PROGRESS.READY);\r\n this.connected = true;\r\n\r\n if (this.waitForRestart) {\r\n window.location.reload(false);\r\n } else {\r\n this._subscribe(true);\r\n this.onConnectionHandlers.forEach(cb => cb(true));\r\n }\r\n });\r\n\r\n this._socket.on('disconnect', () => {\r\n this.connected = false;\r\n this.subscribed = false;\r\n this.onProgress(PROGRESS.CONNECTING);\r\n this.onConnectionHandlers.forEach(cb => cb(false));\r\n });\r\n\r\n this._socket.on('reauthenticate', () =>\r\n this.authenticate());\r\n\r\n this._socket.on('log', message => {\r\n this.props.onLog && this.props.onLog(message);\r\n this.onLogHandlers.forEach(cb => cb(message));\r\n });\r\n\r\n this._socket.on('error', err => {\r\n let _err = err || '';\r\n if (typeof _err.toString !== 'function') {\r\n _err = JSON.stringify(_err);\r\n console.error(`Received strange error: ${_err}`);\r\n }\r\n _err = _err.toString();\r\n if (_err.includes('User not authorized')) {\r\n this.authenticate();\r\n } else {\r\n window.alert(`Socket Error: ${err}`);\r\n }\r\n });\r\n\r\n this._socket.on('connect_error', err =>\r\n console.error(`Connect error: ${err}`));\r\n\r\n this._socket.on('permissionError', err =>\r\n this.onError({ message: 'no permission', operation: err.operation, type: err.type, id: (err.id || '') }));\r\n\r\n this._socket.on('objectChange', (id, obj) =>\r\n setTimeout(() => this.objectChange(id, obj), 0));\r\n\r\n this._socket.on('stateChange', (id, state) =>\r\n setTimeout(() => this.stateChange(id, state), 0));\r\n\r\n this._socket.on('cmdStdout', (id, text) =>\r\n this.onCmdStdoutHandler && this.onCmdStdoutHandler(id, text));\r\n\r\n this._socket.on('cmdStderr', (id, text) =>\r\n this.onCmdStderrHandler && this.onCmdStderrHandler(id, text));\r\n\r\n this._socket.on('cmdExit', (id, exitCode) =>\r\n this.onCmdExitHandler && this.onCmdExitHandler(id, exitCode));\r\n }\r\n\r\n /**\r\n * Called internally.\r\n * @private\r\n * @param {boolean} isOk\r\n * @param {boolean} isSecure\r\n */\r\n onPreConnect(isOk, isSecure) {\r\n if (this._authTimer) {\r\n clearTimeout(this._authTimer);\r\n this._authTimer = null;\r\n }\r\n\r\n this.connected = true;\r\n this.isSecure = isSecure;\r\n\r\n if (this.waitForRestart) {\r\n window.location.reload(false);\r\n } else {\r\n if (this.firstConnect) {\r\n // retry strategy\r\n this.loadTimer = setTimeout(() => {\r\n this.loadTimer = null;\r\n this.loadCounter++;\r\n if (this.loadCounter < 10) {\r\n this.onConnect();\r\n }\r\n }, 1000);\r\n\r\n if (!this.loaded) {\r\n this.onConnect();\r\n }\r\n } else {\r\n this.onProgress(PROGRESS.READY);\r\n }\r\n\r\n this._subscribe(true);\r\n this.onConnectionHandlers.forEach(cb => cb(true));\r\n }\r\n\r\n if (this._waitForFirstConnectionResolve) {\r\n this._waitForFirstConnectionResolve();\r\n this._waitForFirstConnectionResolve = null;\r\n }\r\n }\r\n\r\n /**\r\n * Checks if the socket is connected.\r\n * @returns {boolean} true if connected.\r\n */\r\n isConnected() {\r\n return this.connected;\r\n }\r\n\r\n /**\r\n * Checks if the socket is connected.\r\n * @returns {Promise} Promise resolves if once connected.\r\n */\r\n waitForFirstConnection() {\r\n return this._waitForFirstConnection;\r\n }\r\n\r\n /**\r\n * Called internally.\r\n * @private\r\n */\r\n _getUserPermissions(cb) {\r\n if (this.doNotLoadACL) {\r\n return cb && cb();\r\n } else {\r\n this._socket.emit('getUserPermissions', cb);\r\n }\r\n }\r\n\r\n /**\r\n * Called internally.\r\n * @private\r\n */\r\n onConnect() {\r\n this._getUserPermissions((err, acl) => {\r\n if (err) {\r\n return this.onError('Cannot read user permissions: ' + err);\r\n } else\r\n if (!this.doNotLoadACL) {\r\n if (this.loaded) {\r\n return;\r\n }\r\n this.loaded = true;\r\n clearTimeout(this.loadTimer);\r\n this.loadTimer = null;\r\n\r\n this.onProgress(PROGRESS.CONNECTED);\r\n this.firstConnect = false;\r\n\r\n this.acl = acl;\r\n }\r\n\r\n // Read system configuration\r\n return (this.admin5only && !window.vendorPrefix ? this.getCompactSystemConfig() : this.getSystemConfig())\r\n .then(data => {\r\n if (this.doNotLoadACL) {\r\n if (this.loaded) {\r\n return undefined;\r\n }\r\n this.loaded = true;\r\n clearTimeout(this.loadTimer);\r\n this.loadTimer = null;\r\n\r\n this.onProgress(PROGRESS.CONNECTED);\r\n this.firstConnect = false;\r\n }\r\n\r\n this.systemConfig = data;\r\n if (this.systemConfig && this.systemConfig.common) {\r\n this.systemLang = this.systemConfig.common.language;\r\n } else {\r\n this.systemLang = window.navigator.userLanguage || window.navigator.language;\r\n\r\n if (this.systemLang !== 'en' && this.systemLang !== 'de' && this.systemLang !== 'ru') {\r\n this.systemConfig.common.language = 'en';\r\n this.systemLang = 'en';\r\n }\r\n }\r\n\r\n this.props.onLanguage && this.props.onLanguage(this.systemLang);\r\n\r\n if (!this.doNotLoadAllObjects) {\r\n return this.getObjects()\r\n .then(() => {\r\n this.onProgress(PROGRESS.READY);\r\n this.props.onReady && this.props.onReady(this.objects);\r\n });\r\n } else {\r\n this.objects = this.admin5only ? {} : { 'system.config': data };\r\n this.onProgress(PROGRESS.READY);\r\n this.props.onReady && this.props.onReady(this.objects);\r\n }\r\n return undefined;\r\n })\r\n .catch(e => this.onError('Cannot read system config: ' + e));\r\n });\r\n }\r\n\r\n /**\r\n * Called internally.\r\n * @private\r\n */\r\n authenticate() {\r\n if (window.location.search.includes('&href=')) {\r\n window.location = `${window.location.protocol}//${window.location.host}${window.location.pathname}${window.location.search}${window.location.hash}`;\r\n } else {\r\n window.location = `${window.location.protocol}//${window.location.host}${window.location.pathname}?login&href=${window.location.search}${window.location.hash}`;\r\n }\r\n }\r\n\r\n /**\r\n * Subscribe to changes of the given state.\r\n * @param {string} id The ioBroker state ID.\r\n * @param {ioBroker.StateChangeHandler} cb The callback.\r\n */\r\n /**\r\n * Subscribe to changes of the given state.\r\n * @param {string} id The ioBroker state ID.\r\n * @param {boolean} binary Set to true if the given state is binary and requires Base64 decoding.\r\n * @param {ioBroker.StateChangeHandler} cb The callback.\r\n */\r\n subscribeState(id, binary, cb) {\r\n if (typeof binary === 'function') {\r\n cb = binary;\r\n binary = false;\r\n }\r\n\r\n if (!this.statesSubscribes[id]) {\r\n let reg = id\r\n .replace(/\\./g, '\\\\.')\r\n .replace(/\\*/g, '.*')\r\n .replace(/\\(/g, '\\\\(')\r\n .replace(/\\)/g, '\\\\)')\r\n .replace(/\\+/g, '\\\\+')\r\n .replace(/\\[/g, '\\\\[');\r\n\r\n if (reg.indexOf('*') === -1) {\r\n reg += '$';\r\n }\r\n this.statesSubscribes[id] = { reg: new RegExp(reg), cbs: [] };\r\n this.statesSubscribes[id].cbs.push(cb);\r\n if (this.connected) {\r\n this._socket.emit('subscribe', id);\r\n }\r\n } else {\r\n !this.statesSubscribes[id].cbs.includes(cb) && this.statesSubscribes[id].cbs.push(cb);\r\n }\r\n if (typeof cb === 'function' && this.connected) {\r\n if (binary) {\r\n this.getBinaryState(id)\r\n .then(base64 => cb(id, base64))\r\n .catch(e => console.error(`Cannot getForeignStates \"${id}\": ${JSON.stringify(e)}`));\r\n } else {\r\n if (Connection.isWeb()) {\r\n this._socket.emit('getStates', id, (err, states) => {\r\n err && console.error(`Cannot getForeignStates \"${id}\": ${JSON.stringify(err)}`);\r\n states && Object.keys(states).forEach(id => cb(id, states[id]));\r\n });\r\n } else {\r\n this._socket.emit('getForeignStates', id, (err, states) => {\r\n err && console.error(`Cannot getForeignStates \"${id}\": ${JSON.stringify(err)}`);\r\n states && Object.keys(states).forEach(id => cb(id, states[id]));\r\n });\r\n }\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Unsubscribes all callbacks from changes of the given state.\r\n * @param {string} id The ioBroker state ID.\r\n */\r\n /**\r\n * Unsubscribes the given callback from changes of the given state.\r\n * @param {string} id The ioBroker state ID.\r\n * @param {ioBroker.StateChangeHandler} cb The callback.\r\n */\r\n unsubscribeState(id, cb) {\r\n if (this.statesSubscribes[id]) {\r\n if (cb) {\r\n const pos = this.statesSubscribes[id].cbs.indexOf(cb);\r\n pos !== -1 && this.statesSubscribes[id].cbs.splice(pos, 1);\r\n } else {\r\n this.statesSubscribes[id].cbs = [];\r\n }\r\n\r\n if (!this.statesSubscribes[id].cbs || !this.statesSubscribes[id].cbs.length) {\r\n delete this.statesSubscribes[id];\r\n this.connected && this._socket.emit('unsubscribe', id);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Subscribe to changes of the given object.\r\n * @param {string} id The ioBroker object ID.\r\n * @param {import('./types').ObjectChangeHandler} cb The callback.\r\n * @returns {Promise}\r\n */\r\n subscribeObject(id, cb) {\r\n if (!this.objectsSubscribes[id]) {\r\n let reg = id.replace(/\\./g, '\\\\.').replace(/\\*/g, '.*');\r\n if (!reg.includes('*')) {\r\n reg += '$';\r\n }\r\n this.objectsSubscribes[id] = { reg: new RegExp(reg), cbs: [] };\r\n this.objectsSubscribes[id].cbs.push(cb);\r\n this.connected && this._socket.emit('subscribeObjects', id);\r\n } else {\r\n !this.objectsSubscribes[id].cbs.includes(cb) && this.objectsSubscribes[id].cbs.push(cb);\r\n }\r\n return Promise.resolve();\r\n }\r\n\r\n /**\r\n * Unsubscribes all callbacks from changes of the given object.\r\n * @param {string} id The ioBroker object ID.\r\n * @returns {Promise}\r\n */\r\n /**\r\n * Unsubscribes the given callback from changes of the given object.\r\n * @param {string} id The ioBroker object ID.\r\n * @param {import('./types').ObjectChangeHandler} cb The callback.\r\n * @returns {Promise}\r\n */\r\n unsubscribeObject(id, cb) {\r\n if (this.objectsSubscribes[id]) {\r\n if (cb) {\r\n const pos = this.objectsSubscribes[id].cbs.indexOf(cb);\r\n pos !== -1 && this.objectsSubscribes[id].cbs.splice(pos, 1);\r\n } else {\r\n this.objectsSubscribes[id].cbs = [];\r\n }\r\n\r\n if (this.connected && (!this.objectsSubscribes[id].cbs || !this.objectsSubscribes[id].cbs.length)) {\r\n delete this.objectsSubscribes[id];\r\n this.connected && this._socket.emit('unsubscribeObjects', id);\r\n }\r\n }\r\n return Promise.resolve();\r\n }\r\n\r\n /**\r\n * Called internally.\r\n * @private\r\n * @param {string} id\r\n * @param {ioBroker.Object | null | undefined} obj\r\n */\r\n objectChange(id, obj) {\r\n // update main.objects cache\r\n if (!this.objects) {\r\n return;\r\n }\r\n\r\n /** @type {import(\"./types\").OldObject} */\r\n let oldObj;\r\n\r\n let changed = false;\r\n if (obj) {\r\n if (obj._rev && this.objects[id]) {\r\n this.objects[id]._rev = obj._rev;\r\n }\r\n\r\n if (this.objects[id]) {\r\n oldObj = { _id: id, type: this.objects[id].type };\r\n }\r\n\r\n if (!this.objects[id] || JSON.stringify(this.objects[id]) !== JSON.stringify(obj)) {\r\n this.objects[id] = obj;\r\n changed = true;\r\n }\r\n } else if (this.objects[id]) {\r\n oldObj = { _id: id, type: this.objects[id].type };\r\n delete this.objects[id];\r\n changed = true;\r\n }\r\n\r\n Object.keys(this.objectsSubscribes).forEach(_id => {\r\n if (_id === id || this.objectsSubscribes[_id].reg.test(id)) {\r\n //@ts-ignore\r\n this.objectsSubscribes[_id].cbs.forEach(cb => cb(id, obj, oldObj));\r\n }\r\n });\r\n\r\n if (changed && this.props.onObjectChange) {\r\n this.props.onObjectChange(id, obj);\r\n }\r\n }\r\n\r\n /**\r\n * Called internally.\r\n * @private\r\n * @param {string} id\r\n * @param {ioBroker.State | null | undefined} state\r\n */\r\n stateChange(id, state) {\r\n for (const task in this.statesSubscribes) {\r\n if (this.statesSubscribes.hasOwnProperty(task) && this.statesSubscribes[task].reg.test(id)) {\r\n this.statesSubscribes[task].cbs.forEach(cb => cb(id, state));\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Gets all states.\r\n * @param {boolean} disableProgressUpdate don't call onProgress() when done\r\n * @returns {Promise>}\r\n */\r\n getStates(disableProgressUpdate) {\r\n if (!this.connected) {\r\n return Promise.reject(NOT_CONNECTED);\r\n }\r\n\r\n return new Promise((resolve, reject) =>\r\n this._socket.emit('getStates', (err, res) => {\r\n this.states = res;\r\n //@ts-ignore\r\n !disableProgressUpdate && this.onProgress(PROGRESS.STATES_LOADED);\r\n return err ? reject(err) : resolve(this.states);\r\n }));\r\n }\r\n\r\n /**\r\n * Gets the given state.\r\n * @param {string} id The state ID.\r\n * @returns {Promise}\r\n */\r\n getState(id) {\r\n if (!this.connected) {\r\n return Promise.reject(NOT_CONNECTED);\r\n }\r\n\r\n return new Promise((resolve, reject) =>\r\n this._socket.emit('getState', id, (err, state) => err ? reject(err) : resolve(state)));\r\n }\r\n\r\n /**\r\n * Gets the given binary state.\r\n * @param {string} id The state ID.\r\n * @returns {Promise}\r\n */\r\n getBinaryState(id) {\r\n if (!this.connected) {\r\n return Promise.reject(NOT_CONNECTED);\r\n }\r\n\r\n // the data will come in base64\r\n return new Promise((resolve, reject) =>\r\n this._socket.emit('getBinaryState', id, (err, state) => err ? reject(err) : resolve(state)));\r\n }\r\n\r\n /**\r\n * Sets the given binary state.\r\n * @param {string} id The state ID.\r\n * @param {string} base64 The Base64 encoded binary data.\r\n * @returns {Promise}\r\n */\r\n setBinaryState(id, base64) {\r\n if (!this.connected) {\r\n return Promise.reject(NOT_CONNECTED);\r\n }\r\n\r\n // the data will come in base64\r\n return new Promise((resolve, reject) =>\r\n this._socket.emit('setBinaryState', id, base64, err => err ? reject(err) : resolve()));\r\n }\r\n\r\n /**\r\n * Sets the given state value.\r\n * @param {string} id The state ID.\r\n * @param {string | number | boolean | ioBroker.State | ioBroker.SettableState | null} val The state value.\r\n * @returns {Promise}\r\n */\r\n setState(id, val) {\r\n if (!this.connected) {\r\n return Promise.reject(NOT_CONNECTED);\r\n }\r\n\r\n return new Promise((resolve, reject) =>\r\n this._socket.emit('setState', id, val, err =>\r\n err ? reject(err) : resolve()));\r\n }\r\n\r\n /**\r\n * Gets all objects.\r\n * @param {(objects?: Record) => void} update Callback that is executed when all objects are retrieved.\r\n * @returns {void}\r\n */\r\n /**\r\n * Gets all objects.\r\n * @param {boolean} update Set to true to retrieve all objects from the server (instead of using the local cache).\r\n * @param {boolean} disableProgressUpdate don't call onProgress() when done\r\n * @returns {Promise> | undefined}\r\n */\r\n getObjects(update, disableProgressUpdate) {\r\n if (!this.connected) {\r\n return Promise.reject(NOT_CONNECTED);\r\n } else {\r\n return new Promise((resolve, reject) => {\r\n if (!update && this.objects) {\r\n return resolve(this.objects);\r\n }\r\n\r\n this._socket.emit(Connection.isWeb() ? 'getObjects' : 'getAllObjects', (err, res) => {\r\n this.objects = res;\r\n disableProgressUpdate && this.onProgress(PROGRESS.OBJECTS_LOADED);\r\n err ? reject(err) : resolve(this.objects);\r\n });\r\n });\r\n }\r\n }\r\n\r\n /**\r\n * Called internally.\r\n * @private\r\n * @param {boolean} isEnable\r\n */\r\n _subscribe(isEnable) {\r\n if (isEnable && !this.subscribed) {\r\n this.subscribed = true;\r\n this.autoSubscribes.forEach(id => this._socket.emit('subscribeObjects', id));\r\n // re subscribe objects\r\n Object.keys(this.objectsSubscribes).forEach(id => this._socket.emit('subscribeObjects', id));\r\n // re-subscribe logs\r\n this.autoSubscribeLog && this._socket.emit('requireLog', true);\r\n // re subscribe states\r\n Object.keys(this.statesSubscribes).forEach(id => this._socket.emit('subscribe', id));\r\n } else if (!isEnable && this.subscribed) {\r\n this.subscribed = false;\r\n // un-subscribe objects\r\n this.autoSubscribes.forEach(id => this._socket.emit('unsubscribeObjects', id));\r\n Object.keys(this.objectsSubscribes).forEach(id => this._socket.emit('unsubscribeObjects', id));\r\n // un-subscribe logs\r\n this.autoSubscribeLog && this._socket.emit('requireLog', false);\r\n\r\n // un-subscribe states\r\n Object.keys(this.statesSubscribes).forEach(id => this._socket.emit('unsubscribe', id));\r\n }\r\n }\r\n\r\n /**\r\n * Requests log updates.\r\n * @param {boolean} isEnabled Set to true to get logs.\r\n * @returns {Promise}\r\n */\r\n requireLog(isEnabled) {\r\n if (!this.connected) {\r\n return Promise.reject(NOT_CONNECTED);\r\n }\r\n return new Promise((resolve, reject) =>\r\n this._socket.emit('requireLog', isEnabled, err =>\r\n err ? reject(err) : resolve()));\r\n }\r\n\r\n /**\r\n * Deletes the given object.\r\n * @param {string} id The object ID.\r\n * @param {boolean} maintenance Force deletion of non conform IDs.\r\n * @returns {Promise}\r\n */\r\n delObject(id, maintenance) {\r\n if (!this.connected) {\r\n return Promise.reject(NOT_CONNECTED);\r\n }\r\n return new Promise((resolve, reject) =>\r\n this._socket.emit('delObject', id, { maintenance: !!maintenance }, err =>\r\n err ? reject(err) : resolve()));\r\n }\r\n\r\n /**\r\n * Deletes the given object and all its children.\r\n * @param {string} id The object ID.\r\n * @param {boolean} maintenance Force deletion of non conform IDs.\r\n * @returns {Promise}\r\n */\r\n delObjects(id, maintenance) {\r\n if (!this.connected) {\r\n return Promise.reject(NOT_CONNECTED);\r\n }\r\n return new Promise((resolve, reject) =>\r\n this._socket.emit('delObjects', id, {maintenance: !!maintenance}, err =>\r\n err ? reject(err) : resolve()));\r\n }\r\n\r\n /**\r\n * Sets the object.\r\n * @param {string} id The object ID.\r\n * @param {ioBroker.SettableObject} obj The object.\r\n * @returns {Promise}\r\n */\r\n setObject(id, obj) {\r\n if (!this.connected) {\r\n return Promise.reject(NOT_CONNECTED);\r\n }\r\n\r\n if (!obj) {\r\n return Promise.reject('Null object is not allowed');\r\n }\r\n\r\n obj = JSON.parse(JSON.stringify(obj));\r\n\r\n if (obj.hasOwnProperty('from')) {\r\n delete obj.from;\r\n }\r\n if (obj.hasOwnProperty('user')) {\r\n delete obj.user;\r\n }\r\n if (obj.hasOwnProperty('ts')) {\r\n delete obj.ts;\r\n }\r\n\r\n return new Promise((resolve, reject) =>\r\n this._socket.emit('setObject', id, obj, err =>\r\n err ? reject(err) : resolve()));\r\n }\r\n\r\n /**\r\n * Gets the object with the given id from the server.\r\n * @param {string} id The object ID.\r\n * @returns {ioBroker.GetObjectPromise} The object.\r\n */\r\n getObject(id) {\r\n if (!this.connected) {\r\n return Promise.reject(NOT_CONNECTED);\r\n }\r\n return new Promise((resolve, reject) =>\r\n this._socket.emit('getObject', id, (err, obj) =>\r\n err ? reject(err) : resolve(obj)));\r\n }\r\n\r\n /**\r\n * Get all adapter instances.\r\n * @param {boolean} [update] Force update.\r\n * @returns {Promise}\r\n */\r\n /**\r\n * Get all instances of the given adapter.\r\n * @param {string} adapter The name of the adapter.\r\n * @param {boolean} [update] Force update.\r\n * @returns {Promise}\r\n */\r\n getAdapterInstances(adapter, update) {\r\n if (typeof adapter === 'boolean') {\r\n update = adapter;\r\n adapter = '';\r\n }\r\n adapter = adapter || '';\r\n\r\n if (!update && this._promises['instances_' + adapter]) {\r\n return this._promises['instances_' + adapter];\r\n }\r\n\r\n if (!this.connected) {\r\n return Promise.reject(NOT_CONNECTED);\r\n }\r\n\r\n this._promises['instances_' + adapter] = new Promise((resolve, reject) => {\r\n let timeout = setTimeout(() => {\r\n timeout = null;\r\n this.getObjectView(\r\n `system.adapter.${adapter ? adapter + '.' : ''}`,\r\n `system.adapter.${adapter ? adapter + '.' : ''}\\u9999`,\r\n 'instance'\r\n )\r\n .then(items => resolve(Object.keys(items).map(id => fixAdminUI(items[id]))))\r\n .catch(e => reject(e));\r\n }, TIMEOUT_FOR_ADMIN4);\r\n\r\n this._socket.emit('getAdapterInstances', adapter, (err, instances) => {\r\n if (timeout) {\r\n clearTimeout(timeout);\r\n timeout = null;\r\n return err ? reject(err) : resolve(instances);\r\n }\r\n });\r\n });\r\n\r\n return this._promises['instances_' + adapter];\r\n }\r\n\r\n /**\r\n * Get all adapters.\r\n * @param {boolean} [update] Force update.\r\n * @returns {Promise}\r\n */\r\n /**\r\n * Get adapters with the given name.\r\n * @param {string} adapter The name of the adapter.\r\n * @param {boolean} [update] Force update.\r\n * @returns {Promise}\r\n */\r\n getAdapters(adapter, update) {\r\n if (Connection.isWeb()) {\r\n return Promise.reject('Allowed only in admin');\r\n }\r\n\r\n if (typeof adapter === 'boolean') {\r\n update = adapter;\r\n adapter = '';\r\n }\r\n\r\n adapter = adapter || '';\r\n\r\n if (!update && this._promises['adapter_' + adapter]) {\r\n return this._promises['adapter_' + adapter];\r\n }\r\n\r\n if (!this.connected) {\r\n return Promise.reject(NOT_CONNECTED);\r\n }\r\n\r\n this._promises['adapter_' + adapter] = new Promise((resolve, reject) => {\r\n let timeout = setTimeout(() => {\r\n timeout = null;\r\n this.getObjectView(\r\n `system.adapter.${adapter}.`,\r\n `system.adapter.${adapter}.\\u9999`,\r\n 'adapter'\r\n )\r\n .then(items => resolve(Object.keys(items).map(id => fixAdminUI(items[id]))))\r\n .catch(e => reject(e));\r\n }, TIMEOUT_FOR_ADMIN4);\r\n\r\n this._socket.emit('getAdapters', adapter, (err, adapters) => {\r\n if (timeout) {\r\n clearTimeout(timeout);\r\n timeout = null;\r\n return err ? reject(err) : resolve(adapters);\r\n }\r\n });\r\n });\r\n\r\n return this._promises['adapter_' + adapter];\r\n }\r\n\r\n /**\r\n * Called internally.\r\n * @private\r\n * @param {any[]} objs\r\n * @param {(err?: any) => void} cb\r\n */\r\n _renameGroups(objs, cb) {\r\n if (!objs || !objs.length) {\r\n cb && cb();\r\n } else {\r\n let obj = objs.pop();\r\n let oldId = obj._id;\r\n obj._id = obj.newId;\r\n delete obj.newId;\r\n\r\n this.setObject(obj._id, obj)\r\n .then(() => this.delObject(oldId))\r\n .then(() => setTimeout(() => this._renameGroups(objs, cb), 0))\r\n .catch(err => cb && cb(err));\r\n }\r\n }\r\n\r\n /**\r\n * Rename a group.\r\n * @param {string} id The id.\r\n * @param {string} newId The new id.\r\n * @param {string | { [lang in ioBroker.Languages]?: string; }} newName The new name.\r\n */\r\n renameGroup(id, newId, newName) {\r\n if (Connection.isWeb()) {\r\n return Promise.reject('Allowed only in admin');\r\n }\r\n\r\n return this.getGroups(true)\r\n .then(groups => {\r\n if (groups.length) {\r\n // find all elements\r\n const groupsToRename = groups\r\n .filter(group => group._id.startsWith(id + '.'));\r\n\r\n groupsToRename.forEach(group => group.newId = newId + group._id.substring(id.length));\r\n\r\n return new Promise((resolve, reject) =>\r\n this._renameGroups(groupsToRename, err => err ? reject(err) : resolve()))\r\n .then(() => {\r\n const obj = groups.find(group => group._id === id);\r\n\r\n if (obj) {\r\n obj._id = newId;\r\n if (newName !== undefined) {\r\n obj.common = obj.common || {};\r\n obj.common.name = newName;\r\n }\r\n\r\n return this.setObject(obj._id, obj)\r\n .then(() => this.delObject(id));\r\n }\r\n });\r\n }\r\n });\r\n }\r\n\r\n /**\r\n * Sends a message to a specific instance or all instances of some specific adapter.\r\n * @param {string} instance The instance to send this message to.\r\n * @param {string} [command] Command name of the target instance.\r\n * @param {ioBroker.MessagePayload} [data] The message data to send.\r\n * @returns {Promise}\r\n */\r\n sendTo(instance, command, data) {\r\n if (!this.connected) {\r\n return Promise.reject(NOT_CONNECTED);\r\n }\r\n return new Promise(resolve =>\r\n this._socket.emit('sendTo', instance, command, data, result =>\r\n resolve(result)));\r\n }\r\n\r\n /**\r\n * Extend an object and create it if it might not exist.\r\n * @param {string} id The id.\r\n * @param {ioBroker.PartialObject} obj The object.\r\n */\r\n extendObject(id, obj) {\r\n if (!this.connected) {\r\n return Promise.reject(NOT_CONNECTED);\r\n }\r\n\r\n obj = JSON.parse(JSON.stringify(obj));\r\n\r\n if (obj.hasOwnProperty('from')) {\r\n delete obj.from;\r\n }\r\n if (obj.hasOwnProperty('user')) {\r\n delete obj.user;\r\n }\r\n if (obj.hasOwnProperty('ts')) {\r\n delete obj.ts;\r\n }\r\n\r\n return new Promise((resolve, reject) =>\r\n this._socket.emit('extendObject', id, obj, err => err ? reject(err) : resolve()));\r\n }\r\n\r\n /**\r\n * Register a handler for log messages.\r\n * @param {(message: string) => void} handler The handler.\r\n */\r\n registerLogHandler(handler) {\r\n !this.onLogHandlers.includes(handler) && this.onLogHandlers.push(handler);\r\n }\r\n\r\n /**\r\n * Unregister a handler for log messages.\r\n * @param {(message: string) => void} handler The handler.\r\n */\r\n unregisterLogHandler(handler) {\r\n const pos = this.onLogHandlers.indexOf(handler);\r\n pos !== -1 && this.onLogHandlers.splice(pos, 1);\r\n }\r\n\r\n /**\r\n * Register a handler for the connection state.\r\n * @param {(connected: boolean) => void} handler The handler.\r\n */\r\n registerConnectionHandler(handler) {\r\n !this.onConnectionHandlers.includes(handler) && this.onConnectionHandlers.push(handler);\r\n }\r\n\r\n /**\r\n * Unregister a handler for the connection state.\r\n * @param {(connected: boolean) => void} handler The handler.\r\n */\r\n unregisterConnectionHandler(handler) {\r\n const pos = this.onConnectionHandlers.indexOf(handler);\r\n pos !== -1 && this.onConnectionHandlers.splice(pos, 1);\r\n }\r\n\r\n /**\r\n * Set the handler for standard output of a command.\r\n * @param {(id: string, text: string) => void} handler The handler.\r\n */\r\n registerCmdStdoutHandler(handler) {\r\n this.onCmdStdoutHandler = handler;\r\n }\r\n\r\n /**\r\n * Unset the handler for standard output of a command.\r\n * @param {(id: string, text: string) => void} handler The handler.\r\n */\r\n unregisterCmdStdoutHandler(handler) {\r\n this.onCmdStdoutHandler = null;\r\n }\r\n\r\n /**\r\n * Set the handler for standard error of a command.\r\n * @param {(id: string, text: string) => void} handler The handler.\r\n */\r\n registerCmdStderrHandler(handler) {\r\n this.onCmdStderrHandler = handler;\r\n }\r\n\r\n /**\r\n * Unset the handler for standard error of a command.\r\n * @param {(id: string, text: string) => void} handler The handler.\r\n */\r\n unregisterCmdStderrHandler(handler) {\r\n this.onCmdStderrHandler = null;\r\n }\r\n\r\n /**\r\n * Set the handler for exit of a command.\r\n * @param {(id: string, exitCode: number) => void} handler The handler.\r\n */\r\n registerCmdExitHandler(handler) {\r\n this.onCmdExitHandler = handler;\r\n }\r\n\r\n /**\r\n * Unset the handler for exit of a command.\r\n * @param {(id: string, exitCode: number) => void} handler The handler.\r\n */\r\n unregisterCmdExitHandler(handler) {\r\n this.onCmdExitHandler = null;\r\n }\r\n\r\n /**\r\n * Get all enums with the given name.\r\n * @param {string} [_enum] The name of the enum\r\n * @param {boolean} [update] Force update.\r\n * @returns {Promise>}\r\n */\r\n getEnums(_enum, update) {\r\n if (!update && this._promises['enums_' + (_enum || 'all')]) {\r\n return this._promises['enums_' + (_enum || 'all')];\r\n }\r\n\r\n if (!this.connected) {\r\n return Promise.reject(NOT_CONNECTED);\r\n }\r\n\r\n this._promises['enums_' + (_enum || 'all')] = new Promise((resolve, reject) => {\r\n this._socket.emit('getObjectView', 'system', 'enum', { startkey: 'enum.' + (_enum || ''), endkey: 'enum.' + (_enum ? (_enum + '.') : '') + '\\u9999' }, (err, res) => {\r\n if (!err && res) {\r\n const _res = {};\r\n for (let i = 0; i < res.rows.length; i++) {\r\n if (_enum && res.rows[i].id === 'enum.' + _enum) {\r\n continue;\r\n }\r\n _res[res.rows[i].id] = res.rows[i].value;\r\n }\r\n resolve(_res);\r\n } else {\r\n reject(err);\r\n }\r\n });\r\n });\r\n\r\n return this._promises['enums_' + (_enum || 'all')];\r\n }\r\n\r\n /**\r\n * Query a predefined object view.\r\n * @param {string} start The start ID.\r\n * @param {string} end The end ID.\r\n * @param {string} type The type of object.\r\n * @returns {Promise>}\r\n */\r\n getObjectView(start, end, type) {\r\n if (!this.connected) {\r\n return Promise.reject(NOT_CONNECTED);\r\n }\r\n\r\n start = start || '';\r\n end = end || '\\u9999';\r\n\r\n return new Promise((resolve, reject) => {\r\n this._socket.emit('getObjectView', 'system', type, { startkey: start, endkey: end }, (err, res) => {\r\n if (!err) {\r\n const _res = {};\r\n if (res && res.rows) {\r\n for (let i = 0; i < res.rows.length; i++) {\r\n _res[res.rows[i].id] = res.rows[i].value;\r\n }\r\n }\r\n resolve(_res);\r\n } else {\r\n reject(err);\r\n }\r\n });\r\n });\r\n }\r\n\r\n /**\r\n * Get the stored certificates.\r\n * @param {boolean} [update] Force update.\r\n * @returns {Promise<{name: string; type: 'public' | 'private' | 'chained'}[]>}\r\n */\r\n getCertificates(update) {\r\n if (Connection.isWeb()) {\r\n return Promise.reject('Allowed only in admin');\r\n }\r\n\r\n if (this._promises.cert && !update) {\r\n return this._promises.cert;\r\n }\r\n\r\n if (!this.connected) {\r\n return Promise.reject(NOT_CONNECTED);\r\n }\r\n\r\n this._promises.cert = this.getObject('system.certificates')\r\n .then(res => {\r\n const certs = [];\r\n if (res && res.native && res.native.certificates) {\r\n Object.keys(res.native.certificates).forEach(c => {\r\n const cert = res.native.certificates[c];\r\n if (!cert) {\r\n return;\r\n }\r\n const _cert = {\r\n name: c,\r\n type: ''\r\n };\r\n // If it is filename, it could be everything\r\n if (cert.length < 700 && (cert.indexOf('/') !== -1 || cert.indexOf('\\\\') !== -1)) {\r\n if (c.toLowerCase().includes('private')) {\r\n _cert.type = 'private';\r\n } else if (cert.toLowerCase().includes('private')) {\r\n _cert.type = 'private';\r\n } else if (c.toLowerCase().includes('public')) {\r\n _cert.type = 'public';\r\n } else if (cert.toLowerCase().includes('public')) {\r\n _cert.type = 'public';\r\n }\r\n certs.push(_cert);\r\n } else {\r\n _cert.type = (cert.substring(0, '-----BEGIN RSA PRIVATE KEY'.length) === '-----BEGIN RSA PRIVATE KEY' || cert.substring(0, '-----BEGIN PRIVATE KEY'.length) === '-----BEGIN PRIVATE KEY') ? 'private' : 'public';\r\n\r\n if (_cert.type === 'public') {\r\n const m = cert.split('-----END CERTIFICATE-----');\r\n if (m.filter(t => t.replace(/\\r\\n|\\r|\\n/, '').trim()).length > 1) {\r\n _cert.type = 'chained';\r\n }\r\n }\r\n\r\n certs.push(_cert);\r\n }\r\n });\r\n }\r\n return certs;\r\n });\r\n\r\n return this._promises.cert;\r\n }\r\n\r\n /**\r\n * Get the logs from a host (only for admin connection).\r\n * @param {string} host\r\n * @param {number} [linesNumber]\r\n * @returns {Promise}\r\n */\r\n getLogs(host, linesNumber) {\r\n if (Connection.isWeb()) {\r\n return Promise.reject('Allowed only in admin');\r\n }\r\n\r\n if (!this.connected) {\r\n return Promise.reject(NOT_CONNECTED);\r\n }\r\n\r\n return new Promise(resolve =>\r\n this._socket.emit('sendToHost', host, 'getLogs', linesNumber || 200, lines =>\r\n resolve(lines)));\r\n }\r\n\r\n /**\r\n * Get the log files (only for admin connection).\r\n * @returns {Promise}\r\n */\r\n getLogsFiles(host) {\r\n if (Connection.isWeb()) {\r\n return Promise.reject('Allowed only in admin');\r\n }\r\n if (!this.connected) {\r\n return Promise.reject(NOT_CONNECTED);\r\n }\r\n return new Promise((resolve, reject) =>\r\n this._socket.emit('readLogs', host, (err, files) =>\r\n err ? reject(err) : resolve(files)));\r\n }\r\n\r\n /**\r\n * Delete the logs from a host (only for admin connection).\r\n * @param {string} host\r\n * @returns {Promise}\r\n */\r\n delLogs(host) {\r\n if (Connection.isWeb()) {\r\n return Promise.reject('Allowed only in admin');\r\n }\r\n if (!this.connected) {\r\n return Promise.reject(NOT_CONNECTED);\r\n }\r\n return new Promise((resolve, reject) =>\r\n this._socket.emit('sendToHost', host, 'delLogs', null, error =>\r\n error ? reject(error) : resolve()));\r\n }\r\n\r\n /**\r\n * Read the meta items.\r\n * @returns {Promise}\r\n */\r\n readMetaItems() {\r\n if (!this.connected) {\r\n return Promise.reject(NOT_CONNECTED);\r\n }\r\n return new Promise((resolve, reject) =>\r\n this._socket.emit('getObjectView', 'system', 'meta', { startkey: '', endkey: '\\u9999' }, (err, objs) =>\r\n err ? reject(err) : resolve(objs.rows && objs.rows.map(obj => obj.value))));\r\n }\r\n\r\n /**\r\n * Read the directory of an adapter.\r\n * @param {string} adapter The adapter name.\r\n * @param {string} fileName The directory name.\r\n * @returns {Promise}\r\n */\r\n readDir(adapter, fileName) {\r\n if (!this.connected) {\r\n return Promise.reject(NOT_CONNECTED);\r\n }\r\n return new Promise((resolve, reject) =>\r\n this._socket.emit('readDir', adapter, fileName, (err, files) =>\r\n err ? reject(err) : resolve(files)));\r\n }\r\n\r\n /**\r\n * Read a file of an adapter.\r\n * @param {string} adapter The adapter name.\r\n * @param {string} fileName The file name.\r\n * @param {boolean} base64 If it must be a base64 format\r\n * @returns {Promise}\r\n */\r\n readFile(adapter, fileName, base64) {\r\n if (!this.connected) {\r\n return Promise.reject(NOT_CONNECTED);\r\n }\r\n return new Promise((resolve, reject) => {\r\n if (!base64) {\r\n this._socket.emit('readFile', adapter, fileName, (err, data, type) => {\r\n //@ts-ignore\r\n err ? reject(err) : resolve({data, type});\r\n });\r\n } else {\r\n this._socket.emit('readFile64', adapter, fileName, base64, (err, data) =>\r\n err ? reject(err) : resolve(data));\r\n }\r\n });\r\n }\r\n\r\n /**\r\n * Write a file of an adapter.\r\n * @param {string} adapter The adapter name.\r\n * @param {string} fileName The file name.\r\n * @param {Buffer | string} data The data (if it's a Buffer, it will be converted to Base64).\r\n * @returns {Promise}\r\n */\r\n writeFile64(adapter, fileName, data) {\r\n if (!this.connected) {\r\n return Promise.reject(NOT_CONNECTED);\r\n }\r\n return new Promise((resolve, reject) => {\r\n if (typeof data === 'string') {\r\n this._socket.emit('writeFile', adapter, fileName, data, err =>\r\n err ? reject(err) : resolve());\r\n } else {\r\n const base64 = btoa(\r\n new Uint8Array(data)\r\n .reduce((data, byte) => data + String.fromCharCode(byte), '')\r\n );\r\n\r\n this._socket.emit('writeFile64', adapter, fileName, base64, err =>\r\n err ? reject(err) : resolve());\r\n }\r\n });\r\n }\r\n\r\n /**\r\n * Rename a file or folder of an adapter.\r\n *\r\n * All files in folder will be renamed too.\r\n * @param {string} adapter The adapter name.\r\n * @param {string} oldName The file name of the file to be renamed.\r\n * @param {string} newName The new file name.\r\n * @returns {Promise}\r\n */\r\n rename(adapter, oldName, newName) {\r\n if (!this.connected) {\r\n return Promise.reject(NOT_CONNECTED);\r\n }\r\n return new Promise((resolve, reject) =>\r\n this._socket.emit('rename', adapter, oldName, newName, err =>\r\n err ? reject(err) : resolve()));\r\n }\r\n\r\n /**\r\n * Delete a file of an adapter.\r\n * @param {string} adapter The adapter name.\r\n * @param {string} fileName The file name.\r\n * @returns {Promise}\r\n */\r\n deleteFile(adapter, fileName) {\r\n if (!this.connected) {\r\n return Promise.reject(NOT_CONNECTED);\r\n }\r\n return new Promise((resolve, reject) =>\r\n this._socket.emit('unlink', adapter, fileName, err =>\r\n err ? reject(err) : resolve()));\r\n }\r\n\r\n /**\r\n * Delete a folder of an adapter.\r\n * All files in folder will be deleted.\r\n * @param {string} adapter The adapter name.\r\n * @param {string} folderName The folder name.\r\n * @returns {Promise}\r\n */\r\n deleteFolder(adapter, folderName) {\r\n if (!this.connected) {\r\n return Promise.reject(NOT_CONNECTED);\r\n }\r\n return new Promise((resolve, reject) =>\r\n this._socket.emit('deleteFolder', adapter, folderName, err =>\r\n err ? reject(err) : resolve()));\r\n }\r\n\r\n /**\r\n * Get the list of all hosts.\r\n * @param {boolean} [update] Force update.\r\n * @returns {Promise}\r\n */\r\n getHosts(update) {\r\n if (Connection.isWeb()) {\r\n return Promise.reject('Allowed only in admin');\r\n }\r\n if (!update && this._promises.hosts) {\r\n return this._promises.hosts;\r\n }\r\n\r\n if (!this.connected) {\r\n return Promise.reject(NOT_CONNECTED);\r\n }\r\n\r\n this._promises.hosts = new Promise((resolve, reject) =>\r\n this._socket.emit(\r\n 'getObjectView',\r\n 'system',\r\n 'host',\r\n {startkey: 'system.host.', endkey: 'system.host.\\u9999'},\r\n (err, doc) => {\r\n if (err) {\r\n reject(err);\r\n } else {\r\n resolve(doc.rows.map(item => item.value));\r\n }\r\n }));\r\n\r\n return this._promises.hosts;\r\n }\r\n\r\n /**\r\n * Get the list of all users.\r\n * @param {boolean} [update] Force update.\r\n * @returns {Promise}\r\n */\r\n getUsers(update) {\r\n if (Connection.isWeb()) {\r\n return Promise.reject('Allowed only in admin');\r\n }\r\n if (!update && this._promises.users) {\r\n return this._promises.users;\r\n }\r\n if (!this.connected) {\r\n return Promise.reject(NOT_CONNECTED);\r\n }\r\n\r\n this._promises.users = new Promise((resolve, reject) =>\r\n this._socket.emit(\r\n 'getObjectView',\r\n 'system',\r\n 'user',\r\n {startkey: 'system.user.', endkey: 'system.user.\\u9999'},\r\n (err, doc) => {\r\n if (err) {\r\n reject(err);\r\n } else {\r\n resolve(doc.rows.map(item => item.value));\r\n }\r\n }));\r\n\r\n return this._promises.users;\r\n }\r\n\r\n /**\r\n * Get the list of all groups.\r\n * @param {boolean} [update] Force update.\r\n * @returns {Promise}\r\n */\r\n getGroups(update) {\r\n if (!update && this._promises.groups) {\r\n return this._promises.groups;\r\n }\r\n if (!this.connected) {\r\n return Promise.reject(NOT_CONNECTED);\r\n }\r\n\r\n this._promises.groups = new Promise((resolve, reject) =>\r\n this._socket.emit(\r\n 'getObjectView',\r\n 'system',\r\n 'group',\r\n {startkey: 'system.group.', endkey: 'system.group.\\u9999'},\r\n (err, doc) => {\r\n if (err) {\r\n reject(err);\r\n } else {\r\n resolve(doc.rows.map(item => item.value));\r\n }\r\n }));\r\n\r\n return this._promises.groups;\r\n }\r\n\r\n /**\r\n * Get the host information.\r\n * @param {string} host\r\n * @param {boolean} [update] Force update.\r\n * @param {number} [timeoutMs] optional read timeout.\r\n * @returns {Promise}\r\n */\r\n getHostInfo(host, update, timeoutMs) {\r\n if (Connection.isWeb()) {\r\n return Promise.reject('Allowed only in admin');\r\n }\r\n if (!host.startsWith('system.host.')) {\r\n host += 'system.host.' + host;\r\n }\r\n\r\n if (!update && this._promises['hostInfo' + host]) {\r\n return this._promises['hostInfo' + host];\r\n }\r\n\r\n if (!this.connected) {\r\n return Promise.reject(NOT_CONNECTED);\r\n }\r\n\r\n this._promises['hostInfo' + host] = new Promise((resolve, reject) => {\r\n let timeout = setTimeout(() => {\r\n if (timeout) {\r\n timeout = null;\r\n reject('getHostInfo timeout');\r\n }\r\n }, timeoutMs || this.props.cmdTimeout);\r\n\r\n this._socket.emit('sendToHost', host, 'getHostInfo', null, data => {\r\n if (timeout) {\r\n clearTimeout(timeout);\r\n timeout = null;\r\n if (data === PERMISSION_ERROR) {\r\n reject('May not read \"getHostInfo\"');\r\n } else if (!data) {\r\n reject('Cannot read \"getHostInfo\"');\r\n } else {\r\n resolve(data);\r\n }\r\n }\r\n });\r\n });\r\n\r\n return this._promises['hostInfo' + host];\r\n }\r\n\r\n /**\r\n * Get the host information (short version).\r\n * @param {string} host\r\n * @param {boolean} [update] Force update.\r\n * @param {number} [timeoutMs] optional read timeout.\r\n * @returns {Promise}\r\n */\r\n getHostInfoShort(host, update, timeoutMs) {\r\n if (Connection.isWeb()) {\r\n return Promise.reject('Allowed only in admin');\r\n }\r\n if (!host.startsWith('system.host.')) {\r\n host += 'system.host.' + host;\r\n }\r\n\r\n if (!update && this._promises['hostInfoShort' + host]) {\r\n return this._promises['hostInfoShort' + host];\r\n }\r\n\r\n if (!this.connected) {\r\n return Promise.reject(NOT_CONNECTED);\r\n }\r\n\r\n this._promises['hostInfoShort' + host] = new Promise((resolve, reject) => {\r\n let timeout = setTimeout(() => {\r\n if (timeout) {\r\n timeout = null;\r\n reject('hostInfoShort timeout');\r\n }\r\n }, timeoutMs || this.props.cmdTimeout);\r\n\r\n this._socket.emit('sendToHost', host, 'getHostInfoShort', null, data => {\r\n if (timeout) {\r\n clearTimeout(timeout);\r\n timeout = null;\r\n if (data === PERMISSION_ERROR) {\r\n reject('May not read \"getHostInfoShort\"');\r\n } else if (!data) {\r\n reject('Cannot read \"getHostInfoShort\"');\r\n } else {\r\n resolve(data);\r\n }\r\n }\r\n });\r\n });\r\n\r\n return this._promises['hostInfoShort' + host];\r\n }\r\n\r\n /**\r\n * Get the repository.\r\n * @param {string} host\r\n * @param {any} [args]\r\n * @param {boolean} [update] Force update.\r\n * @param {number} [timeoutMs] timeout in ms.\r\n * @returns {Promise}\r\n */\r\n getRepository(host, args, update, timeoutMs) {\r\n if (Connection.isWeb()) {\r\n return Promise.reject('Allowed only in admin');\r\n }\r\n if (!update && this._promises.repo) {\r\n return this._promises.repo;\r\n }\r\n\r\n if (!this.connected) {\r\n return Promise.reject(NOT_CONNECTED);\r\n }\r\n\r\n if (!host.startsWith('system.host.')) {\r\n host += 'system.host.' + host;\r\n }\r\n\r\n this._promises.repo = new Promise((resolve, reject) => {\r\n let timeout = setTimeout(() => {\r\n if (timeout) {\r\n timeout = null;\r\n reject('getRepository timeout');\r\n }\r\n }, timeoutMs || this.props.cmdTimeout);\r\n\r\n this._socket.emit('sendToHost', host, 'getRepository', args, data => {\r\n if (timeout) {\r\n clearTimeout(timeout);\r\n timeout = null;\r\n if (data === PERMISSION_ERROR) {\r\n reject('May not read \"getRepository\"');\r\n } else if (!data) {\r\n reject('Cannot read \"getRepository\"');\r\n } else {\r\n resolve(data);\r\n }\r\n }\r\n });\r\n });\r\n\r\n return this._promises.repo;\r\n }\r\n\r\n /**\r\n * Get the installed.\r\n * @param {string} host\r\n * @param {boolean} [update] Force update.\r\n * @param {number} [cmdTimeout] timeout in ms (optional)\r\n * @returns {Promise}\r\n */\r\n getInstalled(host, update, cmdTimeout) {\r\n if (Connection.isWeb()) {\r\n return Promise.reject('Allowed only in admin');\r\n }\r\n\r\n this._promises.installed = this._promises.installed || {};\r\n\r\n if (!update && this._promises.installed[host]) {\r\n return this._promises.installed[host];\r\n }\r\n\r\n if (!this.connected) {\r\n return Promise.reject(NOT_CONNECTED);\r\n }\r\n\r\n if (!host.startsWith('system.host.')) {\r\n host += 'system.host.' + host;\r\n }\r\n\r\n this._promises.installed[host] = new Promise((resolve, reject) => {\r\n let timeout = setTimeout(() => {\r\n if (timeout) {\r\n timeout = null;\r\n reject('getInstalled timeout');\r\n }\r\n }, cmdTimeout || this.props.cmdTimeout);\r\n\r\n this._socket.emit('sendToHost', host, 'getInstalled', null, data => {\r\n if (timeout) {\r\n clearTimeout(timeout);\r\n timeout = null;\r\n if (data === PERMISSION_ERROR) {\r\n reject('May not read \"getInstalled\"');\r\n } else if (!data) {\r\n reject('Cannot read \"getInstalled\"');\r\n } else {\r\n resolve(data);\r\n }\r\n }\r\n });\r\n });\r\n\r\n return this._promises.installed[host];\r\n }\r\n\r\n /**\r\n * Execute a command on a host.\r\n * @param {string} host The host name.\r\n * @param {string} cmd The command.\r\n * @param {string} cmdId The command ID.\r\n * @param {number} cmdTimeout Timeout of command in ms\r\n * @returns {Promise}\r\n */\r\n cmdExec(host, cmd, cmdId, cmdTimeout) {\r\n if (Connection.isWeb()) {\r\n return Promise.reject('Allowed only in admin');\r\n }\r\n if (!this.connected) {\r\n return Promise.reject(NOT_CONNECTED);\r\n }\r\n\r\n if (!host.startsWith(host)) {\r\n host += 'system.host.' + host;\r\n }\r\n\r\n return new Promise((resolve, reject) => {\r\n let timeout = cmdTimeout && setTimeout(() => {\r\n if (timeout) {\r\n timeout = null;\r\n reject('cmdExec timeout');\r\n }\r\n }, cmdTimeout);\r\n\r\n this._socket.emit('cmdExec', host, cmdId, cmd, null, err => {\r\n if (!cmdTimeout || timeout) {\r\n timeout && clearTimeout(timeout);\r\n timeout = null;\r\n if (err) {\r\n reject(err);\r\n } else {\r\n resolve();\r\n }\r\n }\r\n });\r\n });\r\n }\r\n\r\n /**\r\n * Checks if a given feature is supported.\r\n * @param {string} feature The feature to check.\r\n * @param {boolean} [update] Force update.\r\n * @returns {Promise}\r\n */\r\n checkFeatureSupported(feature, update) {\r\n if (!update && this._promises['supportedFeatures_' + feature]) {\r\n return this._promises['supportedFeatures_' + feature];\r\n }\r\n\r\n if (!this.connected) {\r\n return Promise.reject(NOT_CONNECTED);\r\n }\r\n\r\n this._promises['supportedFeatures_' + feature] = new Promise((resolve, reject) =>\r\n this._socket.emit('checkFeatureSupported', feature, (err, features) => {\r\n err ? reject(err) : resolve(features)\r\n }));\r\n\r\n return this._promises['supportedFeatures_' + feature];\r\n }\r\n\r\n /**\r\n * Read the base settings of a given host.\r\n * @param {string} host\r\n * @returns {Promise}\r\n */\r\n readBaseSettings(host) {\r\n if (Connection.isWeb()) {\r\n return Promise.reject('Allowed only in admin');\r\n }\r\n return this.checkFeatureSupported('CONTROLLER_READWRITE_BASE_SETTINGS')\r\n .then(result => {\r\n if (result) {\r\n if (!this.connected) {\r\n return Promise.reject(NOT_CONNECTED);\r\n }\r\n return new Promise((resolve, reject) => {\r\n let timeout = setTimeout(() => {\r\n if (timeout) {\r\n timeout = null;\r\n reject('readBaseSettings timeout');\r\n }\r\n }, this.props.cmdTimeout);\r\n\r\n if (host.startsWith('system.host.')) {\r\n host = host.replace(/^system\\.host\\./, '');\r\n }\r\n\r\n this._socket.emit('sendToHost', host, 'readBaseSettings', null, data => {\r\n if (timeout) {\r\n clearTimeout(timeout);\r\n timeout = null;\r\n\r\n if (data === PERMISSION_ERROR) {\r\n reject('May not read \"BaseSettings\"');\r\n } else if (!data) {\r\n reject('Cannot read \"BaseSettings\"');\r\n } else {\r\n resolve(data);\r\n }\r\n }\r\n });\r\n });\r\n } else {\r\n return Promise.reject('Not supported');\r\n }\r\n });\r\n }\r\n\r\n /**\r\n * Write the base settings of a given host.\r\n * @param {string} host\r\n * @param {any} config\r\n * @returns {Promise}\r\n */\r\n writeBaseSettings(host, config) {\r\n if (Connection.isWeb()) {\r\n return Promise.reject('Allowed only in admin');\r\n }\r\n return this.checkFeatureSupported('CONTROLLER_READWRITE_BASE_SETTINGS')\r\n .then(result => {\r\n if (result) {\r\n if (!this.connected) {\r\n return Promise.reject(NOT_CONNECTED);\r\n }\r\n return new Promise((resolve, reject) => {\r\n let timeout = setTimeout(() => {\r\n if (timeout) {\r\n timeout = null;\r\n reject('writeBaseSettings timeout');\r\n }\r\n }, this.props.cmdTimeout);\r\n\r\n this._socket.emit('sendToHost', host, 'writeBaseSettings', config, data => {\r\n if (timeout) {\r\n clearTimeout(timeout);\r\n timeout = null;\r\n\r\n if (data === PERMISSION_ERROR) {\r\n reject('May not write \"BaseSettings\"');\r\n } else if (!data) {\r\n reject('Cannot write \"BaseSettings\"');\r\n } else {\r\n resolve(data);\r\n }\r\n }\r\n });\r\n });\r\n } else {\r\n return Promise.reject('Not supported');\r\n }\r\n })\r\n }\r\n\r\n /**\r\n * Send command to restart the iobroker on host\r\n * @param {string} host\r\n * @returns {Promise}\r\n */\r\n restartController(host) {\r\n if (Connection.isWeb()) {\r\n return Promise.reject('Allowed only in admin');\r\n }\r\n return new Promise((resolve, reject) => {\r\n this._socket.emit('sendToHost', host, 'restartController', null, error => {\r\n error ? reject(error) : resolve(true);\r\n });\r\n });\r\n }\r\n\r\n /**\r\n * Read statistics information from host\r\n * @param {string} host\r\n * @param {string} typeOfDiag one of none, normal, no-city, extended\r\n * @returns {Promise}\r\n */\r\n getDiagData(host, typeOfDiag) {\r\n if (Connection.isWeb()) {\r\n return Promise.reject('Allowed only in admin');\r\n }\r\n return new Promise(resolve => {\r\n this._socket.emit('sendToHost', host, 'getDiagData', typeOfDiag, result =>\r\n resolve(result));\r\n });\r\n }\r\n\r\n /**\r\n * Read all states (which might not belong to this adapter) which match the given pattern.\r\n * @param {string} pattern\r\n * @returns {ioBroker.GetStatesPromise}\r\n */\r\n getForeignStates(pattern) {\r\n if (!this.connected) {\r\n return Promise.reject(NOT_CONNECTED);\r\n }\r\n if (Connection.isWeb()) {\r\n return new Promise((resolve, reject) =>\r\n this._socket.emit('getStates', pattern || '*', (err, states) =>\r\n err ? reject(err) : resolve(states)));\r\n } else {\r\n return new Promise((resolve, reject) =>\r\n this._socket.emit('getForeignStates', pattern || '*', (err, states) =>\r\n err ? reject(err) : resolve(states)));\r\n }\r\n }\r\n\r\n /**\r\n * Get foreign objects by pattern, by specific type and resolve their enums.\r\n * @param {string} pattern\r\n * @param {string} [type]\r\n * @returns {ioBroker.GetObjectsPromise}\r\n */\r\n getForeignObjects(pattern, type) {\r\n if (!this.connected) {\r\n return Promise.reject(NOT_CONNECTED);\r\n }\r\n return new Promise((resolve, reject) =>\r\n this._socket.emit('getForeignObjects', pattern || '*', type, (err, states) =>\r\n err ? reject(err) : resolve(states)));\r\n }\r\n\r\n /**\r\n * Gets the system configuration.\r\n * @param {boolean} [update] Force update.\r\n * @returns {Promise}\r\n */\r\n getSystemConfig(update) {\r\n if (!update && this._promises.systemConfig) {\r\n return this._promises.systemConfig;\r\n }\r\n\r\n if (!this.connected) {\r\n return Promise.reject(NOT_CONNECTED);\r\n }\r\n\r\n this._promises.systemConfig = this.getObject('system.config')\r\n .then(systemConfig => {\r\n //@ts-ignore\r\n systemConfig = systemConfig || {};\r\n //@ts-ignore\r\n systemConfig.common = systemConfig.common || {};\r\n //@ts-ignore\r\n systemConfig.native = systemConfig.native || {};\r\n return systemConfig;\r\n });\r\n\r\n return this._promises.systemConfig;\r\n }\r\n\r\n /**\r\n * Sets the system configuration.\r\n * @param {ioBroker.SettableObjectWorker} obj\r\n * @returns {Promise>}\r\n */\r\n setSystemConfig(obj) {\r\n return this.setObject('system.config', obj)\r\n .then(() => this._promises.systemConfig = Promise.resolve(obj));\r\n }\r\n\r\n /**\r\n * Get the raw socket.io socket.\r\n * @returns {any}\r\n */\r\n getRawSocket() {\r\n return this._socket;\r\n }\r\n\r\n /**\r\n * Get the history of a given state.\r\n * @param {string} id\r\n * @param {ioBroker.GetHistoryOptions} options\r\n * @returns {Promise}\r\n */\r\n getHistory(id, options) {\r\n if (!this.connected) {\r\n return Promise.reject(NOT_CONNECTED);\r\n }\r\n\r\n return new Promise((resolve, reject) =>\r\n this._socket.emit('getHistory', id, options, (err, values) =>\r\n err ? reject(err) : resolve(values)));\r\n }\r\n\r\n /**\r\n * Get the history of a given state.\r\n * @param {string} id\r\n * @param {ioBroker.GetHistoryOptions} options\r\n * @returns {Promise<{values: ioBroker.GetHistoryResult; sesionId: string; stepIgnore: number}>}\r\n */\r\n getHistoryEx(id, options) {\r\n if (!this.connected) {\r\n return Promise.reject(NOT_CONNECTED);\r\n }\r\n\r\n return new Promise((resolve, reject) =>\r\n this._socket.emit('getHistory', id, options, (err, values, stepIgnore, sessionId) =>\r\n err ? reject(err) : resolve({ values, sessionId, stepIgnore })));\r\n }\r\n\r\n /**\r\n * Change the password of the given user.\r\n * @param {string} user\r\n * @param {string} password\r\n * @returns {Promise}\r\n */\r\n changePassword(user, password) {\r\n if (Connection.isWeb()) {\r\n return Promise.reject('Allowed only in admin');\r\n }\r\n return new Promise((resolve, reject) =>\r\n this._socket.emit('changePassword', user, password, err =>\r\n err ? reject(err) : resolve()));\r\n }\r\n\r\n /**\r\n * Get the IP addresses of the given host.\r\n * @param {string} host\r\n * @param {boolean} [update] Force update.\r\n * @returns {Promise}\r\n */\r\n getIpAddresses(host, update) {\r\n if (Connection.isWeb()) {\r\n return Promise.reject('Allowed only in admin');\r\n }\r\n if (!host.startsWith('system.host.')) {\r\n host = 'system.host.' + host;\r\n }\r\n\r\n if (!update && this._promises['IPs_' + host]) {\r\n return this._promises['IPs_' + host];\r\n }\r\n this._promises['IPs_' + host] = this.getObject(host)\r\n .then(obj => obj && obj.common ? obj.common.address || [] : []);\r\n\r\n return this._promises['IPs_' + host];\r\n }\r\n\r\n /**\r\n * Get the IP addresses with interface names of the given host or find host by IP.\r\n * @param {string} ipOrHostName\r\n * @param {boolean} [update] Force update.\r\n * @returns {Promise]>}\r\n */\r\n getHostByIp(ipOrHostName, update) {\r\n if (Connection.isWeb()) {\r\n return Promise.reject('Allowed only in admin');\r\n }\r\n if (ipOrHostName.startsWith('system.host.')) {\r\n ipOrHostName = ipOrHostName.replace(/^system\\.host\\./, '');\r\n }\r\n\r\n if (!update && this._promises['rIPs_' + ipOrHostName]) {\r\n return this._promises['rIPs_' + ipOrHostName];\r\n }\r\n this._promises['rIPs_' + ipOrHostName] = new Promise(resolve =>\r\n this._socket.emit('getHostByIp', ipOrHostName, (ip, host) => {\r\n const IPs4 = [{name: '[IPv4] 0.0.0.0 - Listen on all IPs', address: '0.0.0.0', family: 'ipv4'}];\r\n const IPs6 = [{name: '[IPv6] :: - Listen on all IPs', address: '::', family: 'ipv6'}];\r\n if (host?.native?.hardware?.networkInterfaces) {\r\n for (const eth in host.native.hardware.networkInterfaces) {\r\n if (!host.native.hardware.networkInterfaces.hasOwnProperty(eth)) {\r\n continue;\r\n }\r\n for (let num = 0; num < host.native.hardware.networkInterfaces[eth].length; num++) {\r\n if (host.native.hardware.networkInterfaces[eth][num].family !== 'IPv6') {\r\n IPs4.push({name: `[${host.native.hardware.networkInterfaces[eth][num].family}] ${host.native.hardware.networkInterfaces[eth][num].address} - ${eth}`, address: host.native.hardware.networkInterfaces[eth][num].address, family: 'ipv4'});\r\n } else {\r\n IPs6.push({name: `[${host.native.hardware.networkInterfaces[eth][num].family}] ${host.native.hardware.networkInterfaces[eth][num].address} - ${eth}`, address: host.native.hardware.networkInterfaces[eth][num].address, family: 'ipv6'});\r\n }\r\n }\r\n }\r\n }\r\n for (let i = 0; i < IPs6.length; i++) {\r\n IPs4.push(IPs6[i]);\r\n }\r\n resolve(IPs4);\r\n }));\r\n\r\n return this._promises['rIPs_' + ipOrHostName];\r\n }\r\n\r\n /**\r\n * Encrypt a text\r\n * @param {string} text\r\n * @returns {Promise}\r\n */\r\n encrypt(text) {\r\n if (Connection.isWeb()) {\r\n return Promise.reject('Allowed only in admin');\r\n }\r\n return new Promise((resolve, reject) =>\r\n this._socket.emit('encrypt', text, (err, text) =>\r\n err ? reject(err) : resolve(text)));\r\n }\r\n\r\n /**\r\n * Decrypt a text\r\n * @param {string} encryptedText\r\n * @returns {Promise}\r\n */\r\n decrypt(encryptedText) {\r\n if (Connection.isWeb()) {\r\n return Promise.reject('Allowed only in admin');\r\n }\r\n return new Promise((resolve, reject) =>\r\n this._socket.emit('decrypt', encryptedText, (err, text) =>\r\n err ? reject(err) : resolve(text)));\r\n }\r\n\r\n /**\r\n * Gets the version.\r\n * @returns {Promise<{version: string; serverName: string}>}\r\n */\r\n getVersion(update) {\r\n if (update && this._promises.version) {\r\n this._promises.version = null;\r\n }\r\n\r\n this._promises.version = this._promises.version || new Promise((resolve, reject) =>\r\n this._socket.emit('getVersion', (err, version, serverName) => {\r\n // support of old socket.io\r\n if (err && !version && typeof err === 'string' && err.match(/\\d+\\.\\d+\\.\\d+/)) {\r\n resolve({ version: err, serverName: 'socketio' });\r\n } else {\r\n return err ? reject(err) : resolve({ version, serverName });\r\n }\r\n }));\r\n\r\n return this._promises.version;\r\n }\r\n\r\n /**\r\n * Gets the web server name.\r\n * @returns {Promise}\r\n */\r\n getWebServerName() {\r\n this._promises.webName = this._promises.webName || new Promise((resolve, reject) =>\r\n this._socket.emit('getAdapterName', (err, name) =>\r\n err ? reject(err) : resolve(name)));\r\n\r\n return this._promises.webName;\r\n }\r\n\r\n /**\r\n * Gets the admin version.\r\n * @deprecated use getVersion()\r\n * @returns {Promise<{version: string; serverName: string}>}\r\n */\r\n getAdminVersion() {\r\n console.log('Deprecated: use getVersion');\r\n return this.getVersion();\r\n }\r\n\r\n /**\r\n * Change access rights for file\r\n * @param {string} [adapter] adapter name\r\n * @param {string} [filename] file name with full path. it could be like vis.0/*\r\n * @param {object} [options] like {mode: 0x644}\r\n * @returns {Promise<{entries: array}>}\r\n */\r\n chmodFile(adapter, filename, options) {\r\n if (Connection.isWeb()) {\r\n return Promise.reject('Allowed only in admin');\r\n }\r\n if (!this.connected) {\r\n return Promise.reject(NOT_CONNECTED);\r\n }\r\n\r\n return new Promise((resolve, reject) =>\r\n this._socket.emit('chmodFile', adapter, filename, options, (err, entries, id) =>\r\n err ? reject(err) : resolve({entries, id})));\r\n }\r\n\r\n /**\r\n * Change owner or/and owner group for file\r\n * @param {string} [adapter] adapter name\r\n * @param {string} [filename] file name with full path. it could be like vis.0/*\r\n * @param {object} [options] like {owner: 'newOwner', ownerGroup: 'newGroup'}\r\n * @returns {Promise<{entries: array}>}\r\n */\r\n chownFile(adapter, filename, options) {\r\n if (Connection.isWeb()) {\r\n return Promise.reject('Allowed only in admin');\r\n }\r\n if (!this.connected) {\r\n return Promise.reject(NOT_CONNECTED);\r\n }\r\n\r\n return new Promise((resolve, reject) =>\r\n this._socket.emit('chownFile', adapter, filename, options, (err, entries, id) =>\r\n err ? reject(err) : resolve({entries, id})));\r\n }\r\n\r\n /**\r\n * Check if the file exists\r\n * @param {string} [adapter] adapter name\r\n * @param {string} [filename] file name with full path. it could be like vis.0/*\r\n * @returns {Promise}\r\n */\r\n fileExists(adapter, filename) {\r\n if (!this.connected) {\r\n return Promise.reject(NOT_CONNECTED);\r\n }\r\n\r\n return new Promise((resolve, reject) =>\r\n this._socket.emit('fileExists', adapter, filename, (err, exists) =>\r\n err ? reject(err) : resolve(exists)));\r\n }\r\n\r\n /**\r\n * Get the alarm notifications from a host (only for admin connection).\r\n * @param {string} host\r\n * @param {string} [category] - optional\r\n * @returns {Promise}\r\n */\r\n getNotifications(host, category) {\r\n if (Connection.isWeb()) {\r\n return Promise.reject('Allowed only in admin');\r\n }\r\n\r\n if (!this.connected) {\r\n return Promise.reject(NOT_CONNECTED);\r\n }\r\n return new Promise(resolve =>\r\n this._socket.emit('sendToHost', host, 'getNotifications', {category}, notifications =>\r\n resolve(notifications)));\r\n }\r\n\r\n /**\r\n * Clear the alarm notifications on a host (only for admin connection).\r\n * @param {string} host\r\n * @param {string} [category] - optional\r\n * @returns {Promise}\r\n */\r\n clearNotifications(host, category) {\r\n if (Connection.isWeb()) {\r\n return Promise.reject('Allowed only in admin');\r\n }\r\n\r\n if (!this.connected) {\r\n return Promise.reject(NOT_CONNECTED);\r\n }\r\n return new Promise(resolve =>\r\n this._socket.emit('sendToHost', host, 'clearNotifications', {category}, notifications =>\r\n resolve(notifications)));\r\n }\r\n\r\n /**\r\n * Read if only easy mode is allowed (only for admin connection).\r\n * @returns {Promise}\r\n */\r\n getIsEasyModeStrict() {\r\n if (Connection.isWeb()) {\r\n return Promise.reject('Allowed only in admin');\r\n }\r\n if (!this.connected) {\r\n return Promise.reject(NOT_CONNECTED);\r\n }\r\n return new Promise((resolve, reject) =>\r\n this._socket.emit('getIsEasyModeStrict', (error, isStrict) =>\r\n error ? reject(error) : resolve(isStrict)));\r\n }\r\n\r\n /**\r\n * Read easy mode configuration (only for admin connection).\r\n * @returns {Promise}\r\n */\r\n getEasyMode() {\r\n if (Connection.isWeb()) {\r\n return Promise.reject('Allowed only in admin');\r\n }\r\n if (!this.connected) {\r\n return Promise.reject(NOT_CONNECTED);\r\n }\r\n return new Promise((resolve, reject) =>\r\n this._socket.emit('getEasyMode', (error, config) =>\r\n error ? reject(error) : resolve(config)));\r\n }\r\n\r\n /**\r\n * Read current user\r\n * @returns {Promise}\r\n */\r\n getCurrentUser() {\r\n if (!this.connected) {\r\n return Promise.reject(NOT_CONNECTED);\r\n }\r\n\r\n return new Promise(resolve =>\r\n this._socket.emit('authEnabled', (isSecure, user) =>\r\n resolve(user)));\r\n }\r\n\r\n getCurrentSession(cmdTimeout) {\r\n if (!this.connected) {\r\n return Promise.reject(NOT_CONNECTED);\r\n }\r\n\r\n return new Promise((resolve, reject) => {\r\n const controller = new AbortController();\r\n\r\n let timeout = setTimeout(() => {\r\n if (timeout) {\r\n timeout = null;\r\n controller.abort();\r\n reject('getCurrentSession timeout');\r\n }\r\n }, cmdTimeout || 5000);\r\n\r\n return fetch('./session', { signal: controller.signal })\r\n .then(res => res.json())\r\n .then(json => {\r\n if (timeout) {\r\n clearTimeout(timeout);\r\n timeout = null;\r\n resolve(json);\r\n }\r\n })\r\n .catch(e =>\r\n reject('getCurrentSession: ' + e));\r\n });\r\n }\r\n\r\n /**\r\n * Read adapter ratings\r\n * @returns {Promise}\r\n */\r\n getRatings(update) {\r\n if (Connection.isWeb()) {\r\n return Promise.reject('Allowed only in admin');\r\n }\r\n if (!this.connected) {\r\n return Promise.reject(NOT_CONNECTED);\r\n }\r\n return new Promise((resolve, reject) =>\r\n this._socket.emit('getRatings', update, (err, ratings) =>\r\n err ? reject(err) : resolve(ratings)));\r\n }\r\n\r\n /**\r\n * Read current web, socketio or admin namespace, like admin.0\r\n * @returns {Promise}\r\n */\r\n getCurrentInstance() {\r\n if (!this.connected) {\r\n return Promise.reject(NOT_CONNECTED);\r\n }\r\n\r\n this._promises.currentInstance = this._promises.currentInstance ||\r\n new Promise((resolve, reject) =>\r\n this._socket.emit('getCurrentInstance', (err, namespace) =>\r\n err ? reject(err) : resolve(namespace)));\r\n\r\n return this._promises.currentInstance;\r\n }\r\n\r\n // returns very optimized information for adapters to minimize connection load\r\n getCompactAdapters(update) {\r\n if (Connection.isWeb()) {\r\n return Promise.reject('Allowed only in admin');\r\n }\r\n if (!update && this._promises.compactAdapters) {\r\n return this._promises.compactAdapters;\r\n }\r\n if (!this.connected) {\r\n return Promise.reject(NOT_CONNECTED);\r\n }\r\n this._promises.compactAdapters = new Promise((resolve, reject) =>\r\n this._socket.emit('getCompactAdapters', (err, adapters) =>\r\n err ? reject(err) : resolve(adapters)));\r\n\r\n return this._promises.compactAdapters;\r\n }\r\n\r\n // returns very optimized information for adapters to minimize connection load\r\n getCompactInstances(update) {\r\n if (Connection.isWeb()) {\r\n return Promise.reject('Allowed only in admin');\r\n }\r\n if (!update && this._promises.compactInstances) {\r\n return this._promises.compactInstances;\r\n }\r\n if (!this.connected) {\r\n return Promise.reject(NOT_CONNECTED);\r\n }\r\n\r\n this._promises.compactInstances = new Promise((resolve, reject) =>\r\n this._socket.emit('getCompactInstances', (err, instances) =>\r\n err ? reject(err) : resolve(instances)));\r\n\r\n return this._promises.compactInstances;\r\n }\r\n\r\n // returns very optimized information for adapters to minimize connection load\r\n // reads only version of installed adapter\r\n getCompactInstalled(host, update, cmdTimeout) {\r\n if (Connection.isWeb()) {\r\n return Promise.reject('Allowed only in admin');\r\n }\r\n\r\n this._promises.installedCompact = this._promises.installedCompact || {};\r\n\r\n if (!update && this._promises.installedCompact[host]) {\r\n return this._promises.installedCompact[host];\r\n }\r\n\r\n if (!this.connected) {\r\n return Promise.reject(NOT_CONNECTED);\r\n }\r\n\r\n if (!host.startsWith('system.host.')) {\r\n host += 'system.host.' + host;\r\n }\r\n\r\n this._promises.installedCompact[host] = new Promise((resolve, reject) => {\r\n let timeout = setTimeout(() => {\r\n if (timeout) {\r\n timeout = null;\r\n reject('getCompactInstalled timeout');\r\n }\r\n }, cmdTimeout || this.props.cmdTimeout);\r\n\r\n this._socket.emit('getCompactInstalled', host, data => {\r\n if (timeout) {\r\n clearTimeout(timeout);\r\n timeout = null;\r\n if (data === PERMISSION_ERROR) {\r\n reject('May not read \"getCompactInstalled\"');\r\n } else if (!data) {\r\n reject('Cannot read \"getCompactInstalled\"');\r\n } else {\r\n resolve(data);\r\n }\r\n }\r\n });\r\n });\r\n\r\n return this._promises.installedCompact[host];\r\n }\r\n\r\n // returns very optimized information for adapters to minimize connection load\r\n getCompactSystemConfig(update) {\r\n if (!update && this._promises.systemConfigCommon) {\r\n return this._promises.systemConfigCommon;\r\n }\r\n\r\n if (!this.connected) {\r\n return Promise.reject(NOT_CONNECTED);\r\n }\r\n\r\n this._promises.systemConfigCommon = new Promise((resolve, reject) =>\r\n this._socket.emit('getCompactSystemConfig', (err, systemConfig) =>\r\n err ? reject(err) : resolve(systemConfig)));\r\n\r\n return this._promises.systemConfigCommon;\r\n }\r\n\r\n /**\r\n * Get the repository in compact form (only version and icon).\r\n * @param {string} host\r\n * @param {boolean} [update] Force update.\r\n * @param {number} [timeoutMs] timeout in ms.\r\n * @returns {Promise}\r\n */\r\n getCompactRepository(host, update, timeoutMs) {\r\n if (Connection.isWeb()) {\r\n return Promise.reject('Allowed only in admin');\r\n }\r\n if (!update && this._promises.repoCompact) {\r\n return this._promises.repoCompact;\r\n }\r\n\r\n if (!this.connected) {\r\n return Promise.reject(NOT_CONNECTED);\r\n }\r\n\r\n if (!host.startsWith('system.host.')) {\r\n host += 'system.host.' + host;\r\n }\r\n\r\n this._promises.repoCompact = new Promise((resolve, reject) => {\r\n let timeout = setTimeout(() => {\r\n if (timeout) {\r\n timeout = null;\r\n reject('getCompactRepository timeout');\r\n }\r\n }, timeoutMs || this.props.cmdTimeout);\r\n\r\n this._socket.emit('getCompactRepository', host, data => {\r\n if (timeout) {\r\n clearTimeout(timeout);\r\n timeout = null;\r\n if (data === PERMISSION_ERROR) {\r\n reject('May not read \"getCompactRepository\"');\r\n } else if (!data) {\r\n reject('Cannot read \"getCompactRepository\"');\r\n } else {\r\n resolve(data);\r\n }\r\n }\r\n });\r\n });\r\n\r\n return this._promises.repoCompact;\r\n }\r\n\r\n /**\r\n * Get the list of all hosts in compact form (only _id, common.name, common.icon, common.color, native.hardware.networkInterfaces)\r\n * @param {boolean} [update] Force update.\r\n * @returns {Promise}\r\n */\r\n getCompactHosts(update) {\r\n if (Connection.isWeb()) {\r\n return Promise.reject('Allowed only in admin');\r\n }\r\n if (!update && this._promises.hostsCompact) {\r\n return this._promises.hostsCompact;\r\n }\r\n\r\n if (!this.connected) {\r\n return Promise.reject(NOT_CONNECTED);\r\n }\r\n\r\n this._promises.hostsCompact = new Promise((resolve, reject) =>\r\n this._socket.emit('getCompactHosts', (err, hosts) =>\r\n err ? reject(err) : resolve(hosts)));\r\n\r\n return this._promises.hostsCompact;\r\n }\r\n\r\n /**\r\n * Get uuid\r\n * @returns {Promise}\r\n */\r\n getUuid() {\r\n if (this._promises.uuid) {\r\n return this._promises.uuid;\r\n }\r\n\r\n if (!this.connected) {\r\n return Promise.reject(NOT_CONNECTED);\r\n }\r\n\r\n this._promises.uuid = this.getObject('system.meta.uuid')\r\n //@ts-ignore\r\n .then(obj => obj?.native?.uuid);\r\n\r\n return this._promises.uuid;\r\n }\r\n\r\n /**\r\n * Send log to ioBroker log\r\n * @param {string} [text] Log text\r\n * @param {string} [level] `info`, `debug`, `warn`, `error` or `silly`\r\n * @returns {void}\r\n */\r\n log(text, level) {\r\n text && this._socket.emit('log', text, level || 'debug');\r\n }\r\n\r\n /**\r\n * Logout current user\r\n * @returns {Promise}\r\n */\r\n logout() {\r\n if (!this.connected) {\r\n return Promise.reject(NOT_CONNECTED);\r\n }\r\n\r\n return new Promise((resolve, reject) =>\r\n this._socket.emit('logout', err =>\r\n err ? reject(err) : resolve(null)));\r\n }\r\n}\r\n\r\nConnection.Connection = {\r\n onLog: PropTypes.func,\r\n onReady: PropTypes.func,\r\n onProgress: PropTypes.func,\r\n};\r\n\r\nexport default Connection;\r\n", "/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/explicit-module-boundary-types */\n\nimport type { ParameterizedString, PolymorphicEvent, Primitive } from '@sentry/types';\n\n// eslint-disable-next-line @typescript-eslint/unbound-method\nconst objectToString = Object.prototype.toString;\n\n/**\n * Checks whether given value's type is one of a few Error or Error-like\n * {@link isError}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isError(wat: unknown): wat is Error {\n switch (objectToString.call(wat)) {\n case '[object Error]':\n case '[object Exception]':\n case '[object DOMException]':\n return true;\n default:\n return isInstanceOf(wat, Error);\n }\n}\n/**\n * Checks whether given value is an instance of the given built-in class.\n *\n * @param wat The value to be checked\n * @param className\n * @returns A boolean representing the result.\n */\nfunction isBuiltin(wat: unknown, className: string): boolean {\n return objectToString.call(wat) === `[object ${className}]`;\n}\n\n/**\n * Checks whether given value's type is ErrorEvent\n * {@link isErrorEvent}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isErrorEvent(wat: unknown): boolean {\n return isBuiltin(wat, 'ErrorEvent');\n}\n\n/**\n * Checks whether given value's type is DOMError\n * {@link isDOMError}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isDOMError(wat: unknown): boolean {\n return isBuiltin(wat, 'DOMError');\n}\n\n/**\n * Checks whether given value's type is DOMException\n * {@link isDOMException}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isDOMException(wat: unknown): boolean {\n return isBuiltin(wat, 'DOMException');\n}\n\n/**\n * Checks whether given value's type is a string\n * {@link isString}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isString(wat: unknown): wat is string {\n return isBuiltin(wat, 'String');\n}\n\n/**\n * Checks whether given string is parameterized\n * {@link isParameterizedString}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isParameterizedString(wat: unknown): wat is ParameterizedString {\n return (\n typeof wat === 'object' &&\n wat !== null &&\n '__sentry_template_string__' in wat &&\n '__sentry_template_values__' in wat\n );\n}\n\n/**\n * Checks whether given value is a primitive (undefined, null, number, boolean, string, bigint, symbol)\n * {@link isPrimitive}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isPrimitive(wat: unknown): wat is Primitive {\n return wat === null || isParameterizedString(wat) || (typeof wat !== 'object' && typeof wat !== 'function');\n}\n\n/**\n * Checks whether given value's type is an object literal, or a class instance.\n * {@link isPlainObject}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isPlainObject(wat: unknown): wat is Record {\n return isBuiltin(wat, 'Object');\n}\n\n/**\n * Checks whether given value's type is an Event instance\n * {@link isEvent}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isEvent(wat: unknown): wat is PolymorphicEvent {\n return typeof Event !== 'undefined' && isInstanceOf(wat, Event);\n}\n\n/**\n * Checks whether given value's type is an Element instance\n * {@link isElement}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isElement(wat: unknown): boolean {\n return typeof Element !== 'undefined' && isInstanceOf(wat, Element);\n}\n\n/**\n * Checks whether given value's type is an regexp\n * {@link isRegExp}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isRegExp(wat: unknown): wat is RegExp {\n return isBuiltin(wat, 'RegExp');\n}\n\n/**\n * Checks whether given value has a then function.\n * @param wat A value to be checked.\n */\nexport function isThenable(wat: any): wat is PromiseLike {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return Boolean(wat && wat.then && typeof wat.then === 'function');\n}\n\n/**\n * Checks whether given value's type is a SyntheticEvent\n * {@link isSyntheticEvent}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isSyntheticEvent(wat: unknown): boolean {\n return isPlainObject(wat) && 'nativeEvent' in wat && 'preventDefault' in wat && 'stopPropagation' in wat;\n}\n\n/**\n * Checks whether given value is NaN\n * {@link isNaN}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isNaN(wat: unknown): boolean {\n return typeof wat === 'number' && wat !== wat;\n}\n\n/**\n * Checks whether given value's type is an instance of provided constructor.\n * {@link isInstanceOf}.\n *\n * @param wat A value to be checked.\n * @param base A constructor to be used in a check.\n * @returns A boolean representing the result.\n */\nexport function isInstanceOf(wat: any, base: any): boolean {\n try {\n return wat instanceof base;\n } catch (_e) {\n return false;\n }\n}\n\ninterface VueViewModel {\n // Vue3\n __isVue?: boolean;\n // Vue2\n _isVue?: boolean;\n}\n/**\n * Checks whether given value's type is a Vue ViewModel.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isVueViewModel(wat: unknown): boolean {\n // Not using Object.prototype.toString because in Vue 3 it would read the instance's Symbol(Symbol.toStringTag) property.\n return !!(typeof wat === 'object' && wat !== null && ((wat as VueViewModel).__isVue || (wat as VueViewModel)._isVue));\n}\n", "import { isRegExp, isString, isVueViewModel } from './is';\n\nexport { escapeStringForRegex } from './vendor/escapeStringForRegex';\n\n/**\n * Truncates given string to the maximum characters count\n *\n * @param str An object that contains serializable values\n * @param max Maximum number of characters in truncated string (0 = unlimited)\n * @returns string Encoded\n */\nexport function truncate(str: string, max: number = 0): string {\n if (typeof str !== 'string' || max === 0) {\n return str;\n }\n return str.length <= max ? str : `${str.slice(0, max)}...`;\n}\n\n/**\n * This is basically just `trim_line` from\n * https://github.com/getsentry/sentry/blob/master/src/sentry/lang/javascript/processor.py#L67\n *\n * @param str An object that contains serializable values\n * @param max Maximum number of characters in truncated string\n * @returns string Encoded\n */\nexport function snipLine(line: string, colno: number): string {\n let newLine = line;\n const lineLength = newLine.length;\n if (lineLength <= 150) {\n return newLine;\n }\n if (colno > lineLength) {\n // eslint-disable-next-line no-param-reassign\n colno = lineLength;\n }\n\n let start = Math.max(colno - 60, 0);\n if (start < 5) {\n start = 0;\n }\n\n let end = Math.min(start + 140, lineLength);\n if (end > lineLength - 5) {\n end = lineLength;\n }\n if (end === lineLength) {\n start = Math.max(end - 140, 0);\n }\n\n newLine = newLine.slice(start, end);\n if (start > 0) {\n newLine = `'{snip} ${newLine}`;\n }\n if (end < lineLength) {\n newLine += ' {snip}';\n }\n\n return newLine;\n}\n\n/**\n * Join values in array\n * @param input array of values to be joined together\n * @param delimiter string to be placed in-between values\n * @returns Joined values\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function safeJoin(input: any[], delimiter?: string): string {\n if (!Array.isArray(input)) {\n return '';\n }\n\n const output = [];\n // eslint-disable-next-line @typescript-eslint/prefer-for-of\n for (let i = 0; i < input.length; i++) {\n const value = input[i];\n try {\n // This is a hack to fix a Vue3-specific bug that causes an infinite loop of\n // console warnings. This happens when a Vue template is rendered with\n // an undeclared variable, which we try to stringify, ultimately causing\n // Vue to issue another warning which repeats indefinitely.\n // see: https://github.com/getsentry/sentry-javascript/pull/8981\n if (isVueViewModel(value)) {\n output.push('[VueViewModel]');\n } else {\n output.push(String(value));\n }\n } catch (e) {\n output.push('[value cannot be serialized]');\n }\n }\n\n return output.join(delimiter);\n}\n\n/**\n * Checks if the given value matches a regex or string\n *\n * @param value The string to test\n * @param pattern Either a regex or a string against which `value` will be matched\n * @param requireExactStringMatch If true, `value` must match `pattern` exactly. If false, `value` will match\n * `pattern` if it contains `pattern`. Only applies to string-type patterns.\n */\nexport function isMatchingPattern(\n value: string,\n pattern: RegExp | string,\n requireExactStringMatch: boolean = false,\n): boolean {\n if (!isString(value)) {\n return false;\n }\n\n if (isRegExp(pattern)) {\n return pattern.test(value);\n }\n if (isString(pattern)) {\n return requireExactStringMatch ? value === pattern : value.includes(pattern);\n }\n\n return false;\n}\n\n/**\n * Test the given string against an array of strings and regexes. By default, string matching is done on a\n * substring-inclusion basis rather than a strict equality basis\n *\n * @param testString The string to test\n * @param patterns The patterns against which to test the string\n * @param requireExactStringMatch If true, `testString` must match one of the given string patterns exactly in order to\n * count. If false, `testString` will match a string pattern if it contains that pattern.\n * @returns\n */\nexport function stringMatchesSomePattern(\n testString: string,\n patterns: Array = [],\n requireExactStringMatch: boolean = false,\n): boolean {\n return patterns.some(pattern => isMatchingPattern(testString, pattern, requireExactStringMatch));\n}\n", "import type { Event, EventHint, Exception, ExtendedError, StackParser } from '@sentry/types';\n\nimport { isInstanceOf } from './is';\nimport { truncate } from './string';\n\n/**\n * Creates exceptions inside `event.exception.values` for errors that are nested on properties based on the `key` parameter.\n */\nexport function applyAggregateErrorsToEvent(\n exceptionFromErrorImplementation: (stackParser: StackParser, ex: Error) => Exception,\n parser: StackParser,\n maxValueLimit: number = 250,\n key: string,\n limit: number,\n event: Event,\n hint?: EventHint,\n): void {\n if (!event.exception || !event.exception.values || !hint || !isInstanceOf(hint.originalException, Error)) {\n return;\n }\n\n // Generally speaking the last item in `event.exception.values` is the exception originating from the original Error\n const originalException: Exception | undefined =\n event.exception.values.length > 0 ? event.exception.values[event.exception.values.length - 1] : undefined;\n\n // We only create exception grouping if there is an exception in the event.\n if (originalException) {\n event.exception.values = truncateAggregateExceptions(\n aggregateExceptionsFromError(\n exceptionFromErrorImplementation,\n parser,\n limit,\n hint.originalException as ExtendedError,\n key,\n event.exception.values,\n originalException,\n 0,\n ),\n maxValueLimit,\n );\n }\n}\n\nfunction aggregateExceptionsFromError(\n exceptionFromErrorImplementation: (stackParser: StackParser, ex: Error) => Exception,\n parser: StackParser,\n limit: number,\n error: ExtendedError,\n key: string,\n prevExceptions: Exception[],\n exception: Exception,\n exceptionId: number,\n): Exception[] {\n if (prevExceptions.length >= limit + 1) {\n return prevExceptions;\n }\n\n let newExceptions = [...prevExceptions];\n\n // Recursively call this function in order to walk down a chain of errors\n if (isInstanceOf(error[key], Error)) {\n applyExceptionGroupFieldsForParentException(exception, exceptionId);\n const newException = exceptionFromErrorImplementation(parser, error[key]);\n const newExceptionId = newExceptions.length;\n applyExceptionGroupFieldsForChildException(newException, key, newExceptionId, exceptionId);\n newExceptions = aggregateExceptionsFromError(\n exceptionFromErrorImplementation,\n parser,\n limit,\n error[key],\n key,\n [newException, ...newExceptions],\n newException,\n newExceptionId,\n );\n }\n\n // This will create exception grouping for AggregateErrors\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AggregateError\n if (Array.isArray(error.errors)) {\n error.errors.forEach((childError, i) => {\n if (isInstanceOf(childError, Error)) {\n applyExceptionGroupFieldsForParentException(exception, exceptionId);\n const newException = exceptionFromErrorImplementation(parser, childError);\n const newExceptionId = newExceptions.length;\n applyExceptionGroupFieldsForChildException(newException, `errors[${i}]`, newExceptionId, exceptionId);\n newExceptions = aggregateExceptionsFromError(\n exceptionFromErrorImplementation,\n parser,\n limit,\n childError,\n key,\n [newException, ...newExceptions],\n newException,\n newExceptionId,\n );\n }\n });\n }\n\n return newExceptions;\n}\n\nfunction applyExceptionGroupFieldsForParentException(exception: Exception, exceptionId: number): void {\n // Don't know if this default makes sense. The protocol requires us to set these values so we pick *some* default.\n exception.mechanism = exception.mechanism || { type: 'generic', handled: true };\n\n exception.mechanism = {\n ...exception.mechanism,\n ...(exception.type === 'AggregateError' && { is_exception_group: true }),\n exception_id: exceptionId,\n };\n}\n\nfunction applyExceptionGroupFieldsForChildException(\n exception: Exception,\n source: string,\n exceptionId: number,\n parentId: number | undefined,\n): void {\n // Don't know if this default makes sense. The protocol requires us to set these values so we pick *some* default.\n exception.mechanism = exception.mechanism || { type: 'generic', handled: true };\n\n exception.mechanism = {\n ...exception.mechanism,\n type: 'chained',\n source,\n exception_id: exceptionId,\n parent_id: parentId,\n };\n}\n\n/**\n * Truncate the message (exception.value) of all exceptions in the event.\n * Because this event processor is ran after `applyClientOptions`,\n * we need to truncate the message of the added exceptions here.\n */\nfunction truncateAggregateExceptions(exceptions: Exception[], maxValueLength: number): Exception[] {\n return exceptions.map(exception => {\n if (exception.value) {\n exception.value = truncate(exception.value, maxValueLength);\n }\n return exception;\n });\n}\n", "/**\n * NOTE: In order to avoid circular dependencies, if you add a function to this module and it needs to print something,\n * you must either a) use `console.log` rather than the logger, or b) put your function elsewhere.\n *\n * Note: This file was originally called `global.ts`, but was changed to unblock users which might be doing\n * string replaces with bundlers like Vite for `global` (would break imports that rely on importing from utils/src/global).\n *\n * Why worldwide?\n *\n * Why not?\n */\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\nimport type { Integration } from '@sentry/types';\n\nimport type { SdkSource } from './env';\n\n/** Internal global with common properties and Sentry extensions */\nexport interface InternalGlobal {\n navigator?: { userAgent?: string };\n console: Console;\n Sentry?: {\n Integrations?: Integration[];\n };\n onerror?: {\n (event: object | string, source?: string, lineno?: number, colno?: number, error?: Error): any;\n __SENTRY_INSTRUMENTED__?: true;\n __SENTRY_LOADER__?: true;\n };\n onunhandledrejection?: {\n (event: unknown): boolean;\n __SENTRY_INSTRUMENTED__?: true;\n __SENTRY_LOADER__?: true;\n };\n SENTRY_ENVIRONMENT?: string;\n SENTRY_DSN?: string;\n SENTRY_RELEASE?: {\n id?: string;\n };\n SENTRY_SDK_SOURCE?: SdkSource;\n /**\n * Debug IDs are indirectly injected by Sentry CLI or bundler plugins to directly reference a particular source map\n * for resolving of a source file. The injected code will place an entry into the record for each loaded bundle/JS\n * file.\n */\n _sentryDebugIds?: Record;\n __SENTRY__: {\n globalEventProcessors: any;\n hub: any;\n logger: any;\n extensions?: {\n /** Extension methods for the hub, which are bound to the current Hub instance */\n // eslint-disable-next-line @typescript-eslint/ban-types\n [key: string]: Function;\n };\n };\n /**\n * Raw module metadata that is injected by bundler plugins.\n *\n * Keys are `error.stack` strings, values are the metadata.\n */\n _sentryModuleMetadata?: Record;\n}\n\n// The code below for 'isGlobalObj' and 'GLOBAL_OBJ' was copied from core-js before modification\n// https://github.com/zloirock/core-js/blob/1b944df55282cdc99c90db5f49eb0b6eda2cc0a3/packages/core-js/internals/global.js\n// core-js has the following licence:\n//\n// Copyright (c) 2014-2022 Denis Pushkarev\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\n/** Returns 'obj' if it's the global object, otherwise returns undefined */\nfunction isGlobalObj(obj: { Math?: Math }): any | undefined {\n return obj && obj.Math == Math ? obj : undefined;\n}\n\n/** Get's the global object for the current JavaScript runtime */\nexport const GLOBAL_OBJ: InternalGlobal =\n (typeof globalThis == 'object' && isGlobalObj(globalThis)) ||\n // eslint-disable-next-line no-restricted-globals\n (typeof window == 'object' && isGlobalObj(window)) ||\n (typeof self == 'object' && isGlobalObj(self)) ||\n (typeof global == 'object' && isGlobalObj(global)) ||\n (function (this: any) {\n return this;\n })() ||\n {};\n\n/**\n * @deprecated Use GLOBAL_OBJ instead or WINDOW from @sentry/browser. This will be removed in v8\n */\nexport function getGlobalObject(): T & InternalGlobal {\n return GLOBAL_OBJ as T & InternalGlobal;\n}\n\n/**\n * Returns a global singleton contained in the global `__SENTRY__` object.\n *\n * If the singleton doesn't already exist in `__SENTRY__`, it will be created using the given factory\n * function and added to the `__SENTRY__` object.\n *\n * @param name name of the global singleton on __SENTRY__\n * @param creator creator Factory function to create the singleton if it doesn't already exist on `__SENTRY__`\n * @param obj (Optional) The global object on which to look for `__SENTRY__`, if not `GLOBAL_OBJ`'s return value\n * @returns the singleton\n */\nexport function getGlobalSingleton(name: keyof InternalGlobal['__SENTRY__'], creator: () => T, obj?: unknown): T {\n const gbl = (obj || GLOBAL_OBJ) as InternalGlobal;\n const __SENTRY__ = (gbl.__SENTRY__ = gbl.__SENTRY__ || {});\n const singleton = __SENTRY__[name] || (__SENTRY__[name] = creator());\n return singleton;\n}\n", "import { isString } from './is';\nimport { getGlobalObject } from './worldwide';\n\n// eslint-disable-next-line deprecation/deprecation\nconst WINDOW = getGlobalObject();\n\nconst DEFAULT_MAX_STRING_LENGTH = 80;\n\ntype SimpleNode = {\n parentNode: SimpleNode;\n} | null;\n\n/**\n * Given a child DOM element, returns a query-selector statement describing that\n * and its ancestors\n * e.g. [HTMLElement] => body > div > input#foo.btn[name=baz]\n * @returns generated DOM path\n */\nexport function htmlTreeAsString(\n elem: unknown,\n options: string[] | { keyAttrs?: string[]; maxStringLength?: number } = {},\n): string {\n if (!elem) {\n return '';\n }\n\n // try/catch both:\n // - accessing event.target (see getsentry/raven-js#838, #768)\n // - `htmlTreeAsString` because it's complex, and just accessing the DOM incorrectly\n // - can throw an exception in some circumstances.\n try {\n let currentElem = elem as SimpleNode;\n const MAX_TRAVERSE_HEIGHT = 5;\n const out = [];\n let height = 0;\n let len = 0;\n const separator = ' > ';\n const sepLength = separator.length;\n let nextStr;\n const keyAttrs = Array.isArray(options) ? options : options.keyAttrs;\n const maxStringLength = (!Array.isArray(options) && options.maxStringLength) || DEFAULT_MAX_STRING_LENGTH;\n\n while (currentElem && height++ < MAX_TRAVERSE_HEIGHT) {\n nextStr = _htmlElementAsString(currentElem, keyAttrs);\n // bail out if\n // - nextStr is the 'html' element\n // - the length of the string that would be created exceeds maxStringLength\n // (ignore this limit if we are on the first iteration)\n if (nextStr === 'html' || (height > 1 && len + out.length * sepLength + nextStr.length >= maxStringLength)) {\n break;\n }\n\n out.push(nextStr);\n\n len += nextStr.length;\n currentElem = currentElem.parentNode;\n }\n\n return out.reverse().join(separator);\n } catch (_oO) {\n return '';\n }\n}\n\n/**\n * Returns a simple, query-selector representation of a DOM element\n * e.g. [HTMLElement] => input#foo.btn[name=baz]\n * @returns generated DOM path\n */\nfunction _htmlElementAsString(el: unknown, keyAttrs?: string[]): string {\n const elem = el as {\n tagName?: string;\n id?: string;\n className?: string;\n getAttribute(key: string): string;\n };\n\n const out = [];\n let className;\n let classes;\n let key;\n let attr;\n let i;\n\n if (!elem || !elem.tagName) {\n return '';\n }\n\n // @ts-expect-error WINDOW has HTMLElement\n if (WINDOW.HTMLElement) {\n // If using the component name annotation plugin, this value may be available on the DOM node\n if (elem instanceof HTMLElement && elem.dataset && elem.dataset['sentryComponent']) {\n return elem.dataset['sentryComponent'];\n }\n }\n\n out.push(elem.tagName.toLowerCase());\n\n // Pairs of attribute keys defined in `serializeAttribute` and their values on element.\n const keyAttrPairs =\n keyAttrs && keyAttrs.length\n ? keyAttrs.filter(keyAttr => elem.getAttribute(keyAttr)).map(keyAttr => [keyAttr, elem.getAttribute(keyAttr)])\n : null;\n\n if (keyAttrPairs && keyAttrPairs.length) {\n keyAttrPairs.forEach(keyAttrPair => {\n out.push(`[${keyAttrPair[0]}=\"${keyAttrPair[1]}\"]`);\n });\n } else {\n if (elem.id) {\n out.push(`#${elem.id}`);\n }\n\n // eslint-disable-next-line prefer-const\n className = elem.className;\n if (className && isString(className)) {\n classes = className.split(/\\s+/);\n for (i = 0; i < classes.length; i++) {\n out.push(`.${classes[i]}`);\n }\n }\n }\n const allowedAttrs = ['aria-label', 'type', 'name', 'title', 'alt'];\n for (i = 0; i < allowedAttrs.length; i++) {\n key = allowedAttrs[i];\n attr = elem.getAttribute(key);\n if (attr) {\n out.push(`[${key}=\"${attr}\"]`);\n }\n }\n return out.join('');\n}\n\n/**\n * A safe form of location.href\n */\nexport function getLocationHref(): string {\n try {\n return WINDOW.document.location.href;\n } catch (oO) {\n return '';\n }\n}\n\n/**\n * Gets a DOM element by using document.querySelector.\n *\n * This wrapper will first check for the existance of the function before\n * actually calling it so that we don't have to take care of this check,\n * every time we want to access the DOM.\n *\n * Reason: DOM/querySelector is not available in all environments.\n *\n * We have to cast to any because utils can be consumed by a variety of environments,\n * and we don't want to break TS users. If you know what element will be selected by\n * `document.querySelector`, specify it as part of the generic call. For example,\n * `const element = getDomElement('selector');`\n *\n * @param selector the selector string passed on to document.querySelector\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function getDomElement(selector: string): E | null {\n if (WINDOW.document && WINDOW.document.querySelector) {\n return WINDOW.document.querySelector(selector) as unknown as E;\n }\n return null;\n}\n\n/**\n * Given a DOM element, traverses up the tree until it finds the first ancestor node\n * that has the `data-sentry-component` attribute. This attribute is added at build-time\n * by projects that have the component name annotation plugin installed.\n *\n * @returns a string representation of the component for the provided DOM element, or `null` if not found\n */\nexport function getComponentName(elem: unknown): string | null {\n // @ts-expect-error WINDOW has HTMLElement\n if (!WINDOW.HTMLElement) {\n return null;\n }\n\n let currentElem = elem as SimpleNode;\n const MAX_TRAVERSE_HEIGHT = 5;\n for (let i = 0; i < MAX_TRAVERSE_HEIGHT; i++) {\n if (!currentElem) {\n return null;\n }\n\n if (currentElem instanceof HTMLElement && currentElem.dataset['sentryComponent']) {\n return currentElem.dataset['sentryComponent'];\n }\n\n currentElem = currentElem.parentNode;\n }\n\n return null;\n}\n", "declare const __DEBUG_BUILD__: boolean;\n\n/**\n * This serves as a build time flag that will be true by default, but false in non-debug builds or if users replace `__SENTRY_DEBUG__` in their generated code.\n *\n * ATTENTION: This constant must never cross package boundaries (i.e. be exported) to guarantee that it can be used for tree shaking.\n */\nexport const DEBUG_BUILD = __DEBUG_BUILD__;\n", "import type { ConsoleLevel } from '@sentry/types';\n\nimport { DEBUG_BUILD } from './debug-build';\nimport { GLOBAL_OBJ } from './worldwide';\n\n/** Prefix for logging strings */\nconst PREFIX = 'Sentry Logger ';\n\nexport const CONSOLE_LEVELS: readonly ConsoleLevel[] = [\n 'debug',\n 'info',\n 'warn',\n 'error',\n 'log',\n 'assert',\n 'trace',\n] as const;\n\ntype LoggerMethod = (...args: unknown[]) => void;\ntype LoggerConsoleMethods = Record;\n\n/** This may be mutated by the console instrumentation. */\nexport const originalConsoleMethods: {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [key in ConsoleLevel]?: (...args: any[]) => void;\n} = {};\n\n/** JSDoc */\ninterface Logger extends LoggerConsoleMethods {\n disable(): void;\n enable(): void;\n isEnabled(): boolean;\n}\n\n/**\n * Temporarily disable sentry console instrumentations.\n *\n * @param callback The function to run against the original `console` messages\n * @returns The results of the callback\n */\nexport function consoleSandbox(callback: () => T): T {\n if (!('console' in GLOBAL_OBJ)) {\n return callback();\n }\n\n const console = GLOBAL_OBJ.console as Console;\n const wrappedFuncs: Partial = {};\n\n const wrappedLevels = Object.keys(originalConsoleMethods) as ConsoleLevel[];\n\n // Restore all wrapped console methods\n wrappedLevels.forEach(level => {\n const originalConsoleMethod = originalConsoleMethods[level] as LoggerMethod;\n wrappedFuncs[level] = console[level] as LoggerMethod | undefined;\n console[level] = originalConsoleMethod;\n });\n\n try {\n return callback();\n } finally {\n // Revert restoration to wrapped state\n wrappedLevels.forEach(level => {\n console[level] = wrappedFuncs[level] as LoggerMethod;\n });\n }\n}\n\nfunction makeLogger(): Logger {\n let enabled = false;\n const logger: Partial = {\n enable: () => {\n enabled = true;\n },\n disable: () => {\n enabled = false;\n },\n isEnabled: () => enabled,\n };\n\n if (DEBUG_BUILD) {\n CONSOLE_LEVELS.forEach(name => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n logger[name] = (...args: any[]) => {\n if (enabled) {\n consoleSandbox(() => {\n GLOBAL_OBJ.console[name](`${PREFIX}[${name}]:`, ...args);\n });\n }\n };\n });\n } else {\n CONSOLE_LEVELS.forEach(name => {\n logger[name] = () => undefined;\n });\n }\n\n return logger as Logger;\n}\n\nexport const logger = makeLogger();\n", "import type { DsnComponents, DsnLike, DsnProtocol } from '@sentry/types';\n\nimport { DEBUG_BUILD } from './debug-build';\nimport { consoleSandbox, logger } from './logger';\n\n/** Regular expression used to parse a Dsn. */\nconst DSN_REGEX = /^(?:(\\w+):)\\/\\/(?:(\\w+)(?::(\\w+)?)?@)([\\w.-]+)(?::(\\d+))?\\/(.+)/;\n\nfunction isValidProtocol(protocol?: string): protocol is DsnProtocol {\n return protocol === 'http' || protocol === 'https';\n}\n\n/**\n * Renders the string representation of this Dsn.\n *\n * By default, this will render the public representation without the password\n * component. To get the deprecated private representation, set `withPassword`\n * to true.\n *\n * @param withPassword When set to true, the password will be included.\n */\nexport function dsnToString(dsn: DsnComponents, withPassword: boolean = false): string {\n const { host, path, pass, port, projectId, protocol, publicKey } = dsn;\n return (\n `${protocol}://${publicKey}${withPassword && pass ? `:${pass}` : ''}` +\n `@${host}${port ? `:${port}` : ''}/${path ? `${path}/` : path}${projectId}`\n );\n}\n\n/**\n * Parses a Dsn from a given string.\n *\n * @param str A Dsn as string\n * @returns Dsn as DsnComponents or undefined if @param str is not a valid DSN string\n */\nexport function dsnFromString(str: string): DsnComponents | undefined {\n const match = DSN_REGEX.exec(str);\n\n if (!match) {\n // This should be logged to the console\n consoleSandbox(() => {\n // eslint-disable-next-line no-console\n console.error(`Invalid Sentry Dsn: ${str}`);\n });\n return undefined;\n }\n\n const [protocol, publicKey, pass = '', host, port = '', lastPath] = match.slice(1);\n let path = '';\n let projectId = lastPath;\n\n const split = projectId.split('/');\n if (split.length > 1) {\n path = split.slice(0, -1).join('/');\n projectId = split.pop() as string;\n }\n\n if (projectId) {\n const projectMatch = projectId.match(/^\\d+/);\n if (projectMatch) {\n projectId = projectMatch[0];\n }\n }\n\n return dsnFromComponents({ host, pass, path, projectId, port, protocol: protocol as DsnProtocol, publicKey });\n}\n\nfunction dsnFromComponents(components: DsnComponents): DsnComponents {\n return {\n protocol: components.protocol,\n publicKey: components.publicKey || '',\n pass: components.pass || '',\n host: components.host,\n port: components.port || '',\n path: components.path || '',\n projectId: components.projectId,\n };\n}\n\nfunction validateDsn(dsn: DsnComponents): boolean {\n if (!DEBUG_BUILD) {\n return true;\n }\n\n const { port, projectId, protocol } = dsn;\n\n const requiredComponents: ReadonlyArray = ['protocol', 'publicKey', 'host', 'projectId'];\n const hasMissingRequiredComponent = requiredComponents.find(component => {\n if (!dsn[component]) {\n logger.error(`Invalid Sentry Dsn: ${component} missing`);\n return true;\n }\n return false;\n });\n\n if (hasMissingRequiredComponent) {\n return false;\n }\n\n if (!projectId.match(/^\\d+$/)) {\n logger.error(`Invalid Sentry Dsn: Invalid projectId ${projectId}`);\n return false;\n }\n\n if (!isValidProtocol(protocol)) {\n logger.error(`Invalid Sentry Dsn: Invalid protocol ${protocol}`);\n return false;\n }\n\n if (port && isNaN(parseInt(port, 10))) {\n logger.error(`Invalid Sentry Dsn: Invalid port ${port}`);\n return false;\n }\n\n return true;\n}\n\n/**\n * Creates a valid Sentry Dsn object, identifying a Sentry instance and project.\n * @returns a valid DsnComponents object or `undefined` if @param from is an invalid DSN source\n */\nexport function makeDsn(from: DsnLike): DsnComponents | undefined {\n const components = typeof from === 'string' ? dsnFromString(from) : dsnFromComponents(from);\n if (!components || !validateDsn(components)) {\n return undefined;\n }\n return components;\n}\n", "import type { ConsoleLevel } from '@sentry/types';\n\n/** An error emitted by Sentry SDKs and related utilities. */\nexport class SentryError extends Error {\n /** Display name of this error instance. */\n public name: string;\n\n public logLevel: ConsoleLevel;\n\n public constructor(public message: string, logLevel: ConsoleLevel = 'warn') {\n super(message);\n\n this.name = new.target.prototype.constructor.name;\n // This sets the prototype to be `Error`, not `SentryError`. It's unclear why we do this, but commenting this line\n // out causes various (seemingly totally unrelated) playwright tests consistently time out. FYI, this makes\n // instances of `SentryError` fail `obj instanceof SentryError` checks.\n Object.setPrototypeOf(this, new.target.prototype);\n this.logLevel = logLevel;\n }\n}\n", "/* eslint-disable max-lines */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type { WrappedFunction } from '@sentry/types';\n\nimport { htmlTreeAsString } from './browser';\nimport { DEBUG_BUILD } from './debug-build';\nimport { isElement, isError, isEvent, isInstanceOf, isPlainObject, isPrimitive } from './is';\nimport { logger } from './logger';\nimport { truncate } from './string';\n\n/**\n * Replace a method in an object with a wrapped version of itself.\n *\n * @param source An object that contains a method to be wrapped.\n * @param name The name of the method to be wrapped.\n * @param replacementFactory A higher-order function that takes the original version of the given method and returns a\n * wrapped version. Note: The function returned by `replacementFactory` needs to be a non-arrow function, in order to\n * preserve the correct value of `this`, and the original method must be called using `origMethod.call(this, )` or `origMethod.apply(this, [])` (rather than being called directly), again to preserve `this`.\n * @returns void\n */\nexport function fill(source: { [key: string]: any }, name: string, replacementFactory: (...args: any[]) => any): void {\n if (!(name in source)) {\n return;\n }\n\n const original = source[name] as () => any;\n const wrapped = replacementFactory(original) as WrappedFunction;\n\n // Make sure it's a function first, as we need to attach an empty prototype for `defineProperties` to work\n // otherwise it'll throw \"TypeError: Object.defineProperties called on non-object\"\n if (typeof wrapped === 'function') {\n markFunctionWrapped(wrapped, original);\n }\n\n source[name] = wrapped;\n}\n\n/**\n * Defines a non-enumerable property on the given object.\n *\n * @param obj The object on which to set the property\n * @param name The name of the property to be set\n * @param value The value to which to set the property\n */\nexport function addNonEnumerableProperty(obj: object, name: string, value: unknown): void {\n try {\n Object.defineProperty(obj, name, {\n // enumerable: false, // the default, so we can save on bundle size by not explicitly setting it\n value: value,\n writable: true,\n configurable: true,\n });\n } catch (o_O) {\n DEBUG_BUILD && logger.log(`Failed to add non-enumerable property \"${name}\" to object`, obj);\n }\n}\n\n/**\n * Remembers the original function on the wrapped function and\n * patches up the prototype.\n *\n * @param wrapped the wrapper function\n * @param original the original function that gets wrapped\n */\nexport function markFunctionWrapped(wrapped: WrappedFunction, original: WrappedFunction): void {\n try {\n const proto = original.prototype || {};\n wrapped.prototype = original.prototype = proto;\n addNonEnumerableProperty(wrapped, '__sentry_original__', original);\n } catch (o_O) {} // eslint-disable-line no-empty\n}\n\n/**\n * This extracts the original function if available. See\n * `markFunctionWrapped` for more information.\n *\n * @param func the function to unwrap\n * @returns the unwrapped version of the function if available.\n */\nexport function getOriginalFunction(func: WrappedFunction): WrappedFunction | undefined {\n return func.__sentry_original__;\n}\n\n/**\n * Encodes given object into url-friendly format\n *\n * @param object An object that contains serializable values\n * @returns string Encoded\n */\nexport function urlEncode(object: { [key: string]: any }): string {\n return Object.keys(object)\n .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(object[key])}`)\n .join('&');\n}\n\n/**\n * Transforms any `Error` or `Event` into a plain object with all of their enumerable properties, and some of their\n * non-enumerable properties attached.\n *\n * @param value Initial source that we have to transform in order for it to be usable by the serializer\n * @returns An Event or Error turned into an object - or the value argurment itself, when value is neither an Event nor\n * an Error.\n */\nexport function convertToPlainObject(\n value: V,\n):\n | {\n [ownProps: string]: unknown;\n type: string;\n target: string;\n currentTarget: string;\n detail?: unknown;\n }\n | {\n [ownProps: string]: unknown;\n message: string;\n name: string;\n stack?: string;\n }\n | V {\n if (isError(value)) {\n return {\n message: value.message,\n name: value.name,\n stack: value.stack,\n ...getOwnProperties(value),\n };\n } else if (isEvent(value)) {\n const newObj: {\n [ownProps: string]: unknown;\n type: string;\n target: string;\n currentTarget: string;\n detail?: unknown;\n } = {\n type: value.type,\n target: serializeEventTarget(value.target),\n currentTarget: serializeEventTarget(value.currentTarget),\n ...getOwnProperties(value),\n };\n\n if (typeof CustomEvent !== 'undefined' && isInstanceOf(value, CustomEvent)) {\n newObj.detail = value.detail;\n }\n\n return newObj;\n } else {\n return value;\n }\n}\n\n/** Creates a string representation of the target of an `Event` object */\nfunction serializeEventTarget(target: unknown): string {\n try {\n return isElement(target) ? htmlTreeAsString(target) : Object.prototype.toString.call(target);\n } catch (_oO) {\n return '';\n }\n}\n\n/** Filters out all but an object's own properties */\nfunction getOwnProperties(obj: unknown): { [key: string]: unknown } {\n if (typeof obj === 'object' && obj !== null) {\n const extractedProps: { [key: string]: unknown } = {};\n for (const property in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, property)) {\n extractedProps[property] = (obj as Record)[property];\n }\n }\n return extractedProps;\n } else {\n return {};\n }\n}\n\n/**\n * Given any captured exception, extract its keys and create a sorted\n * and truncated list that will be used inside the event message.\n * eg. `Non-error exception captured with keys: foo, bar, baz`\n */\nexport function extractExceptionKeysForMessage(exception: Record, maxLength: number = 40): string {\n const keys = Object.keys(convertToPlainObject(exception));\n keys.sort();\n\n if (!keys.length) {\n return '[object has no keys]';\n }\n\n if (keys[0].length >= maxLength) {\n return truncate(keys[0], maxLength);\n }\n\n for (let includedKeys = keys.length; includedKeys > 0; includedKeys--) {\n const serialized = keys.slice(0, includedKeys).join(', ');\n if (serialized.length > maxLength) {\n continue;\n }\n if (includedKeys === keys.length) {\n return serialized;\n }\n return truncate(serialized, maxLength);\n }\n\n return '';\n}\n\n/**\n * Given any object, return a new object having removed all fields whose value was `undefined`.\n * Works recursively on objects and arrays.\n *\n * Attention: This function keeps circular references in the returned object.\n */\nexport function dropUndefinedKeys(inputValue: T): T {\n // This map keeps track of what already visited nodes map to.\n // Our Set - based memoBuilder doesn't work here because we want to the output object to have the same circular\n // references as the input object.\n const memoizationMap = new Map();\n\n // This function just proxies `_dropUndefinedKeys` to keep the `memoBuilder` out of this function's API\n return _dropUndefinedKeys(inputValue, memoizationMap);\n}\n\nfunction _dropUndefinedKeys(inputValue: T, memoizationMap: Map): T {\n if (isPojo(inputValue)) {\n // If this node has already been visited due to a circular reference, return the object it was mapped to in the new object\n const memoVal = memoizationMap.get(inputValue);\n if (memoVal !== undefined) {\n return memoVal as T;\n }\n\n const returnValue: { [key: string]: any } = {};\n // Store the mapping of this value in case we visit it again, in case of circular data\n memoizationMap.set(inputValue, returnValue);\n\n for (const key of Object.keys(inputValue)) {\n if (typeof inputValue[key] !== 'undefined') {\n returnValue[key] = _dropUndefinedKeys(inputValue[key], memoizationMap);\n }\n }\n\n return returnValue as T;\n }\n\n if (Array.isArray(inputValue)) {\n // If this node has already been visited due to a circular reference, return the array it was mapped to in the new object\n const memoVal = memoizationMap.get(inputValue);\n if (memoVal !== undefined) {\n return memoVal as T;\n }\n\n const returnValue: unknown[] = [];\n // Store the mapping of this value in case we visit it again, in case of circular data\n memoizationMap.set(inputValue, returnValue);\n\n inputValue.forEach((item: unknown) => {\n returnValue.push(_dropUndefinedKeys(item, memoizationMap));\n });\n\n return returnValue as unknown as T;\n }\n\n return inputValue;\n}\n\nfunction isPojo(input: unknown): input is Record {\n if (!isPlainObject(input)) {\n return false;\n }\n\n try {\n const name = (Object.getPrototypeOf(input) as { constructor: { name: string } }).constructor.name;\n return !name || name === 'Object';\n } catch {\n return true;\n }\n}\n\n/**\n * Ensure that something is an object.\n *\n * Turns `undefined` and `null` into `String`s and all other primitives into instances of their respective wrapper\n * classes (String, Boolean, Number, etc.). Acts as the identity function on non-primitives.\n *\n * @param wat The subject of the objectification\n * @returns A version of `wat` which can safely be used with `Object` class methods\n */\nexport function objectify(wat: unknown): typeof Object {\n let objectified;\n switch (true) {\n case wat === undefined || wat === null:\n objectified = new String(wat);\n break;\n\n // Though symbols and bigints do have wrapper classes (`Symbol` and `BigInt`, respectively), for whatever reason\n // those classes don't have constructors which can be used with the `new` keyword. We therefore need to cast each as\n // an object in order to wrap it.\n case typeof wat === 'symbol' || typeof wat === 'bigint':\n objectified = Object(wat);\n break;\n\n // this will catch the remaining primitives: `String`, `Number`, and `Boolean`\n case isPrimitive(wat):\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n objectified = new (wat as any).constructor(wat);\n break;\n\n // by process of elimination, at this point we know that `wat` must already be an object\n default:\n objectified = wat;\n break;\n }\n return objectified;\n}\n", "// This code was originally forked from https://github.com/felixge/node-stack-trace\n// Since then it has been highly modified to fit our needs.\n\n// Copyright (c) 2011 Felix Geisendörfer (felix@debuggable.com)//\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions://\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.//\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nimport type { StackLineParserFn } from '@sentry/types';\n\nexport type GetModuleFn = (filename: string | undefined) => string | undefined;\n\n/**\n * Does this filename look like it's part of the app code?\n */\nexport function filenameIsInApp(filename: string, isNative: boolean = false): boolean {\n const isInternal =\n isNative ||\n (filename &&\n // It's not internal if it's an absolute linux path\n !filename.startsWith('/') &&\n // It's not internal if it's an absolute windows path\n !filename.match(/^[A-Z]:/) &&\n // It's not internal if the path is starting with a dot\n !filename.startsWith('.') &&\n // It's not internal if the frame has a protocol. In node, this is usually the case if the file got pre-processed with a bundler like webpack\n !filename.match(/^[a-zA-Z]([a-zA-Z0-9.\\-+])*:\\/\\//)); // Schema from: https://stackoverflow.com/a/3641782\n\n // in_app is all that's not an internal Node function or a module within node_modules\n // note that isNative appears to return true even for node core libraries\n // see https://github.com/getsentry/raven-node/issues/176\n\n return !isInternal && filename !== undefined && !filename.includes('node_modules/');\n}\n\n/** Node Stack line parser */\n// eslint-disable-next-line complexity\nexport function node(getModule?: GetModuleFn): StackLineParserFn {\n const FILENAME_MATCH = /^\\s*[-]{4,}$/;\n const FULL_MATCH = /at (?:async )?(?:(.+?)\\s+\\()?(?:(.+):(\\d+):(\\d+)?|([^)]+))\\)?/;\n\n // eslint-disable-next-line complexity\n return (line: string) => {\n const lineMatch = line.match(FULL_MATCH);\n\n if (lineMatch) {\n let object: string | undefined;\n let method: string | undefined;\n let functionName: string | undefined;\n let typeName: string | undefined;\n let methodName: string | undefined;\n\n if (lineMatch[1]) {\n functionName = lineMatch[1];\n\n let methodStart = functionName.lastIndexOf('.');\n if (functionName[methodStart - 1] === '.') {\n methodStart--;\n }\n\n if (methodStart > 0) {\n object = functionName.slice(0, methodStart);\n method = functionName.slice(methodStart + 1);\n const objectEnd = object.indexOf('.Module');\n if (objectEnd > 0) {\n functionName = functionName.slice(objectEnd + 1);\n object = object.slice(0, objectEnd);\n }\n }\n typeName = undefined;\n }\n\n if (method) {\n typeName = object;\n methodName = method;\n }\n\n if (method === '') {\n methodName = undefined;\n functionName = undefined;\n }\n\n if (functionName === undefined) {\n methodName = methodName || '';\n functionName = typeName ? `${typeName}.${methodName}` : methodName;\n }\n\n let filename = lineMatch[2] && lineMatch[2].startsWith('file://') ? lineMatch[2].slice(7) : lineMatch[2];\n const isNative = lineMatch[5] === 'native';\n\n // If it's a Windows path, trim the leading slash so that `/C:/foo` becomes `C:/foo`\n if (filename && filename.match(/\\/[A-Z]:/)) {\n filename = filename.slice(1);\n }\n\n if (!filename && lineMatch[5] && !isNative) {\n filename = lineMatch[5];\n }\n\n return {\n filename,\n module: getModule ? getModule(filename) : undefined,\n function: functionName,\n lineno: parseInt(lineMatch[3], 10) || undefined,\n colno: parseInt(lineMatch[4], 10) || undefined,\n in_app: filenameIsInApp(filename, isNative),\n };\n }\n\n if (line.match(FILENAME_MATCH)) {\n return {\n filename: line,\n };\n }\n\n return undefined;\n };\n}\n", "import type { StackFrame, StackLineParser, StackParser } from '@sentry/types';\n\nimport type { GetModuleFn } from './node-stack-trace';\nimport { filenameIsInApp, node } from './node-stack-trace';\n\nexport { filenameIsInApp };\n\nconst STACKTRACE_FRAME_LIMIT = 50;\n// Used to sanitize webpack (error: *) wrapped stack errors\nconst WEBPACK_ERROR_REGEXP = /\\(error: (.*)\\)/;\nconst STRIP_FRAME_REGEXP = /captureMessage|captureException/;\n\n/**\n * Creates a stack parser with the supplied line parsers\n *\n * StackFrames are returned in the correct order for Sentry Exception\n * frames and with Sentry SDK internal frames removed from the top and bottom\n *\n */\nexport function createStackParser(...parsers: StackLineParser[]): StackParser {\n const sortedParsers = parsers.sort((a, b) => a[0] - b[0]).map(p => p[1]);\n\n return (stack: string, skipFirst: number = 0): StackFrame[] => {\n const frames: StackFrame[] = [];\n const lines = stack.split('\\n');\n\n for (let i = skipFirst; i < lines.length; i++) {\n const line = lines[i];\n // Ignore lines over 1kb as they are unlikely to be stack frames.\n // Many of the regular expressions use backtracking which results in run time that increases exponentially with\n // input size. Huge strings can result in hangs/Denial of Service:\n // https://github.com/getsentry/sentry-javascript/issues/2286\n if (line.length > 1024) {\n continue;\n }\n\n // https://github.com/getsentry/sentry-javascript/issues/5459\n // Remove webpack (error: *) wrappers\n const cleanedLine = WEBPACK_ERROR_REGEXP.test(line) ? line.replace(WEBPACK_ERROR_REGEXP, '$1') : line;\n\n // https://github.com/getsentry/sentry-javascript/issues/7813\n // Skip Error: lines\n if (cleanedLine.match(/\\S*Error: /)) {\n continue;\n }\n\n for (const parser of sortedParsers) {\n const frame = parser(cleanedLine);\n\n if (frame) {\n frames.push(frame);\n break;\n }\n }\n\n if (frames.length >= STACKTRACE_FRAME_LIMIT) {\n break;\n }\n }\n\n return stripSentryFramesAndReverse(frames);\n };\n}\n\n/**\n * Gets a stack parser implementation from Options.stackParser\n * @see Options\n *\n * If options contains an array of line parsers, it is converted into a parser\n */\nexport function stackParserFromStackParserOptions(stackParser: StackParser | StackLineParser[]): StackParser {\n if (Array.isArray(stackParser)) {\n return createStackParser(...stackParser);\n }\n return stackParser;\n}\n\n/**\n * Removes Sentry frames from the top and bottom of the stack if present and enforces a limit of max number of frames.\n * Assumes stack input is ordered from top to bottom and returns the reverse representation so call site of the\n * function that caused the crash is the last frame in the array.\n * @hidden\n */\nexport function stripSentryFramesAndReverse(stack: ReadonlyArray): StackFrame[] {\n if (!stack.length) {\n return [];\n }\n\n const localStack = Array.from(stack);\n\n // If stack starts with one of our API calls, remove it (starts, meaning it's the top of the stack - aka last call)\n if (/sentryWrapped/.test(localStack[localStack.length - 1].function || '')) {\n localStack.pop();\n }\n\n // Reversing in the middle of the procedure allows us to just pop the values off the stack\n localStack.reverse();\n\n // If stack ends with one of our internal API calls, remove it (ends, meaning it's the bottom of the stack - aka top-most call)\n if (STRIP_FRAME_REGEXP.test(localStack[localStack.length - 1].function || '')) {\n localStack.pop();\n\n // When using synthetic events, we will have a 2 levels deep stack, as `new Error('Sentry syntheticException')`\n // is produced within the hub itself, making it:\n //\n // Sentry.captureException()\n // getCurrentHub().captureException()\n //\n // instead of just the top `Sentry` call itself.\n // This forces us to possibly strip an additional frame in the exact same was as above.\n if (STRIP_FRAME_REGEXP.test(localStack[localStack.length - 1].function || '')) {\n localStack.pop();\n }\n }\n\n return localStack.slice(0, STACKTRACE_FRAME_LIMIT).map(frame => ({\n ...frame,\n filename: frame.filename || localStack[localStack.length - 1].filename,\n function: frame.function || '?',\n }));\n}\n\nconst defaultFunctionName = '';\n\n/**\n * Safely extract function name from itself\n */\nexport function getFunctionName(fn: unknown): string {\n try {\n if (!fn || typeof fn !== 'function') {\n return defaultFunctionName;\n }\n return fn.name || defaultFunctionName;\n } catch (e) {\n // Just accessing custom props in some Selenium environments\n // can cause a \"Permission denied\" exception (see raven-js#495).\n return defaultFunctionName;\n }\n}\n\n/**\n * Node.js stack line parser\n *\n * This is in @sentry/utils so it can be used from the Electron SDK in the browser for when `nodeIntegration == true`.\n * This allows it to be used without referencing or importing any node specific code which causes bundlers to complain\n */\nexport function nodeStackLineParser(getModule?: GetModuleFn): StackLineParser {\n return [90, node(getModule)];\n}\n", "import { DEBUG_BUILD } from '../debug-build';\nimport { logger } from '../logger';\nimport { getFunctionName } from '../stacktrace';\n\nexport type InstrumentHandlerType = 'console' | 'dom' | 'fetch' | 'history' | 'xhr' | 'error' | 'unhandledrejection';\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type InstrumentHandlerCallback = (data: any) => void;\n\n// We keep the handlers globally\nconst handlers: { [key in InstrumentHandlerType]?: InstrumentHandlerCallback[] } = {};\nconst instrumented: { [key in InstrumentHandlerType]?: boolean } = {};\n\n/** Add a handler function. */\nexport function addHandler(type: InstrumentHandlerType, handler: InstrumentHandlerCallback): void {\n handlers[type] = handlers[type] || [];\n (handlers[type] as InstrumentHandlerCallback[]).push(handler);\n}\n\n/**\n * Reset all instrumentation handlers.\n * This can be used by tests to ensure we have a clean slate of instrumentation handlers.\n */\nexport function resetInstrumentationHandlers(): void {\n Object.keys(handlers).forEach(key => {\n handlers[key as InstrumentHandlerType] = undefined;\n });\n}\n\n/** Maybe run an instrumentation function, unless it was already called. */\nexport function maybeInstrument(type: InstrumentHandlerType, instrumentFn: () => void): void {\n if (!instrumented[type]) {\n instrumentFn();\n instrumented[type] = true;\n }\n}\n\n/** Trigger handlers for a given instrumentation type. */\nexport function triggerHandlers(type: InstrumentHandlerType, data: unknown): void {\n const typeHandlers = type && handlers[type];\n if (!typeHandlers) {\n return;\n }\n\n for (const handler of typeHandlers) {\n try {\n handler(data);\n } catch (e) {\n DEBUG_BUILD &&\n logger.error(\n `Error while triggering instrumentation handler.\\nType: ${type}\\nName: ${getFunctionName(handler)}\\nError:`,\n e,\n );\n }\n }\n}\n", "/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/ban-types */\nimport type { ConsoleLevel, HandlerDataConsole } from '@sentry/types';\n\nimport { CONSOLE_LEVELS, originalConsoleMethods } from '../logger';\nimport { fill } from '../object';\nimport { GLOBAL_OBJ } from '../worldwide';\nimport { addHandler, maybeInstrument, triggerHandlers } from './_handlers';\n\n/**\n * Add an instrumentation handler for when a console.xxx method is called.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nexport function addConsoleInstrumentationHandler(handler: (data: HandlerDataConsole) => void): void {\n const type = 'console';\n addHandler(type, handler);\n maybeInstrument(type, instrumentConsole);\n}\n\nfunction instrumentConsole(): void {\n if (!('console' in GLOBAL_OBJ)) {\n return;\n }\n\n CONSOLE_LEVELS.forEach(function (level: ConsoleLevel): void {\n if (!(level in GLOBAL_OBJ.console)) {\n return;\n }\n\n fill(GLOBAL_OBJ.console, level, function (originalConsoleMethod: () => any): Function {\n originalConsoleMethods[level] = originalConsoleMethod;\n\n return function (...args: any[]): void {\n const handlerData: HandlerDataConsole = { args, level };\n triggerHandlers('console', handlerData);\n\n const log = originalConsoleMethods[level];\n log && log.apply(GLOBAL_OBJ.console, args);\n };\n });\n });\n}\n", "/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type { Event, Exception, Mechanism, StackFrame } from '@sentry/types';\n\nimport { addNonEnumerableProperty } from './object';\nimport { snipLine } from './string';\nimport { GLOBAL_OBJ } from './worldwide';\n\ninterface CryptoInternal {\n getRandomValues(array: Uint8Array): Uint8Array;\n randomUUID?(): string;\n}\n\n/** An interface for common properties on global */\ninterface CryptoGlobal {\n msCrypto?: CryptoInternal;\n crypto?: CryptoInternal;\n}\n\n/**\n * UUID4 generator\n *\n * @returns string Generated UUID4.\n */\nexport function uuid4(): string {\n const gbl = GLOBAL_OBJ as typeof GLOBAL_OBJ & CryptoGlobal;\n const crypto = gbl.crypto || gbl.msCrypto;\n\n let getRandomByte = (): number => Math.random() * 16;\n try {\n if (crypto && crypto.randomUUID) {\n return crypto.randomUUID().replace(/-/g, '');\n }\n if (crypto && crypto.getRandomValues) {\n getRandomByte = () => {\n // crypto.getRandomValues might return undefined instead of the typed array\n // in old Chromium versions (e.g. 23.0.1235.0 (151422))\n // However, `typedArray` is still filled in-place.\n // @see https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues#typedarray\n const typedArray = new Uint8Array(1);\n crypto.getRandomValues(typedArray);\n return typedArray[0];\n };\n }\n } catch (_) {\n // some runtimes can crash invoking crypto\n // https://github.com/getsentry/sentry-javascript/issues/8935\n }\n\n // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#2117523\n // Concatenating the following numbers as strings results in '10000000100040008000100000000000'\n return (([1e7] as unknown as string) + 1e3 + 4e3 + 8e3 + 1e11).replace(/[018]/g, c =>\n // eslint-disable-next-line no-bitwise\n ((c as unknown as number) ^ ((getRandomByte() & 15) >> ((c as unknown as number) / 4))).toString(16),\n );\n}\n\nfunction getFirstException(event: Event): Exception | undefined {\n return event.exception && event.exception.values ? event.exception.values[0] : undefined;\n}\n\n/**\n * Extracts either message or type+value from an event that can be used for user-facing logs\n * @returns event's description\n */\nexport function getEventDescription(event: Event): string {\n const { message, event_id: eventId } = event;\n if (message) {\n return message;\n }\n\n const firstException = getFirstException(event);\n if (firstException) {\n if (firstException.type && firstException.value) {\n return `${firstException.type}: ${firstException.value}`;\n }\n return firstException.type || firstException.value || eventId || '';\n }\n return eventId || '';\n}\n\n/**\n * Adds exception values, type and value to an synthetic Exception.\n * @param event The event to modify.\n * @param value Value of the exception.\n * @param type Type of the exception.\n * @hidden\n */\nexport function addExceptionTypeValue(event: Event, value?: string, type?: string): void {\n const exception = (event.exception = event.exception || {});\n const values = (exception.values = exception.values || []);\n const firstException = (values[0] = values[0] || {});\n if (!firstException.value) {\n firstException.value = value || '';\n }\n if (!firstException.type) {\n firstException.type = type || 'Error';\n }\n}\n\n/**\n * Adds exception mechanism data to a given event. Uses defaults if the second parameter is not passed.\n *\n * @param event The event to modify.\n * @param newMechanism Mechanism data to add to the event.\n * @hidden\n */\nexport function addExceptionMechanism(event: Event, newMechanism?: Partial): void {\n const firstException = getFirstException(event);\n if (!firstException) {\n return;\n }\n\n const defaultMechanism = { type: 'generic', handled: true };\n const currentMechanism = firstException.mechanism;\n firstException.mechanism = { ...defaultMechanism, ...currentMechanism, ...newMechanism };\n\n if (newMechanism && 'data' in newMechanism) {\n const mergedData = { ...(currentMechanism && currentMechanism.data), ...newMechanism.data };\n firstException.mechanism.data = mergedData;\n }\n}\n\n// https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string\nconst SEMVER_REGEXP =\n /^(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-]+)*))?$/;\n\n/**\n * Represents Semantic Versioning object\n */\ninterface SemVer {\n major?: number;\n minor?: number;\n patch?: number;\n prerelease?: string;\n buildmetadata?: string;\n}\n\n/**\n * Parses input into a SemVer interface\n * @param input string representation of a semver version\n */\nexport function parseSemver(input: string): SemVer {\n const match = input.match(SEMVER_REGEXP) || [];\n const major = parseInt(match[1], 10);\n const minor = parseInt(match[2], 10);\n const patch = parseInt(match[3], 10);\n return {\n buildmetadata: match[5],\n major: isNaN(major) ? undefined : major,\n minor: isNaN(minor) ? undefined : minor,\n patch: isNaN(patch) ? undefined : patch,\n prerelease: match[4],\n };\n}\n\n/**\n * This function adds context (pre/post/line) lines to the provided frame\n *\n * @param lines string[] containing all lines\n * @param frame StackFrame that will be mutated\n * @param linesOfContext number of context lines we want to add pre/post\n */\nexport function addContextToFrame(lines: string[], frame: StackFrame, linesOfContext: number = 5): void {\n // When there is no line number in the frame, attaching context is nonsensical and will even break grouping\n if (frame.lineno === undefined) {\n return;\n }\n\n const maxLines = lines.length;\n const sourceLine = Math.max(Math.min(maxLines - 1, frame.lineno - 1), 0);\n\n frame.pre_context = lines\n .slice(Math.max(0, sourceLine - linesOfContext), sourceLine)\n .map((line: string) => snipLine(line, 0));\n\n frame.context_line = snipLine(lines[Math.min(maxLines - 1, sourceLine)], frame.colno || 0);\n\n frame.post_context = lines\n .slice(Math.min(sourceLine + 1, maxLines), sourceLine + 1 + linesOfContext)\n .map((line: string) => snipLine(line, 0));\n}\n\n/**\n * Checks whether or not we've already captured the given exception (note: not an identical exception - the very object\n * in question), and marks it captured if not.\n *\n * This is useful because it's possible for an error to get captured by more than one mechanism. After we intercept and\n * record an error, we rethrow it (assuming we've intercepted it before it's reached the top-level global handlers), so\n * that we don't interfere with whatever effects the error might have had were the SDK not there. At that point, because\n * the error has been rethrown, it's possible for it to bubble up to some other code we've instrumented. If it's not\n * caught after that, it will bubble all the way up to the global handlers (which of course we also instrument). This\n * function helps us ensure that even if we encounter the same error more than once, we only record it the first time we\n * see it.\n *\n * Note: It will ignore primitives (always return `false` and not mark them as seen), as properties can't be set on\n * them. {@link: Object.objectify} can be used on exceptions to convert any that are primitives into their equivalent\n * object wrapper forms so that this check will always work. However, because we need to flag the exact object which\n * will get rethrown, and because that rethrowing happens outside of the event processing pipeline, the objectification\n * must be done before the exception captured.\n *\n * @param A thrown exception to check or flag as having been seen\n * @returns `true` if the exception has already been captured, `false` if not (with the side effect of marking it seen)\n */\nexport function checkOrSetAlreadyCaught(exception: unknown): boolean {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n if (exception && (exception as any).__sentry_captured__) {\n return true;\n }\n\n try {\n // set it this way rather than by assignment so that it's not ennumerable and therefore isn't recorded by the\n // `ExtraErrorData` integration\n addNonEnumerableProperty(exception as { [key: string]: unknown }, '__sentry_captured__', true);\n } catch (err) {\n // `exception` is a primitive, so we can't mark it seen\n }\n\n return false;\n}\n\n/**\n * Checks whether the given input is already an array, and if it isn't, wraps it in one.\n *\n * @param maybeArray Input to turn into an array, if necessary\n * @returns The input, if already an array, or an array with the input as the only element, if not\n */\nexport function arrayify(maybeArray: T | T[]): T[] {\n return Array.isArray(maybeArray) ? maybeArray : [maybeArray];\n}\n", "// TODO(v8): Move everything in this file into the browser package. Nothing here is generic and we run risk of leaking browser types into non-browser packages.\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/ban-types */\nimport type { HandlerDataDom } from '@sentry/types';\n\nimport { uuid4 } from '../misc';\nimport { addNonEnumerableProperty, fill } from '../object';\nimport { GLOBAL_OBJ } from '../worldwide';\nimport { addHandler, maybeInstrument, triggerHandlers } from './_handlers';\n\ntype SentryWrappedTarget = HTMLElement & { _sentryId?: string };\n\ntype AddEventListener = (\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | AddEventListenerOptions,\n) => void;\ntype RemoveEventListener = (\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | EventListenerOptions,\n) => void;\n\ntype InstrumentedElement = Element & {\n __sentry_instrumentation_handlers__?: {\n [key in 'click' | 'keypress']?: {\n handler?: Function;\n /** The number of custom listeners attached to this element */\n refCount: number;\n };\n };\n};\n\nconst WINDOW = GLOBAL_OBJ as unknown as Window;\nconst DEBOUNCE_DURATION = 1000;\n\nlet debounceTimerID: number | undefined;\nlet lastCapturedEventType: string | undefined;\nlet lastCapturedEventTargetId: string | undefined;\n\n/**\n * Add an instrumentation handler for when a click or a keypress happens.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nexport function addClickKeypressInstrumentationHandler(handler: (data: HandlerDataDom) => void): void {\n const type = 'dom';\n addHandler(type, handler);\n maybeInstrument(type, instrumentDOM);\n}\n\n/** Exported for tests only. */\nexport function instrumentDOM(): void {\n if (!WINDOW.document) {\n return;\n }\n\n // Make it so that any click or keypress that is unhandled / bubbled up all the way to the document triggers our dom\n // handlers. (Normally we have only one, which captures a breadcrumb for each click or keypress.) Do this before\n // we instrument `addEventListener` so that we don't end up attaching this handler twice.\n const triggerDOMHandler = triggerHandlers.bind(null, 'dom');\n const globalDOMEventHandler = makeDOMEventHandler(triggerDOMHandler, true);\n WINDOW.document.addEventListener('click', globalDOMEventHandler, false);\n WINDOW.document.addEventListener('keypress', globalDOMEventHandler, false);\n\n // After hooking into click and keypress events bubbled up to `document`, we also hook into user-handled\n // clicks & keypresses, by adding an event listener of our own to any element to which they add a listener. That\n // way, whenever one of their handlers is triggered, ours will be, too. (This is needed because their handler\n // could potentially prevent the event from bubbling up to our global listeners. This way, our handler are still\n // guaranteed to fire at least once.)\n ['EventTarget', 'Node'].forEach((target: string) => {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n const proto = (WINDOW as any)[target] && (WINDOW as any)[target].prototype;\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, no-prototype-builtins\n if (!proto || !proto.hasOwnProperty || !proto.hasOwnProperty('addEventListener')) {\n return;\n }\n\n fill(proto, 'addEventListener', function (originalAddEventListener: AddEventListener): AddEventListener {\n return function (\n this: Element,\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | AddEventListenerOptions,\n ): AddEventListener {\n if (type === 'click' || type == 'keypress') {\n try {\n const el = this as InstrumentedElement;\n const handlers = (el.__sentry_instrumentation_handlers__ = el.__sentry_instrumentation_handlers__ || {});\n const handlerForType = (handlers[type] = handlers[type] || { refCount: 0 });\n\n if (!handlerForType.handler) {\n const handler = makeDOMEventHandler(triggerDOMHandler);\n handlerForType.handler = handler;\n originalAddEventListener.call(this, type, handler, options);\n }\n\n handlerForType.refCount++;\n } catch (e) {\n // Accessing dom properties is always fragile.\n // Also allows us to skip `addEventListenrs` calls with no proper `this` context.\n }\n }\n\n return originalAddEventListener.call(this, type, listener, options);\n };\n });\n\n fill(\n proto,\n 'removeEventListener',\n function (originalRemoveEventListener: RemoveEventListener): RemoveEventListener {\n return function (\n this: Element,\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | EventListenerOptions,\n ): () => void {\n if (type === 'click' || type == 'keypress') {\n try {\n const el = this as InstrumentedElement;\n const handlers = el.__sentry_instrumentation_handlers__ || {};\n const handlerForType = handlers[type];\n\n if (handlerForType) {\n handlerForType.refCount--;\n // If there are no longer any custom handlers of the current type on this element, we can remove ours, too.\n if (handlerForType.refCount <= 0) {\n originalRemoveEventListener.call(this, type, handlerForType.handler, options);\n handlerForType.handler = undefined;\n delete handlers[type]; // eslint-disable-line @typescript-eslint/no-dynamic-delete\n }\n\n // If there are no longer any custom handlers of any type on this element, cleanup everything.\n if (Object.keys(handlers).length === 0) {\n delete el.__sentry_instrumentation_handlers__;\n }\n }\n } catch (e) {\n // Accessing dom properties is always fragile.\n // Also allows us to skip `addEventListenrs` calls with no proper `this` context.\n }\n }\n\n return originalRemoveEventListener.call(this, type, listener, options);\n };\n },\n );\n });\n}\n\n/**\n * Check whether the event is similar to the last captured one. For example, two click events on the same button.\n */\nfunction isSimilarToLastCapturedEvent(event: Event): boolean {\n // If both events have different type, then user definitely performed two separate actions. e.g. click + keypress.\n if (event.type !== lastCapturedEventType) {\n return false;\n }\n\n try {\n // If both events have the same type, it's still possible that actions were performed on different targets.\n // e.g. 2 clicks on different buttons.\n if (!event.target || (event.target as SentryWrappedTarget)._sentryId !== lastCapturedEventTargetId) {\n return false;\n }\n } catch (e) {\n // just accessing `target` property can throw an exception in some rare circumstances\n // see: https://github.com/getsentry/sentry-javascript/issues/838\n }\n\n // If both events have the same type _and_ same `target` (an element which triggered an event, _not necessarily_\n // to which an event listener was attached), we treat them as the same action, as we want to capture\n // only one breadcrumb. e.g. multiple clicks on the same button, or typing inside a user input box.\n return true;\n}\n\n/**\n * Decide whether an event should be captured.\n * @param event event to be captured\n */\nfunction shouldSkipDOMEvent(eventType: string, target: SentryWrappedTarget | null): boolean {\n // We are only interested in filtering `keypress` events for now.\n if (eventType !== 'keypress') {\n return false;\n }\n\n if (!target || !target.tagName) {\n return true;\n }\n\n // Only consider keypress events on actual input elements. This will disregard keypresses targeting body\n // e.g.tabbing through elements, hotkeys, etc.\n if (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable) {\n return false;\n }\n\n return true;\n}\n\n/**\n * Wraps addEventListener to capture UI breadcrumbs\n */\nfunction makeDOMEventHandler(\n handler: (data: HandlerDataDom) => void,\n globalListener: boolean = false,\n): (event: Event) => void {\n return (event: Event & { _sentryCaptured?: true }): void => {\n // It's possible this handler might trigger multiple times for the same\n // event (e.g. event propagation through node ancestors).\n // Ignore if we've already captured that event.\n if (!event || event['_sentryCaptured']) {\n return;\n }\n\n const target = getEventTarget(event);\n\n // We always want to skip _some_ events.\n if (shouldSkipDOMEvent(event.type, target)) {\n return;\n }\n\n // Mark event as \"seen\"\n addNonEnumerableProperty(event, '_sentryCaptured', true);\n\n if (target && !target._sentryId) {\n // Add UUID to event target so we can identify if\n addNonEnumerableProperty(target, '_sentryId', uuid4());\n }\n\n const name = event.type === 'keypress' ? 'input' : event.type;\n\n // If there is no last captured event, it means that we can safely capture the new event and store it for future comparisons.\n // If there is a last captured event, see if the new event is different enough to treat it as a unique one.\n // If that's the case, emit the previous event and store locally the newly-captured DOM event.\n if (!isSimilarToLastCapturedEvent(event)) {\n const handlerData: HandlerDataDom = { event, name, global: globalListener };\n handler(handlerData);\n lastCapturedEventType = event.type;\n lastCapturedEventTargetId = target ? target._sentryId : undefined;\n }\n\n // Start a new debounce timer that will prevent us from capturing multiple events that should be grouped together.\n clearTimeout(debounceTimerID);\n debounceTimerID = WINDOW.setTimeout(() => {\n lastCapturedEventTargetId = undefined;\n lastCapturedEventType = undefined;\n }, DEBOUNCE_DURATION);\n };\n}\n\nfunction getEventTarget(event: Event): SentryWrappedTarget | null {\n try {\n return event.target as SentryWrappedTarget | null;\n } catch (e) {\n // just accessing `target` property can throw an exception in some rare circumstances\n // see: https://github.com/getsentry/sentry-javascript/issues/838\n return null;\n }\n}\n", "import { DEBUG_BUILD } from './debug-build';\nimport { logger } from './logger';\nimport { getGlobalObject } from './worldwide';\n\n// eslint-disable-next-line deprecation/deprecation\nconst WINDOW = getGlobalObject();\n\ndeclare const EdgeRuntime: string | undefined;\n\nexport { supportsHistory } from './vendor/supportsHistory';\n\n/**\n * Tells whether current environment supports ErrorEvent objects\n * {@link supportsErrorEvent}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsErrorEvent(): boolean {\n try {\n new ErrorEvent('');\n return true;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Tells whether current environment supports DOMError objects\n * {@link supportsDOMError}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsDOMError(): boolean {\n try {\n // Chrome: VM89:1 Uncaught TypeError: Failed to construct 'DOMError':\n // 1 argument required, but only 0 present.\n // @ts-expect-error It really needs 1 argument, not 0.\n new DOMError('');\n return true;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Tells whether current environment supports DOMException objects\n * {@link supportsDOMException}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsDOMException(): boolean {\n try {\n new DOMException('');\n return true;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Tells whether current environment supports Fetch API\n * {@link supportsFetch}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsFetch(): boolean {\n if (!('fetch' in WINDOW)) {\n return false;\n }\n\n try {\n new Headers();\n new Request('http://www.example.com');\n new Response();\n return true;\n } catch (e) {\n return false;\n }\n}\n/**\n * isNativeFetch checks if the given function is a native implementation of fetch()\n */\n// eslint-disable-next-line @typescript-eslint/ban-types\nexport function isNativeFetch(func: Function): boolean {\n return func && /^function fetch\\(\\)\\s+\\{\\s+\\[native code\\]\\s+\\}$/.test(func.toString());\n}\n\n/**\n * Tells whether current environment supports Fetch API natively\n * {@link supportsNativeFetch}.\n *\n * @returns true if `window.fetch` is natively implemented, false otherwise\n */\nexport function supportsNativeFetch(): boolean {\n if (typeof EdgeRuntime === 'string') {\n return true;\n }\n\n if (!supportsFetch()) {\n return false;\n }\n\n // Fast path to avoid DOM I/O\n // eslint-disable-next-line @typescript-eslint/unbound-method\n if (isNativeFetch(WINDOW.fetch)) {\n return true;\n }\n\n // window.fetch is implemented, but is polyfilled or already wrapped (e.g: by a chrome extension)\n // so create a \"pure\" iframe to see if that has native fetch\n let result = false;\n const doc = WINDOW.document;\n // eslint-disable-next-line deprecation/deprecation\n if (doc && typeof (doc.createElement as unknown) === 'function') {\n try {\n const sandbox = doc.createElement('iframe');\n sandbox.hidden = true;\n doc.head.appendChild(sandbox);\n if (sandbox.contentWindow && sandbox.contentWindow.fetch) {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n result = isNativeFetch(sandbox.contentWindow.fetch);\n }\n doc.head.removeChild(sandbox);\n } catch (err) {\n DEBUG_BUILD &&\n logger.warn('Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ', err);\n }\n }\n\n return result;\n}\n\n/**\n * Tells whether current environment supports ReportingObserver API\n * {@link supportsReportingObserver}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsReportingObserver(): boolean {\n return 'ReportingObserver' in WINDOW;\n}\n\n/**\n * Tells whether current environment supports Referrer Policy API\n * {@link supportsReferrerPolicy}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsReferrerPolicy(): boolean {\n // Despite all stars in the sky saying that Edge supports old draft syntax, aka 'never', 'always', 'origin' and 'default'\n // (see https://caniuse.com/#feat=referrer-policy),\n // it doesn't. And it throws an exception instead of ignoring this parameter...\n // REF: https://github.com/getsentry/raven-js/issues/1233\n\n if (!supportsFetch()) {\n return false;\n }\n\n try {\n new Request('_', {\n referrerPolicy: 'origin' as ReferrerPolicy,\n });\n return true;\n } catch (e) {\n return false;\n }\n}\n", "/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/ban-types */\nimport type { HandlerDataFetch } from '@sentry/types';\n\nimport { fill } from '../object';\nimport { supportsNativeFetch } from '../supports';\nimport { GLOBAL_OBJ } from '../worldwide';\nimport { addHandler, maybeInstrument, triggerHandlers } from './_handlers';\n\ntype FetchResource = string | { toString(): string } | { url: string };\n\n/**\n * Add an instrumentation handler for when a fetch request happens.\n * The handler function is called once when the request starts and once when it ends,\n * which can be identified by checking if it has an `endTimestamp`.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nexport function addFetchInstrumentationHandler(handler: (data: HandlerDataFetch) => void): void {\n const type = 'fetch';\n addHandler(type, handler);\n maybeInstrument(type, instrumentFetch);\n}\n\nfunction instrumentFetch(): void {\n if (!supportsNativeFetch()) {\n return;\n }\n\n fill(GLOBAL_OBJ, 'fetch', function (originalFetch: () => void): () => void {\n return function (...args: any[]): void {\n const { method, url } = parseFetchArgs(args);\n\n const handlerData: HandlerDataFetch = {\n args,\n fetchData: {\n method,\n url,\n },\n startTimestamp: Date.now(),\n };\n\n triggerHandlers('fetch', {\n ...handlerData,\n });\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return originalFetch.apply(GLOBAL_OBJ, args).then(\n (response: Response) => {\n const finishedHandlerData: HandlerDataFetch = {\n ...handlerData,\n endTimestamp: Date.now(),\n response,\n };\n\n triggerHandlers('fetch', finishedHandlerData);\n return response;\n },\n (error: Error) => {\n const erroredHandlerData: HandlerDataFetch = {\n ...handlerData,\n endTimestamp: Date.now(),\n error,\n };\n\n triggerHandlers('fetch', erroredHandlerData);\n // NOTE: If you are a Sentry user, and you are seeing this stack frame,\n // it means the sentry.javascript SDK caught an error invoking your application code.\n // This is expected behavior and NOT indicative of a bug with sentry.javascript.\n throw error;\n },\n );\n };\n });\n}\n\nfunction hasProp(obj: unknown, prop: T): obj is Record {\n return !!obj && typeof obj === 'object' && !!(obj as Record)[prop];\n}\n\nfunction getUrlFromResource(resource: FetchResource): string {\n if (typeof resource === 'string') {\n return resource;\n }\n\n if (!resource) {\n return '';\n }\n\n if (hasProp(resource, 'url')) {\n return resource.url;\n }\n\n if (resource.toString) {\n return resource.toString();\n }\n\n return '';\n}\n\n/**\n * Parses the fetch arguments to find the used Http method and the url of the request.\n * Exported for tests only.\n */\nexport function parseFetchArgs(fetchArgs: unknown[]): { method: string; url: string } {\n if (fetchArgs.length === 0) {\n return { method: 'GET', url: '' };\n }\n\n if (fetchArgs.length === 2) {\n const [url, options] = fetchArgs as [FetchResource, object];\n\n return {\n url: getUrlFromResource(url),\n method: hasProp(options, 'method') ? String(options.method).toUpperCase() : 'GET',\n };\n }\n\n const arg = fetchArgs[0];\n return {\n url: getUrlFromResource(arg as FetchResource),\n method: hasProp(arg, 'method') ? String(arg.method).toUpperCase() : 'GET',\n };\n}\n", "import type { HandlerDataError } from '@sentry/types';\n\nimport { GLOBAL_OBJ } from '../worldwide';\nimport { addHandler, maybeInstrument, triggerHandlers } from './_handlers';\n\nlet _oldOnErrorHandler: (typeof GLOBAL_OBJ)['onerror'] | null = null;\n\n/**\n * Add an instrumentation handler for when an error is captured by the global error handler.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nexport function addGlobalErrorInstrumentationHandler(handler: (data: HandlerDataError) => void): void {\n const type = 'error';\n addHandler(type, handler);\n maybeInstrument(type, instrumentError);\n}\n\nfunction instrumentError(): void {\n _oldOnErrorHandler = GLOBAL_OBJ.onerror;\n\n GLOBAL_OBJ.onerror = function (\n msg: string | object,\n url?: string,\n line?: number,\n column?: number,\n error?: Error,\n ): boolean {\n const handlerData: HandlerDataError = {\n column,\n error,\n line,\n msg,\n url,\n };\n triggerHandlers('error', handlerData);\n\n if (_oldOnErrorHandler && !_oldOnErrorHandler.__SENTRY_LOADER__) {\n // eslint-disable-next-line prefer-rest-params\n return _oldOnErrorHandler.apply(this, arguments);\n }\n\n return false;\n };\n\n GLOBAL_OBJ.onerror.__SENTRY_INSTRUMENTED__ = true;\n}\n", "/* eslint-disable @typescript-eslint/no-explicit-any */\n\nimport type { HandlerDataUnhandledRejection } from '@sentry/types';\n\nimport { GLOBAL_OBJ } from '../worldwide';\nimport { addHandler, maybeInstrument, triggerHandlers } from './_handlers';\n\nlet _oldOnUnhandledRejectionHandler: (typeof GLOBAL_OBJ)['onunhandledrejection'] | null = null;\n\n/**\n * Add an instrumentation handler for when an unhandled promise rejection is captured.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nexport function addGlobalUnhandledRejectionInstrumentationHandler(\n handler: (data: HandlerDataUnhandledRejection) => void,\n): void {\n const type = 'unhandledrejection';\n addHandler(type, handler);\n maybeInstrument(type, instrumentUnhandledRejection);\n}\n\nfunction instrumentUnhandledRejection(): void {\n _oldOnUnhandledRejectionHandler = GLOBAL_OBJ.onunhandledrejection;\n\n GLOBAL_OBJ.onunhandledrejection = function (e: any): boolean {\n const handlerData: HandlerDataUnhandledRejection = e;\n triggerHandlers('unhandledrejection', handlerData);\n\n if (_oldOnUnhandledRejectionHandler && !_oldOnUnhandledRejectionHandler.__SENTRY_LOADER__) {\n // eslint-disable-next-line prefer-rest-params\n return _oldOnUnhandledRejectionHandler.apply(this, arguments);\n }\n\n return true;\n };\n\n GLOBAL_OBJ.onunhandledrejection.__SENTRY_INSTRUMENTED__ = true;\n}\n", "// Based on https://github.com/angular/angular.js/pull/13945/files\n// The MIT License\n\n// Copyright (c) 2010-2016 Google, Inc. http://angularjs.org\n\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nimport { getGlobalObject } from '../worldwide';\n\n// eslint-disable-next-line deprecation/deprecation\nconst WINDOW = getGlobalObject();\n\n/**\n * Tells whether current environment supports History API\n * {@link supportsHistory}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsHistory(): boolean {\n // NOTE: in Chrome App environment, touching history.pushState, *even inside\n // a try/catch block*, will cause Chrome to output an error to console.error\n // borrowed from: https://github.com/angular/angular.js/pull/13945/files\n /* eslint-disable @typescript-eslint/no-unsafe-member-access */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const chromeVar = (WINDOW as any).chrome;\n const isChromePackagedApp = chromeVar && chromeVar.app && chromeVar.app.runtime;\n /* eslint-enable @typescript-eslint/no-unsafe-member-access */\n const hasHistoryApi = 'history' in WINDOW && !!WINDOW.history.pushState && !!WINDOW.history.replaceState;\n\n return !isChromePackagedApp && hasHistoryApi;\n}\n", "// TODO(v8): Move everything in this file into the browser package. Nothing here is generic and we run risk of leaking browser types into non-browser packages.\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/ban-types */\nimport type { HandlerDataHistory } from '@sentry/types';\n\nimport { fill } from '../object';\nimport { supportsHistory } from '../supports';\nimport { GLOBAL_OBJ } from '../worldwide';\nimport { addHandler, maybeInstrument, triggerHandlers } from './_handlers';\n\nconst WINDOW = GLOBAL_OBJ as unknown as Window;\n\nlet lastHref: string | undefined;\n\n/**\n * Add an instrumentation handler for when a fetch request happens.\n * The handler function is called once when the request starts and once when it ends,\n * which can be identified by checking if it has an `endTimestamp`.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nexport function addHistoryInstrumentationHandler(handler: (data: HandlerDataHistory) => void): void {\n const type = 'history';\n addHandler(type, handler);\n maybeInstrument(type, instrumentHistory);\n}\n\nfunction instrumentHistory(): void {\n if (!supportsHistory()) {\n return;\n }\n\n const oldOnPopState = WINDOW.onpopstate;\n WINDOW.onpopstate = function (this: WindowEventHandlers, ...args: any[]): any {\n const to = WINDOW.location.href;\n // keep track of the current URL state, as we always receive only the updated state\n const from = lastHref;\n lastHref = to;\n const handlerData: HandlerDataHistory = { from, to };\n triggerHandlers('history', handlerData);\n if (oldOnPopState) {\n // Apparently this can throw in Firefox when incorrectly implemented plugin is installed.\n // https://github.com/getsentry/sentry-javascript/issues/3344\n // https://github.com/bugsnag/bugsnag-js/issues/469\n try {\n return oldOnPopState.apply(this, args);\n } catch (_oO) {\n // no-empty\n }\n }\n };\n\n function historyReplacementFunction(originalHistoryFunction: () => void): () => void {\n return function (this: History, ...args: any[]): void {\n const url = args.length > 2 ? args[2] : undefined;\n if (url) {\n // coerce to string (this is what pushState does)\n const from = lastHref;\n const to = String(url);\n // keep track of the current URL state, as we always receive only the updated state\n lastHref = to;\n const handlerData: HandlerDataHistory = { from, to };\n triggerHandlers('history', handlerData);\n }\n return originalHistoryFunction.apply(this, args);\n };\n }\n\n fill(WINDOW.history, 'pushState', historyReplacementFunction);\n fill(WINDOW.history, 'replaceState', historyReplacementFunction);\n}\n", "// TODO(v8): Move everything in this file into the browser package. Nothing here is generic and we run risk of leaking browser types into non-browser packages.\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/ban-types */\nimport type { HandlerDataXhr, SentryWrappedXMLHttpRequest, WrappedFunction } from '@sentry/types';\n\nimport { isString } from '../is';\nimport { fill } from '../object';\nimport { GLOBAL_OBJ } from '../worldwide';\nimport { addHandler, maybeInstrument, triggerHandlers } from './_handlers';\n\nconst WINDOW = GLOBAL_OBJ as unknown as Window;\n\nexport const SENTRY_XHR_DATA_KEY = '__sentry_xhr_v3__';\n\n/**\n * Add an instrumentation handler for when an XHR request happens.\n * The handler function is called once when the request starts and once when it ends,\n * which can be identified by checking if it has an `endTimestamp`.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nexport function addXhrInstrumentationHandler(handler: (data: HandlerDataXhr) => void): void {\n const type = 'xhr';\n addHandler(type, handler);\n maybeInstrument(type, instrumentXHR);\n}\n\n/** Exported only for tests. */\nexport function instrumentXHR(): void {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n if (!(WINDOW as any).XMLHttpRequest) {\n return;\n }\n\n const xhrproto = XMLHttpRequest.prototype;\n\n fill(xhrproto, 'open', function (originalOpen: () => void): () => void {\n return function (this: XMLHttpRequest & SentryWrappedXMLHttpRequest, ...args: any[]): void {\n const startTimestamp = Date.now();\n\n // open() should always be called with two or more arguments\n // But to be on the safe side, we actually validate this and bail out if we don't have a method & url\n const method = isString(args[0]) ? args[0].toUpperCase() : undefined;\n const url = parseUrl(args[1]);\n\n if (!method || !url) {\n return originalOpen.apply(this, args);\n }\n\n this[SENTRY_XHR_DATA_KEY] = {\n method,\n url,\n request_headers: {},\n };\n\n // if Sentry key appears in URL, don't capture it as a request\n if (method === 'POST' && url.match(/sentry_key/)) {\n this.__sentry_own_request__ = true;\n }\n\n const onreadystatechangeHandler: () => void = () => {\n // For whatever reason, this is not the same instance here as from the outer method\n const xhrInfo = this[SENTRY_XHR_DATA_KEY];\n\n if (!xhrInfo) {\n return;\n }\n\n if (this.readyState === 4) {\n try {\n // touching statusCode in some platforms throws\n // an exception\n xhrInfo.status_code = this.status;\n } catch (e) {\n /* do nothing */\n }\n\n const handlerData: HandlerDataXhr = {\n args: [method, url],\n endTimestamp: Date.now(),\n startTimestamp,\n xhr: this,\n };\n triggerHandlers('xhr', handlerData);\n }\n };\n\n if ('onreadystatechange' in this && typeof this.onreadystatechange === 'function') {\n fill(this, 'onreadystatechange', function (original: WrappedFunction): Function {\n return function (this: SentryWrappedXMLHttpRequest, ...readyStateArgs: any[]): void {\n onreadystatechangeHandler();\n return original.apply(this, readyStateArgs);\n };\n });\n } else {\n this.addEventListener('readystatechange', onreadystatechangeHandler);\n }\n\n // Intercepting `setRequestHeader` to access the request headers of XHR instance.\n // This will only work for user/library defined headers, not for the default/browser-assigned headers.\n // Request cookies are also unavailable for XHR, as `Cookie` header can't be defined by `setRequestHeader`.\n fill(this, 'setRequestHeader', function (original: WrappedFunction): Function {\n return function (this: SentryWrappedXMLHttpRequest, ...setRequestHeaderArgs: unknown[]): void {\n const [header, value] = setRequestHeaderArgs;\n\n const xhrInfo = this[SENTRY_XHR_DATA_KEY];\n\n if (xhrInfo && isString(header) && isString(value)) {\n xhrInfo.request_headers[header.toLowerCase()] = value;\n }\n\n return original.apply(this, setRequestHeaderArgs);\n };\n });\n\n return originalOpen.apply(this, args);\n };\n });\n\n fill(xhrproto, 'send', function (originalSend: () => void): () => void {\n return function (this: XMLHttpRequest & SentryWrappedXMLHttpRequest, ...args: any[]): void {\n const sentryXhrData = this[SENTRY_XHR_DATA_KEY];\n\n if (!sentryXhrData) {\n return originalSend.apply(this, args);\n }\n\n if (args[0] !== undefined) {\n sentryXhrData.body = args[0];\n }\n\n const handlerData: HandlerDataXhr = {\n args: [sentryXhrData.method, sentryXhrData.url],\n startTimestamp: Date.now(),\n xhr: this,\n };\n triggerHandlers('xhr', handlerData);\n\n return originalSend.apply(this, args);\n };\n });\n}\n\nfunction parseUrl(url: string | unknown): string | undefined {\n if (isString(url)) {\n return url;\n }\n\n try {\n // url can be a string or URL\n // but since URL is not available in IE11, we do not check for it,\n // but simply assume it is an URL and return `toString()` from it (which returns the full URL)\n // If that fails, we just return undefined\n return (url as URL).toString();\n } catch {} // eslint-disable-line no-empty\n\n return undefined;\n}\n", "// TODO(v8): Consider moving this file (or at least parts of it) into the browser package. The registered handlers are mostly non-generic and we risk leaking runtime specific code into generic packages.\n\nimport { DEBUG_BUILD } from '../debug-build';\nimport { logger } from './../logger';\nimport type {\n InstrumentHandlerCallback as _InstrumentHandlerCallback,\n InstrumentHandlerType as _InstrumentHandlerType,\n} from './_handlers';\nimport { resetInstrumentationHandlers } from './_handlers';\nimport { addConsoleInstrumentationHandler } from './console';\nimport { addClickKeypressInstrumentationHandler } from './dom';\nimport { addFetchInstrumentationHandler } from './fetch';\nimport { addGlobalErrorInstrumentationHandler } from './globalError';\nimport { addGlobalUnhandledRejectionInstrumentationHandler } from './globalUnhandledRejection';\nimport { addHistoryInstrumentationHandler } from './history';\nimport { SENTRY_XHR_DATA_KEY, addXhrInstrumentationHandler } from './xhr';\n\n/**\n * Add handler that will be called when given type of instrumentation triggers.\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n * @deprecated Use the proper function per instrumentation type instead!\n */\nexport function addInstrumentationHandler(type: _InstrumentHandlerType, callback: _InstrumentHandlerCallback): void {\n switch (type) {\n case 'console':\n return addConsoleInstrumentationHandler(callback);\n case 'dom':\n return addClickKeypressInstrumentationHandler(callback);\n case 'xhr':\n return addXhrInstrumentationHandler(callback);\n case 'fetch':\n return addFetchInstrumentationHandler(callback);\n case 'history':\n return addHistoryInstrumentationHandler(callback);\n case 'error':\n return addGlobalErrorInstrumentationHandler(callback);\n case 'unhandledrejection':\n return addGlobalUnhandledRejectionInstrumentationHandler(callback);\n default:\n DEBUG_BUILD && logger.warn('unknown instrumentation type:', type);\n }\n}\n\n/**\n * @deprecated Use the specific handler data types from @sentry/types instead, e.g. HandlerDataFetch, HandlerDataConsole, ...\n */\ntype InstrumentHandlerCallback = _InstrumentHandlerCallback;\n\n/**\n * @deprecated Use the specific handler functions instead, e.g. addConsoleInstrumentationHandler, ...\n */\ntype InstrumentHandlerType = _InstrumentHandlerType;\n\n// eslint-disable-next-line deprecation/deprecation\nexport type { InstrumentHandlerCallback, InstrumentHandlerType };\n\nexport {\n addConsoleInstrumentationHandler,\n addClickKeypressInstrumentationHandler,\n addXhrInstrumentationHandler,\n addFetchInstrumentationHandler,\n addHistoryInstrumentationHandler,\n addGlobalErrorInstrumentationHandler,\n addGlobalUnhandledRejectionInstrumentationHandler,\n SENTRY_XHR_DATA_KEY,\n // Only exported for tests\n resetInstrumentationHandlers,\n};\n", "/*\n * This module exists for optimizations in the build process through rollup and terser. We define some global\n * constants, which can be overridden during build. By guarding certain pieces of code with functions that return these\n * constants, we can control whether or not they appear in the final bundle. (Any code guarded by a false condition will\n * never run, and will hence be dropped during treeshaking.) The two primary uses for this are stripping out calls to\n * `logger` and preventing node-related code from appearing in browser bundles.\n *\n * Attention:\n * This file should not be used to define constants/flags that are intended to be used for tree-shaking conducted by\n * users. These flags should live in their respective packages, as we identified user tooling (specifically webpack)\n * having issues tree-shaking these constants across package boundaries.\n * An example for this is the __SENTRY_DEBUG__ constant. It is declared in each package individually because we want\n * users to be able to shake away expressions that it guards.\n */\n\ndeclare const __SENTRY_BROWSER_BUNDLE__: boolean | undefined;\n\nexport type SdkSource = 'npm' | 'cdn' | 'loader';\n\n/**\n * Figures out if we're building a browser bundle.\n *\n * @returns true if this is a browser bundle build.\n */\nexport function isBrowserBundle(): boolean {\n return typeof __SENTRY_BROWSER_BUNDLE__ !== 'undefined' && !!__SENTRY_BROWSER_BUNDLE__;\n}\n\n/**\n * Get source of SDK.\n */\nexport function getSDKSource(): SdkSource {\n // @ts-expect-error __SENTRY_SDK_SOURCE__ is injected by rollup during build process\n return __SENTRY_SDK_SOURCE__;\n}\n", "/**\n * NOTE: In order to avoid circular dependencies, if you add a function to this module and it needs to print something,\n * you must either a) use `console.log` rather than the logger, or b) put your function elsewhere.\n */\n\nimport { isBrowserBundle } from './env';\n\n/**\n * Checks whether we're in the Node.js or Browser environment\n *\n * @returns Answer to given question\n */\nexport function isNodeEnv(): boolean {\n // explicitly check for browser bundles as those can be optimized statically\n // by terser/rollup.\n return (\n !isBrowserBundle() &&\n Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]'\n );\n}\n\n/**\n * Requires a module which is protected against bundler minification.\n *\n * @param request The module path to resolve\n */\n// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any\nexport function dynamicRequire(mod: any, request: string): any {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return mod.require(request);\n}\n\n/**\n * Helper for dynamically loading module that should work with linked dependencies.\n * The problem is that we _should_ be using `require(require.resolve(moduleName, { paths: [cwd()] }))`\n * However it's _not possible_ to do that with Webpack, as it has to know all the dependencies during\n * build time. `require.resolve` is also not available in any other way, so we cannot create,\n * a fake helper like we do with `dynamicRequire`.\n *\n * We always prefer to use local package, thus the value is not returned early from each `try/catch` block.\n * That is to mimic the behavior of `require.resolve` exactly.\n *\n * @param moduleName module name to require\n * @returns possibly required module\n */\nexport function loadModule(moduleName: string): T | undefined {\n let mod: T | undefined;\n\n try {\n mod = dynamicRequire(module, moduleName);\n } catch (e) {\n // no-empty\n }\n\n try {\n const { cwd } = dynamicRequire(module, 'process');\n mod = dynamicRequire(module, `${cwd()}/node_modules/${moduleName}`) as T;\n } catch (e) {\n // no-empty\n }\n\n return mod;\n}\n", "import { isNodeEnv } from './node';\nimport { GLOBAL_OBJ } from './worldwide';\n\n/**\n * Returns true if we are in the browser.\n */\nexport function isBrowser(): boolean {\n // eslint-disable-next-line no-restricted-globals\n return typeof window !== 'undefined' && (!isNodeEnv() || isElectronNodeRenderer());\n}\n\ntype ElectronProcess = { type?: string };\n\n// Electron renderers with nodeIntegration enabled are detected as Node.js so we specifically test for them\nfunction isElectronNodeRenderer(): boolean {\n return (\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any\n (GLOBAL_OBJ as any).process !== undefined && ((GLOBAL_OBJ as any).process as ElectronProcess).type === 'renderer'\n );\n}\n", "/* eslint-disable @typescript-eslint/no-unsafe-member-access */\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\nexport type MemoFunc = [\n // memoize\n (obj: any) => boolean,\n // unmemoize\n (obj: any) => void,\n];\n\n/**\n * Helper to decycle json objects\n */\nexport function memoBuilder(): MemoFunc {\n const hasWeakSet = typeof WeakSet === 'function';\n const inner: any = hasWeakSet ? new WeakSet() : [];\n function memoize(obj: any): boolean {\n if (hasWeakSet) {\n if (inner.has(obj)) {\n return true;\n }\n inner.add(obj);\n return false;\n }\n // eslint-disable-next-line @typescript-eslint/prefer-for-of\n for (let i = 0; i < inner.length; i++) {\n const value = inner[i];\n if (value === obj) {\n return true;\n }\n }\n inner.push(obj);\n return false;\n }\n\n function unmemoize(obj: any): void {\n if (hasWeakSet) {\n inner.delete(obj);\n } else {\n for (let i = 0; i < inner.length; i++) {\n if (inner[i] === obj) {\n inner.splice(i, 1);\n break;\n }\n }\n }\n }\n return [memoize, unmemoize];\n}\n", "import type { Primitive } from '@sentry/types';\n\nimport { isNaN, isSyntheticEvent, isVueViewModel } from './is';\nimport type { MemoFunc } from './memo';\nimport { memoBuilder } from './memo';\nimport { convertToPlainObject } from './object';\nimport { getFunctionName } from './stacktrace';\n\ntype Prototype = { constructor: (...args: unknown[]) => unknown };\n// This is a hack to placate TS, relying on the fact that technically, arrays are objects with integer keys. Normally we\n// think of those keys as actual numbers, but `arr['0']` turns out to work just as well as `arr[0]`, and doing it this\n// way lets us use a single type in the places where behave as if we are only dealing with objects, even if some of them\n// might be arrays.\ntype ObjOrArray = { [key: string]: T };\n\n/**\n * Recursively normalizes the given object.\n *\n * - Creates a copy to prevent original input mutation\n * - Skips non-enumerable properties\n * - When stringifying, calls `toJSON` if implemented\n * - Removes circular references\n * - Translates non-serializable values (`undefined`/`NaN`/functions) to serializable format\n * - Translates known global objects/classes to a string representations\n * - Takes care of `Error` object serialization\n * - Optionally limits depth of final output\n * - Optionally limits number of properties/elements included in any single object/array\n *\n * @param input The object to be normalized.\n * @param depth The max depth to which to normalize the object. (Anything deeper stringified whole.)\n * @param maxProperties The max number of elements or properties to be included in any single array or\n * object in the normallized output.\n * @returns A normalized version of the object, or `\"**non-serializable**\"` if any errors are thrown during normalization.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function normalize(input: unknown, depth: number = 100, maxProperties: number = +Infinity): any {\n try {\n // since we're at the outermost level, we don't provide a key\n return visit('', input, depth, maxProperties);\n } catch (err) {\n return { ERROR: `**non-serializable** (${err})` };\n }\n}\n\n/** JSDoc */\nexport function normalizeToSize(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n object: { [key: string]: any },\n // Default Node.js REPL depth\n depth: number = 3,\n // 100kB, as 200kB is max payload size, so half sounds reasonable\n maxSize: number = 100 * 1024,\n): T {\n const normalized = normalize(object, depth);\n\n if (jsonSize(normalized) > maxSize) {\n return normalizeToSize(object, depth - 1, maxSize);\n }\n\n return normalized as T;\n}\n\n/**\n * Visits a node to perform normalization on it\n *\n * @param key The key corresponding to the given node\n * @param value The node to be visited\n * @param depth Optional number indicating the maximum recursion depth\n * @param maxProperties Optional maximum number of properties/elements included in any single object/array\n * @param memo Optional Memo class handling decycling\n */\nfunction visit(\n key: string,\n value: unknown,\n depth: number = +Infinity,\n maxProperties: number = +Infinity,\n memo: MemoFunc = memoBuilder(),\n): Primitive | ObjOrArray {\n const [memoize, unmemoize] = memo;\n\n // Get the simple cases out of the way first\n if (\n value == null || // this matches null and undefined -> eqeq not eqeqeq\n (['number', 'boolean', 'string'].includes(typeof value) && !isNaN(value))\n ) {\n return value as Primitive;\n }\n\n const stringified = stringifyValue(key, value);\n\n // Anything we could potentially dig into more (objects or arrays) will have come back as `\"[object XXXX]\"`.\n // Everything else will have already been serialized, so if we don't see that pattern, we're done.\n if (!stringified.startsWith('[object ')) {\n return stringified;\n }\n\n // From here on, we can assert that `value` is either an object or an array.\n\n // Do not normalize objects that we know have already been normalized. As a general rule, the\n // \"__sentry_skip_normalization__\" property should only be used sparingly and only should only be set on objects that\n // have already been normalized.\n if ((value as ObjOrArray)['__sentry_skip_normalization__']) {\n return value as ObjOrArray;\n }\n\n // We can set `__sentry_override_normalization_depth__` on an object to ensure that from there\n // We keep a certain amount of depth.\n // This should be used sparingly, e.g. we use it for the redux integration to ensure we get a certain amount of state.\n const remainingDepth =\n typeof (value as ObjOrArray)['__sentry_override_normalization_depth__'] === 'number'\n ? ((value as ObjOrArray)['__sentry_override_normalization_depth__'] as number)\n : depth;\n\n // We're also done if we've reached the max depth\n if (remainingDepth === 0) {\n // At this point we know `serialized` is a string of the form `\"[object XXXX]\"`. Clean it up so it's just `\"[XXXX]\"`.\n return stringified.replace('object ', '');\n }\n\n // If we've already visited this branch, bail out, as it's circular reference. If not, note that we're seeing it now.\n if (memoize(value)) {\n return '[Circular ~]';\n }\n\n // If the value has a `toJSON` method, we call it to extract more information\n const valueWithToJSON = value as unknown & { toJSON?: () => unknown };\n if (valueWithToJSON && typeof valueWithToJSON.toJSON === 'function') {\n try {\n const jsonValue = valueWithToJSON.toJSON();\n // We need to normalize the return value of `.toJSON()` in case it has circular references\n return visit('', jsonValue, remainingDepth - 1, maxProperties, memo);\n } catch (err) {\n // pass (The built-in `toJSON` failed, but we can still try to do it ourselves)\n }\n }\n\n // At this point we know we either have an object or an array, we haven't seen it before, and we're going to recurse\n // because we haven't yet reached the max depth. Create an accumulator to hold the results of visiting each\n // property/entry, and keep track of the number of items we add to it.\n const normalized = (Array.isArray(value) ? [] : {}) as ObjOrArray;\n let numAdded = 0;\n\n // Before we begin, convert`Error` and`Event` instances into plain objects, since some of each of their relevant\n // properties are non-enumerable and otherwise would get missed.\n const visitable = convertToPlainObject(value as ObjOrArray);\n\n for (const visitKey in visitable) {\n // Avoid iterating over fields in the prototype if they've somehow been exposed to enumeration.\n if (!Object.prototype.hasOwnProperty.call(visitable, visitKey)) {\n continue;\n }\n\n if (numAdded >= maxProperties) {\n normalized[visitKey] = '[MaxProperties ~]';\n break;\n }\n\n // Recursively visit all the child nodes\n const visitValue = visitable[visitKey];\n normalized[visitKey] = visit(visitKey, visitValue, remainingDepth - 1, maxProperties, memo);\n\n numAdded++;\n }\n\n // Once we've visited all the branches, remove the parent from memo storage\n unmemoize(value);\n\n // Return accumulated values\n return normalized;\n}\n\n/**\n * @deprecated This export will be removed in v8.\n */\nexport { visit as walk };\n\n/* eslint-disable complexity */\n/**\n * Stringify the given value. Handles various known special values and types.\n *\n * Not meant to be used on simple primitives which already have a string representation, as it will, for example, turn\n * the number 1231 into \"[Object Number]\", nor on `null`, as it will throw.\n *\n * @param value The value to stringify\n * @returns A stringified representation of the given value\n */\nfunction stringifyValue(\n key: unknown,\n // this type is a tiny bit of a cheat, since this function does handle NaN (which is technically a number), but for\n // our internal use, it'll do\n value: Exclude,\n): string {\n try {\n if (key === 'domain' && value && typeof value === 'object' && (value as { _events: unknown })._events) {\n return '[Domain]';\n }\n\n if (key === 'domainEmitter') {\n return '[DomainEmitter]';\n }\n\n // It's safe to use `global`, `window`, and `document` here in this manner, as we are asserting using `typeof` first\n // which won't throw if they are not present.\n\n if (typeof global !== 'undefined' && value === global) {\n return '[Global]';\n }\n\n // eslint-disable-next-line no-restricted-globals\n if (typeof window !== 'undefined' && value === window) {\n return '[Window]';\n }\n\n // eslint-disable-next-line no-restricted-globals\n if (typeof document !== 'undefined' && value === document) {\n return '[Document]';\n }\n\n if (isVueViewModel(value)) {\n return '[VueViewModel]';\n }\n\n // React's SyntheticEvent thingy\n if (isSyntheticEvent(value)) {\n return '[SyntheticEvent]';\n }\n\n if (typeof value === 'number' && value !== value) {\n return '[NaN]';\n }\n\n if (typeof value === 'function') {\n return `[Function: ${getFunctionName(value)}]`;\n }\n\n if (typeof value === 'symbol') {\n return `[${String(value)}]`;\n }\n\n // stringified BigInts are indistinguishable from regular numbers, so we need to label them to avoid confusion\n if (typeof value === 'bigint') {\n return `[BigInt: ${String(value)}]`;\n }\n\n // Now that we've knocked out all the special cases and the primitives, all we have left are objects. Simply casting\n // them to strings means that instances of classes which haven't defined their `toStringTag` will just come out as\n // `\"[object Object]\"`. If we instead look at the constructor's name (which is the same as the name of the class),\n // we can make sure that only plain objects come out that way.\n const objName = getConstructorName(value);\n\n // Handle HTML Elements\n if (/^HTML(\\w*)Element$/.test(objName)) {\n return `[HTMLElement: ${objName}]`;\n }\n\n return `[object ${objName}]`;\n } catch (err) {\n return `**non-serializable** (${err})`;\n }\n}\n/* eslint-enable complexity */\n\nfunction getConstructorName(value: unknown): string {\n const prototype: Prototype | null = Object.getPrototypeOf(value);\n\n return prototype ? prototype.constructor.name : 'null prototype';\n}\n\n/** Calculates bytes size of input string */\nfunction utf8Length(value: string): number {\n // eslint-disable-next-line no-bitwise\n return ~-encodeURI(value).split(/%..|./).length;\n}\n\n/** Calculates bytes size of input object */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction jsonSize(value: any): number {\n return utf8Length(JSON.stringify(value));\n}\n\n/**\n * Normalizes URLs in exceptions and stacktraces to a base path so Sentry can fingerprint\n * across platforms and working directory.\n *\n * @param url The URL to be normalized.\n * @param basePath The application base path.\n * @returns The normalized URL.\n */\nexport function normalizeUrlToBase(url: string, basePath: string): string {\n const escapedBase = basePath\n // Backslash to forward\n .replace(/\\\\/g, '/')\n // Escape RegExp special characters\n .replace(/[|\\\\{}()[\\]^$+*?.]/g, '\\\\$&');\n\n let newUrl = url;\n try {\n newUrl = decodeURI(url);\n } catch (_Oo) {\n // Sometime this breaks\n }\n return (\n newUrl\n .replace(/\\\\/g, '/')\n .replace(/webpack:\\/?/g, '') // Remove intermediate base path\n // eslint-disable-next-line @sentry-internal/sdk/no-regexp-constructor\n .replace(new RegExp(`(file://)?/*${escapedBase}/*`, 'ig'), 'app:///')\n );\n}\n", "// Slightly modified (no IE8 support, ES6) and transcribed to TypeScript\n// https://github.com/calvinmetcalf/rollup-plugin-node-builtins/blob/63ab8aacd013767445ca299e468d9a60a95328d7/src/es6/path.js\n//\n// Copyright Joyent, Inc.and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n/** JSDoc */\nfunction normalizeArray(parts: string[], allowAboveRoot?: boolean): string[] {\n // if the path tries to go above the root, `up` ends up > 0\n let up = 0;\n for (let i = parts.length - 1; i >= 0; i--) {\n const last = parts[i];\n if (last === '.') {\n parts.splice(i, 1);\n } else if (last === '..') {\n parts.splice(i, 1);\n up++;\n } else if (up) {\n parts.splice(i, 1);\n up--;\n }\n }\n\n // if the path is allowed to go above the root, restore leading ..s\n if (allowAboveRoot) {\n for (; up--; up) {\n parts.unshift('..');\n }\n }\n\n return parts;\n}\n\n// Split a filename into [root, dir, basename, ext], unix version\n// 'root' is just a slash, or nothing.\nconst splitPathRe = /^(\\S+:\\\\|\\/?)([\\s\\S]*?)((?:\\.{1,2}|[^/\\\\]+?|)(\\.[^./\\\\]*|))(?:[/\\\\]*)$/;\n/** JSDoc */\nfunction splitPath(filename: string): string[] {\n // Truncate files names greater than 1024 characters to avoid regex dos\n // https://github.com/getsentry/sentry-javascript/pull/8737#discussion_r1285719172\n const truncated = filename.length > 1024 ? `${filename.slice(-1024)}` : filename;\n const parts = splitPathRe.exec(truncated);\n return parts ? parts.slice(1) : [];\n}\n\n// path.resolve([from ...], to)\n// posix version\n/** JSDoc */\nexport function resolve(...args: string[]): string {\n let resolvedPath = '';\n let resolvedAbsolute = false;\n\n for (let i = args.length - 1; i >= -1 && !resolvedAbsolute; i--) {\n const path = i >= 0 ? args[i] : '/';\n\n // Skip empty entries\n if (!path) {\n continue;\n }\n\n resolvedPath = `${path}/${resolvedPath}`;\n resolvedAbsolute = path.charAt(0) === '/';\n }\n\n // At this point the path should be resolved to a full absolute path, but\n // handle relative paths to be safe (might happen when process.cwd() fails)\n\n // Normalize the path\n resolvedPath = normalizeArray(\n resolvedPath.split('/').filter(p => !!p),\n !resolvedAbsolute,\n ).join('/');\n\n return (resolvedAbsolute ? '/' : '') + resolvedPath || '.';\n}\n\n/** JSDoc */\nfunction trim(arr: string[]): string[] {\n let start = 0;\n for (; start < arr.length; start++) {\n if (arr[start] !== '') {\n break;\n }\n }\n\n let end = arr.length - 1;\n for (; end >= 0; end--) {\n if (arr[end] !== '') {\n break;\n }\n }\n\n if (start > end) {\n return [];\n }\n return arr.slice(start, end - start + 1);\n}\n\n// path.relative(from, to)\n// posix version\n/** JSDoc */\nexport function relative(from: string, to: string): string {\n /* eslint-disable no-param-reassign */\n from = resolve(from).slice(1);\n to = resolve(to).slice(1);\n /* eslint-enable no-param-reassign */\n\n const fromParts = trim(from.split('/'));\n const toParts = trim(to.split('/'));\n\n const length = Math.min(fromParts.length, toParts.length);\n let samePartsLength = length;\n for (let i = 0; i < length; i++) {\n if (fromParts[i] !== toParts[i]) {\n samePartsLength = i;\n break;\n }\n }\n\n let outputParts = [];\n for (let i = samePartsLength; i < fromParts.length; i++) {\n outputParts.push('..');\n }\n\n outputParts = outputParts.concat(toParts.slice(samePartsLength));\n\n return outputParts.join('/');\n}\n\n// path.normalize(path)\n// posix version\n/** JSDoc */\nexport function normalizePath(path: string): string {\n const isPathAbsolute = isAbsolute(path);\n const trailingSlash = path.slice(-1) === '/';\n\n // Normalize the path\n let normalizedPath = normalizeArray(\n path.split('/').filter(p => !!p),\n !isPathAbsolute,\n ).join('/');\n\n if (!normalizedPath && !isPathAbsolute) {\n normalizedPath = '.';\n }\n if (normalizedPath && trailingSlash) {\n normalizedPath += '/';\n }\n\n return (isPathAbsolute ? '/' : '') + normalizedPath;\n}\n\n// posix version\n/** JSDoc */\nexport function isAbsolute(path: string): boolean {\n return path.charAt(0) === '/';\n}\n\n// posix version\n/** JSDoc */\nexport function join(...args: string[]): string {\n return normalizePath(args.join('/'));\n}\n\n/** JSDoc */\nexport function dirname(path: string): string {\n const result = splitPath(path);\n const root = result[0];\n let dir = result[1];\n\n if (!root && !dir) {\n // No dirname whatsoever\n return '.';\n }\n\n if (dir) {\n // It has a dirname, strip trailing slash\n dir = dir.slice(0, dir.length - 1);\n }\n\n return root + dir;\n}\n\n/** JSDoc */\nexport function basename(path: string, ext?: string): string {\n let f = splitPath(path)[2];\n if (ext && f.slice(ext.length * -1) === ext) {\n f = f.slice(0, f.length - ext.length);\n }\n return f;\n}\n", "/* eslint-disable @typescript-eslint/explicit-function-return-type */\n/* eslint-disable @typescript-eslint/typedef */\n/* eslint-disable @typescript-eslint/explicit-module-boundary-types */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { isThenable } from './is';\n\n/** SyncPromise internal states */\nconst enum States {\n /** Pending */\n PENDING = 0,\n /** Resolved / OK */\n RESOLVED = 1,\n /** Rejected / Error */\n REJECTED = 2,\n}\n\n// Overloads so we can call resolvedSyncPromise without arguments and generic argument\nexport function resolvedSyncPromise(): PromiseLike;\nexport function resolvedSyncPromise(value: T | PromiseLike): PromiseLike;\n\n/**\n * Creates a resolved sync promise.\n *\n * @param value the value to resolve the promise with\n * @returns the resolved sync promise\n */\nexport function resolvedSyncPromise(value?: T | PromiseLike): PromiseLike {\n return new SyncPromise(resolve => {\n resolve(value);\n });\n}\n\n/**\n * Creates a rejected sync promise.\n *\n * @param value the value to reject the promise with\n * @returns the rejected sync promise\n */\nexport function rejectedSyncPromise(reason?: any): PromiseLike {\n return new SyncPromise((_, reject) => {\n reject(reason);\n });\n}\n\n/**\n * Thenable class that behaves like a Promise and follows it's interface\n * but is not async internally\n */\nclass SyncPromise implements PromiseLike {\n private _state: States;\n private _handlers: Array<[boolean, (value: T) => void, (reason: any) => any]>;\n private _value: any;\n\n public constructor(\n executor: (resolve: (value?: T | PromiseLike | null) => void, reject: (reason?: any) => void) => void,\n ) {\n this._state = States.PENDING;\n this._handlers = [];\n\n try {\n executor(this._resolve, this._reject);\n } catch (e) {\n this._reject(e);\n }\n }\n\n /** JSDoc */\n public then(\n onfulfilled?: ((value: T) => TResult1 | PromiseLike) | null,\n onrejected?: ((reason: any) => TResult2 | PromiseLike) | null,\n ): PromiseLike {\n return new SyncPromise((resolve, reject) => {\n this._handlers.push([\n false,\n result => {\n if (!onfulfilled) {\n // TODO: ¯\\_(ツ)_/¯\n // TODO: FIXME\n resolve(result as any);\n } else {\n try {\n resolve(onfulfilled(result));\n } catch (e) {\n reject(e);\n }\n }\n },\n reason => {\n if (!onrejected) {\n reject(reason);\n } else {\n try {\n resolve(onrejected(reason));\n } catch (e) {\n reject(e);\n }\n }\n },\n ]);\n this._executeHandlers();\n });\n }\n\n /** JSDoc */\n public catch(\n onrejected?: ((reason: any) => TResult | PromiseLike) | null,\n ): PromiseLike {\n return this.then(val => val, onrejected);\n }\n\n /** JSDoc */\n public finally(onfinally?: (() => void) | null): PromiseLike {\n return new SyncPromise((resolve, reject) => {\n let val: TResult | any;\n let isRejected: boolean;\n\n return this.then(\n value => {\n isRejected = false;\n val = value;\n if (onfinally) {\n onfinally();\n }\n },\n reason => {\n isRejected = true;\n val = reason;\n if (onfinally) {\n onfinally();\n }\n },\n ).then(() => {\n if (isRejected) {\n reject(val);\n return;\n }\n\n resolve(val as unknown as any);\n });\n });\n }\n\n /** JSDoc */\n private readonly _resolve = (value?: T | PromiseLike | null) => {\n this._setResult(States.RESOLVED, value);\n };\n\n /** JSDoc */\n private readonly _reject = (reason?: any) => {\n this._setResult(States.REJECTED, reason);\n };\n\n /** JSDoc */\n private readonly _setResult = (state: States, value?: T | PromiseLike | any) => {\n if (this._state !== States.PENDING) {\n return;\n }\n\n if (isThenable(value)) {\n void (value as PromiseLike).then(this._resolve, this._reject);\n return;\n }\n\n this._state = state;\n this._value = value;\n\n this._executeHandlers();\n };\n\n /** JSDoc */\n private readonly _executeHandlers = () => {\n if (this._state === States.PENDING) {\n return;\n }\n\n const cachedHandlers = this._handlers.slice();\n this._handlers = [];\n\n cachedHandlers.forEach(handler => {\n if (handler[0]) {\n return;\n }\n\n if (this._state === States.RESOLVED) {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n handler[1](this._value as unknown as any);\n }\n\n if (this._state === States.REJECTED) {\n handler[2](this._value);\n }\n\n handler[0] = true;\n });\n };\n}\n\nexport { SyncPromise };\n", "import { SentryError } from './error';\nimport { SyncPromise, rejectedSyncPromise, resolvedSyncPromise } from './syncpromise';\n\nexport interface PromiseBuffer {\n // exposes the internal array so tests can assert on the state of it.\n // XXX: this really should not be public api.\n $: Array>;\n add(taskProducer: () => PromiseLike): PromiseLike;\n drain(timeout?: number): PromiseLike;\n}\n\n/**\n * Creates an new PromiseBuffer object with the specified limit\n * @param limit max number of promises that can be stored in the buffer\n */\nexport function makePromiseBuffer(limit?: number): PromiseBuffer {\n const buffer: Array> = [];\n\n function isReady(): boolean {\n return limit === undefined || buffer.length < limit;\n }\n\n /**\n * Remove a promise from the queue.\n *\n * @param task Can be any PromiseLike\n * @returns Removed promise.\n */\n function remove(task: PromiseLike): PromiseLike {\n return buffer.splice(buffer.indexOf(task), 1)[0];\n }\n\n /**\n * Add a promise (representing an in-flight action) to the queue, and set it to remove itself on fulfillment.\n *\n * @param taskProducer A function producing any PromiseLike; In previous versions this used to be `task:\n * PromiseLike`, but under that model, Promises were instantly created on the call-site and their executor\n * functions therefore ran immediately. Thus, even if the buffer was full, the action still happened. By\n * requiring the promise to be wrapped in a function, we can defer promise creation until after the buffer\n * limit check.\n * @returns The original promise.\n */\n function add(taskProducer: () => PromiseLike): PromiseLike {\n if (!isReady()) {\n return rejectedSyncPromise(new SentryError('Not adding Promise because buffer limit was reached.'));\n }\n\n // start the task and add its promise to the queue\n const task = taskProducer();\n if (buffer.indexOf(task) === -1) {\n buffer.push(task);\n }\n void task\n .then(() => remove(task))\n // Use `then(null, rejectionHandler)` rather than `catch(rejectionHandler)` so that we can use `PromiseLike`\n // rather than `Promise`. `PromiseLike` doesn't have a `.catch` method, making its polyfill smaller. (ES5 didn't\n // have promises, so TS has to polyfill when down-compiling.)\n .then(null, () =>\n remove(task).then(null, () => {\n // We have to add another catch here because `remove()` starts a new promise chain.\n }),\n );\n return task;\n }\n\n /**\n * Wait for all promises in the queue to resolve or for timeout to expire, whichever comes first.\n *\n * @param timeout The time, in ms, after which to resolve to `false` if the queue is still non-empty. Passing `0` (or\n * not passing anything) will make the promise wait as long as it takes for the queue to drain before resolving to\n * `true`.\n * @returns A promise which will resolve to `true` if the queue is already empty or drains before the timeout, and\n * `false` otherwise\n */\n function drain(timeout?: number): PromiseLike {\n return new SyncPromise((resolve, reject) => {\n let counter = buffer.length;\n\n if (!counter) {\n return resolve(true);\n }\n\n // wait for `timeout` ms and then resolve to `false` (if not cancelled first)\n const capturedSetTimeout = setTimeout(() => {\n if (timeout && timeout > 0) {\n resolve(false);\n }\n }, timeout);\n\n // if all promises resolve in time, cancel the timer and resolve to `true`\n buffer.forEach(item => {\n void resolvedSyncPromise(item).then(() => {\n if (!--counter) {\n clearTimeout(capturedSetTimeout);\n resolve(true);\n }\n }, reject);\n });\n });\n }\n\n return {\n $: buffer,\n add,\n drain,\n };\n}\n", "/**\n * This code was originally copied from the 'cookie` module at v0.5.0 and was simplified for our use case.\n * https://github.com/jshttp/cookie/blob/a0c84147aab6266bdb3996cf4062e93907c0b0fc/index.js\n * It had the following license:\n *\n * (The MIT License)\n *\n * Copyright (c) 2012-2014 Roman Shtylman \n * Copyright (c) 2015 Douglas Christopher Wilson \n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * 'Software'), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\n\n/**\n * Parses a cookie string\n */\nexport function parseCookie(str: string): Record {\n const obj: Record = {};\n let index = 0;\n\n while (index < str.length) {\n const eqIdx = str.indexOf('=', index);\n\n // no more cookie pairs\n if (eqIdx === -1) {\n break;\n }\n\n let endIdx = str.indexOf(';', index);\n\n if (endIdx === -1) {\n endIdx = str.length;\n } else if (endIdx < eqIdx) {\n // backtrack on prior semicolon\n index = str.lastIndexOf(';', eqIdx - 1) + 1;\n continue;\n }\n\n const key = str.slice(index, eqIdx).trim();\n\n // only assign once\n if (undefined === obj[key]) {\n let val = str.slice(eqIdx + 1, endIdx).trim();\n\n // quoted values\n if (val.charCodeAt(0) === 0x22) {\n val = val.slice(1, -1);\n }\n\n try {\n obj[key] = val.indexOf('%') !== -1 ? decodeURIComponent(val) : val;\n } catch (e) {\n obj[key] = val;\n }\n }\n\n index = endIdx + 1;\n }\n\n return obj;\n}\n", "type PartialURL = {\n host?: string;\n path?: string;\n protocol?: string;\n relative?: string;\n search?: string;\n hash?: string;\n};\n\n/**\n * Parses string form of URL into an object\n * // borrowed from https://tools.ietf.org/html/rfc3986#appendix-B\n * // intentionally using regex and not href parsing trick because React Native and other\n * // environments where DOM might not be available\n * @returns parsed URL object\n */\nexport function parseUrl(url: string): PartialURL {\n if (!url) {\n return {};\n }\n\n const match = url.match(/^(([^:/?#]+):)?(\\/\\/([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?$/);\n\n if (!match) {\n return {};\n }\n\n // coerce to undefined values to empty string so we don't get 'undefined'\n const query = match[6] || '';\n const fragment = match[8] || '';\n return {\n host: match[4],\n path: match[5],\n protocol: match[2],\n search: query,\n hash: fragment,\n relative: match[5] + query + fragment, // everything minus origin\n };\n}\n\n/**\n * Strip the query string and fragment off of a given URL or path (if present)\n *\n * @param urlPath Full URL or path, including possible query string and/or fragment\n * @returns URL or path without query string or fragment\n */\nexport function stripUrlQueryAndFragment(urlPath: string): string {\n // eslint-disable-next-line no-useless-escape\n return urlPath.split(/[\\?#]/, 1)[0];\n}\n\n/**\n * Returns number of URL segments of a passed string URL.\n */\nexport function getNumberOfUrlSegments(url: string): number {\n // split at '/' or at '\\/' to split regex urls correctly\n return url.split(/\\\\?\\//).filter(s => s.length > 0 && s !== ',').length;\n}\n\n/**\n * Takes a URL object and returns a sanitized string which is safe to use as span description\n * see: https://develop.sentry.dev/sdk/data-handling/#structuring-data\n */\nexport function getSanitizedUrlString(url: PartialURL): string {\n const { protocol, host, path } = url;\n\n const filteredHost =\n (host &&\n host\n // Always filter out authority\n .replace(/^.*@/, '[filtered]:[filtered]@')\n // Don't show standard :80 (http) and :443 (https) ports to reduce the noise\n // TODO: Use new URL global if it exists\n .replace(/(:80)$/, '')\n .replace(/(:443)$/, '')) ||\n '';\n\n return `${protocol ? `${protocol}://` : ''}${filteredHost}${path}`;\n}\n", "import type {\n Event,\n ExtractedNodeRequestData,\n PolymorphicRequest,\n Transaction,\n TransactionSource,\n WebFetchHeaders,\n WebFetchRequest,\n} from '@sentry/types';\n\nimport { parseCookie } from './cookie';\nimport { DEBUG_BUILD } from './debug-build';\nimport { isPlainObject, isString } from './is';\nimport { logger } from './logger';\nimport { normalize } from './normalize';\nimport { stripUrlQueryAndFragment } from './url';\n\nconst DEFAULT_INCLUDES = {\n ip: false,\n request: true,\n transaction: true,\n user: true,\n};\nconst DEFAULT_REQUEST_INCLUDES = ['cookies', 'data', 'headers', 'method', 'query_string', 'url'];\nexport const DEFAULT_USER_INCLUDES = ['id', 'username', 'email'];\n\ntype InjectedNodeDeps = {\n cookie: {\n parse: (cookieStr: string) => Record;\n };\n url: {\n parse: (urlStr: string) => {\n query: string | null;\n };\n };\n};\n\n/**\n * Options deciding what parts of the request to use when enhancing an event\n */\nexport type AddRequestDataToEventOptions = {\n /** Flags controlling whether each type of data should be added to the event */\n include?: {\n ip?: boolean;\n request?: boolean | Array<(typeof DEFAULT_REQUEST_INCLUDES)[number]>;\n transaction?: boolean | TransactionNamingScheme;\n user?: boolean | Array<(typeof DEFAULT_USER_INCLUDES)[number]>;\n };\n\n /** Injected platform-specific dependencies */\n deps?: {\n cookie: {\n parse: (cookieStr: string) => Record;\n };\n url: {\n parse: (urlStr: string) => {\n query: string | null;\n };\n };\n };\n};\n\nexport type TransactionNamingScheme = 'path' | 'methodPath' | 'handler';\n\n/**\n * Sets parameterized route as transaction name e.g.: `GET /users/:id`\n * Also adds more context data on the transaction from the request.\n *\n * @deprecated This utility will be removed in v8.\n */\nexport function addRequestDataToTransaction(\n transaction: Transaction | undefined,\n req: PolymorphicRequest,\n deps?: InjectedNodeDeps,\n): void {\n if (!transaction) return;\n // eslint-disable-next-line deprecation/deprecation\n if (!transaction.metadata.source || transaction.metadata.source === 'url') {\n // Attempt to grab a parameterized route off of the request\n const [name, source] = extractPathForTransaction(req, { path: true, method: true });\n transaction.updateName(name);\n // TODO: SEMANTIC_ATTRIBUTE_SENTRY_SOURCE is in core, align this once we merge utils & core\n // eslint-disable-next-line deprecation/deprecation\n transaction.setMetadata({ source });\n }\n transaction.setAttribute('url', req.originalUrl || req.url);\n if (req.baseUrl) {\n transaction.setAttribute('baseUrl', req.baseUrl);\n }\n // TODO: We need to rewrite this to a flat format?\n // eslint-disable-next-line deprecation/deprecation\n transaction.setData('query', extractQueryParams(req, deps));\n}\n\n/**\n * Extracts a complete and parameterized path from the request object and uses it to construct transaction name.\n * If the parameterized transaction name cannot be extracted, we fall back to the raw URL.\n *\n * Additionally, this function determines and returns the transaction name source\n *\n * eg. GET /mountpoint/user/:id\n *\n * @param req A request object\n * @param options What to include in the transaction name (method, path, or a custom route name to be\n * used instead of the request's route)\n *\n * @returns A tuple of the fully constructed transaction name [0] and its source [1] (can be either 'route' or 'url')\n */\nexport function extractPathForTransaction(\n req: PolymorphicRequest,\n options: { path?: boolean; method?: boolean; customRoute?: string } = {},\n): [string, TransactionSource] {\n const method = req.method && req.method.toUpperCase();\n\n let path = '';\n let source: TransactionSource = 'url';\n\n // Check to see if there's a parameterized route we can use (as there is in Express)\n if (options.customRoute || req.route) {\n path = options.customRoute || `${req.baseUrl || ''}${req.route && req.route.path}`;\n source = 'route';\n }\n\n // Otherwise, just take the original URL\n else if (req.originalUrl || req.url) {\n path = stripUrlQueryAndFragment(req.originalUrl || req.url || '');\n }\n\n let name = '';\n if (options.method && method) {\n name += method;\n }\n if (options.method && options.path) {\n name += ' ';\n }\n if (options.path && path) {\n name += path;\n }\n\n return [name, source];\n}\n\n/** JSDoc */\nfunction extractTransaction(req: PolymorphicRequest, type: boolean | TransactionNamingScheme): string {\n switch (type) {\n case 'path': {\n return extractPathForTransaction(req, { path: true })[0];\n }\n case 'handler': {\n return (req.route && req.route.stack && req.route.stack[0] && req.route.stack[0].name) || '';\n }\n case 'methodPath':\n default: {\n // if exist _reconstructedRoute return that path instead of route.path\n const customRoute = req._reconstructedRoute ? req._reconstructedRoute : undefined;\n return extractPathForTransaction(req, { path: true, method: true, customRoute })[0];\n }\n }\n}\n\n/** JSDoc */\nfunction extractUserData(\n user: {\n [key: string]: unknown;\n },\n keys: boolean | string[],\n): { [key: string]: unknown } {\n const extractedUser: { [key: string]: unknown } = {};\n const attributes = Array.isArray(keys) ? keys : DEFAULT_USER_INCLUDES;\n\n attributes.forEach(key => {\n if (user && key in user) {\n extractedUser[key] = user[key];\n }\n });\n\n return extractedUser;\n}\n\n/**\n * Normalize data from the request object, accounting for framework differences.\n *\n * @param req The request object from which to extract data\n * @param options.include An optional array of keys to include in the normalized data. Defaults to\n * DEFAULT_REQUEST_INCLUDES if not provided.\n * @param options.deps Injected, platform-specific dependencies\n * @returns An object containing normalized request data\n */\nexport function extractRequestData(\n req: PolymorphicRequest,\n options?: {\n include?: string[];\n deps?: InjectedNodeDeps;\n },\n): ExtractedNodeRequestData {\n const { include = DEFAULT_REQUEST_INCLUDES, deps } = options || {};\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const requestData: { [key: string]: any } = {};\n\n // headers:\n // node, express, koa, nextjs: req.headers\n const headers = (req.headers || {}) as {\n host?: string;\n cookie?: string;\n };\n // method:\n // node, express, koa, nextjs: req.method\n const method = req.method;\n // host:\n // express: req.hostname in > 4 and req.host in < 4\n // koa: req.host\n // node, nextjs: req.headers.host\n // Express 4 mistakenly strips off port number from req.host / req.hostname so we can't rely on them\n // See: https://github.com/expressjs/express/issues/3047#issuecomment-236653223\n // Also: https://github.com/getsentry/sentry-javascript/issues/1917\n const host = headers.host || req.hostname || req.host || '';\n // protocol:\n // node, nextjs: \n // express, koa: req.protocol\n const protocol = req.protocol === 'https' || (req.socket && req.socket.encrypted) ? 'https' : 'http';\n // url (including path and query string):\n // node, express: req.originalUrl\n // koa, nextjs: req.url\n const originalUrl = req.originalUrl || req.url || '';\n // absolute url\n const absoluteUrl = originalUrl.startsWith(protocol) ? originalUrl : `${protocol}://${host}${originalUrl}`;\n include.forEach(key => {\n switch (key) {\n case 'headers': {\n requestData.headers = headers;\n\n // Remove the Cookie header in case cookie data should not be included in the event\n if (!include.includes('cookies')) {\n delete (requestData.headers as { cookie?: string }).cookie;\n }\n\n break;\n }\n case 'method': {\n requestData.method = method;\n break;\n }\n case 'url': {\n requestData.url = absoluteUrl;\n break;\n }\n case 'cookies': {\n // cookies:\n // node, express, koa: req.headers.cookie\n // vercel, sails.js, express (w/ cookie middleware), nextjs: req.cookies\n requestData.cookies =\n // TODO (v8 / #5257): We're only sending the empty object for backwards compatibility, so the last bit can\n // come off in v8\n req.cookies || (headers.cookie && parseCookie(headers.cookie)) || {};\n break;\n }\n case 'query_string': {\n // query string:\n // node: req.url (raw)\n // express, koa, nextjs: req.query\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n requestData.query_string = extractQueryParams(req, deps);\n break;\n }\n case 'data': {\n if (method === 'GET' || method === 'HEAD') {\n break;\n }\n // body data:\n // express, koa, nextjs: req.body\n //\n // when using node by itself, you have to read the incoming stream(see\n // https://nodejs.dev/learn/get-http-request-body-data-using-nodejs); if a user is doing that, we can't know\n // where they're going to store the final result, so they'll have to capture this data themselves\n if (req.body !== undefined) {\n requestData.data = isString(req.body) ? req.body : JSON.stringify(normalize(req.body));\n }\n break;\n }\n default: {\n if ({}.hasOwnProperty.call(req, key)) {\n requestData[key] = (req as { [key: string]: unknown })[key];\n }\n }\n }\n });\n\n return requestData;\n}\n\n/**\n * Add data from the given request to the given event\n *\n * @param event The event to which the request data will be added\n * @param req Request object\n * @param options.include Flags to control what data is included\n * @param options.deps Injected platform-specific dependencies\n * @returns The mutated `Event` object\n */\nexport function addRequestDataToEvent(\n event: Event,\n req: PolymorphicRequest,\n options?: AddRequestDataToEventOptions,\n): Event {\n const include = {\n ...DEFAULT_INCLUDES,\n ...(options && options.include),\n };\n\n if (include.request) {\n const extractedRequestData = Array.isArray(include.request)\n ? extractRequestData(req, { include: include.request, deps: options && options.deps })\n : extractRequestData(req, { deps: options && options.deps });\n\n event.request = {\n ...event.request,\n ...extractedRequestData,\n };\n }\n\n if (include.user) {\n const extractedUser = req.user && isPlainObject(req.user) ? extractUserData(req.user, include.user) : {};\n\n if (Object.keys(extractedUser).length) {\n event.user = {\n ...event.user,\n ...extractedUser,\n };\n }\n }\n\n // client ip:\n // node, nextjs: req.socket.remoteAddress\n // express, koa: req.ip\n if (include.ip) {\n const ip = req.ip || (req.socket && req.socket.remoteAddress);\n if (ip) {\n event.user = {\n ...event.user,\n ip_address: ip,\n };\n }\n }\n\n if (include.transaction && !event.transaction) {\n // TODO do we even need this anymore?\n // TODO make this work for nextjs\n event.transaction = extractTransaction(req, include.transaction);\n }\n\n return event;\n}\n\nfunction extractQueryParams(\n req: PolymorphicRequest,\n deps?: InjectedNodeDeps,\n): string | Record | undefined {\n // url (including path and query string):\n // node, express: req.originalUrl\n // koa, nextjs: req.url\n let originalUrl = req.originalUrl || req.url || '';\n\n if (!originalUrl) {\n return;\n }\n\n // The `URL` constructor can't handle internal URLs of the form `/some/path/here`, so stick a dummy protocol and\n // hostname on the beginning. Since the point here is just to grab the query string, it doesn't matter what we use.\n if (originalUrl.startsWith('/')) {\n originalUrl = `http://dogs.are.great${originalUrl}`;\n }\n\n try {\n return (\n req.query ||\n (typeof URL !== 'undefined' && new URL(originalUrl).search.slice(1)) ||\n // In Node 8, `URL` isn't in the global scope, so we have to use the built-in module from Node\n (deps && deps.url && deps.url.parse(originalUrl).query) ||\n undefined\n );\n } catch {\n return undefined;\n }\n}\n\n/**\n * Transforms a `Headers` object that implements the `Web Fetch API` (https://developer.mozilla.org/en-US/docs/Web/API/Headers) into a simple key-value dict.\n * The header keys will be lower case: e.g. A \"Content-Type\" header will be stored as \"content-type\".\n */\n// TODO(v8): Make this function return undefined when the extraction fails.\nexport function winterCGHeadersToDict(winterCGHeaders: WebFetchHeaders): Record {\n const headers: Record = {};\n try {\n winterCGHeaders.forEach((value, key) => {\n if (typeof value === 'string') {\n // We check that value is a string even though it might be redundant to make sure prototype pollution is not possible.\n headers[key] = value;\n }\n });\n } catch (e) {\n DEBUG_BUILD &&\n logger.warn('Sentry failed extracting headers from a request object. If you see this, please file an issue.');\n }\n\n return headers;\n}\n\n/**\n * Converts a `Request` object that implements the `Web Fetch API` (https://developer.mozilla.org/en-US/docs/Web/API/Headers) into the format that the `RequestData` integration understands.\n */\nexport function winterCGRequestToRequestData(req: WebFetchRequest): PolymorphicRequest {\n const headers = winterCGHeadersToDict(req.headers);\n return {\n method: req.method,\n url: req.url,\n headers,\n };\n}\n", "/* eslint-disable deprecation/deprecation */\nimport type { Severity, SeverityLevel } from '@sentry/types';\n\n// Note: Ideally the `SeverityLevel` type would be derived from `validSeverityLevels`, but that would mean either\n//\n// a) moving `validSeverityLevels` to `@sentry/types`,\n// b) moving the`SeverityLevel` type here, or\n// c) importing `validSeverityLevels` from here into `@sentry/types`.\n//\n// Option A would make `@sentry/types` a runtime dependency of `@sentry/utils` (not good), and options B and C would\n// create a circular dependency between `@sentry/types` and `@sentry/utils` (also not good). So a TODO accompanying the\n// type, reminding anyone who changes it to change this list also, will have to do.\n\nexport const validSeverityLevels = ['fatal', 'error', 'warning', 'log', 'info', 'debug'];\n\n/**\n * Converts a string-based level into a member of the deprecated {@link Severity} enum.\n *\n * @deprecated `severityFromString` is deprecated. Please use `severityLevelFromString` instead.\n *\n * @param level String representation of Severity\n * @returns Severity\n */\nexport function severityFromString(level: Severity | SeverityLevel | string): Severity {\n return severityLevelFromString(level) as Severity;\n}\n\n/**\n * Converts a string-based level into a `SeverityLevel`, normalizing it along the way.\n *\n * @param level String representation of desired `SeverityLevel`.\n * @returns The `SeverityLevel` corresponding to the given string, or 'log' if the string isn't a valid level.\n */\nexport function severityLevelFromString(level: SeverityLevel | string): SeverityLevel {\n return (level === 'warn' ? 'warning' : validSeverityLevels.includes(level) ? level : 'log') as SeverityLevel;\n}\n", "import { GLOBAL_OBJ } from './worldwide';\n\nconst ONE_SECOND_IN_MS = 1000;\n\n/**\n * A partial definition of the [Performance Web API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Performance}\n * for accessing a high-resolution monotonic clock.\n */\ninterface Performance {\n /**\n * The millisecond timestamp at which measurement began, measured in Unix time.\n */\n timeOrigin: number;\n /**\n * Returns the current millisecond timestamp, where 0 represents the start of measurement.\n */\n now(): number;\n}\n\n/**\n * Returns a timestamp in seconds since the UNIX epoch using the Date API.\n *\n * TODO(v8): Return type should be rounded.\n */\nexport function dateTimestampInSeconds(): number {\n return Date.now() / ONE_SECOND_IN_MS;\n}\n\n/**\n * Returns a wrapper around the native Performance API browser implementation, or undefined for browsers that do not\n * support the API.\n *\n * Wrapping the native API works around differences in behavior from different browsers.\n */\nfunction createUnixTimestampInSecondsFunc(): () => number {\n const { performance } = GLOBAL_OBJ as typeof GLOBAL_OBJ & { performance?: Performance };\n if (!performance || !performance.now) {\n return dateTimestampInSeconds;\n }\n\n // Some browser and environments don't have a timeOrigin, so we fallback to\n // using Date.now() to compute the starting time.\n const approxStartingTimeOrigin = Date.now() - performance.now();\n const timeOrigin = performance.timeOrigin == undefined ? approxStartingTimeOrigin : performance.timeOrigin;\n\n // performance.now() is a monotonic clock, which means it starts at 0 when the process begins. To get the current\n // wall clock time (actual UNIX timestamp), we need to add the starting time origin and the current time elapsed.\n //\n // TODO: This does not account for the case where the monotonic clock that powers performance.now() drifts from the\n // wall clock time, which causes the returned timestamp to be inaccurate. We should investigate how to detect and\n // correct for this.\n // See: https://github.com/getsentry/sentry-javascript/issues/2590\n // See: https://github.com/mdn/content/issues/4713\n // See: https://dev.to/noamr/when-a-millisecond-is-not-a-millisecond-3h6\n return () => {\n return (timeOrigin + performance.now()) / ONE_SECOND_IN_MS;\n };\n}\n\n/**\n * Returns a timestamp in seconds since the UNIX epoch using either the Performance or Date APIs, depending on the\n * availability of the Performance API.\n *\n * BUG: Note that because of how browsers implement the Performance API, the clock might stop when the computer is\n * asleep. This creates a skew between `dateTimestampInSeconds` and `timestampInSeconds`. The\n * skew can grow to arbitrary amounts like days, weeks or months.\n * See https://github.com/getsentry/sentry-javascript/issues/2590.\n */\nexport const timestampInSeconds = createUnixTimestampInSecondsFunc();\n\n/**\n * Re-exported with an old name for backwards-compatibility.\n * TODO (v8): Remove this\n *\n * @deprecated Use `timestampInSeconds` instead.\n */\nexport const timestampWithMs = timestampInSeconds;\n\n/**\n * Internal helper to store what is the source of browserPerformanceTimeOrigin below. For debugging only.\n */\nexport let _browserPerformanceTimeOriginMode: string;\n\n/**\n * The number of milliseconds since the UNIX epoch. This value is only usable in a browser, and only when the\n * performance API is available.\n */\nexport const browserPerformanceTimeOrigin = ((): number | undefined => {\n // Unfortunately browsers may report an inaccurate time origin data, through either performance.timeOrigin or\n // performance.timing.navigationStart, which results in poor results in performance data. We only treat time origin\n // data as reliable if they are within a reasonable threshold of the current time.\n\n const { performance } = GLOBAL_OBJ as typeof GLOBAL_OBJ & Window;\n if (!performance || !performance.now) {\n _browserPerformanceTimeOriginMode = 'none';\n return undefined;\n }\n\n const threshold = 3600 * 1000;\n const performanceNow = performance.now();\n const dateNow = Date.now();\n\n // if timeOrigin isn't available set delta to threshold so it isn't used\n const timeOriginDelta = performance.timeOrigin\n ? Math.abs(performance.timeOrigin + performanceNow - dateNow)\n : threshold;\n const timeOriginIsReliable = timeOriginDelta < threshold;\n\n // While performance.timing.navigationStart is deprecated in favor of performance.timeOrigin, performance.timeOrigin\n // is not as widely supported. Namely, performance.timeOrigin is undefined in Safari as of writing.\n // Also as of writing, performance.timing is not available in Web Workers in mainstream browsers, so it is not always\n // a valid fallback. In the absence of an initial time provided by the browser, fallback to the current time from the\n // Date API.\n // eslint-disable-next-line deprecation/deprecation\n const navigationStart = performance.timing && performance.timing.navigationStart;\n const hasNavigationStart = typeof navigationStart === 'number';\n // if navigationStart isn't available set delta to threshold so it isn't used\n const navigationStartDelta = hasNavigationStart ? Math.abs(navigationStart + performanceNow - dateNow) : threshold;\n const navigationStartIsReliable = navigationStartDelta < threshold;\n\n if (timeOriginIsReliable || navigationStartIsReliable) {\n // Use the more reliable time origin\n if (timeOriginDelta <= navigationStartDelta) {\n _browserPerformanceTimeOriginMode = 'timeOrigin';\n return performance.timeOrigin;\n } else {\n _browserPerformanceTimeOriginMode = 'navigationStart';\n return navigationStart;\n }\n }\n\n // Either both timeOrigin and navigationStart are skewed or neither is available, fallback to Date.\n _browserPerformanceTimeOriginMode = 'dateNow';\n return dateNow;\n})();\n", "import type { DynamicSamplingContext } from '@sentry/types';\n\nimport { DEBUG_BUILD } from './debug-build';\nimport { isString } from './is';\nimport { logger } from './logger';\n\nexport const BAGGAGE_HEADER_NAME = 'baggage';\n\nexport const SENTRY_BAGGAGE_KEY_PREFIX = 'sentry-';\n\nexport const SENTRY_BAGGAGE_KEY_PREFIX_REGEX = /^sentry-/;\n\n/**\n * Max length of a serialized baggage string\n *\n * https://www.w3.org/TR/baggage/#limits\n */\nexport const MAX_BAGGAGE_STRING_LENGTH = 8192;\n\n/**\n * Takes a baggage header and turns it into Dynamic Sampling Context, by extracting all the \"sentry-\" prefixed values\n * from it.\n *\n * @param baggageHeader A very bread definition of a baggage header as it might appear in various frameworks.\n * @returns The Dynamic Sampling Context that was found on `baggageHeader`, if there was any, `undefined` otherwise.\n */\nexport function baggageHeaderToDynamicSamplingContext(\n // Very liberal definition of what any incoming header might look like\n baggageHeader: string | string[] | number | null | undefined | boolean,\n): Partial | undefined {\n if (!isString(baggageHeader) && !Array.isArray(baggageHeader)) {\n return undefined;\n }\n\n // Intermediary object to store baggage key value pairs of incoming baggage headers on.\n // It is later used to read Sentry-DSC-values from.\n let baggageObject: Readonly> = {};\n\n if (Array.isArray(baggageHeader)) {\n // Combine all baggage headers into one object containing the baggage values so we can later read the Sentry-DSC-values from it\n baggageObject = baggageHeader.reduce>((acc, curr) => {\n const currBaggageObject = baggageHeaderToObject(curr);\n for (const key of Object.keys(currBaggageObject)) {\n acc[key] = currBaggageObject[key];\n }\n return acc;\n }, {});\n } else {\n // Return undefined if baggage header is an empty string (technically an empty baggage header is not spec conform but\n // this is how we choose to handle it)\n if (!baggageHeader) {\n return undefined;\n }\n\n baggageObject = baggageHeaderToObject(baggageHeader);\n }\n\n // Read all \"sentry-\" prefixed values out of the baggage object and put it onto a dynamic sampling context object.\n const dynamicSamplingContext = Object.entries(baggageObject).reduce>((acc, [key, value]) => {\n if (key.match(SENTRY_BAGGAGE_KEY_PREFIX_REGEX)) {\n const nonPrefixedKey = key.slice(SENTRY_BAGGAGE_KEY_PREFIX.length);\n acc[nonPrefixedKey] = value;\n }\n return acc;\n }, {});\n\n // Only return a dynamic sampling context object if there are keys in it.\n // A keyless object means there were no sentry values on the header, which means that there is no DSC.\n if (Object.keys(dynamicSamplingContext).length > 0) {\n return dynamicSamplingContext as Partial;\n } else {\n return undefined;\n }\n}\n\n/**\n * Turns a Dynamic Sampling Object into a baggage header by prefixing all the keys on the object with \"sentry-\".\n *\n * @param dynamicSamplingContext The Dynamic Sampling Context to turn into a header. For convenience and compatibility\n * with the `getDynamicSamplingContext` method on the Transaction class ,this argument can also be `undefined`. If it is\n * `undefined` the function will return `undefined`.\n * @returns a baggage header, created from `dynamicSamplingContext`, or `undefined` either if `dynamicSamplingContext`\n * was `undefined`, or if `dynamicSamplingContext` didn't contain any values.\n */\nexport function dynamicSamplingContextToSentryBaggageHeader(\n // this also takes undefined for convenience and bundle size in other places\n dynamicSamplingContext?: Partial,\n): string | undefined {\n if (!dynamicSamplingContext) {\n return undefined;\n }\n\n // Prefix all DSC keys with \"sentry-\" and put them into a new object\n const sentryPrefixedDSC = Object.entries(dynamicSamplingContext).reduce>(\n (acc, [dscKey, dscValue]) => {\n if (dscValue) {\n acc[`${SENTRY_BAGGAGE_KEY_PREFIX}${dscKey}`] = dscValue;\n }\n return acc;\n },\n {},\n );\n\n return objectToBaggageHeader(sentryPrefixedDSC);\n}\n\n/**\n * Will parse a baggage header, which is a simple key-value map, into a flat object.\n *\n * @param baggageHeader The baggage header to parse.\n * @returns a flat object containing all the key-value pairs from `baggageHeader`.\n */\nfunction baggageHeaderToObject(baggageHeader: string): Record {\n return baggageHeader\n .split(',')\n .map(baggageEntry => baggageEntry.split('=').map(keyOrValue => decodeURIComponent(keyOrValue.trim())))\n .reduce>((acc, [key, value]) => {\n acc[key] = value;\n return acc;\n }, {});\n}\n\n/**\n * Turns a flat object (key-value pairs) into a baggage header, which is also just key-value pairs.\n *\n * @param object The object to turn into a baggage header.\n * @returns a baggage header string, or `undefined` if the object didn't have any values, since an empty baggage header\n * is not spec compliant.\n */\nfunction objectToBaggageHeader(object: Record): string | undefined {\n if (Object.keys(object).length === 0) {\n // An empty baggage header is not spec compliant: We return undefined.\n return undefined;\n }\n\n return Object.entries(object).reduce((baggageHeader, [objectKey, objectValue], currentIndex) => {\n const baggageEntry = `${encodeURIComponent(objectKey)}=${encodeURIComponent(objectValue)}`;\n const newBaggageHeader = currentIndex === 0 ? baggageEntry : `${baggageHeader},${baggageEntry}`;\n if (newBaggageHeader.length > MAX_BAGGAGE_STRING_LENGTH) {\n DEBUG_BUILD &&\n logger.warn(\n `Not adding key: ${objectKey} with val: ${objectValue} to baggage header due to exceeding baggage size limits.`,\n );\n return baggageHeader;\n } else {\n return newBaggageHeader;\n }\n }, '');\n}\n", "import type { PropagationContext, TraceparentData } from '@sentry/types';\n\nimport { baggageHeaderToDynamicSamplingContext } from './baggage';\nimport { uuid4 } from './misc';\n\n// eslint-disable-next-line @sentry-internal/sdk/no-regexp-constructor -- RegExp is used for readability here\nexport const TRACEPARENT_REGEXP = new RegExp(\n '^[ \\\\t]*' + // whitespace\n '([0-9a-f]{32})?' + // trace_id\n '-?([0-9a-f]{16})?' + // span_id\n '-?([01])?' + // sampled\n '[ \\\\t]*$', // whitespace\n);\n\n/**\n * Extract transaction context data from a `sentry-trace` header.\n *\n * @param traceparent Traceparent string\n *\n * @returns Object containing data from the header, or undefined if traceparent string is malformed\n */\nexport function extractTraceparentData(traceparent?: string): TraceparentData | undefined {\n if (!traceparent) {\n return undefined;\n }\n\n const matches = traceparent.match(TRACEPARENT_REGEXP);\n if (!matches) {\n return undefined;\n }\n\n let parentSampled: boolean | undefined;\n if (matches[3] === '1') {\n parentSampled = true;\n } else if (matches[3] === '0') {\n parentSampled = false;\n }\n\n return {\n traceId: matches[1],\n parentSampled,\n parentSpanId: matches[2],\n };\n}\n\n/**\n * Create tracing context from incoming headers.\n *\n * @deprecated Use `propagationContextFromHeaders` instead.\n */\n// TODO(v8): Remove this function\nexport function tracingContextFromHeaders(\n sentryTrace: Parameters[0],\n baggage: Parameters[0],\n): {\n traceparentData: ReturnType;\n dynamicSamplingContext: ReturnType;\n propagationContext: PropagationContext;\n} {\n const traceparentData = extractTraceparentData(sentryTrace);\n const dynamicSamplingContext = baggageHeaderToDynamicSamplingContext(baggage);\n\n const { traceId, parentSpanId, parentSampled } = traceparentData || {};\n\n if (!traceparentData) {\n return {\n traceparentData,\n dynamicSamplingContext: undefined,\n propagationContext: {\n traceId: traceId || uuid4(),\n spanId: uuid4().substring(16),\n },\n };\n } else {\n return {\n traceparentData,\n dynamicSamplingContext: dynamicSamplingContext || {}, // If we have traceparent data but no DSC it means we are not head of trace and we must freeze it\n propagationContext: {\n traceId: traceId || uuid4(),\n parentSpanId: parentSpanId || uuid4().substring(16),\n spanId: uuid4().substring(16),\n sampled: parentSampled,\n dsc: dynamicSamplingContext || {}, // If we have traceparent data but no DSC it means we are not head of trace and we must freeze it\n },\n };\n }\n}\n\n/**\n * Create a propagation context from incoming headers.\n */\nexport function propagationContextFromHeaders(\n sentryTrace: string | undefined,\n baggage: string | number | boolean | string[] | null | undefined,\n): PropagationContext {\n const traceparentData = extractTraceparentData(sentryTrace);\n const dynamicSamplingContext = baggageHeaderToDynamicSamplingContext(baggage);\n\n const { traceId, parentSpanId, parentSampled } = traceparentData || {};\n\n if (!traceparentData) {\n return {\n traceId: traceId || uuid4(),\n spanId: uuid4().substring(16),\n };\n } else {\n return {\n traceId: traceId || uuid4(),\n parentSpanId: parentSpanId || uuid4().substring(16),\n spanId: uuid4().substring(16),\n sampled: parentSampled,\n dsc: dynamicSamplingContext || {}, // If we have traceparent data but no DSC it means we are not head of trace and we must freeze it\n };\n }\n}\n\n/**\n * Create sentry-trace header from span context values.\n */\nexport function generateSentryTraceHeader(\n traceId: string = uuid4(),\n spanId: string = uuid4().substring(16),\n sampled?: boolean,\n): string {\n let sampledString = '';\n if (sampled !== undefined) {\n sampledString = sampled ? '-1' : '-0';\n }\n return `${traceId}-${spanId}${sampledString}`;\n}\n", "import type {\n Attachment,\n AttachmentItem,\n BaseEnvelopeHeaders,\n BaseEnvelopeItemHeaders,\n DataCategory,\n DsnComponents,\n Envelope,\n EnvelopeItemType,\n Event,\n EventEnvelopeHeaders,\n SdkInfo,\n SdkMetadata,\n TextEncoderInternal,\n} from '@sentry/types';\n\nimport { dsnToString } from './dsn';\nimport { normalize } from './normalize';\nimport { dropUndefinedKeys } from './object';\n\n/**\n * Creates an envelope.\n * Make sure to always explicitly provide the generic to this function\n * so that the envelope types resolve correctly.\n */\nexport function createEnvelope(headers: E[0], items: E[1] = []): E {\n return [headers, items] as E;\n}\n\n/**\n * Add an item to an envelope.\n * Make sure to always explicitly provide the generic to this function\n * so that the envelope types resolve correctly.\n */\nexport function addItemToEnvelope(envelope: E, newItem: E[1][number]): E {\n const [headers, items] = envelope;\n return [headers, [...items, newItem]] as unknown as E;\n}\n\n/**\n * Convenience function to loop through the items and item types of an envelope.\n * (This function was mostly created because working with envelope types is painful at the moment)\n *\n * If the callback returns true, the rest of the items will be skipped.\n */\nexport function forEachEnvelopeItem(\n envelope: Envelope,\n callback: (envelopeItem: E[1][number], envelopeItemType: E[1][number][0]['type']) => boolean | void,\n): boolean {\n const envelopeItems = envelope[1];\n\n for (const envelopeItem of envelopeItems) {\n const envelopeItemType = envelopeItem[0].type;\n const result = callback(envelopeItem, envelopeItemType);\n\n if (result) {\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Returns true if the envelope contains any of the given envelope item types\n */\nexport function envelopeContainsItemType(envelope: Envelope, types: EnvelopeItemType[]): boolean {\n return forEachEnvelopeItem(envelope, (_, type) => types.includes(type));\n}\n\n/**\n * Encode a string to UTF8.\n */\nfunction encodeUTF8(input: string, textEncoder?: TextEncoderInternal): Uint8Array {\n const utf8 = textEncoder || new TextEncoder();\n return utf8.encode(input);\n}\n\n/**\n * Serializes an envelope.\n */\nexport function serializeEnvelope(envelope: Envelope, textEncoder?: TextEncoderInternal): string | Uint8Array {\n const [envHeaders, items] = envelope;\n\n // Initially we construct our envelope as a string and only convert to binary chunks if we encounter binary data\n let parts: string | Uint8Array[] = JSON.stringify(envHeaders);\n\n function append(next: string | Uint8Array): void {\n if (typeof parts === 'string') {\n parts = typeof next === 'string' ? parts + next : [encodeUTF8(parts, textEncoder), next];\n } else {\n parts.push(typeof next === 'string' ? encodeUTF8(next, textEncoder) : next);\n }\n }\n\n for (const item of items) {\n const [itemHeaders, payload] = item;\n\n append(`\\n${JSON.stringify(itemHeaders)}\\n`);\n\n if (typeof payload === 'string' || payload instanceof Uint8Array) {\n append(payload);\n } else {\n let stringifiedPayload: string;\n try {\n stringifiedPayload = JSON.stringify(payload);\n } catch (e) {\n // In case, despite all our efforts to keep `payload` circular-dependency-free, `JSON.strinify()` still\n // fails, we try again after normalizing it again with infinite normalization depth. This of course has a\n // performance impact but in this case a performance hit is better than throwing.\n stringifiedPayload = JSON.stringify(normalize(payload));\n }\n append(stringifiedPayload);\n }\n }\n\n return typeof parts === 'string' ? parts : concatBuffers(parts);\n}\n\nfunction concatBuffers(buffers: Uint8Array[]): Uint8Array {\n const totalLength = buffers.reduce((acc, buf) => acc + buf.length, 0);\n\n const merged = new Uint8Array(totalLength);\n let offset = 0;\n for (const buffer of buffers) {\n merged.set(buffer, offset);\n offset += buffer.length;\n }\n\n return merged;\n}\n\nexport interface TextDecoderInternal {\n decode(input?: Uint8Array): string;\n}\n\n/**\n * Parses an envelope\n */\nexport function parseEnvelope(\n env: string | Uint8Array,\n textEncoder: TextEncoderInternal,\n textDecoder: TextDecoderInternal,\n): Envelope {\n let buffer = typeof env === 'string' ? textEncoder.encode(env) : env;\n\n function readBinary(length: number): Uint8Array {\n const bin = buffer.subarray(0, length);\n // Replace the buffer with the remaining data excluding trailing newline\n buffer = buffer.subarray(length + 1);\n return bin;\n }\n\n function readJson(): T {\n let i = buffer.indexOf(0xa);\n // If we couldn't find a newline, we must have found the end of the buffer\n if (i < 0) {\n i = buffer.length;\n }\n\n return JSON.parse(textDecoder.decode(readBinary(i))) as T;\n }\n\n const envelopeHeader = readJson();\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const items: [any, any][] = [];\n\n while (buffer.length) {\n const itemHeader = readJson();\n const binaryLength = typeof itemHeader.length === 'number' ? itemHeader.length : undefined;\n\n items.push([itemHeader, binaryLength ? readBinary(binaryLength) : readJson()]);\n }\n\n return [envelopeHeader, items];\n}\n\n/**\n * Creates attachment envelope items\n */\nexport function createAttachmentEnvelopeItem(\n attachment: Attachment,\n textEncoder?: TextEncoderInternal,\n): AttachmentItem {\n const buffer = typeof attachment.data === 'string' ? encodeUTF8(attachment.data, textEncoder) : attachment.data;\n\n return [\n dropUndefinedKeys({\n type: 'attachment',\n length: buffer.length,\n filename: attachment.filename,\n content_type: attachment.contentType,\n attachment_type: attachment.attachmentType,\n }),\n buffer,\n ];\n}\n\nconst ITEM_TYPE_TO_DATA_CATEGORY_MAP: Record = {\n session: 'session',\n sessions: 'session',\n attachment: 'attachment',\n transaction: 'transaction',\n event: 'error',\n client_report: 'internal',\n user_report: 'default',\n profile: 'profile',\n replay_event: 'replay',\n replay_recording: 'replay',\n check_in: 'monitor',\n feedback: 'feedback',\n span: 'span',\n statsd: 'metric_bucket',\n};\n\n/**\n * Maps the type of an envelope item to a data category.\n */\nexport function envelopeItemTypeToDataCategory(type: EnvelopeItemType): DataCategory {\n return ITEM_TYPE_TO_DATA_CATEGORY_MAP[type];\n}\n\n/** Extracts the minimal SDK info from the metadata or an events */\nexport function getSdkMetadataForEnvelopeHeader(metadataOrEvent?: SdkMetadata | Event): SdkInfo | undefined {\n if (!metadataOrEvent || !metadataOrEvent.sdk) {\n return;\n }\n const { name, version } = metadataOrEvent.sdk;\n return { name, version };\n}\n\n/**\n * Creates event envelope headers, based on event, sdk info and tunnel\n * Note: This function was extracted from the core package to make it available in Replay\n */\nexport function createEventEnvelopeHeaders(\n event: Event,\n sdkInfo: SdkInfo | undefined,\n tunnel: string | undefined,\n dsn?: DsnComponents,\n): EventEnvelopeHeaders {\n const dynamicSamplingContext = event.sdkProcessingMetadata && event.sdkProcessingMetadata.dynamicSamplingContext;\n return {\n event_id: event.event_id as string,\n sent_at: new Date().toISOString(),\n ...(sdkInfo && { sdk: sdkInfo }),\n ...(!!tunnel && dsn && { dsn: dsnToString(dsn) }),\n ...(dynamicSamplingContext && {\n trace: dropUndefinedKeys({ ...dynamicSamplingContext }),\n }),\n };\n}\n", "import type { ClientReport, ClientReportEnvelope, ClientReportItem } from '@sentry/types';\n\nimport { createEnvelope } from './envelope';\nimport { dateTimestampInSeconds } from './time';\n\n/**\n * Creates client report envelope\n * @param discarded_events An array of discard events\n * @param dsn A DSN that can be set on the header. Optional.\n */\nexport function createClientReportEnvelope(\n discarded_events: ClientReport['discarded_events'],\n dsn?: string,\n timestamp?: number,\n): ClientReportEnvelope {\n const clientReportItem: ClientReportItem = [\n { type: 'client_report' },\n {\n timestamp: timestamp || dateTimestampInSeconds(),\n discarded_events,\n },\n ];\n return createEnvelope(dsn ? { dsn } : {}, [clientReportItem]);\n}\n", "import type { DataCategory, TransportMakeRequestResponse } from '@sentry/types';\n\n// Intentionally keeping the key broad, as we don't know for sure what rate limit headers get returned from backend\nexport type RateLimits = Record;\n\nexport const DEFAULT_RETRY_AFTER = 60 * 1000; // 60 seconds\n\n/**\n * Extracts Retry-After value from the request header or returns default value\n * @param header string representation of 'Retry-After' header\n * @param now current unix timestamp\n *\n */\nexport function parseRetryAfterHeader(header: string, now: number = Date.now()): number {\n const headerDelay = parseInt(`${header}`, 10);\n if (!isNaN(headerDelay)) {\n return headerDelay * 1000;\n }\n\n const headerDate = Date.parse(`${header}`);\n if (!isNaN(headerDate)) {\n return headerDate - now;\n }\n\n return DEFAULT_RETRY_AFTER;\n}\n\n/**\n * Gets the time that the given category is disabled until for rate limiting.\n * In case no category-specific limit is set but a general rate limit across all categories is active,\n * that time is returned.\n *\n * @return the time in ms that the category is disabled until or 0 if there's no active rate limit.\n */\nexport function disabledUntil(limits: RateLimits, dataCategory: DataCategory): number {\n return limits[dataCategory] || limits.all || 0;\n}\n\n/**\n * Checks if a category is rate limited\n */\nexport function isRateLimited(limits: RateLimits, dataCategory: DataCategory, now: number = Date.now()): boolean {\n return disabledUntil(limits, dataCategory) > now;\n}\n\n/**\n * Update ratelimits from incoming headers.\n *\n * @return the updated RateLimits object.\n */\nexport function updateRateLimits(\n limits: RateLimits,\n { statusCode, headers }: TransportMakeRequestResponse,\n now: number = Date.now(),\n): RateLimits {\n const updatedRateLimits: RateLimits = {\n ...limits,\n };\n\n // \"The name is case-insensitive.\"\n // https://developer.mozilla.org/en-US/docs/Web/API/Headers/get\n const rateLimitHeader = headers && headers['x-sentry-rate-limits'];\n const retryAfterHeader = headers && headers['retry-after'];\n\n if (rateLimitHeader) {\n /**\n * rate limit headers are of the form\n *
,
,..\n * where each
is of the form\n * : : : : \n * where\n * is a delay in seconds\n * is the event type(s) (error, transaction, etc) being rate limited and is of the form\n * ;;...\n * is what's being limited (org, project, or key) - ignored by SDK\n * is an arbitrary string like \"org_quota\" - ignored by SDK\n * Semicolon-separated list of metric namespace identifiers. Defines which namespace(s) will be affected.\n * Only present if rate limit applies to the metric_bucket data category.\n */\n for (const limit of rateLimitHeader.trim().split(',')) {\n const [retryAfter, categories, , , namespaces] = limit.split(':', 5);\n const headerDelay = parseInt(retryAfter, 10);\n const delay = (!isNaN(headerDelay) ? headerDelay : 60) * 1000; // 60sec default\n if (!categories) {\n updatedRateLimits.all = now + delay;\n } else {\n for (const category of categories.split(';')) {\n if (category === 'metric_bucket') {\n // namespaces will be present when category === 'metric_bucket'\n if (!namespaces || namespaces.split(';').includes('custom')) {\n updatedRateLimits[category] = now + delay;\n }\n } else {\n updatedRateLimits[category] = now + delay;\n }\n }\n }\n }\n } else if (retryAfterHeader) {\n updatedRateLimits.all = now + parseRetryAfterHeader(retryAfterHeader, now);\n } else if (statusCode === 429) {\n updatedRateLimits.all = now + 60 * 1000;\n }\n\n return updatedRateLimits;\n}\n", "import type { Integration } from '@sentry/types';\n\nexport type UserIntegrationsFunction = (integrations: Integration[]) => Integration[];\nexport type UserIntegrations = Integration[] | UserIntegrationsFunction;\nexport type IntegrationWithExclusionOption = Integration & {\n /**\n * Allow the user to exclude this integration by not returning it from a function provided as the `integrations` option\n * in `Sentry.init()`. Meant to be used with default integrations, the idea being that if a user has actively filtered\n * an integration out, we should be able to respect that choice if we wish.\n */\n allowExclusionByUser?: boolean;\n};\n\ntype ForcedIntegrationOptions = {\n [keyPath: string]: unknown;\n};\n\n/**\n * Recursively traverses an object to update an existing nested key.\n * Note: The provided key path must include existing properties,\n * the function will not create objects while traversing.\n *\n * @param obj An object to update\n * @param value The value to update the nested key with\n * @param keyPath The path to the key to update ex. fizz.buzz.foo\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction setNestedKey(obj: Record, keyPath: string, value: unknown): void {\n // Ex. foo.bar.zoop will extract foo and bar.zoop\n const match = keyPath.match(/([a-z_]+)\\.(.*)/i);\n // The match will be null when there's no more recursing to do, i.e., when we've reached the right level of the object\n if (match === null) {\n obj[keyPath] = value;\n } else {\n // `match[1]` is the initial segment of the path, and `match[2]` is the remainder of the path\n const innerObj = obj[match[1]];\n setNestedKey(innerObj, match[2], value);\n }\n}\n\n/**\n * Enforces inclusion of a given integration with specified options in an integration array originally determined by the\n * user, by either including the given default instance or by patching an existing user instance with the given options.\n *\n * Ideally this would happen when integrations are set up, but there isn't currently a mechanism there for merging\n * options from a default integration instance with those from a user-provided instance of the same integration, only\n * for allowing the user to override a default instance entirely. (TODO: Fix that.)\n *\n * @param defaultIntegrationInstance An instance of the integration with the correct options already set\n * @param userIntegrations Integrations defined by the user.\n * @param forcedOptions Options with which to patch an existing user-derived instance on the integration.\n * @returns A final integrations array.\n *\n * @deprecated This will be removed in v8.\n */\nexport function addOrUpdateIntegration(\n defaultIntegrationInstance: Integration,\n userIntegrations: T,\n forcedOptions: ForcedIntegrationOptions = {},\n): T {\n return (\n Array.isArray(userIntegrations)\n ? addOrUpdateIntegrationInArray(defaultIntegrationInstance, userIntegrations, forcedOptions)\n : addOrUpdateIntegrationInFunction(\n defaultIntegrationInstance,\n // Somehow TS can't figure out that not being an array makes this necessarily a function\n userIntegrations as UserIntegrationsFunction,\n forcedOptions,\n )\n ) as T;\n}\n\nfunction addOrUpdateIntegrationInArray(\n defaultIntegrationInstance: Integration,\n userIntegrations: Integration[],\n forcedOptions: ForcedIntegrationOptions,\n): Integration[] {\n const userInstance = userIntegrations.find(integration => integration.name === defaultIntegrationInstance.name);\n\n if (userInstance) {\n for (const [keyPath, value] of Object.entries(forcedOptions)) {\n setNestedKey(userInstance, keyPath, value);\n }\n\n return userIntegrations;\n }\n\n return [...userIntegrations, defaultIntegrationInstance];\n}\n\nfunction addOrUpdateIntegrationInFunction(\n defaultIntegrationInstance: IntegrationWithExclusionOption,\n userIntegrationsFunc: UserIntegrationsFunction,\n forcedOptions: ForcedIntegrationOptions,\n): UserIntegrationsFunction {\n const wrapper: UserIntegrationsFunction = defaultIntegrations => {\n const userFinalIntegrations = userIntegrationsFunc(defaultIntegrations);\n\n // There are instances where we want the user to be able to prevent an integration from appearing at all, which they\n // would do by providing a function which filters out the integration in question. If that's happened in one of\n // those cases, don't add our default back in.\n if (defaultIntegrationInstance.allowExclusionByUser) {\n const userFinalInstance = userFinalIntegrations.find(\n integration => integration.name === defaultIntegrationInstance.name,\n );\n if (!userFinalInstance) {\n return userFinalIntegrations;\n }\n }\n\n return addOrUpdateIntegrationInArray(defaultIntegrationInstance, userFinalIntegrations, forcedOptions);\n };\n\n return wrapper;\n}\n", "/**\n * Creates a cache that evicts keys in fifo order\n * @param size {Number}\n */\nexport function makeFifoCache(\n size: number,\n): {\n get: (key: Key) => Value | undefined;\n add: (key: Key, value: Value) => void;\n delete: (key: Key) => boolean;\n clear: () => void;\n size: () => number;\n} {\n // Maintain a fifo queue of keys, we cannot rely on Object.keys as the browser may not support it.\n let evictionOrder: Key[] = [];\n let cache: Record = {};\n\n return {\n add(key: Key, value: Value) {\n while (evictionOrder.length >= size) {\n // shift is O(n) but this is small size and only happens if we are\n // exceeding the cache size so it should be fine.\n const evictCandidate = evictionOrder.shift();\n\n if (evictCandidate !== undefined) {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete cache[evictCandidate];\n }\n }\n\n // in case we have a collision, delete the old key.\n if (cache[key]) {\n this.delete(key);\n }\n\n evictionOrder.push(key);\n cache[key] = value;\n },\n clear() {\n cache = {};\n evictionOrder = [];\n },\n get(key: Key): Value | undefined {\n return cache[key];\n },\n size() {\n return evictionOrder.length;\n },\n // Delete cache key and return true if it existed, false otherwise.\n delete(key: Key): boolean {\n if (!cache[key]) {\n return false;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete cache[key];\n\n for (let i = 0; i < evictionOrder.length; i++) {\n if (evictionOrder[i] === key) {\n evictionOrder.splice(i, 1);\n break;\n }\n }\n\n return true;\n },\n };\n}\n", "import type {\n Client,\n Event,\n EventHint,\n Exception,\n Extras,\n Hub,\n Mechanism,\n ParameterizedString,\n Severity,\n SeverityLevel,\n StackFrame,\n StackParser,\n} from '@sentry/types';\n\nimport { isError, isParameterizedString, isPlainObject } from './is';\nimport { addExceptionMechanism, addExceptionTypeValue } from './misc';\nimport { normalizeToSize } from './normalize';\nimport { extractExceptionKeysForMessage } from './object';\n\n/**\n * Extracts stack frames from the error.stack string\n */\nexport function parseStackFrames(stackParser: StackParser, error: Error): StackFrame[] {\n return stackParser(error.stack || '', 1);\n}\n\n/**\n * Extracts stack frames from the error and builds a Sentry Exception\n */\nexport function exceptionFromError(stackParser: StackParser, error: Error): Exception {\n const exception: Exception = {\n type: error.name || error.constructor.name,\n value: error.message,\n };\n\n const frames = parseStackFrames(stackParser, error);\n if (frames.length) {\n exception.stacktrace = { frames };\n }\n\n return exception;\n}\n\nfunction getMessageForObject(exception: object): string {\n if ('name' in exception && typeof exception.name === 'string') {\n let message = `'${exception.name}' captured as exception`;\n\n if ('message' in exception && typeof exception.message === 'string') {\n message += ` with message '${exception.message}'`;\n }\n\n return message;\n } else if ('message' in exception && typeof exception.message === 'string') {\n return exception.message;\n } else {\n // This will allow us to group events based on top-level keys\n // which is much better than creating new group when any key/value change\n return `Object captured as exception with keys: ${extractExceptionKeysForMessage(\n exception as Record,\n )}`;\n }\n}\n\n/**\n * Builds and Event from a Exception\n *\n * TODO(v8): Remove getHub fallback\n * @hidden\n */\nexport function eventFromUnknownInput(\n // eslint-disable-next-line deprecation/deprecation\n getHubOrClient: (() => Hub) | Client | undefined,\n stackParser: StackParser,\n exception: unknown,\n hint?: EventHint,\n): Event {\n const client =\n typeof getHubOrClient === 'function'\n ? // eslint-disable-next-line deprecation/deprecation\n getHubOrClient().getClient()\n : getHubOrClient;\n\n let ex: unknown = exception;\n const providedMechanism: Mechanism | undefined =\n hint && hint.data && (hint.data as { mechanism: Mechanism }).mechanism;\n const mechanism: Mechanism = providedMechanism || {\n handled: true,\n type: 'generic',\n };\n\n let extras: Extras | undefined;\n\n if (!isError(exception)) {\n if (isPlainObject(exception)) {\n const normalizeDepth = client && client.getOptions().normalizeDepth;\n extras = { ['__serialized__']: normalizeToSize(exception as Record, normalizeDepth) };\n\n const message = getMessageForObject(exception);\n ex = (hint && hint.syntheticException) || new Error(message);\n (ex as Error).message = message;\n } else {\n // This handles when someone does: `throw \"something awesome\";`\n // We use synthesized Error here so we can extract a (rough) stack trace.\n ex = (hint && hint.syntheticException) || new Error(exception as string);\n (ex as Error).message = exception as string;\n }\n mechanism.synthetic = true;\n }\n\n const event: Event = {\n exception: {\n values: [exceptionFromError(stackParser, ex as Error)],\n },\n };\n\n if (extras) {\n event.extra = extras;\n }\n\n addExceptionTypeValue(event, undefined, undefined);\n addExceptionMechanism(event, mechanism);\n\n return {\n ...event,\n event_id: hint && hint.event_id,\n };\n}\n\n/**\n * Builds and Event from a Message\n * @hidden\n */\nexport function eventFromMessage(\n stackParser: StackParser,\n message: ParameterizedString,\n // eslint-disable-next-line deprecation/deprecation\n level: Severity | SeverityLevel = 'info',\n hint?: EventHint,\n attachStacktrace?: boolean,\n): Event {\n const event: Event = {\n event_id: hint && hint.event_id,\n level,\n };\n\n if (attachStacktrace && hint && hint.syntheticException) {\n const frames = parseStackFrames(stackParser, hint.syntheticException);\n if (frames.length) {\n event.exception = {\n values: [\n {\n value: message,\n stacktrace: { frames },\n },\n ],\n };\n }\n }\n\n if (isParameterizedString(message)) {\n const { __sentry_template_string__, __sentry_template_values__ } = message;\n\n event.logentry = {\n message: __sentry_template_string__,\n params: __sentry_template_values__,\n };\n return event;\n }\n\n event.message = message;\n return event;\n}\n", "import type { StackFrame } from '@sentry/types';\n\nimport { dropUndefinedKeys } from './object';\nimport { filenameIsInApp } from './stacktrace';\n\ntype WatchdogReturn = {\n /** Resets the watchdog timer */\n poll: () => void;\n /** Enables or disables the watchdog timer */\n enabled: (state: boolean) => void;\n};\n\ntype CreateTimerImpl = () => { getTimeMs: () => number; reset: () => void };\n\n/**\n * A node.js watchdog timer\n * @param pollInterval The interval that we expect to get polled at\n * @param anrThreshold The threshold for when we consider ANR\n * @param callback The callback to call for ANR\n * @returns An object with `poll` and `enabled` functions {@link WatchdogReturn}\n */\nexport function watchdogTimer(\n createTimer: CreateTimerImpl,\n pollInterval: number,\n anrThreshold: number,\n callback: () => void,\n): WatchdogReturn {\n const timer = createTimer();\n let triggered = false;\n let enabled = true;\n\n setInterval(() => {\n const diffMs = timer.getTimeMs();\n\n if (triggered === false && diffMs > pollInterval + anrThreshold) {\n triggered = true;\n if (enabled) {\n callback();\n }\n }\n\n if (diffMs < pollInterval + anrThreshold) {\n triggered = false;\n }\n }, 20);\n\n return {\n poll: () => {\n timer.reset();\n },\n enabled: (state: boolean) => {\n enabled = state;\n },\n };\n}\n\n// types copied from inspector.d.ts\ninterface Location {\n scriptId: string;\n lineNumber: number;\n columnNumber?: number;\n}\n\ninterface CallFrame {\n functionName: string;\n location: Location;\n url: string;\n}\n\n/**\n * Converts Debugger.CallFrame to Sentry StackFrame\n */\nexport function callFrameToStackFrame(\n frame: CallFrame,\n url: string | undefined,\n getModuleFromFilename: (filename: string | undefined) => string | undefined,\n): StackFrame {\n const filename = url ? url.replace(/^file:\\/\\//, '') : undefined;\n\n // CallFrame row/col are 0 based, whereas StackFrame are 1 based\n const colno = frame.location.columnNumber ? frame.location.columnNumber + 1 : undefined;\n const lineno = frame.location.lineNumber ? frame.location.lineNumber + 1 : undefined;\n\n return dropUndefinedKeys({\n filename,\n module: getModuleFromFilename(filename),\n function: frame.functionName || '?',\n colno,\n lineno,\n in_app: filename ? filenameIsInApp(filename) : undefined,\n });\n}\n", "/** A simple Least Recently Used map */\nexport class LRUMap {\n private readonly _cache: Map;\n\n public constructor(private readonly _maxSize: number) {\n this._cache = new Map();\n }\n\n /** Get the current size of the cache */\n public get size(): number {\n return this._cache.size;\n }\n\n /** Get an entry or undefined if it was not in the cache. Re-inserts to update the recently used order */\n public get(key: K): V | undefined {\n const value = this._cache.get(key);\n if (value === undefined) {\n return undefined;\n }\n // Remove and re-insert to update the order\n this._cache.delete(key);\n this._cache.set(key, value);\n return value;\n }\n\n /** Insert an entry and evict an older entry if we've reached maxSize */\n public set(key: K, value: V): void {\n if (this._cache.size >= this._maxSize) {\n // keys() returns an iterator in insertion order so keys().next() gives us the oldest key\n this._cache.delete(this._cache.keys().next().value);\n }\n this._cache.set(key, value);\n }\n\n /** Remove an entry and return the entry if it was in the cache */\n public remove(key: K): V | undefined {\n const value = this._cache.get(key);\n if (value) {\n this._cache.delete(key);\n }\n return value;\n }\n\n /** Clear all entries */\n public clear(): void {\n this._cache.clear();\n }\n\n /** Get all the keys */\n public keys(): Array {\n return Array.from(this._cache.keys());\n }\n\n /** Get all the values */\n public values(): Array {\n const values: V[] = [];\n this._cache.forEach(value => values.push(value));\n return values;\n }\n}\n", "// https://github.com/alangpierce/sucrase/tree/265887868966917f3b924ce38dfad01fbab1329f\n//\n// The MIT License (MIT)\n//\n// Copyright (c) 2012-2018 various contributors (see AUTHORS)\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n/**\n * Polyfill for the nullish coalescing operator (`??`).\n *\n * Note that the RHS is wrapped in a function so that if it's a computed value, that evaluation won't happen unless the\n * LHS evaluates to a nullish value, to mimic the operator's short-circuiting behavior.\n *\n * Adapted from Sucrase (https://github.com/alangpierce/sucrase)\n *\n * @param lhs The value of the expression to the left of the `??`\n * @param rhsFn A function returning the value of the expression to the right of the `??`\n * @returns The LHS value, unless it's `null` or `undefined`, in which case, the RHS value\n */\nexport function _nullishCoalesce(lhs: unknown, rhsFn: () => unknown): unknown {\n // by checking for loose equality to `null`, we catch both `null` and `undefined`\n return lhs != null ? lhs : rhsFn();\n}\n\n// Sucrase version:\n// function _nullishCoalesce(lhs, rhsFn) {\n// if (lhs != null) {\n// return lhs;\n// } else {\n// return rhsFn();\n// }\n// }\n", "// https://github.com/alangpierce/sucrase/tree/265887868966917f3b924ce38dfad01fbab1329f\n//\n// The MIT License (MIT)\n//\n// Copyright (c) 2012-2018 various contributors (see AUTHORS)\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\nimport { _nullishCoalesce } from './_nullishCoalesce';\n\n/**\n * Polyfill for the nullish coalescing operator (`??`), when used in situations where at least one of the values is the\n * result of an async operation.\n *\n * Note that the RHS is wrapped in a function so that if it's a computed value, that evaluation won't happen unless the\n * LHS evaluates to a nullish value, to mimic the operator's short-circuiting behavior.\n *\n * Adapted from Sucrase (https://github.com/alangpierce/sucrase)\n *\n * @param lhs The value of the expression to the left of the `??`\n * @param rhsFn A function returning the value of the expression to the right of the `??`\n * @returns The LHS value, unless it's `null` or `undefined`, in which case, the RHS value\n */\nexport async function _asyncNullishCoalesce(lhs: unknown, rhsFn: () => unknown): Promise {\n return _nullishCoalesce(lhs, rhsFn);\n}\n\n// Sucrase version:\n// async function _asyncNullishCoalesce(lhs, rhsFn) {\n// if (lhs != null) {\n// return lhs;\n// } else {\n// return await rhsFn();\n// }\n// }\n", "// https://github.com/alangpierce/sucrase/tree/265887868966917f3b924ce38dfad01fbab1329f\n//\n// The MIT License (MIT)\n//\n// Copyright (c) 2012-2018 various contributors (see AUTHORS)\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\nimport type { GenericFunction } from './types';\n\n/**\n * Polyfill for the optional chain operator, `?.`, given previous conversion of the expression into an array of values,\n * descriptors, and functions, for situations in which at least one part of the expression is async.\n *\n * Adapted from Sucrase (https://github.com/alangpierce/sucrase) See\n * https://github.com/alangpierce/sucrase/blob/265887868966917f3b924ce38dfad01fbab1329f/src/transformers/OptionalChainingNullishTransformer.ts#L15\n *\n * @param ops Array result of expression conversion\n * @returns The value of the expression\n */\nexport async function _asyncOptionalChain(ops: unknown[]): Promise {\n let lastAccessLHS: unknown = undefined;\n let value = ops[0];\n let i = 1;\n while (i < ops.length) {\n const op = ops[i] as string;\n const fn = ops[i + 1] as (intermediateValue: unknown) => Promise;\n i += 2;\n // by checking for loose equality to `null`, we catch both `null` and `undefined`\n if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) {\n // really we're meaning to return `undefined` as an actual value here, but it saves bytes not to write it\n return;\n }\n if (op === 'access' || op === 'optionalAccess') {\n lastAccessLHS = value;\n value = await fn(value);\n } else if (op === 'call' || op === 'optionalCall') {\n value = await fn((...args: unknown[]) => (value as GenericFunction).call(lastAccessLHS, ...args));\n lastAccessLHS = undefined;\n }\n }\n return value;\n}\n\n// Sucrase version:\n// async function _asyncOptionalChain(ops) {\n// let lastAccessLHS = undefined;\n// let value = ops[0];\n// let i = 1;\n// while (i < ops.length) {\n// const op = ops[i];\n// const fn = ops[i + 1];\n// i += 2;\n// if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) {\n// return undefined;\n// }\n// if (op === 'access' || op === 'optionalAccess') {\n// lastAccessLHS = value;\n// value = await fn(value);\n// } else if (op === 'call' || op === 'optionalCall') {\n// value = await fn((...args) => value.call(lastAccessLHS, ...args));\n// lastAccessLHS = undefined;\n// }\n// }\n// return value;\n// }\n", "// https://github.com/alangpierce/sucrase/tree/265887868966917f3b924ce38dfad01fbab1329f\n//\n// The MIT License (MIT)\n//\n// Copyright (c) 2012-2018 various contributors (see AUTHORS)\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\nimport { _asyncOptionalChain } from './_asyncOptionalChain';\n\n/**\n * Polyfill for the optional chain operator, `?.`, given previous conversion of the expression into an array of values,\n * descriptors, and functions, in cases where the value of the expression is to be deleted.\n *\n * Adapted from Sucrase (https://github.com/alangpierce/sucrase) See\n * https://github.com/alangpierce/sucrase/blob/265887868966917f3b924ce38dfad01fbab1329f/src/transformers/OptionalChainingNullishTransformer.ts#L15\n *\n * @param ops Array result of expression conversion\n * @returns The return value of the `delete` operator: `true`, unless the deletion target is an own, non-configurable\n * property (one which can't be deleted or turned into an accessor, and whose enumerability can't be changed), in which\n * case `false`.\n */\nexport async function _asyncOptionalChainDelete(ops: unknown[]): Promise {\n const result = (await _asyncOptionalChain(ops)) as Promise;\n // If `result` is `null`, it means we didn't get to the end of the chain and so nothing was deleted (in which case,\n // return `true` since that's what `delete` does when it no-ops). If it's non-null, we know the delete happened, in\n // which case we return whatever the `delete` returned, which will be a boolean.\n return result == null ? true : (result as Promise);\n}\n\n// Sucrase version:\n// async function asyncOptionalChainDelete(ops) {\n// const result = await ASYNC_OPTIONAL_CHAIN_NAME(ops);\n// return result == null ? true : result;\n// }\n", "// https://github.com/alangpierce/sucrase/tree/265887868966917f3b924ce38dfad01fbab1329f\n//\n// The MIT License (MIT)\n//\n// Copyright (c) 2012-2018 various contributors (see AUTHORS)\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\nimport type { GenericFunction } from './types';\n\n/**\n * Polyfill for the optional chain operator, `?.`, given previous conversion of the expression into an array of values,\n * descriptors, and functions.\n *\n * Adapted from Sucrase (https://github.com/alangpierce/sucrase)\n * See https://github.com/alangpierce/sucrase/blob/265887868966917f3b924ce38dfad01fbab1329f/src/transformers/OptionalChainingNullishTransformer.ts#L15\n *\n * @param ops Array result of expression conversion\n * @returns The value of the expression\n */\nexport function _optionalChain(ops: unknown[]): unknown {\n let lastAccessLHS: unknown = undefined;\n let value = ops[0];\n let i = 1;\n while (i < ops.length) {\n const op = ops[i] as string;\n const fn = ops[i + 1] as (intermediateValue: unknown) => unknown;\n i += 2;\n // by checking for loose equality to `null`, we catch both `null` and `undefined`\n if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) {\n // really we're meaning to return `undefined` as an actual value here, but it saves bytes not to write it\n return;\n }\n if (op === 'access' || op === 'optionalAccess') {\n lastAccessLHS = value;\n value = fn(value);\n } else if (op === 'call' || op === 'optionalCall') {\n value = fn((...args: unknown[]) => (value as GenericFunction).call(lastAccessLHS, ...args));\n lastAccessLHS = undefined;\n }\n }\n return value;\n}\n\n// Sucrase version\n// function _optionalChain(ops) {\n// let lastAccessLHS = undefined;\n// let value = ops[0];\n// let i = 1;\n// while (i < ops.length) {\n// const op = ops[i];\n// const fn = ops[i + 1];\n// i += 2;\n// if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) {\n// return undefined;\n// }\n// if (op === 'access' || op === 'optionalAccess') {\n// lastAccessLHS = value;\n// value = fn(value);\n// } else if (op === 'call' || op === 'optionalCall') {\n// value = fn((...args) => value.call(lastAccessLHS, ...args));\n// lastAccessLHS = undefined;\n// }\n// }\n// return value;\n// }\n", "// https://github.com/alangpierce/sucrase/tree/265887868966917f3b924ce38dfad01fbab1329f\n//\n// The MIT License (MIT)\n//\n// Copyright (c) 2012-2018 various contributors (see AUTHORS)\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\nimport { _optionalChain } from './_optionalChain';\n\n/**\n * Polyfill for the optional chain operator, `?.`, given previous conversion of the expression into an array of values,\n * descriptors, and functions, in cases where the value of the expression is to be deleted.\n *\n * Adapted from Sucrase (https://github.com/alangpierce/sucrase) See\n * https://github.com/alangpierce/sucrase/blob/265887868966917f3b924ce38dfad01fbab1329f/src/transformers/OptionalChainingNullishTransformer.ts#L15\n *\n * @param ops Array result of expression conversion\n * @returns The return value of the `delete` operator: `true`, unless the deletion target is an own, non-configurable\n * property (one which can't be deleted or turned into an accessor, and whose enumerability can't be changed), in which\n * case `false`.\n */\nexport function _optionalChainDelete(ops: unknown[]): boolean {\n const result = _optionalChain(ops) as boolean | null;\n // If `result` is `null`, it means we didn't get to the end of the chain and so nothing was deleted (in which case,\n // return `true` since that's what `delete` does when it no-ops). If it's non-null, we know the delete happened, in\n // which case we return whatever the `delete` returned, which will be a boolean.\n return result == null ? true : result;\n}\n\n// Sucrase version:\n// function _optionalChainDelete(ops) {\n// const result = _optionalChain(ops);\n// // by checking for loose equality to `null`, we catch both `null` and `undefined`\n// return result == null ? true : result;\n// }\n", "// Based on https://github.com/sindresorhus/escape-string-regexp but with modifications to:\n// a) reduce the size by skipping the runtime type - checking\n// b) ensure it gets down - compiled for old versions of Node(the published package only supports Node 12+).\n//\n// MIT License\n//\n// Copyright (c) Sindre Sorhus (https://sindresorhus.com)\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n// documentation files(the \"Software\"), to deal in the Software without restriction, including without limitation\n// the rights to use, copy, modify, merge, publish, distribute, sublicense, and / or sell copies of the Software, and\n// to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all copies or substantial portions of\n// the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO\n// THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n// IN THE SOFTWARE.\n\n/**\n * Given a string, escape characters which have meaning in the regex grammar, such that the result is safe to feed to\n * `new RegExp()`.\n *\n * @param regexString The string to escape\n * @returns An version of the string with all special regex characters escaped\n */\nexport function escapeStringForRegex(regexString: string): string {\n // escape the hyphen separately so we can also replace it with a unicode literal hyphen, to avoid the problems\n // discussed in https://github.com/sindresorhus/escape-string-regexp/issues/20.\n return regexString.replace(/[|\\\\{}()[\\]^$+*?.]/g, '\\\\$&').replace(/-/g, '\\\\x2d');\n}\n", "Object.defineProperty(exports, '__esModule', { value: true });\n\nconst aggregateErrors = require('./aggregate-errors.js');\nconst browser = require('./browser.js');\nconst dsn = require('./dsn.js');\nconst error = require('./error.js');\nconst worldwide = require('./worldwide.js');\nconst index = require('./instrument/index.js');\nconst is = require('./is.js');\nconst isBrowser = require('./isBrowser.js');\nconst logger = require('./logger.js');\nconst memo = require('./memo.js');\nconst misc = require('./misc.js');\nconst node = require('./node.js');\nconst normalize = require('./normalize.js');\nconst object = require('./object.js');\nconst path = require('./path.js');\nconst promisebuffer = require('./promisebuffer.js');\nconst requestdata = require('./requestdata.js');\nconst severity = require('./severity.js');\nconst stacktrace = require('./stacktrace.js');\nconst string = require('./string.js');\nconst supports = require('./supports.js');\nconst syncpromise = require('./syncpromise.js');\nconst time = require('./time.js');\nconst tracing = require('./tracing.js');\nconst env = require('./env.js');\nconst envelope = require('./envelope.js');\nconst clientreport = require('./clientreport.js');\nconst ratelimit = require('./ratelimit.js');\nconst baggage = require('./baggage.js');\nconst url = require('./url.js');\nconst userIntegrations = require('./userIntegrations.js');\nconst cache = require('./cache.js');\nconst eventbuilder = require('./eventbuilder.js');\nconst anr = require('./anr.js');\nconst lru = require('./lru.js');\nconst _asyncNullishCoalesce = require('./buildPolyfills/_asyncNullishCoalesce.js');\nconst _asyncOptionalChain = require('./buildPolyfills/_asyncOptionalChain.js');\nconst _asyncOptionalChainDelete = require('./buildPolyfills/_asyncOptionalChainDelete.js');\nconst _nullishCoalesce = require('./buildPolyfills/_nullishCoalesce.js');\nconst _optionalChain = require('./buildPolyfills/_optionalChain.js');\nconst _optionalChainDelete = require('./buildPolyfills/_optionalChainDelete.js');\nconst console = require('./instrument/console.js');\nconst dom = require('./instrument/dom.js');\nconst xhr = require('./instrument/xhr.js');\nconst fetch = require('./instrument/fetch.js');\nconst history = require('./instrument/history.js');\nconst globalError = require('./instrument/globalError.js');\nconst globalUnhandledRejection = require('./instrument/globalUnhandledRejection.js');\nconst _handlers = require('./instrument/_handlers.js');\nconst nodeStackTrace = require('./node-stack-trace.js');\nconst escapeStringForRegex = require('./vendor/escapeStringForRegex.js');\nconst supportsHistory = require('./vendor/supportsHistory.js');\n\n\n\nexports.applyAggregateErrorsToEvent = aggregateErrors.applyAggregateErrorsToEvent;\nexports.getComponentName = browser.getComponentName;\nexports.getDomElement = browser.getDomElement;\nexports.getLocationHref = browser.getLocationHref;\nexports.htmlTreeAsString = browser.htmlTreeAsString;\nexports.dsnFromString = dsn.dsnFromString;\nexports.dsnToString = dsn.dsnToString;\nexports.makeDsn = dsn.makeDsn;\nexports.SentryError = error.SentryError;\nexports.GLOBAL_OBJ = worldwide.GLOBAL_OBJ;\nexports.getGlobalObject = worldwide.getGlobalObject;\nexports.getGlobalSingleton = worldwide.getGlobalSingleton;\nexports.addInstrumentationHandler = index.addInstrumentationHandler;\nexports.isDOMError = is.isDOMError;\nexports.isDOMException = is.isDOMException;\nexports.isElement = is.isElement;\nexports.isError = is.isError;\nexports.isErrorEvent = is.isErrorEvent;\nexports.isEvent = is.isEvent;\nexports.isInstanceOf = is.isInstanceOf;\nexports.isNaN = is.isNaN;\nexports.isParameterizedString = is.isParameterizedString;\nexports.isPlainObject = is.isPlainObject;\nexports.isPrimitive = is.isPrimitive;\nexports.isRegExp = is.isRegExp;\nexports.isString = is.isString;\nexports.isSyntheticEvent = is.isSyntheticEvent;\nexports.isThenable = is.isThenable;\nexports.isVueViewModel = is.isVueViewModel;\nexports.isBrowser = isBrowser.isBrowser;\nexports.CONSOLE_LEVELS = logger.CONSOLE_LEVELS;\nexports.consoleSandbox = logger.consoleSandbox;\nexports.logger = logger.logger;\nexports.originalConsoleMethods = logger.originalConsoleMethods;\nexports.memoBuilder = memo.memoBuilder;\nexports.addContextToFrame = misc.addContextToFrame;\nexports.addExceptionMechanism = misc.addExceptionMechanism;\nexports.addExceptionTypeValue = misc.addExceptionTypeValue;\nexports.arrayify = misc.arrayify;\nexports.checkOrSetAlreadyCaught = misc.checkOrSetAlreadyCaught;\nexports.getEventDescription = misc.getEventDescription;\nexports.parseSemver = misc.parseSemver;\nexports.uuid4 = misc.uuid4;\nexports.dynamicRequire = node.dynamicRequire;\nexports.isNodeEnv = node.isNodeEnv;\nexports.loadModule = node.loadModule;\nexports.normalize = normalize.normalize;\nexports.normalizeToSize = normalize.normalizeToSize;\nexports.normalizeUrlToBase = normalize.normalizeUrlToBase;\nexports.walk = normalize.walk;\nexports.addNonEnumerableProperty = object.addNonEnumerableProperty;\nexports.convertToPlainObject = object.convertToPlainObject;\nexports.dropUndefinedKeys = object.dropUndefinedKeys;\nexports.extractExceptionKeysForMessage = object.extractExceptionKeysForMessage;\nexports.fill = object.fill;\nexports.getOriginalFunction = object.getOriginalFunction;\nexports.markFunctionWrapped = object.markFunctionWrapped;\nexports.objectify = object.objectify;\nexports.urlEncode = object.urlEncode;\nexports.basename = path.basename;\nexports.dirname = path.dirname;\nexports.isAbsolute = path.isAbsolute;\nexports.join = path.join;\nexports.normalizePath = path.normalizePath;\nexports.relative = path.relative;\nexports.resolve = path.resolve;\nexports.makePromiseBuffer = promisebuffer.makePromiseBuffer;\nexports.DEFAULT_USER_INCLUDES = requestdata.DEFAULT_USER_INCLUDES;\nexports.addRequestDataToEvent = requestdata.addRequestDataToEvent;\nexports.addRequestDataToTransaction = requestdata.addRequestDataToTransaction;\nexports.extractPathForTransaction = requestdata.extractPathForTransaction;\nexports.extractRequestData = requestdata.extractRequestData;\nexports.winterCGHeadersToDict = requestdata.winterCGHeadersToDict;\nexports.winterCGRequestToRequestData = requestdata.winterCGRequestToRequestData;\nexports.severityFromString = severity.severityFromString;\nexports.severityLevelFromString = severity.severityLevelFromString;\nexports.validSeverityLevels = severity.validSeverityLevels;\nexports.createStackParser = stacktrace.createStackParser;\nexports.getFunctionName = stacktrace.getFunctionName;\nexports.nodeStackLineParser = stacktrace.nodeStackLineParser;\nexports.stackParserFromStackParserOptions = stacktrace.stackParserFromStackParserOptions;\nexports.stripSentryFramesAndReverse = stacktrace.stripSentryFramesAndReverse;\nexports.isMatchingPattern = string.isMatchingPattern;\nexports.safeJoin = string.safeJoin;\nexports.snipLine = string.snipLine;\nexports.stringMatchesSomePattern = string.stringMatchesSomePattern;\nexports.truncate = string.truncate;\nexports.isNativeFetch = supports.isNativeFetch;\nexports.supportsDOMError = supports.supportsDOMError;\nexports.supportsDOMException = supports.supportsDOMException;\nexports.supportsErrorEvent = supports.supportsErrorEvent;\nexports.supportsFetch = supports.supportsFetch;\nexports.supportsNativeFetch = supports.supportsNativeFetch;\nexports.supportsReferrerPolicy = supports.supportsReferrerPolicy;\nexports.supportsReportingObserver = supports.supportsReportingObserver;\nexports.SyncPromise = syncpromise.SyncPromise;\nexports.rejectedSyncPromise = syncpromise.rejectedSyncPromise;\nexports.resolvedSyncPromise = syncpromise.resolvedSyncPromise;\nObject.defineProperty(exports, '_browserPerformanceTimeOriginMode', {\n\tenumerable: true,\n\tget: () => time._browserPerformanceTimeOriginMode\n});\nexports.browserPerformanceTimeOrigin = time.browserPerformanceTimeOrigin;\nexports.dateTimestampInSeconds = time.dateTimestampInSeconds;\nexports.timestampInSeconds = time.timestampInSeconds;\nexports.timestampWithMs = time.timestampWithMs;\nexports.TRACEPARENT_REGEXP = tracing.TRACEPARENT_REGEXP;\nexports.extractTraceparentData = tracing.extractTraceparentData;\nexports.generateSentryTraceHeader = tracing.generateSentryTraceHeader;\nexports.propagationContextFromHeaders = tracing.propagationContextFromHeaders;\nexports.tracingContextFromHeaders = tracing.tracingContextFromHeaders;\nexports.getSDKSource = env.getSDKSource;\nexports.isBrowserBundle = env.isBrowserBundle;\nexports.addItemToEnvelope = envelope.addItemToEnvelope;\nexports.createAttachmentEnvelopeItem = envelope.createAttachmentEnvelopeItem;\nexports.createEnvelope = envelope.createEnvelope;\nexports.createEventEnvelopeHeaders = envelope.createEventEnvelopeHeaders;\nexports.envelopeContainsItemType = envelope.envelopeContainsItemType;\nexports.envelopeItemTypeToDataCategory = envelope.envelopeItemTypeToDataCategory;\nexports.forEachEnvelopeItem = envelope.forEachEnvelopeItem;\nexports.getSdkMetadataForEnvelopeHeader = envelope.getSdkMetadataForEnvelopeHeader;\nexports.parseEnvelope = envelope.parseEnvelope;\nexports.serializeEnvelope = envelope.serializeEnvelope;\nexports.createClientReportEnvelope = clientreport.createClientReportEnvelope;\nexports.DEFAULT_RETRY_AFTER = ratelimit.DEFAULT_RETRY_AFTER;\nexports.disabledUntil = ratelimit.disabledUntil;\nexports.isRateLimited = ratelimit.isRateLimited;\nexports.parseRetryAfterHeader = ratelimit.parseRetryAfterHeader;\nexports.updateRateLimits = ratelimit.updateRateLimits;\nexports.BAGGAGE_HEADER_NAME = baggage.BAGGAGE_HEADER_NAME;\nexports.MAX_BAGGAGE_STRING_LENGTH = baggage.MAX_BAGGAGE_STRING_LENGTH;\nexports.SENTRY_BAGGAGE_KEY_PREFIX = baggage.SENTRY_BAGGAGE_KEY_PREFIX;\nexports.SENTRY_BAGGAGE_KEY_PREFIX_REGEX = baggage.SENTRY_BAGGAGE_KEY_PREFIX_REGEX;\nexports.baggageHeaderToDynamicSamplingContext = baggage.baggageHeaderToDynamicSamplingContext;\nexports.dynamicSamplingContextToSentryBaggageHeader = baggage.dynamicSamplingContextToSentryBaggageHeader;\nexports.getNumberOfUrlSegments = url.getNumberOfUrlSegments;\nexports.getSanitizedUrlString = url.getSanitizedUrlString;\nexports.parseUrl = url.parseUrl;\nexports.stripUrlQueryAndFragment = url.stripUrlQueryAndFragment;\nexports.addOrUpdateIntegration = userIntegrations.addOrUpdateIntegration;\nexports.makeFifoCache = cache.makeFifoCache;\nexports.eventFromMessage = eventbuilder.eventFromMessage;\nexports.eventFromUnknownInput = eventbuilder.eventFromUnknownInput;\nexports.exceptionFromError = eventbuilder.exceptionFromError;\nexports.parseStackFrames = eventbuilder.parseStackFrames;\nexports.callFrameToStackFrame = anr.callFrameToStackFrame;\nexports.watchdogTimer = anr.watchdogTimer;\nexports.LRUMap = lru.LRUMap;\nexports._asyncNullishCoalesce = _asyncNullishCoalesce._asyncNullishCoalesce;\nexports._asyncOptionalChain = _asyncOptionalChain._asyncOptionalChain;\nexports._asyncOptionalChainDelete = _asyncOptionalChainDelete._asyncOptionalChainDelete;\nexports._nullishCoalesce = _nullishCoalesce._nullishCoalesce;\nexports._optionalChain = _optionalChain._optionalChain;\nexports._optionalChainDelete = _optionalChainDelete._optionalChainDelete;\nexports.addConsoleInstrumentationHandler = console.addConsoleInstrumentationHandler;\nexports.addClickKeypressInstrumentationHandler = dom.addClickKeypressInstrumentationHandler;\nexports.SENTRY_XHR_DATA_KEY = xhr.SENTRY_XHR_DATA_KEY;\nexports.addXhrInstrumentationHandler = xhr.addXhrInstrumentationHandler;\nexports.addFetchInstrumentationHandler = fetch.addFetchInstrumentationHandler;\nexports.addHistoryInstrumentationHandler = history.addHistoryInstrumentationHandler;\nexports.addGlobalErrorInstrumentationHandler = globalError.addGlobalErrorInstrumentationHandler;\nexports.addGlobalUnhandledRejectionInstrumentationHandler = globalUnhandledRejection.addGlobalUnhandledRejectionInstrumentationHandler;\nexports.resetInstrumentationHandlers = _handlers.resetInstrumentationHandlers;\nexports.filenameIsInApp = nodeStackTrace.filenameIsInApp;\nexports.escapeStringForRegex = escapeStringForRegex.escapeStringForRegex;\nexports.supportsHistory = supportsHistory.supportsHistory;\n//# sourceMappingURL=index.js.map\n", "declare const __DEBUG_BUILD__: boolean;\n\n/**\n * This serves as a build time flag that will be true by default, but false in non-debug builds or if users replace `__SENTRY_DEBUG__` in their generated code.\n *\n * ATTENTION: This constant must never cross package boundaries (i.e. be exported) to guarantee that it can be used for tree shaking.\n */\nexport const DEBUG_BUILD = __DEBUG_BUILD__;\n", "export const DEFAULT_ENVIRONMENT = 'production';\n", "import type { Event, EventHint, EventProcessor } from '@sentry/types';\nimport { SyncPromise, getGlobalSingleton, isThenable, logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from './debug-build';\n\n/**\n * Returns the global event processors.\n * @deprecated Global event processors will be removed in v8.\n */\nexport function getGlobalEventProcessors(): EventProcessor[] {\n return getGlobalSingleton('globalEventProcessors', () => []);\n}\n\n/**\n * Add a EventProcessor to be kept globally.\n * @deprecated Use `addEventProcessor` instead. Global event processors will be removed in v8.\n */\nexport function addGlobalEventProcessor(callback: EventProcessor): void {\n // eslint-disable-next-line deprecation/deprecation\n getGlobalEventProcessors().push(callback);\n}\n\n/**\n * Process an array of event processors, returning the processed event (or `null` if the event was dropped).\n */\nexport function notifyEventProcessors(\n processors: EventProcessor[],\n event: Event | null,\n hint: EventHint,\n index: number = 0,\n): PromiseLike {\n return new SyncPromise((resolve, reject) => {\n const processor = processors[index];\n if (event === null || typeof processor !== 'function') {\n resolve(event);\n } else {\n const result = processor({ ...event }, hint) as Event | null;\n\n DEBUG_BUILD && processor.id && result === null && logger.log(`Event processor \"${processor.id}\" dropped event`);\n\n if (isThenable(result)) {\n void result\n .then(final => notifyEventProcessors(processors, final, hint, index + 1).then(resolve))\n .then(null, reject);\n } else {\n void notifyEventProcessors(processors, result, hint, index + 1)\n .then(resolve)\n .then(null, reject);\n }\n }\n });\n}\n", "import type { SerializedSession, Session, SessionContext, SessionStatus } from '@sentry/types';\nimport { dropUndefinedKeys, timestampInSeconds, uuid4 } from '@sentry/utils';\n/**\n * Creates a new `Session` object by setting certain default parameters. If optional @param context\n * is passed, the passed properties are applied to the session object.\n *\n * @param context (optional) additional properties to be applied to the returned session object\n *\n * @returns a new `Session` object\n */\nexport function makeSession(context?: Omit): Session {\n // Both timestamp and started are in seconds since the UNIX epoch.\n const startingTime = timestampInSeconds();\n\n const session: Session = {\n sid: uuid4(),\n init: true,\n timestamp: startingTime,\n started: startingTime,\n duration: 0,\n status: 'ok',\n errors: 0,\n ignoreDuration: false,\n toJSON: () => sessionToJSON(session),\n };\n\n if (context) {\n updateSession(session, context);\n }\n\n return session;\n}\n\n/**\n * Updates a session object with the properties passed in the context.\n *\n * Note that this function mutates the passed object and returns void.\n * (Had to do this instead of returning a new and updated session because closing and sending a session\n * makes an update to the session after it was passed to the sending logic.\n * @see BaseClient.captureSession )\n *\n * @param session the `Session` to update\n * @param context the `SessionContext` holding the properties that should be updated in @param session\n */\n// eslint-disable-next-line complexity\nexport function updateSession(session: Session, context: SessionContext = {}): void {\n if (context.user) {\n if (!session.ipAddress && context.user.ip_address) {\n session.ipAddress = context.user.ip_address;\n }\n\n if (!session.did && !context.did) {\n session.did = context.user.id || context.user.email || context.user.username;\n }\n }\n\n session.timestamp = context.timestamp || timestampInSeconds();\n\n if (context.abnormal_mechanism) {\n session.abnormal_mechanism = context.abnormal_mechanism;\n }\n\n if (context.ignoreDuration) {\n session.ignoreDuration = context.ignoreDuration;\n }\n if (context.sid) {\n // Good enough uuid validation. — Kamil\n session.sid = context.sid.length === 32 ? context.sid : uuid4();\n }\n if (context.init !== undefined) {\n session.init = context.init;\n }\n if (!session.did && context.did) {\n session.did = `${context.did}`;\n }\n if (typeof context.started === 'number') {\n session.started = context.started;\n }\n if (session.ignoreDuration) {\n session.duration = undefined;\n } else if (typeof context.duration === 'number') {\n session.duration = context.duration;\n } else {\n const duration = session.timestamp - session.started;\n session.duration = duration >= 0 ? duration : 0;\n }\n if (context.release) {\n session.release = context.release;\n }\n if (context.environment) {\n session.environment = context.environment;\n }\n if (!session.ipAddress && context.ipAddress) {\n session.ipAddress = context.ipAddress;\n }\n if (!session.userAgent && context.userAgent) {\n session.userAgent = context.userAgent;\n }\n if (typeof context.errors === 'number') {\n session.errors = context.errors;\n }\n if (context.status) {\n session.status = context.status;\n }\n}\n\n/**\n * Closes a session by setting its status and updating the session object with it.\n * Internally calls `updateSession` to update the passed session object.\n *\n * Note that this function mutates the passed session (@see updateSession for explanation).\n *\n * @param session the `Session` object to be closed\n * @param status the `SessionStatus` with which the session was closed. If you don't pass a status,\n * this function will keep the previously set status, unless it was `'ok'` in which case\n * it is changed to `'exited'`.\n */\nexport function closeSession(session: Session, status?: Exclude): void {\n let context = {};\n if (status) {\n context = { status };\n } else if (session.status === 'ok') {\n context = { status: 'exited' };\n }\n\n updateSession(session, context);\n}\n\n/**\n * Serializes a passed session object to a JSON object with a slightly different structure.\n * This is necessary because the Sentry backend requires a slightly different schema of a session\n * than the one the JS SDKs use internally.\n *\n * @param session the session to be converted\n *\n * @returns a JSON object of the passed session\n */\nfunction sessionToJSON(session: Session): SerializedSession {\n return dropUndefinedKeys({\n sid: `${session.sid}`,\n init: session.init,\n // Make sure that sec is converted to ms for date constructor\n started: new Date(session.started * 1000).toISOString(),\n timestamp: new Date(session.timestamp * 1000).toISOString(),\n status: session.status,\n errors: session.errors,\n did: typeof session.did === 'number' || typeof session.did === 'string' ? `${session.did}` : undefined,\n duration: session.duration,\n abnormal_mechanism: session.abnormal_mechanism,\n attrs: {\n release: session.release,\n environment: session.environment,\n ip_address: session.ipAddress,\n user_agent: session.userAgent,\n },\n });\n}\n", "import type { Span, SpanJSON, SpanTimeInput, TraceContext } from '@sentry/types';\nimport { dropUndefinedKeys, generateSentryTraceHeader, timestampInSeconds } from '@sentry/utils';\nimport type { Span as SpanClass } from '../tracing/span';\n\n// These are aligned with OpenTelemetry trace flags\nexport const TRACE_FLAG_NONE = 0x0;\nexport const TRACE_FLAG_SAMPLED = 0x1;\n\n/**\n * Convert a span to a trace context, which can be sent as the `trace` context in an event.\n */\nexport function spanToTraceContext(span: Span): TraceContext {\n const { spanId: span_id, traceId: trace_id } = span.spanContext();\n const { data, op, parent_span_id, status, tags, origin } = spanToJSON(span);\n\n return dropUndefinedKeys({\n data,\n op,\n parent_span_id,\n span_id,\n status,\n tags,\n trace_id,\n origin,\n });\n}\n\n/**\n * Convert a Span to a Sentry trace header.\n */\nexport function spanToTraceHeader(span: Span): string {\n const { traceId, spanId } = span.spanContext();\n const sampled = spanIsSampled(span);\n return generateSentryTraceHeader(traceId, spanId, sampled);\n}\n\n/**\n * Convert a span time input intp a timestamp in seconds.\n */\nexport function spanTimeInputToSeconds(input: SpanTimeInput | undefined): number {\n if (typeof input === 'number') {\n return ensureTimestampInSeconds(input);\n }\n\n if (Array.isArray(input)) {\n // See {@link HrTime} for the array-based time format\n return input[0] + input[1] / 1e9;\n }\n\n if (input instanceof Date) {\n return ensureTimestampInSeconds(input.getTime());\n }\n\n return timestampInSeconds();\n}\n\n/**\n * Converts a timestamp to second, if it was in milliseconds, or keeps it as second.\n */\nfunction ensureTimestampInSeconds(timestamp: number): number {\n const isMs = timestamp > 9999999999;\n return isMs ? timestamp / 1000 : timestamp;\n}\n\n/**\n * Convert a span to a JSON representation.\n * Note that all fields returned here are optional and need to be guarded against.\n *\n * Note: Because of this, we currently have a circular type dependency (which we opted out of in package.json).\n * This is not avoidable as we need `spanToJSON` in `spanUtils.ts`, which in turn is needed by `span.ts` for backwards compatibility.\n * And `spanToJSON` needs the Span class from `span.ts` to check here.\n * TODO v8: When we remove the deprecated stuff from `span.ts`, we can remove the circular dependency again.\n */\nexport function spanToJSON(span: Span): Partial {\n if (spanIsSpanClass(span)) {\n return span.getSpanJSON();\n }\n\n // Fallback: We also check for `.toJSON()` here...\n // eslint-disable-next-line deprecation/deprecation\n if (typeof span.toJSON === 'function') {\n // eslint-disable-next-line deprecation/deprecation\n return span.toJSON();\n }\n\n return {};\n}\n\n/**\n * Sadly, due to circular dependency checks we cannot actually import the Span class here and check for instanceof.\n * :( So instead we approximate this by checking if it has the `getSpanJSON` method.\n */\nfunction spanIsSpanClass(span: Span): span is SpanClass {\n return typeof (span as SpanClass).getSpanJSON === 'function';\n}\n\n/**\n * Returns true if a span is sampled.\n * In most cases, you should just use `span.isRecording()` instead.\n * However, this has a slightly different semantic, as it also returns false if the span is finished.\n * So in the case where this distinction is important, use this method.\n */\nexport function spanIsSampled(span: Span): boolean {\n // We align our trace flags with the ones OpenTelemetry use\n // So we also check for sampled the same way they do.\n const { traceFlags } = span.spanContext();\n // eslint-disable-next-line no-bitwise\n return Boolean(traceFlags & TRACE_FLAG_SAMPLED);\n}\n", "import type {\n CaptureContext,\n Client,\n ClientOptions,\n Event,\n EventHint,\n Scope as ScopeInterface,\n ScopeContext,\n StackFrame,\n StackParser,\n} from '@sentry/types';\nimport { GLOBAL_OBJ, addExceptionMechanism, dateTimestampInSeconds, normalize, truncate, uuid4 } from '@sentry/utils';\n\nimport { DEFAULT_ENVIRONMENT } from '../constants';\nimport { getGlobalEventProcessors, notifyEventProcessors } from '../eventProcessors';\nimport { Scope, getGlobalScope } from '../scope';\nimport { applyScopeDataToEvent, mergeScopeData } from './applyScopeDataToEvent';\nimport { spanToJSON } from './spanUtils';\n\n/**\n * This type makes sure that we get either a CaptureContext, OR an EventHint.\n * It does not allow mixing them, which could lead to unexpected outcomes, e.g. this is disallowed:\n * { user: { id: '123' }, mechanism: { handled: false } }\n */\nexport type ExclusiveEventHintOrCaptureContext =\n | (CaptureContext & Partial<{ [key in keyof EventHint]: never }>)\n | (EventHint & Partial<{ [key in keyof ScopeContext]: never }>);\n\n/**\n * Adds common information to events.\n *\n * The information includes release and environment from `options`,\n * breadcrumbs and context (extra, tags and user) from the scope.\n *\n * Information that is already present in the event is never overwritten. For\n * nested objects, such as the context, keys are merged.\n *\n * Note: This also triggers callbacks for `addGlobalEventProcessor`, but not `beforeSend`.\n *\n * @param event The original event.\n * @param hint May contain additional information about the original exception.\n * @param scope A scope containing event metadata.\n * @returns A new event with more information.\n * @hidden\n */\nexport function prepareEvent(\n options: ClientOptions,\n event: Event,\n hint: EventHint,\n scope?: Scope,\n client?: Client,\n isolationScope?: Scope,\n): PromiseLike {\n const { normalizeDepth = 3, normalizeMaxBreadth = 1_000 } = options;\n const prepared: Event = {\n ...event,\n event_id: event.event_id || hint.event_id || uuid4(),\n timestamp: event.timestamp || dateTimestampInSeconds(),\n };\n const integrations = hint.integrations || options.integrations.map(i => i.name);\n\n applyClientOptions(prepared, options);\n applyIntegrationsMetadata(prepared, integrations);\n\n // Only put debug IDs onto frames for error events.\n if (event.type === undefined) {\n applyDebugIds(prepared, options.stackParser);\n }\n\n // If we have scope given to us, use it as the base for further modifications.\n // This allows us to prevent unnecessary copying of data if `captureContext` is not provided.\n const finalScope = getFinalScope(scope, hint.captureContext);\n\n if (hint.mechanism) {\n addExceptionMechanism(prepared, hint.mechanism);\n }\n\n const clientEventProcessors = client && client.getEventProcessors ? client.getEventProcessors() : [];\n\n // This should be the last thing called, since we want that\n // {@link Hub.addEventProcessor} gets the finished prepared event.\n // Merge scope data together\n const data = getGlobalScope().getScopeData();\n\n if (isolationScope) {\n const isolationData = isolationScope.getScopeData();\n mergeScopeData(data, isolationData);\n }\n\n if (finalScope) {\n const finalScopeData = finalScope.getScopeData();\n mergeScopeData(data, finalScopeData);\n }\n\n const attachments = [...(hint.attachments || []), ...data.attachments];\n if (attachments.length) {\n hint.attachments = attachments;\n }\n\n applyScopeDataToEvent(prepared, data);\n\n // TODO (v8): Update this order to be: Global > Client > Scope\n const eventProcessors = [\n ...clientEventProcessors,\n // eslint-disable-next-line deprecation/deprecation\n ...getGlobalEventProcessors(),\n // Run scope event processors _after_ all other processors\n ...data.eventProcessors,\n ];\n\n const result = notifyEventProcessors(eventProcessors, prepared, hint);\n\n return result.then(evt => {\n if (evt) {\n // We apply the debug_meta field only after all event processors have ran, so that if any event processors modified\n // file names (e.g.the RewriteFrames integration) the filename -> debug ID relationship isn't destroyed.\n // This should not cause any PII issues, since we're only moving data that is already on the event and not adding\n // any new data\n applyDebugMeta(evt);\n }\n\n if (typeof normalizeDepth === 'number' && normalizeDepth > 0) {\n return normalizeEvent(evt, normalizeDepth, normalizeMaxBreadth);\n }\n return evt;\n });\n}\n\n/**\n * Enhances event using the client configuration.\n * It takes care of all \"static\" values like environment, release and `dist`,\n * as well as truncating overly long values.\n * @param event event instance to be enhanced\n */\nfunction applyClientOptions(event: Event, options: ClientOptions): void {\n const { environment, release, dist, maxValueLength = 250 } = options;\n\n if (!('environment' in event)) {\n event.environment = 'environment' in options ? environment : DEFAULT_ENVIRONMENT;\n }\n\n if (event.release === undefined && release !== undefined) {\n event.release = release;\n }\n\n if (event.dist === undefined && dist !== undefined) {\n event.dist = dist;\n }\n\n if (event.message) {\n event.message = truncate(event.message, maxValueLength);\n }\n\n const exception = event.exception && event.exception.values && event.exception.values[0];\n if (exception && exception.value) {\n exception.value = truncate(exception.value, maxValueLength);\n }\n\n const request = event.request;\n if (request && request.url) {\n request.url = truncate(request.url, maxValueLength);\n }\n}\n\nconst debugIdStackParserCache = new WeakMap>();\n\n/**\n * Puts debug IDs into the stack frames of an error event.\n */\nexport function applyDebugIds(event: Event, stackParser: StackParser): void {\n const debugIdMap = GLOBAL_OBJ._sentryDebugIds;\n\n if (!debugIdMap) {\n return;\n }\n\n let debugIdStackFramesCache: Map;\n const cachedDebugIdStackFrameCache = debugIdStackParserCache.get(stackParser);\n if (cachedDebugIdStackFrameCache) {\n debugIdStackFramesCache = cachedDebugIdStackFrameCache;\n } else {\n debugIdStackFramesCache = new Map();\n debugIdStackParserCache.set(stackParser, debugIdStackFramesCache);\n }\n\n // Build a map of filename -> debug_id\n const filenameDebugIdMap = Object.keys(debugIdMap).reduce>((acc, debugIdStackTrace) => {\n let parsedStack: StackFrame[];\n const cachedParsedStack = debugIdStackFramesCache.get(debugIdStackTrace);\n if (cachedParsedStack) {\n parsedStack = cachedParsedStack;\n } else {\n parsedStack = stackParser(debugIdStackTrace);\n debugIdStackFramesCache.set(debugIdStackTrace, parsedStack);\n }\n\n for (let i = parsedStack.length - 1; i >= 0; i--) {\n const stackFrame = parsedStack[i];\n if (stackFrame.filename) {\n acc[stackFrame.filename] = debugIdMap[debugIdStackTrace];\n break;\n }\n }\n return acc;\n }, {});\n\n try {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n event!.exception!.values!.forEach(exception => {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n exception.stacktrace!.frames!.forEach(frame => {\n if (frame.filename) {\n frame.debug_id = filenameDebugIdMap[frame.filename];\n }\n });\n });\n } catch (e) {\n // To save bundle size we're just try catching here instead of checking for the existence of all the different objects.\n }\n}\n\n/**\n * Moves debug IDs from the stack frames of an error event into the debug_meta field.\n */\nexport function applyDebugMeta(event: Event): void {\n // Extract debug IDs and filenames from the stack frames on the event.\n const filenameDebugIdMap: Record = {};\n try {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n event.exception!.values!.forEach(exception => {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n exception.stacktrace!.frames!.forEach(frame => {\n if (frame.debug_id) {\n if (frame.abs_path) {\n filenameDebugIdMap[frame.abs_path] = frame.debug_id;\n } else if (frame.filename) {\n filenameDebugIdMap[frame.filename] = frame.debug_id;\n }\n delete frame.debug_id;\n }\n });\n });\n } catch (e) {\n // To save bundle size we're just try catching here instead of checking for the existence of all the different objects.\n }\n\n if (Object.keys(filenameDebugIdMap).length === 0) {\n return;\n }\n\n // Fill debug_meta information\n event.debug_meta = event.debug_meta || {};\n event.debug_meta.images = event.debug_meta.images || [];\n const images = event.debug_meta.images;\n Object.keys(filenameDebugIdMap).forEach(filename => {\n images.push({\n type: 'sourcemap',\n code_file: filename,\n debug_id: filenameDebugIdMap[filename],\n });\n });\n}\n\n/**\n * This function adds all used integrations to the SDK info in the event.\n * @param event The event that will be filled with all integrations.\n */\nfunction applyIntegrationsMetadata(event: Event, integrationNames: string[]): void {\n if (integrationNames.length > 0) {\n event.sdk = event.sdk || {};\n event.sdk.integrations = [...(event.sdk.integrations || []), ...integrationNames];\n }\n}\n\n/**\n * Applies `normalize` function on necessary `Event` attributes to make them safe for serialization.\n * Normalized keys:\n * - `breadcrumbs.data`\n * - `user`\n * - `contexts`\n * - `extra`\n * @param event Event\n * @returns Normalized event\n */\nfunction normalizeEvent(event: Event | null, depth: number, maxBreadth: number): Event | null {\n if (!event) {\n return null;\n }\n\n const normalized: Event = {\n ...event,\n ...(event.breadcrumbs && {\n breadcrumbs: event.breadcrumbs.map(b => ({\n ...b,\n ...(b.data && {\n data: normalize(b.data, depth, maxBreadth),\n }),\n })),\n }),\n ...(event.user && {\n user: normalize(event.user, depth, maxBreadth),\n }),\n ...(event.contexts && {\n contexts: normalize(event.contexts, depth, maxBreadth),\n }),\n ...(event.extra && {\n extra: normalize(event.extra, depth, maxBreadth),\n }),\n };\n\n // event.contexts.trace stores information about a Transaction. Similarly,\n // event.spans[] stores information about child Spans. Given that a\n // Transaction is conceptually a Span, normalization should apply to both\n // Transactions and Spans consistently.\n // For now the decision is to skip normalization of Transactions and Spans,\n // so this block overwrites the normalized event to add back the original\n // Transaction information prior to normalization.\n if (event.contexts && event.contexts.trace && normalized.contexts) {\n normalized.contexts.trace = event.contexts.trace;\n\n // event.contexts.trace.data may contain circular/dangerous data so we need to normalize it\n if (event.contexts.trace.data) {\n normalized.contexts.trace.data = normalize(event.contexts.trace.data, depth, maxBreadth);\n }\n }\n\n // event.spans[].data may contain circular/dangerous data so we need to normalize it\n if (event.spans) {\n normalized.spans = event.spans.map(span => {\n const data = spanToJSON(span).data;\n\n if (data) {\n // This is a bit weird, as we generally have `Span` instances here, but to be safe we do not assume so\n // eslint-disable-next-line deprecation/deprecation\n span.data = normalize(data, depth, maxBreadth);\n }\n\n return span;\n });\n }\n\n return normalized;\n}\n\nfunction getFinalScope(scope: Scope | undefined, captureContext: CaptureContext | undefined): Scope | undefined {\n if (!captureContext) {\n return scope;\n }\n\n const finalScope = scope ? scope.clone() : new Scope();\n finalScope.update(captureContext);\n return finalScope;\n}\n\n/**\n * Parse either an `EventHint` directly, or convert a `CaptureContext` to an `EventHint`.\n * This is used to allow to update method signatures that used to accept a `CaptureContext` but should now accept an `EventHint`.\n */\nexport function parseEventHintOrCaptureContext(\n hint: ExclusiveEventHintOrCaptureContext | undefined,\n): EventHint | undefined {\n if (!hint) {\n return undefined;\n }\n\n // If you pass a Scope or `() => Scope` as CaptureContext, we just return this as captureContext\n if (hintIsScopeOrFunction(hint)) {\n return { captureContext: hint };\n }\n\n if (hintIsScopeContext(hint)) {\n return {\n captureContext: hint,\n };\n }\n\n return hint;\n}\n\nfunction hintIsScopeOrFunction(\n hint: CaptureContext | EventHint,\n): hint is ScopeInterface | ((scope: ScopeInterface) => ScopeInterface) {\n return hint instanceof Scope || typeof hint === 'function';\n}\n\ntype ScopeContextProperty = keyof ScopeContext;\nconst captureContextKeys: readonly ScopeContextProperty[] = [\n 'user',\n 'level',\n 'extra',\n 'contexts',\n 'tags',\n 'fingerprint',\n 'requestSession',\n 'propagationContext',\n] as const;\n\nfunction hintIsScopeContext(hint: Partial | EventHint): hint is Partial {\n return Object.keys(hint).some(key => captureContextKeys.includes(key as ScopeContextProperty));\n}\n", "import type {\n Breadcrumb,\n BreadcrumbHint,\n CaptureContext,\n CheckIn,\n Client,\n CustomSamplingContext,\n Event,\n EventHint,\n Extra,\n Extras,\n FinishedCheckIn,\n MonitorConfig,\n Primitive,\n Scope as ScopeInterface,\n Session,\n SessionContext,\n Severity,\n SeverityLevel,\n Span,\n TransactionContext,\n User,\n} from '@sentry/types';\nimport { GLOBAL_OBJ, isThenable, logger, timestampInSeconds, uuid4 } from '@sentry/utils';\n\nimport { DEFAULT_ENVIRONMENT } from './constants';\nimport { DEBUG_BUILD } from './debug-build';\nimport type { Hub } from './hub';\nimport { runWithAsyncContext } from './hub';\nimport { getCurrentHub, getIsolationScope } from './hub';\nimport type { Scope } from './scope';\nimport { closeSession, makeSession, updateSession } from './session';\nimport type { ExclusiveEventHintOrCaptureContext } from './utils/prepareEvent';\nimport { parseEventHintOrCaptureContext } from './utils/prepareEvent';\n\n/**\n * Captures an exception event and sends it to Sentry.\n *\n * @param exception The exception to capture.\n * @param hint Optional additional data to attach to the Sentry event.\n * @returns the id of the captured Sentry event.\n */\nexport function captureException(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n exception: any,\n hint?: ExclusiveEventHintOrCaptureContext,\n): string {\n // eslint-disable-next-line deprecation/deprecation\n return getCurrentHub().captureException(exception, parseEventHintOrCaptureContext(hint));\n}\n\n/**\n * Captures a message event and sends it to Sentry.\n *\n * @param exception The exception to capture.\n * @param captureContext Define the level of the message or pass in additional data to attach to the message.\n * @returns the id of the captured message.\n */\nexport function captureMessage(\n message: string,\n // eslint-disable-next-line deprecation/deprecation\n captureContext?: CaptureContext | Severity | SeverityLevel,\n): string {\n // This is necessary to provide explicit scopes upgrade, without changing the original\n // arity of the `captureMessage(message, level)` method.\n const level = typeof captureContext === 'string' ? captureContext : undefined;\n const context = typeof captureContext !== 'string' ? { captureContext } : undefined;\n // eslint-disable-next-line deprecation/deprecation\n return getCurrentHub().captureMessage(message, level, context);\n}\n\n/**\n * Captures a manually created event and sends it to Sentry.\n *\n * @param exception The event to send to Sentry.\n * @param hint Optional additional data to attach to the Sentry event.\n * @returns the id of the captured event.\n */\nexport function captureEvent(event: Event, hint?: EventHint): string {\n // eslint-disable-next-line deprecation/deprecation\n return getCurrentHub().captureEvent(event, hint);\n}\n\n/**\n * Callback to set context information onto the scope.\n * @param callback Callback function that receives Scope.\n *\n * @deprecated Use getCurrentScope() directly.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function configureScope(callback: (scope: Scope) => void): ReturnType {\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub().configureScope(callback);\n}\n\n/**\n * Records a new breadcrumb which will be attached to future events.\n *\n * Breadcrumbs will be added to subsequent events to provide more context on\n * user's actions prior to an error or crash.\n *\n * @param breadcrumb The breadcrumb to record.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function addBreadcrumb(breadcrumb: Breadcrumb, hint?: BreadcrumbHint): ReturnType {\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub().addBreadcrumb(breadcrumb, hint);\n}\n\n/**\n * Sets context data with the given name.\n * @param name of the context\n * @param context Any kind of data. This data will be normalized.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any, deprecation/deprecation\nexport function setContext(name: string, context: { [key: string]: any } | null): ReturnType {\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub().setContext(name, context);\n}\n\n/**\n * Set an object that will be merged sent as extra data with the event.\n * @param extras Extras object to merge into current context.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function setExtras(extras: Extras): ReturnType {\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub().setExtras(extras);\n}\n\n/**\n * Set key:value that will be sent as extra data with the event.\n * @param key String of extra\n * @param extra Any kind of data. This data will be normalized.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function setExtra(key: string, extra: Extra): ReturnType {\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub().setExtra(key, extra);\n}\n\n/**\n * Set an object that will be merged sent as tags data with the event.\n * @param tags Tags context object to merge into current context.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function setTags(tags: { [key: string]: Primitive }): ReturnType {\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub().setTags(tags);\n}\n\n/**\n * Set key:value that will be sent as tags data with the event.\n *\n * Can also be used to unset a tag, by passing `undefined`.\n *\n * @param key String key of tag\n * @param value Value of tag\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function setTag(key: string, value: Primitive): ReturnType {\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub().setTag(key, value);\n}\n\n/**\n * Updates user context information for future events.\n *\n * @param user User context object to be set in the current context. Pass `null` to unset the user.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function setUser(user: User | null): ReturnType {\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub().setUser(user);\n}\n\n/**\n * Creates a new scope with and executes the given operation within.\n * The scope is automatically removed once the operation\n * finishes or throws.\n *\n * This is essentially a convenience function for:\n *\n * pushScope();\n * callback();\n * popScope();\n */\nexport function withScope(callback: (scope: Scope) => T): T;\n/**\n * Set the given scope as the active scope in the callback.\n */\nexport function withScope(scope: ScopeInterface | undefined, callback: (scope: Scope) => T): T;\n/**\n * Either creates a new active scope, or sets the given scope as active scope in the given callback.\n */\nexport function withScope(\n ...rest: [callback: (scope: Scope) => T] | [scope: ScopeInterface | undefined, callback: (scope: Scope) => T]\n): T {\n // eslint-disable-next-line deprecation/deprecation\n const hub = getCurrentHub();\n\n // If a scope is defined, we want to make this the active scope instead of the default one\n if (rest.length === 2) {\n const [scope, callback] = rest;\n if (!scope) {\n // eslint-disable-next-line deprecation/deprecation\n return hub.withScope(callback);\n }\n\n // eslint-disable-next-line deprecation/deprecation\n return hub.withScope(() => {\n // eslint-disable-next-line deprecation/deprecation\n hub.getStackTop().scope = scope as Scope;\n return callback(scope as Scope);\n });\n }\n\n // eslint-disable-next-line deprecation/deprecation\n return hub.withScope(rest[0]);\n}\n\n/**\n * Attempts to fork the current isolation scope and the current scope based on the current async context strategy. If no\n * async context strategy is set, the isolation scope and the current scope will not be forked (this is currently the\n * case, for example, in the browser).\n *\n * Usage of this function in environments without async context strategy is discouraged and may lead to unexpected behaviour.\n *\n * This function is intended for Sentry SDK and SDK integration development. It is not recommended to be used in \"normal\"\n * applications directly because it comes with pitfalls. Use at your own risk!\n *\n * @param callback The callback in which the passed isolation scope is active. (Note: In environments without async\n * context strategy, the currently active isolation scope may change within execution of the callback.)\n * @returns The same value that `callback` returns.\n */\nexport function withIsolationScope(callback: (isolationScope: Scope) => T): T {\n return runWithAsyncContext(() => {\n return callback(getIsolationScope());\n });\n}\n\n/**\n * Forks the current scope and sets the provided span as active span in the context of the provided callback.\n *\n * @param span Spans started in the context of the provided callback will be children of this span.\n * @param callback Execution context in which the provided span will be active. Is passed the newly forked scope.\n * @returns the value returned from the provided callback function.\n */\nexport function withActiveSpan(span: Span, callback: (scope: Scope) => T): T {\n return withScope(scope => {\n // eslint-disable-next-line deprecation/deprecation\n scope.setSpan(span);\n return callback(scope);\n });\n}\n\n/**\n * Starts a new `Transaction` and returns it. This is the entry point to manual tracing instrumentation.\n *\n * A tree structure can be built by adding child spans to the transaction, and child spans to other spans. To start a\n * new child span within the transaction or any span, call the respective `.startChild()` method.\n *\n * Every child span must be finished before the transaction is finished, otherwise the unfinished spans are discarded.\n *\n * The transaction must be finished with a call to its `.end()` method, at which point the transaction with all its\n * finished child spans will be sent to Sentry.\n *\n * NOTE: This function should only be used for *manual* instrumentation. Auto-instrumentation should call\n * `startTransaction` directly on the hub.\n *\n * @param context Properties of the new `Transaction`.\n * @param customSamplingContext Information given to the transaction sampling function (along with context-dependent\n * default values). See {@link Options.tracesSampler}.\n *\n * @returns The transaction which was just started\n *\n * @deprecated Use `startSpan()`, `startSpanManual()` or `startInactiveSpan()` instead.\n */\nexport function startTransaction(\n context: TransactionContext,\n customSamplingContext?: CustomSamplingContext,\n // eslint-disable-next-line deprecation/deprecation\n): ReturnType {\n // eslint-disable-next-line deprecation/deprecation\n return getCurrentHub().startTransaction({ ...context }, customSamplingContext);\n}\n\n/**\n * Create a cron monitor check in and send it to Sentry.\n *\n * @param checkIn An object that describes a check in.\n * @param upsertMonitorConfig An optional object that describes a monitor config. Use this if you want\n * to create a monitor automatically when sending a check in.\n */\nexport function captureCheckIn(checkIn: CheckIn, upsertMonitorConfig?: MonitorConfig): string {\n const scope = getCurrentScope();\n const client = getClient();\n if (!client) {\n DEBUG_BUILD && logger.warn('Cannot capture check-in. No client defined.');\n } else if (!client.captureCheckIn) {\n DEBUG_BUILD && logger.warn('Cannot capture check-in. Client does not support sending check-ins.');\n } else {\n return client.captureCheckIn(checkIn, upsertMonitorConfig, scope);\n }\n\n return uuid4();\n}\n\n/**\n * Wraps a callback with a cron monitor check in. The check in will be sent to Sentry when the callback finishes.\n *\n * @param monitorSlug The distinct slug of the monitor.\n * @param upsertMonitorConfig An optional object that describes a monitor config. Use this if you want\n * to create a monitor automatically when sending a check in.\n */\nexport function withMonitor(\n monitorSlug: CheckIn['monitorSlug'],\n callback: () => T,\n upsertMonitorConfig?: MonitorConfig,\n): T {\n const checkInId = captureCheckIn({ monitorSlug, status: 'in_progress' }, upsertMonitorConfig);\n const now = timestampInSeconds();\n\n function finishCheckIn(status: FinishedCheckIn['status']): void {\n captureCheckIn({ monitorSlug, status, checkInId, duration: timestampInSeconds() - now });\n }\n\n let maybePromiseResult: T;\n try {\n maybePromiseResult = callback();\n } catch (e) {\n finishCheckIn('error');\n throw e;\n }\n\n if (isThenable(maybePromiseResult)) {\n Promise.resolve(maybePromiseResult).then(\n () => {\n finishCheckIn('ok');\n },\n () => {\n finishCheckIn('error');\n },\n );\n } else {\n finishCheckIn('ok');\n }\n\n return maybePromiseResult;\n}\n\n/**\n * Call `flush()` on the current client, if there is one. See {@link Client.flush}.\n *\n * @param timeout Maximum time in ms the client should wait to flush its event queue. Omitting this parameter will cause\n * the client to wait until all events are sent before resolving the promise.\n * @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it\n * doesn't (or if there's no client defined).\n */\nexport async function flush(timeout?: number): Promise {\n const client = getClient();\n if (client) {\n return client.flush(timeout);\n }\n DEBUG_BUILD && logger.warn('Cannot flush events. No client defined.');\n return Promise.resolve(false);\n}\n\n/**\n * Call `close()` on the current client, if there is one. See {@link Client.close}.\n *\n * @param timeout Maximum time in ms the client should wait to flush its event queue before shutting down. Omitting this\n * parameter will cause the client to wait until all events are sent before disabling itself.\n * @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it\n * doesn't (or if there's no client defined).\n */\nexport async function close(timeout?: number): Promise {\n const client = getClient();\n if (client) {\n return client.close(timeout);\n }\n DEBUG_BUILD && logger.warn('Cannot flush events and disable SDK. No client defined.');\n return Promise.resolve(false);\n}\n\n/**\n * This is the getter for lastEventId.\n *\n * @returns The last event id of a captured event.\n */\nexport function lastEventId(): string | undefined {\n // eslint-disable-next-line deprecation/deprecation\n return getCurrentHub().lastEventId();\n}\n\n/**\n * Get the currently active client.\n */\nexport function getClient(): C | undefined {\n // eslint-disable-next-line deprecation/deprecation\n return getCurrentHub().getClient();\n}\n\n/**\n * Returns true if Sentry has been properly initialized.\n */\nexport function isInitialized(): boolean {\n return !!getClient();\n}\n\n/**\n * Get the currently active scope.\n */\nexport function getCurrentScope(): Scope {\n // eslint-disable-next-line deprecation/deprecation\n return getCurrentHub().getScope();\n}\n\n/**\n * Start a session on the current isolation scope.\n *\n * @param context (optional) additional properties to be applied to the returned session object\n *\n * @returns the new active session\n */\nexport function startSession(context?: SessionContext): Session {\n const client = getClient();\n const isolationScope = getIsolationScope();\n const currentScope = getCurrentScope();\n\n const { release, environment = DEFAULT_ENVIRONMENT } = (client && client.getOptions()) || {};\n\n // Will fetch userAgent if called from browser sdk\n const { userAgent } = GLOBAL_OBJ.navigator || {};\n\n const session = makeSession({\n release,\n environment,\n user: currentScope.getUser() || isolationScope.getUser(),\n ...(userAgent && { userAgent }),\n ...context,\n });\n\n // End existing session if there's one\n const currentSession = isolationScope.getSession();\n if (currentSession && currentSession.status === 'ok') {\n updateSession(currentSession, { status: 'exited' });\n }\n\n endSession();\n\n // Afterwards we set the new session on the scope\n isolationScope.setSession(session);\n\n // TODO (v8): Remove this and only use the isolation scope(?).\n // For v7 though, we can't \"soft-break\" people using getCurrentHub().getScope().setSession()\n currentScope.setSession(session);\n\n return session;\n}\n\n/**\n * End the session on the current isolation scope.\n */\nexport function endSession(): void {\n const isolationScope = getIsolationScope();\n const currentScope = getCurrentScope();\n\n const session = currentScope.getSession() || isolationScope.getSession();\n if (session) {\n closeSession(session);\n }\n _sendSessionUpdate();\n\n // the session is over; take it off of the scope\n isolationScope.setSession();\n\n // TODO (v8): Remove this and only use the isolation scope(?).\n // For v7 though, we can't \"soft-break\" people using getCurrentHub().getScope().setSession()\n currentScope.setSession();\n}\n\n/**\n * Sends the current Session on the scope\n */\nfunction _sendSessionUpdate(): void {\n const isolationScope = getIsolationScope();\n const currentScope = getCurrentScope();\n const client = getClient();\n // TODO (v8): Remove currentScope and only use the isolation scope(?).\n // For v7 though, we can't \"soft-break\" people using getCurrentHub().getScope().setSession()\n const session = currentScope.getSession() || isolationScope.getSession();\n if (session && client && client.captureSession) {\n client.captureSession(session);\n }\n}\n\n/**\n * Sends the current session on the scope to Sentry\n *\n * @param end If set the session will be marked as exited and removed from the scope.\n * Defaults to `false`.\n */\nexport function captureSession(end: boolean = false): void {\n // both send the update and pull the session from the scope\n if (end) {\n endSession();\n return;\n }\n\n // only send the update\n _sendSessionUpdate();\n}\n", "import type { Span } from '@sentry/types';\n\n/**\n * Returns the root span of a given span.\n *\n * As long as we use `Transaction`s internally, the returned root span\n * will be a `Transaction` but be aware that this might change in the future.\n *\n * If the given span has no root span or transaction, `undefined` is returned.\n */\nexport function getRootSpan(span: Span): Span | undefined {\n // TODO (v8): Remove this check and just return span\n // eslint-disable-next-line deprecation/deprecation\n return span.transaction;\n}\n", "import type { Client, DynamicSamplingContext, Scope, Span, Transaction } from '@sentry/types';\nimport { dropUndefinedKeys } from '@sentry/utils';\n\nimport { DEFAULT_ENVIRONMENT } from '../constants';\nimport { getClient, getCurrentScope } from '../exports';\nimport { getRootSpan } from '../utils/getRootSpan';\nimport { spanIsSampled, spanToJSON } from '../utils/spanUtils';\n\n/**\n * Creates a dynamic sampling context from a client.\n *\n * Dispatches the `createDsc` lifecycle hook as a side effect.\n */\nexport function getDynamicSamplingContextFromClient(\n trace_id: string,\n client: Client,\n scope?: Scope,\n): DynamicSamplingContext {\n const options = client.getOptions();\n\n const { publicKey: public_key } = client.getDsn() || {};\n // TODO(v8): Remove segment from User\n // eslint-disable-next-line deprecation/deprecation\n const { segment: user_segment } = (scope && scope.getUser()) || {};\n\n const dsc = dropUndefinedKeys({\n environment: options.environment || DEFAULT_ENVIRONMENT,\n release: options.release,\n user_segment,\n public_key,\n trace_id,\n }) as DynamicSamplingContext;\n\n client.emit && client.emit('createDsc', dsc);\n\n return dsc;\n}\n\n/**\n * A Span with a frozen dynamic sampling context.\n */\ntype TransactionWithV7FrozenDsc = Transaction & { _frozenDynamicSamplingContext?: DynamicSamplingContext };\n\n/**\n * Creates a dynamic sampling context from a span (and client and scope)\n *\n * @param span the span from which a few values like the root span name and sample rate are extracted.\n *\n * @returns a dynamic sampling context\n */\nexport function getDynamicSamplingContextFromSpan(span: Span): Readonly> {\n const client = getClient();\n if (!client) {\n return {};\n }\n\n // passing emit=false here to only emit later once the DSC is actually populated\n const dsc = getDynamicSamplingContextFromClient(spanToJSON(span).trace_id || '', client, getCurrentScope());\n\n // TODO (v8): Remove v7FrozenDsc as a Transaction will no longer have _frozenDynamicSamplingContext\n const txn = getRootSpan(span) as TransactionWithV7FrozenDsc | undefined;\n if (!txn) {\n return dsc;\n }\n\n // TODO (v8): Remove v7FrozenDsc as a Transaction will no longer have _frozenDynamicSamplingContext\n // For now we need to avoid breaking users who directly created a txn with a DSC, where this field is still set.\n // @see Transaction class constructor\n const v7FrozenDsc = txn && txn._frozenDynamicSamplingContext;\n if (v7FrozenDsc) {\n return v7FrozenDsc;\n }\n\n // TODO (v8): Replace txn.metadata with txn.attributes[]\n // We can't do this yet because attributes aren't always set yet.\n // eslint-disable-next-line deprecation/deprecation\n const { sampleRate: maybeSampleRate, source } = txn.metadata;\n if (maybeSampleRate != null) {\n dsc.sample_rate = `${maybeSampleRate}`;\n }\n\n // We don't want to have a transaction name in the DSC if the source is \"url\" because URLs might contain PII\n const jsonSpan = spanToJSON(txn);\n\n // after JSON conversion, txn.name becomes jsonSpan.description\n if (source && source !== 'url') {\n dsc.transaction = jsonSpan.description;\n }\n\n dsc.sampled = String(spanIsSampled(txn));\n\n client.emit && client.emit('createDsc', dsc);\n\n return dsc;\n}\n", "import type { Breadcrumb, Event, ScopeData, Span } from '@sentry/types';\nimport { arrayify, dropUndefinedKeys } from '@sentry/utils';\nimport { getDynamicSamplingContextFromSpan } from '../tracing/dynamicSamplingContext';\nimport { getRootSpan } from './getRootSpan';\nimport { spanToJSON, spanToTraceContext } from './spanUtils';\n\n/**\n * Applies data from the scope to the event and runs all event processors on it.\n */\nexport function applyScopeDataToEvent(event: Event, data: ScopeData): void {\n const { fingerprint, span, breadcrumbs, sdkProcessingMetadata } = data;\n\n // Apply general data\n applyDataToEvent(event, data);\n\n // We want to set the trace context for normal events only if there isn't already\n // a trace context on the event. There is a product feature in place where we link\n // errors with transaction and it relies on that.\n if (span) {\n applySpanToEvent(event, span);\n }\n\n applyFingerprintToEvent(event, fingerprint);\n applyBreadcrumbsToEvent(event, breadcrumbs);\n applySdkMetadataToEvent(event, sdkProcessingMetadata);\n}\n\n/** Merge data of two scopes together. */\nexport function mergeScopeData(data: ScopeData, mergeData: ScopeData): void {\n const {\n extra,\n tags,\n user,\n contexts,\n level,\n sdkProcessingMetadata,\n breadcrumbs,\n fingerprint,\n eventProcessors,\n attachments,\n propagationContext,\n // eslint-disable-next-line deprecation/deprecation\n transactionName,\n span,\n } = mergeData;\n\n mergeAndOverwriteScopeData(data, 'extra', extra);\n mergeAndOverwriteScopeData(data, 'tags', tags);\n mergeAndOverwriteScopeData(data, 'user', user);\n mergeAndOverwriteScopeData(data, 'contexts', contexts);\n mergeAndOverwriteScopeData(data, 'sdkProcessingMetadata', sdkProcessingMetadata);\n\n if (level) {\n data.level = level;\n }\n\n if (transactionName) {\n // eslint-disable-next-line deprecation/deprecation\n data.transactionName = transactionName;\n }\n\n if (span) {\n data.span = span;\n }\n\n if (breadcrumbs.length) {\n data.breadcrumbs = [...data.breadcrumbs, ...breadcrumbs];\n }\n\n if (fingerprint.length) {\n data.fingerprint = [...data.fingerprint, ...fingerprint];\n }\n\n if (eventProcessors.length) {\n data.eventProcessors = [...data.eventProcessors, ...eventProcessors];\n }\n\n if (attachments.length) {\n data.attachments = [...data.attachments, ...attachments];\n }\n\n data.propagationContext = { ...data.propagationContext, ...propagationContext };\n}\n\n/**\n * Merges certain scope data. Undefined values will overwrite any existing values.\n * Exported only for tests.\n */\nexport function mergeAndOverwriteScopeData<\n Prop extends 'extra' | 'tags' | 'user' | 'contexts' | 'sdkProcessingMetadata',\n Data extends ScopeData,\n>(data: Data, prop: Prop, mergeVal: Data[Prop]): void {\n if (mergeVal && Object.keys(mergeVal).length) {\n // Clone object\n data[prop] = { ...data[prop] };\n for (const key in mergeVal) {\n if (Object.prototype.hasOwnProperty.call(mergeVal, key)) {\n data[prop][key] = mergeVal[key];\n }\n }\n }\n}\n\n/** Exported only for tests */\nexport function mergeArray(\n event: Event,\n prop: Prop,\n mergeVal: ScopeData[Prop],\n): void {\n const prevVal = event[prop];\n // If we are not merging any new values,\n // we only need to proceed if there was an empty array before (as we want to replace it with undefined)\n if (!mergeVal.length && (!prevVal || prevVal.length)) {\n return;\n }\n\n const merged = [...(prevVal || []), ...mergeVal] as ScopeData[Prop];\n event[prop] = merged.length ? merged : undefined;\n}\n\nfunction applyDataToEvent(event: Event, data: ScopeData): void {\n const {\n extra,\n tags,\n user,\n contexts,\n level,\n // eslint-disable-next-line deprecation/deprecation\n transactionName,\n } = data;\n\n const cleanedExtra = dropUndefinedKeys(extra);\n if (cleanedExtra && Object.keys(cleanedExtra).length) {\n event.extra = { ...cleanedExtra, ...event.extra };\n }\n\n const cleanedTags = dropUndefinedKeys(tags);\n if (cleanedTags && Object.keys(cleanedTags).length) {\n event.tags = { ...cleanedTags, ...event.tags };\n }\n\n const cleanedUser = dropUndefinedKeys(user);\n if (cleanedUser && Object.keys(cleanedUser).length) {\n event.user = { ...cleanedUser, ...event.user };\n }\n\n const cleanedContexts = dropUndefinedKeys(contexts);\n if (cleanedContexts && Object.keys(cleanedContexts).length) {\n event.contexts = { ...cleanedContexts, ...event.contexts };\n }\n\n if (level) {\n event.level = level;\n }\n\n if (transactionName) {\n event.transaction = transactionName;\n }\n}\n\nfunction applyBreadcrumbsToEvent(event: Event, breadcrumbs: Breadcrumb[]): void {\n const mergedBreadcrumbs = [...(event.breadcrumbs || []), ...breadcrumbs];\n event.breadcrumbs = mergedBreadcrumbs.length ? mergedBreadcrumbs : undefined;\n}\n\nfunction applySdkMetadataToEvent(event: Event, sdkProcessingMetadata: ScopeData['sdkProcessingMetadata']): void {\n event.sdkProcessingMetadata = {\n ...event.sdkProcessingMetadata,\n ...sdkProcessingMetadata,\n };\n}\n\nfunction applySpanToEvent(event: Event, span: Span): void {\n event.contexts = { trace: spanToTraceContext(span), ...event.contexts };\n const rootSpan = getRootSpan(span);\n if (rootSpan) {\n event.sdkProcessingMetadata = {\n dynamicSamplingContext: getDynamicSamplingContextFromSpan(span),\n ...event.sdkProcessingMetadata,\n };\n const transactionName = spanToJSON(rootSpan).description;\n if (transactionName) {\n event.tags = { transaction: transactionName, ...event.tags };\n }\n }\n}\n\n/**\n * Applies fingerprint from the scope to the event if there's one,\n * uses message if there's one instead or get rid of empty fingerprint\n */\nfunction applyFingerprintToEvent(event: Event, fingerprint: ScopeData['fingerprint'] | undefined): void {\n // Make sure it's an array first and we actually have something in place\n event.fingerprint = event.fingerprint ? arrayify(event.fingerprint) : [];\n\n // If we have something on the scope, then merge it with event\n if (fingerprint) {\n event.fingerprint = event.fingerprint.concat(fingerprint);\n }\n\n // If we have no data at all, remove empty array default\n if (event.fingerprint && !event.fingerprint.length) {\n delete event.fingerprint;\n }\n}\n", "/* eslint-disable max-lines */\nimport type {\n Attachment,\n Breadcrumb,\n CaptureContext,\n Client,\n Context,\n Contexts,\n Event,\n EventHint,\n EventProcessor,\n Extra,\n Extras,\n Primitive,\n PropagationContext,\n RequestSession,\n Scope as ScopeInterface,\n ScopeContext,\n ScopeData,\n Session,\n Severity,\n SeverityLevel,\n Span,\n Transaction,\n User,\n} from '@sentry/types';\nimport { dateTimestampInSeconds, isPlainObject, logger, uuid4 } from '@sentry/utils';\n\nimport { getGlobalEventProcessors, notifyEventProcessors } from './eventProcessors';\nimport { updateSession } from './session';\nimport { applyScopeDataToEvent } from './utils/applyScopeDataToEvent';\n\n/**\n * Default value for maximum number of breadcrumbs added to an event.\n */\nconst DEFAULT_MAX_BREADCRUMBS = 100;\n\n/**\n * The global scope is kept in this module.\n * When accessing this via `getGlobalScope()` we'll make sure to set one if none is currently present.\n */\nlet globalScope: ScopeInterface | undefined;\n\n/**\n * Holds additional event information. {@link Scope.applyToEvent} will be\n * called by the client before an event will be sent.\n */\nexport class Scope implements ScopeInterface {\n /** Flag if notifying is happening. */\n protected _notifyingListeners: boolean;\n\n /** Callback for client to receive scope changes. */\n protected _scopeListeners: Array<(scope: Scope) => void>;\n\n /** Callback list that will be called after {@link applyToEvent}. */\n protected _eventProcessors: EventProcessor[];\n\n /** Array of breadcrumbs. */\n protected _breadcrumbs: Breadcrumb[];\n\n /** User */\n protected _user: User;\n\n /** Tags */\n protected _tags: { [key: string]: Primitive };\n\n /** Extra */\n protected _extra: Extras;\n\n /** Contexts */\n protected _contexts: Contexts;\n\n /** Attachments */\n protected _attachments: Attachment[];\n\n /** Propagation Context for distributed tracing */\n protected _propagationContext: PropagationContext;\n\n /**\n * A place to stash data which is needed at some point in the SDK's event processing pipeline but which shouldn't get\n * sent to Sentry\n */\n protected _sdkProcessingMetadata: { [key: string]: unknown };\n\n /** Fingerprint */\n protected _fingerprint?: string[];\n\n /** Severity */\n // eslint-disable-next-line deprecation/deprecation\n protected _level?: Severity | SeverityLevel;\n\n /**\n * Transaction Name\n */\n protected _transactionName?: string;\n\n /** Span */\n protected _span?: Span;\n\n /** Session */\n protected _session?: Session;\n\n /** Request Mode Session Status */\n protected _requestSession?: RequestSession;\n\n /** The client on this scope */\n protected _client?: Client;\n\n // NOTE: Any field which gets added here should get added not only to the constructor but also to the `clone` method.\n\n public constructor() {\n this._notifyingListeners = false;\n this._scopeListeners = [];\n this._eventProcessors = [];\n this._breadcrumbs = [];\n this._attachments = [];\n this._user = {};\n this._tags = {};\n this._extra = {};\n this._contexts = {};\n this._sdkProcessingMetadata = {};\n this._propagationContext = generatePropagationContext();\n }\n\n /**\n * Inherit values from the parent scope.\n * @deprecated Use `scope.clone()` and `new Scope()` instead.\n */\n public static clone(scope?: Scope): Scope {\n return scope ? scope.clone() : new Scope();\n }\n\n /**\n * Clone this scope instance.\n */\n public clone(): Scope {\n const newScope = new Scope();\n newScope._breadcrumbs = [...this._breadcrumbs];\n newScope._tags = { ...this._tags };\n newScope._extra = { ...this._extra };\n newScope._contexts = { ...this._contexts };\n newScope._user = this._user;\n newScope._level = this._level;\n newScope._span = this._span;\n newScope._session = this._session;\n newScope._transactionName = this._transactionName;\n newScope._fingerprint = this._fingerprint;\n newScope._eventProcessors = [...this._eventProcessors];\n newScope._requestSession = this._requestSession;\n newScope._attachments = [...this._attachments];\n newScope._sdkProcessingMetadata = { ...this._sdkProcessingMetadata };\n newScope._propagationContext = { ...this._propagationContext };\n newScope._client = this._client;\n\n return newScope;\n }\n\n /** Update the client on the scope. */\n public setClient(client: Client | undefined): void {\n this._client = client;\n }\n\n /**\n * Get the client assigned to this scope.\n *\n * It is generally recommended to use the global function `Sentry.getClient()` instead, unless you know what you are doing.\n */\n public getClient(): Client | undefined {\n return this._client;\n }\n\n /**\n * Add internal on change listener. Used for sub SDKs that need to store the scope.\n * @hidden\n */\n public addScopeListener(callback: (scope: Scope) => void): void {\n this._scopeListeners.push(callback);\n }\n\n /**\n * @inheritDoc\n */\n public addEventProcessor(callback: EventProcessor): this {\n this._eventProcessors.push(callback);\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setUser(user: User | null): this {\n // If null is passed we want to unset everything, but still define keys,\n // so that later down in the pipeline any existing values are cleared.\n this._user = user || {\n email: undefined,\n id: undefined,\n ip_address: undefined,\n segment: undefined,\n username: undefined,\n };\n\n if (this._session) {\n updateSession(this._session, { user });\n }\n\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public getUser(): User | undefined {\n return this._user;\n }\n\n /**\n * @inheritDoc\n */\n public getRequestSession(): RequestSession | undefined {\n return this._requestSession;\n }\n\n /**\n * @inheritDoc\n */\n public setRequestSession(requestSession?: RequestSession): this {\n this._requestSession = requestSession;\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setTags(tags: { [key: string]: Primitive }): this {\n this._tags = {\n ...this._tags,\n ...tags,\n };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setTag(key: string, value: Primitive): this {\n this._tags = { ...this._tags, [key]: value };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setExtras(extras: Extras): this {\n this._extra = {\n ...this._extra,\n ...extras,\n };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setExtra(key: string, extra: Extra): this {\n this._extra = { ...this._extra, [key]: extra };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setFingerprint(fingerprint: string[]): this {\n this._fingerprint = fingerprint;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setLevel(\n // eslint-disable-next-line deprecation/deprecation\n level: Severity | SeverityLevel,\n ): this {\n this._level = level;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * Sets the transaction name on the scope for future events.\n */\n public setTransactionName(name?: string): this {\n this._transactionName = name;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setContext(key: string, context: Context | null): this {\n if (context === null) {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete this._contexts[key];\n } else {\n this._contexts[key] = context;\n }\n\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * Sets the Span on the scope.\n * @param span Span\n * @deprecated Instead of setting a span on a scope, use `startSpan()`/`startSpanManual()` instead.\n */\n public setSpan(span?: Span): this {\n this._span = span;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * Returns the `Span` if there is one.\n * @deprecated Use `getActiveSpan()` instead.\n */\n public getSpan(): Span | undefined {\n return this._span;\n }\n\n /**\n * Returns the `Transaction` attached to the scope (if there is one).\n * @deprecated You should not rely on the transaction, but just use `startSpan()` APIs instead.\n */\n public getTransaction(): Transaction | undefined {\n // Often, this span (if it exists at all) will be a transaction, but it's not guaranteed to be. Regardless, it will\n // have a pointer to the currently-active transaction.\n const span = this._span;\n // Cannot replace with getRootSpan because getRootSpan returns a span, not a transaction\n // Also, this method will be removed anyway.\n // eslint-disable-next-line deprecation/deprecation\n return span && span.transaction;\n }\n\n /**\n * @inheritDoc\n */\n public setSession(session?: Session): this {\n if (!session) {\n delete this._session;\n } else {\n this._session = session;\n }\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public getSession(): Session | undefined {\n return this._session;\n }\n\n /**\n * @inheritDoc\n */\n public update(captureContext?: CaptureContext): this {\n if (!captureContext) {\n return this;\n }\n\n const scopeToMerge = typeof captureContext === 'function' ? captureContext(this) : captureContext;\n\n if (scopeToMerge instanceof Scope) {\n const scopeData = scopeToMerge.getScopeData();\n\n this._tags = { ...this._tags, ...scopeData.tags };\n this._extra = { ...this._extra, ...scopeData.extra };\n this._contexts = { ...this._contexts, ...scopeData.contexts };\n if (scopeData.user && Object.keys(scopeData.user).length) {\n this._user = scopeData.user;\n }\n if (scopeData.level) {\n this._level = scopeData.level;\n }\n if (scopeData.fingerprint.length) {\n this._fingerprint = scopeData.fingerprint;\n }\n if (scopeToMerge.getRequestSession()) {\n this._requestSession = scopeToMerge.getRequestSession();\n }\n if (scopeData.propagationContext) {\n this._propagationContext = scopeData.propagationContext;\n }\n } else if (isPlainObject(scopeToMerge)) {\n const scopeContext = captureContext as ScopeContext;\n this._tags = { ...this._tags, ...scopeContext.tags };\n this._extra = { ...this._extra, ...scopeContext.extra };\n this._contexts = { ...this._contexts, ...scopeContext.contexts };\n if (scopeContext.user) {\n this._user = scopeContext.user;\n }\n if (scopeContext.level) {\n this._level = scopeContext.level;\n }\n if (scopeContext.fingerprint) {\n this._fingerprint = scopeContext.fingerprint;\n }\n if (scopeContext.requestSession) {\n this._requestSession = scopeContext.requestSession;\n }\n if (scopeContext.propagationContext) {\n this._propagationContext = scopeContext.propagationContext;\n }\n }\n\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public clear(): this {\n this._breadcrumbs = [];\n this._tags = {};\n this._extra = {};\n this._user = {};\n this._contexts = {};\n this._level = undefined;\n this._transactionName = undefined;\n this._fingerprint = undefined;\n this._requestSession = undefined;\n this._span = undefined;\n this._session = undefined;\n this._notifyScopeListeners();\n this._attachments = [];\n this._propagationContext = generatePropagationContext();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public addBreadcrumb(breadcrumb: Breadcrumb, maxBreadcrumbs?: number): this {\n const maxCrumbs = typeof maxBreadcrumbs === 'number' ? maxBreadcrumbs : DEFAULT_MAX_BREADCRUMBS;\n\n // No data has been changed, so don't notify scope listeners\n if (maxCrumbs <= 0) {\n return this;\n }\n\n const mergedBreadcrumb = {\n timestamp: dateTimestampInSeconds(),\n ...breadcrumb,\n };\n\n const breadcrumbs = this._breadcrumbs;\n breadcrumbs.push(mergedBreadcrumb);\n this._breadcrumbs = breadcrumbs.length > maxCrumbs ? breadcrumbs.slice(-maxCrumbs) : breadcrumbs;\n\n this._notifyScopeListeners();\n\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public getLastBreadcrumb(): Breadcrumb | undefined {\n return this._breadcrumbs[this._breadcrumbs.length - 1];\n }\n\n /**\n * @inheritDoc\n */\n public clearBreadcrumbs(): this {\n this._breadcrumbs = [];\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public addAttachment(attachment: Attachment): this {\n this._attachments.push(attachment);\n return this;\n }\n\n /**\n * @inheritDoc\n * @deprecated Use `getScopeData()` instead.\n */\n public getAttachments(): Attachment[] {\n const data = this.getScopeData();\n\n return data.attachments;\n }\n\n /**\n * @inheritDoc\n */\n public clearAttachments(): this {\n this._attachments = [];\n return this;\n }\n\n /** @inheritDoc */\n public getScopeData(): ScopeData {\n const {\n _breadcrumbs,\n _attachments,\n _contexts,\n _tags,\n _extra,\n _user,\n _level,\n _fingerprint,\n _eventProcessors,\n _propagationContext,\n _sdkProcessingMetadata,\n _transactionName,\n _span,\n } = this;\n\n return {\n breadcrumbs: _breadcrumbs,\n attachments: _attachments,\n contexts: _contexts,\n tags: _tags,\n extra: _extra,\n user: _user,\n level: _level,\n fingerprint: _fingerprint || [],\n eventProcessors: _eventProcessors,\n propagationContext: _propagationContext,\n sdkProcessingMetadata: _sdkProcessingMetadata,\n transactionName: _transactionName,\n span: _span,\n };\n }\n\n /**\n * Applies data from the scope to the event and runs all event processors on it.\n *\n * @param event Event\n * @param hint Object containing additional information about the original exception, for use by the event processors.\n * @hidden\n * @deprecated Use `applyScopeDataToEvent()` directly\n */\n public applyToEvent(\n event: Event,\n hint: EventHint = {},\n additionalEventProcessors: EventProcessor[] = [],\n ): PromiseLike {\n applyScopeDataToEvent(event, this.getScopeData());\n\n // TODO (v8): Update this order to be: Global > Client > Scope\n const eventProcessors: EventProcessor[] = [\n ...additionalEventProcessors,\n // eslint-disable-next-line deprecation/deprecation\n ...getGlobalEventProcessors(),\n ...this._eventProcessors,\n ];\n\n return notifyEventProcessors(eventProcessors, event, hint);\n }\n\n /**\n * Add data which will be accessible during event processing but won't get sent to Sentry\n */\n public setSDKProcessingMetadata(newData: { [key: string]: unknown }): this {\n this._sdkProcessingMetadata = { ...this._sdkProcessingMetadata, ...newData };\n\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setPropagationContext(context: PropagationContext): this {\n this._propagationContext = context;\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public getPropagationContext(): PropagationContext {\n return this._propagationContext;\n }\n\n /**\n * Capture an exception for this scope.\n *\n * @param exception The exception to capture.\n * @param hint Optinal additional data to attach to the Sentry event.\n * @returns the id of the captured Sentry event.\n */\n public captureException(exception: unknown, hint?: EventHint): string {\n const eventId = hint && hint.event_id ? hint.event_id : uuid4();\n\n if (!this._client) {\n logger.warn('No client configured on scope - will not capture exception!');\n return eventId;\n }\n\n const syntheticException = new Error('Sentry syntheticException');\n\n this._client.captureException(\n exception,\n {\n originalException: exception,\n syntheticException,\n ...hint,\n event_id: eventId,\n },\n this,\n );\n\n return eventId;\n }\n\n /**\n * Capture a message for this scope.\n *\n * @param message The message to capture.\n * @param level An optional severity level to report the message with.\n * @param hint Optional additional data to attach to the Sentry event.\n * @returns the id of the captured message.\n */\n public captureMessage(message: string, level?: SeverityLevel, hint?: EventHint): string {\n const eventId = hint && hint.event_id ? hint.event_id : uuid4();\n\n if (!this._client) {\n logger.warn('No client configured on scope - will not capture message!');\n return eventId;\n }\n\n const syntheticException = new Error(message);\n\n this._client.captureMessage(\n message,\n level,\n {\n originalException: message,\n syntheticException,\n ...hint,\n event_id: eventId,\n },\n this,\n );\n\n return eventId;\n }\n\n /**\n * Captures a manually created event for this scope and sends it to Sentry.\n *\n * @param exception The event to capture.\n * @param hint Optional additional data to attach to the Sentry event.\n * @returns the id of the captured event.\n */\n public captureEvent(event: Event, hint?: EventHint): string {\n const eventId = hint && hint.event_id ? hint.event_id : uuid4();\n\n if (!this._client) {\n logger.warn('No client configured on scope - will not capture event!');\n return eventId;\n }\n\n this._client.captureEvent(event, { ...hint, event_id: eventId }, this);\n\n return eventId;\n }\n\n /**\n * This will be called on every set call.\n */\n protected _notifyScopeListeners(): void {\n // We need this check for this._notifyingListeners to be able to work on scope during updates\n // If this check is not here we'll produce endless recursion when something is done with the scope\n // during the callback.\n if (!this._notifyingListeners) {\n this._notifyingListeners = true;\n this._scopeListeners.forEach(callback => {\n callback(this);\n });\n this._notifyingListeners = false;\n }\n }\n}\n\n/**\n * Get the global scope.\n * This scope is applied to _all_ events.\n */\nexport function getGlobalScope(): ScopeInterface {\n if (!globalScope) {\n globalScope = new Scope();\n }\n\n return globalScope;\n}\n\n/**\n * This is mainly needed for tests.\n * DO NOT USE this, as this is an internal API and subject to change.\n * @hidden\n */\nexport function setGlobalScope(scope: ScopeInterface | undefined): void {\n globalScope = scope;\n}\n\nfunction generatePropagationContext(): PropagationContext {\n return {\n traceId: uuid4(),\n spanId: uuid4().substring(16),\n };\n}\n", "export const SDK_VERSION = '7.119.2';\n", "/* eslint-disable max-lines */\nimport type {\n Breadcrumb,\n BreadcrumbHint,\n Client,\n CustomSamplingContext,\n Event,\n EventHint,\n Extra,\n Extras,\n Hub as HubInterface,\n Integration,\n IntegrationClass,\n Primitive,\n Session,\n SessionContext,\n Severity,\n SeverityLevel,\n Transaction,\n TransactionContext,\n User,\n} from '@sentry/types';\nimport {\n GLOBAL_OBJ,\n consoleSandbox,\n dateTimestampInSeconds,\n getGlobalSingleton,\n isThenable,\n logger,\n uuid4,\n} from '@sentry/utils';\n\nimport { DEFAULT_ENVIRONMENT } from './constants';\nimport { DEBUG_BUILD } from './debug-build';\nimport { Scope } from './scope';\nimport { closeSession, makeSession, updateSession } from './session';\nimport { SDK_VERSION } from './version';\n\n/**\n * API compatibility version of this hub.\n *\n * WARNING: This number should only be increased when the global interface\n * changes and new methods are introduced.\n *\n * @hidden\n */\nexport const API_VERSION = parseFloat(SDK_VERSION);\n\n/**\n * Default maximum number of breadcrumbs added to an event. Can be overwritten\n * with {@link Options.maxBreadcrumbs}.\n */\nconst DEFAULT_BREADCRUMBS = 100;\n\nexport interface RunWithAsyncContextOptions {\n /** Whether to reuse an existing async context if one exists. Defaults to false. */\n reuseExisting?: boolean;\n}\n\n/**\n * @private Private API with no semver guarantees!\n *\n * Strategy used to track async context.\n */\nexport interface AsyncContextStrategy {\n /**\n * Gets the current async context. Returns undefined if there is no current async context.\n */\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub: () => Hub | undefined;\n /**\n * Runs the supplied callback in its own async context.\n */\n runWithAsyncContext(callback: () => T, options: RunWithAsyncContextOptions): T;\n}\n\n/**\n * A layer in the process stack.\n * @hidden\n */\nexport interface Layer {\n client?: Client;\n scope: Scope;\n}\n\n/**\n * An object that contains a hub and maintains a scope stack.\n * @hidden\n */\nexport interface Carrier {\n __SENTRY__?: {\n // eslint-disable-next-line deprecation/deprecation\n hub?: Hub;\n acs?: AsyncContextStrategy;\n /**\n * Extra Hub properties injected by various SDKs\n */\n integrations?: Integration[];\n extensions?: {\n /** Extension methods for the hub, which are bound to the current Hub instance */\n // eslint-disable-next-line @typescript-eslint/ban-types\n [key: string]: Function;\n };\n };\n}\n\n/**\n * @deprecated The `Hub` class will be removed in version 8 of the SDK in favour of `Scope` and `Client` objects.\n *\n * If you previously used the `Hub` class directly, replace it with `Scope` and `Client` objects. More information:\n * - [Multiple Sentry Instances](https://docs.sentry.io/platforms/javascript/best-practices/multiple-sentry-instances/)\n * - [Browser Extensions](https://docs.sentry.io/platforms/javascript/best-practices/browser-extensions/)\n *\n * Some of our APIs are typed with the Hub class instead of the interface (e.g. `getCurrentHub`). Most of them are deprecated\n * themselves and will also be removed in version 8. More information:\n * - [Migration Guide](https://github.com/getsentry/sentry-javascript/blob/develop/MIGRATION.md#deprecate-hub)\n */\n// eslint-disable-next-line deprecation/deprecation\nexport class Hub implements HubInterface {\n /** Is a {@link Layer}[] containing the client and scope */\n private readonly _stack: Layer[];\n\n /** Contains the last event id of a captured event. */\n private _lastEventId?: string;\n\n private _isolationScope: Scope;\n\n /**\n * Creates a new instance of the hub, will push one {@link Layer} into the\n * internal stack on creation.\n *\n * @param client bound to the hub.\n * @param scope bound to the hub.\n * @param version number, higher number means higher priority.\n *\n * @deprecated Instantiation of Hub objects is deprecated and the constructor will be removed in version 8 of the SDK.\n *\n * If you are currently using the Hub for multi-client use like so:\n *\n * ```\n * // OLD\n * const hub = new Hub();\n * hub.bindClient(client);\n * makeMain(hub)\n * ```\n *\n * instead initialize the client as follows:\n *\n * ```\n * // NEW\n * Sentry.withIsolationScope(() => {\n * Sentry.setCurrentClient(client);\n * client.init();\n * });\n * ```\n *\n * If you are using the Hub to capture events like so:\n *\n * ```\n * // OLD\n * const client = new Client();\n * const hub = new Hub(client);\n * hub.captureException()\n * ```\n *\n * instead capture isolated events as follows:\n *\n * ```\n * // NEW\n * const client = new Client();\n * const scope = new Scope();\n * scope.setClient(client);\n * scope.captureException();\n * ```\n */\n public constructor(\n client?: Client,\n scope?: Scope,\n isolationScope?: Scope,\n private readonly _version: number = API_VERSION,\n ) {\n let assignedScope;\n if (!scope) {\n assignedScope = new Scope();\n assignedScope.setClient(client);\n } else {\n assignedScope = scope;\n }\n\n let assignedIsolationScope;\n if (!isolationScope) {\n assignedIsolationScope = new Scope();\n assignedIsolationScope.setClient(client);\n } else {\n assignedIsolationScope = isolationScope;\n }\n\n this._stack = [{ scope: assignedScope }];\n\n if (client) {\n // eslint-disable-next-line deprecation/deprecation\n this.bindClient(client);\n }\n\n this._isolationScope = assignedIsolationScope;\n }\n\n /**\n * Checks if this hub's version is older than the given version.\n *\n * @param version A version number to compare to.\n * @return True if the given version is newer; otherwise false.\n *\n * @deprecated This will be removed in v8.\n */\n public isOlderThan(version: number): boolean {\n return this._version < version;\n }\n\n /**\n * This binds the given client to the current scope.\n * @param client An SDK client (client) instance.\n *\n * @deprecated Use `initAndBind()` directly, or `setCurrentClient()` and/or `client.init()` instead.\n */\n public bindClient(client?: Client): void {\n // eslint-disable-next-line deprecation/deprecation\n const top = this.getStackTop();\n top.client = client;\n top.scope.setClient(client);\n // eslint-disable-next-line deprecation/deprecation\n if (client && client.setupIntegrations) {\n // eslint-disable-next-line deprecation/deprecation\n client.setupIntegrations();\n }\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `withScope` instead.\n */\n public pushScope(): Scope {\n // We want to clone the content of prev scope\n // eslint-disable-next-line deprecation/deprecation\n const scope = this.getScope().clone();\n // eslint-disable-next-line deprecation/deprecation\n this.getStack().push({\n // eslint-disable-next-line deprecation/deprecation\n client: this.getClient(),\n scope,\n });\n return scope;\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `withScope` instead.\n */\n public popScope(): boolean {\n // eslint-disable-next-line deprecation/deprecation\n if (this.getStack().length <= 1) return false;\n // eslint-disable-next-line deprecation/deprecation\n return !!this.getStack().pop();\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `Sentry.withScope()` instead.\n */\n public withScope(callback: (scope: Scope) => T): T {\n // eslint-disable-next-line deprecation/deprecation\n const scope = this.pushScope();\n\n let maybePromiseResult: T;\n try {\n maybePromiseResult = callback(scope);\n } catch (e) {\n // eslint-disable-next-line deprecation/deprecation\n this.popScope();\n throw e;\n }\n\n if (isThenable(maybePromiseResult)) {\n // @ts-expect-error - isThenable returns the wrong type\n return maybePromiseResult.then(\n res => {\n // eslint-disable-next-line deprecation/deprecation\n this.popScope();\n return res;\n },\n e => {\n // eslint-disable-next-line deprecation/deprecation\n this.popScope();\n throw e;\n },\n );\n }\n\n // eslint-disable-next-line deprecation/deprecation\n this.popScope();\n return maybePromiseResult;\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `Sentry.getClient()` instead.\n */\n public getClient(): C | undefined {\n // eslint-disable-next-line deprecation/deprecation\n return this.getStackTop().client as C;\n }\n\n /**\n * Returns the scope of the top stack.\n *\n * @deprecated Use `Sentry.getCurrentScope()` instead.\n */\n public getScope(): Scope {\n // eslint-disable-next-line deprecation/deprecation\n return this.getStackTop().scope;\n }\n\n /**\n * @deprecated Use `Sentry.getIsolationScope()` instead.\n */\n public getIsolationScope(): Scope {\n return this._isolationScope;\n }\n\n /**\n * Returns the scope stack for domains or the process.\n * @deprecated This will be removed in v8.\n */\n public getStack(): Layer[] {\n return this._stack;\n }\n\n /**\n * Returns the topmost scope layer in the order domain > local > process.\n * @deprecated This will be removed in v8.\n */\n public getStackTop(): Layer {\n return this._stack[this._stack.length - 1];\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `Sentry.captureException()` instead.\n */\n public captureException(exception: unknown, hint?: EventHint): string {\n const eventId = (this._lastEventId = hint && hint.event_id ? hint.event_id : uuid4());\n const syntheticException = new Error('Sentry syntheticException');\n // eslint-disable-next-line deprecation/deprecation\n this.getScope().captureException(exception, {\n originalException: exception,\n syntheticException,\n ...hint,\n event_id: eventId,\n });\n\n return eventId;\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `Sentry.captureMessage()` instead.\n */\n public captureMessage(\n message: string,\n // eslint-disable-next-line deprecation/deprecation\n level?: Severity | SeverityLevel,\n hint?: EventHint,\n ): string {\n const eventId = (this._lastEventId = hint && hint.event_id ? hint.event_id : uuid4());\n const syntheticException = new Error(message);\n // eslint-disable-next-line deprecation/deprecation\n this.getScope().captureMessage(message, level, {\n originalException: message,\n syntheticException,\n ...hint,\n event_id: eventId,\n });\n\n return eventId;\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `Sentry.captureEvent()` instead.\n */\n public captureEvent(event: Event, hint?: EventHint): string {\n const eventId = hint && hint.event_id ? hint.event_id : uuid4();\n if (!event.type) {\n this._lastEventId = eventId;\n }\n // eslint-disable-next-line deprecation/deprecation\n this.getScope().captureEvent(event, { ...hint, event_id: eventId });\n return eventId;\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated This will be removed in v8.\n */\n public lastEventId(): string | undefined {\n return this._lastEventId;\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `Sentry.addBreadcrumb()` instead.\n */\n public addBreadcrumb(breadcrumb: Breadcrumb, hint?: BreadcrumbHint): void {\n // eslint-disable-next-line deprecation/deprecation\n const { scope, client } = this.getStackTop();\n\n if (!client) return;\n\n const { beforeBreadcrumb = null, maxBreadcrumbs = DEFAULT_BREADCRUMBS } =\n (client.getOptions && client.getOptions()) || {};\n\n if (maxBreadcrumbs <= 0) return;\n\n const timestamp = dateTimestampInSeconds();\n const mergedBreadcrumb = { timestamp, ...breadcrumb };\n const finalBreadcrumb = beforeBreadcrumb\n ? (consoleSandbox(() => beforeBreadcrumb(mergedBreadcrumb, hint)) as Breadcrumb | null)\n : mergedBreadcrumb;\n\n if (finalBreadcrumb === null) return;\n\n if (client.emit) {\n client.emit('beforeAddBreadcrumb', finalBreadcrumb, hint);\n }\n\n // TODO(v8): I know this comment doesn't make much sense because the hub will be deprecated but I still wanted to\n // write it down. In theory, we would have to add the breadcrumbs to the isolation scope here, however, that would\n // duplicate all of the breadcrumbs. There was the possibility of adding breadcrumbs to both, the isolation scope\n // and the normal scope, and deduplicating it down the line in the event processing pipeline. However, that would\n // have been very fragile, because the breadcrumb objects would have needed to keep their identity all throughout\n // the event processing pipeline.\n // In the new implementation, the top level `Sentry.addBreadcrumb()` should ONLY write to the isolation scope.\n\n scope.addBreadcrumb(finalBreadcrumb, maxBreadcrumbs);\n }\n\n /**\n * @inheritDoc\n * @deprecated Use `Sentry.setUser()` instead.\n */\n public setUser(user: User | null): void {\n // TODO(v8): The top level `Sentry.setUser()` function should write ONLY to the isolation scope.\n // eslint-disable-next-line deprecation/deprecation\n this.getScope().setUser(user);\n // eslint-disable-next-line deprecation/deprecation\n this.getIsolationScope().setUser(user);\n }\n\n /**\n * @inheritDoc\n * @deprecated Use `Sentry.setTags()` instead.\n */\n public setTags(tags: { [key: string]: Primitive }): void {\n // TODO(v8): The top level `Sentry.setTags()` function should write ONLY to the isolation scope.\n // eslint-disable-next-line deprecation/deprecation\n this.getScope().setTags(tags);\n // eslint-disable-next-line deprecation/deprecation\n this.getIsolationScope().setTags(tags);\n }\n\n /**\n * @inheritDoc\n * @deprecated Use `Sentry.setExtras()` instead.\n */\n public setExtras(extras: Extras): void {\n // TODO(v8): The top level `Sentry.setExtras()` function should write ONLY to the isolation scope.\n // eslint-disable-next-line deprecation/deprecation\n this.getScope().setExtras(extras);\n // eslint-disable-next-line deprecation/deprecation\n this.getIsolationScope().setExtras(extras);\n }\n\n /**\n * @inheritDoc\n * @deprecated Use `Sentry.setTag()` instead.\n */\n public setTag(key: string, value: Primitive): void {\n // TODO(v8): The top level `Sentry.setTag()` function should write ONLY to the isolation scope.\n // eslint-disable-next-line deprecation/deprecation\n this.getScope().setTag(key, value);\n // eslint-disable-next-line deprecation/deprecation\n this.getIsolationScope().setTag(key, value);\n }\n\n /**\n * @inheritDoc\n * @deprecated Use `Sentry.setExtra()` instead.\n */\n public setExtra(key: string, extra: Extra): void {\n // TODO(v8): The top level `Sentry.setExtra()` function should write ONLY to the isolation scope.\n // eslint-disable-next-line deprecation/deprecation\n this.getScope().setExtra(key, extra);\n // eslint-disable-next-line deprecation/deprecation\n this.getIsolationScope().setExtra(key, extra);\n }\n\n /**\n * @inheritDoc\n * @deprecated Use `Sentry.setContext()` instead.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n public setContext(name: string, context: { [key: string]: any } | null): void {\n // TODO(v8): The top level `Sentry.setContext()` function should write ONLY to the isolation scope.\n // eslint-disable-next-line deprecation/deprecation\n this.getScope().setContext(name, context);\n // eslint-disable-next-line deprecation/deprecation\n this.getIsolationScope().setContext(name, context);\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `getScope()` directly.\n */\n public configureScope(callback: (scope: Scope) => void): void {\n // eslint-disable-next-line deprecation/deprecation\n const { scope, client } = this.getStackTop();\n if (client) {\n callback(scope);\n }\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line deprecation/deprecation\n public run(callback: (hub: Hub) => void): void {\n // eslint-disable-next-line deprecation/deprecation\n const oldHub = makeMain(this);\n try {\n callback(this);\n } finally {\n // eslint-disable-next-line deprecation/deprecation\n makeMain(oldHub);\n }\n }\n\n /**\n * @inheritDoc\n * @deprecated Use `Sentry.getClient().getIntegrationByName()` instead.\n */\n public getIntegration(integration: IntegrationClass): T | null {\n // eslint-disable-next-line deprecation/deprecation\n const client = this.getClient();\n if (!client) return null;\n try {\n // eslint-disable-next-line deprecation/deprecation\n return client.getIntegration(integration);\n } catch (_oO) {\n DEBUG_BUILD && logger.warn(`Cannot retrieve integration ${integration.id} from the current Hub`);\n return null;\n }\n }\n\n /**\n * Starts a new `Transaction` and returns it. This is the entry point to manual tracing instrumentation.\n *\n * A tree structure can be built by adding child spans to the transaction, and child spans to other spans. To start a\n * new child span within the transaction or any span, call the respective `.startChild()` method.\n *\n * Every child span must be finished before the transaction is finished, otherwise the unfinished spans are discarded.\n *\n * The transaction must be finished with a call to its `.end()` method, at which point the transaction with all its\n * finished child spans will be sent to Sentry.\n *\n * @param context Properties of the new `Transaction`.\n * @param customSamplingContext Information given to the transaction sampling function (along with context-dependent\n * default values). See {@link Options.tracesSampler}.\n *\n * @returns The transaction which was just started\n *\n * @deprecated Use `startSpan()`, `startSpanManual()` or `startInactiveSpan()` instead.\n */\n public startTransaction(context: TransactionContext, customSamplingContext?: CustomSamplingContext): Transaction {\n const result = this._callExtensionMethod('startTransaction', context, customSamplingContext);\n\n if (DEBUG_BUILD && !result) {\n // eslint-disable-next-line deprecation/deprecation\n const client = this.getClient();\n if (!client) {\n logger.warn(\n \"Tracing extension 'startTransaction' is missing. You should 'init' the SDK before calling 'startTransaction'\",\n );\n } else {\n logger.warn(`Tracing extension 'startTransaction' has not been added. Call 'addTracingExtensions' before calling 'init':\nSentry.addTracingExtensions();\nSentry.init({...});\n`);\n }\n }\n\n return result;\n }\n\n /**\n * @inheritDoc\n * @deprecated Use `spanToTraceHeader()` instead.\n */\n public traceHeaders(): { [key: string]: string } {\n return this._callExtensionMethod<{ [key: string]: string }>('traceHeaders');\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use top level `captureSession` instead.\n */\n public captureSession(endSession: boolean = false): void {\n // both send the update and pull the session from the scope\n if (endSession) {\n // eslint-disable-next-line deprecation/deprecation\n return this.endSession();\n }\n\n // only send the update\n this._sendSessionUpdate();\n }\n\n /**\n * @inheritDoc\n * @deprecated Use top level `endSession` instead.\n */\n public endSession(): void {\n // eslint-disable-next-line deprecation/deprecation\n const layer = this.getStackTop();\n const scope = layer.scope;\n const session = scope.getSession();\n if (session) {\n closeSession(session);\n }\n this._sendSessionUpdate();\n\n // the session is over; take it off of the scope\n scope.setSession();\n }\n\n /**\n * @inheritDoc\n * @deprecated Use top level `startSession` instead.\n */\n public startSession(context?: SessionContext): Session {\n // eslint-disable-next-line deprecation/deprecation\n const { scope, client } = this.getStackTop();\n const { release, environment = DEFAULT_ENVIRONMENT } = (client && client.getOptions()) || {};\n\n // Will fetch userAgent if called from browser sdk\n const { userAgent } = GLOBAL_OBJ.navigator || {};\n\n const session = makeSession({\n release,\n environment,\n user: scope.getUser(),\n ...(userAgent && { userAgent }),\n ...context,\n });\n\n // End existing session if there's one\n const currentSession = scope.getSession && scope.getSession();\n if (currentSession && currentSession.status === 'ok') {\n updateSession(currentSession, { status: 'exited' });\n }\n // eslint-disable-next-line deprecation/deprecation\n this.endSession();\n\n // Afterwards we set the new session on the scope\n scope.setSession(session);\n\n return session;\n }\n\n /**\n * Returns if default PII should be sent to Sentry and propagated in ourgoing requests\n * when Tracing is used.\n *\n * @deprecated Use top-level `getClient().getOptions().sendDefaultPii` instead. This function\n * only unnecessarily increased API surface but only wrapped accessing the option.\n */\n public shouldSendDefaultPii(): boolean {\n // eslint-disable-next-line deprecation/deprecation\n const client = this.getClient();\n const options = client && client.getOptions();\n return Boolean(options && options.sendDefaultPii);\n }\n\n /**\n * Sends the current Session on the scope\n */\n private _sendSessionUpdate(): void {\n // eslint-disable-next-line deprecation/deprecation\n const { scope, client } = this.getStackTop();\n\n const session = scope.getSession();\n if (session && client && client.captureSession) {\n client.captureSession(session);\n }\n }\n\n /**\n * Calls global extension method and binding current instance to the function call\n */\n // @ts-expect-error Function lacks ending return statement and return type does not include 'undefined'. ts(2366)\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private _callExtensionMethod(method: string, ...args: any[]): T {\n const carrier = getMainCarrier();\n const sentry = carrier.__SENTRY__;\n if (sentry && sentry.extensions && typeof sentry.extensions[method] === 'function') {\n return sentry.extensions[method].apply(this, args);\n }\n DEBUG_BUILD && logger.warn(`Extension method ${method} couldn't be found, doing nothing.`);\n }\n}\n\n/**\n * Returns the global shim registry.\n *\n * FIXME: This function is problematic, because despite always returning a valid Carrier,\n * it has an optional `__SENTRY__` property, which then in turn requires us to always perform an unnecessary check\n * at the call-site. We always access the carrier through this function, so we can guarantee that `__SENTRY__` is there.\n **/\nexport function getMainCarrier(): Carrier {\n GLOBAL_OBJ.__SENTRY__ = GLOBAL_OBJ.__SENTRY__ || {\n extensions: {},\n hub: undefined,\n };\n return GLOBAL_OBJ;\n}\n\n/**\n * Replaces the current main hub with the passed one on the global object\n *\n * @returns The old replaced hub\n *\n * @deprecated Use `setCurrentClient()` instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function makeMain(hub: Hub): Hub {\n const registry = getMainCarrier();\n const oldHub = getHubFromCarrier(registry);\n setHubOnCarrier(registry, hub);\n return oldHub;\n}\n\n/**\n * Returns the default hub instance.\n *\n * If a hub is already registered in the global carrier but this module\n * contains a more recent version, it replaces the registered version.\n * Otherwise, the currently registered hub will be returned.\n *\n * @deprecated Use the respective replacement method directly instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function getCurrentHub(): Hub {\n // Get main carrier (global for every environment)\n const registry = getMainCarrier();\n\n if (registry.__SENTRY__ && registry.__SENTRY__.acs) {\n const hub = registry.__SENTRY__.acs.getCurrentHub();\n\n if (hub) {\n return hub;\n }\n }\n\n // Return hub that lives on a global object\n return getGlobalHub(registry);\n}\n\n/**\n * Get the currently active isolation scope.\n * The isolation scope is active for the current exection context,\n * meaning that it will remain stable for the same Hub.\n */\nexport function getIsolationScope(): Scope {\n // eslint-disable-next-line deprecation/deprecation\n return getCurrentHub().getIsolationScope();\n}\n\n// eslint-disable-next-line deprecation/deprecation\nfunction getGlobalHub(registry: Carrier = getMainCarrier()): Hub {\n // If there's no hub, or its an old API, assign a new one\n\n if (\n !hasHubOnCarrier(registry) ||\n // eslint-disable-next-line deprecation/deprecation\n getHubFromCarrier(registry).isOlderThan(API_VERSION)\n ) {\n // eslint-disable-next-line deprecation/deprecation\n setHubOnCarrier(registry, new Hub());\n }\n\n // Return hub that lives on a global object\n return getHubFromCarrier(registry);\n}\n\n/**\n * @private Private API with no semver guarantees!\n *\n * If the carrier does not contain a hub, a new hub is created with the global hub client and scope.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function ensureHubOnCarrier(carrier: Carrier, parent: Hub = getGlobalHub()): void {\n // If there's no hub on current domain, or it's an old API, assign a new one\n if (\n !hasHubOnCarrier(carrier) ||\n // eslint-disable-next-line deprecation/deprecation\n getHubFromCarrier(carrier).isOlderThan(API_VERSION)\n ) {\n // eslint-disable-next-line deprecation/deprecation\n const client = parent.getClient();\n // eslint-disable-next-line deprecation/deprecation\n const scope = parent.getScope();\n // eslint-disable-next-line deprecation/deprecation\n const isolationScope = parent.getIsolationScope();\n // eslint-disable-next-line deprecation/deprecation\n setHubOnCarrier(carrier, new Hub(client, scope.clone(), isolationScope.clone()));\n }\n}\n\n/**\n * @private Private API with no semver guarantees!\n *\n * Sets the global async context strategy\n */\nexport function setAsyncContextStrategy(strategy: AsyncContextStrategy | undefined): void {\n // Get main carrier (global for every environment)\n const registry = getMainCarrier();\n registry.__SENTRY__ = registry.__SENTRY__ || {};\n registry.__SENTRY__.acs = strategy;\n}\n\n/**\n * Runs the supplied callback in its own async context. Async Context strategies are defined per SDK.\n *\n * @param callback The callback to run in its own async context\n * @param options Options to pass to the async context strategy\n * @returns The result of the callback\n */\nexport function runWithAsyncContext(callback: () => T, options: RunWithAsyncContextOptions = {}): T {\n const registry = getMainCarrier();\n\n if (registry.__SENTRY__ && registry.__SENTRY__.acs) {\n return registry.__SENTRY__.acs.runWithAsyncContext(callback, options);\n }\n\n // if there was no strategy, fallback to just calling the callback\n return callback();\n}\n\n/**\n * This will tell whether a carrier has a hub on it or not\n * @param carrier object\n */\nfunction hasHubOnCarrier(carrier: Carrier): boolean {\n return !!(carrier && carrier.__SENTRY__ && carrier.__SENTRY__.hub);\n}\n\n/**\n * This will create a new {@link Hub} and add to the passed object on\n * __SENTRY__.hub.\n * @param carrier object\n * @hidden\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function getHubFromCarrier(carrier: Carrier): Hub {\n // eslint-disable-next-line deprecation/deprecation\n return getGlobalSingleton('hub', () => new Hub(), carrier);\n}\n\n/**\n * This will set passed {@link Hub} on the passed object's __SENTRY__.hub attribute\n * @param carrier object\n * @param hub Hub\n * @returns A boolean indicating success or failure\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function setHubOnCarrier(carrier: Carrier, hub: Hub): boolean {\n if (!carrier) return false;\n const __SENTRY__ = (carrier.__SENTRY__ = carrier.__SENTRY__ || {});\n __SENTRY__.hub = hub;\n return true;\n}\n", "import type { Transaction } from '@sentry/types';\nimport { extractTraceparentData as _extractTraceparentData } from '@sentry/utils';\n\nimport type { Hub } from '../hub';\nimport { getCurrentHub } from '../hub';\n\n/**\n * Grabs active transaction off scope.\n *\n * @deprecated You should not rely on the transaction, but just use `startSpan()` APIs instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function getActiveTransaction(maybeHub?: Hub): T | undefined {\n // eslint-disable-next-line deprecation/deprecation\n const hub = maybeHub || getCurrentHub();\n // eslint-disable-next-line deprecation/deprecation\n const scope = hub.getScope();\n // eslint-disable-next-line deprecation/deprecation\n return scope.getTransaction() as T | undefined;\n}\n\n// so it can be used in manual instrumentation without necessitating a hard dependency on @sentry/utils\nexport { stripUrlQueryAndFragment } from '@sentry/utils';\n\n/**\n * The `extractTraceparentData` function and `TRACEPARENT_REGEXP` constant used\n * to be declared in this file. It was later moved into `@sentry/utils` as part of a\n * move to remove `@sentry/tracing` dependencies from `@sentry/node` (`extractTraceparentData`\n * is the only tracing function used by `@sentry/node`).\n *\n * These exports are kept here for backwards compatability's sake.\n *\n * See https://github.com/getsentry/sentry-javascript/issues/4642 for more details.\n *\n * @deprecated Import this function from `@sentry/utils` instead\n */\nexport const extractTraceparentData = _extractTraceparentData;\n", "import {\n addGlobalErrorInstrumentationHandler,\n addGlobalUnhandledRejectionInstrumentationHandler,\n logger,\n} from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { SpanStatusType } from './spanstatus';\nimport { getActiveTransaction } from './utils';\n\nlet errorsInstrumented = false;\n\n/**\n * Configures global error listeners\n */\nexport function registerErrorInstrumentation(): void {\n if (errorsInstrumented) {\n return;\n }\n\n errorsInstrumented = true;\n addGlobalErrorInstrumentationHandler(errorCallback);\n addGlobalUnhandledRejectionInstrumentationHandler(errorCallback);\n}\n\n/**\n * If an error or unhandled promise occurs, we mark the active transaction as failed\n */\nfunction errorCallback(): void {\n // eslint-disable-next-line deprecation/deprecation\n const activeTransaction = getActiveTransaction();\n if (activeTransaction) {\n const status: SpanStatusType = 'internal_error';\n DEBUG_BUILD && logger.log(`[Tracing] Transaction: ${status} -> Global error occured`);\n activeTransaction.setStatus(status);\n }\n}\n\n// The function name will be lost when bundling but we need to be able to identify this listener later to maintain the\n// node.js default exit behaviour\nerrorCallback.tag = 'sentry_tracingErrorCallback';\n", "import type { Span } from '@sentry/types';\n\n/** The status of an Span.\n *\n * @deprecated Use string literals - if you require type casting, cast to SpanStatusType type\n */\nexport enum SpanStatus {\n /** The operation completed successfully. */\n Ok = 'ok',\n /** Deadline expired before operation could complete. */\n DeadlineExceeded = 'deadline_exceeded',\n /** 401 Unauthorized (actually does mean unauthenticated according to RFC 7235) */\n Unauthenticated = 'unauthenticated',\n /** 403 Forbidden */\n PermissionDenied = 'permission_denied',\n /** 404 Not Found. Some requested entity (file or directory) was not found. */\n NotFound = 'not_found',\n /** 429 Too Many Requests */\n ResourceExhausted = 'resource_exhausted',\n /** Client specified an invalid argument. 4xx. */\n InvalidArgument = 'invalid_argument',\n /** 501 Not Implemented */\n Unimplemented = 'unimplemented',\n /** 503 Service Unavailable */\n Unavailable = 'unavailable',\n /** Other/generic 5xx. */\n InternalError = 'internal_error',\n /** Unknown. Any non-standard HTTP status code. */\n UnknownError = 'unknown_error',\n /** The operation was cancelled (typically by the user). */\n Cancelled = 'cancelled',\n /** Already exists (409) */\n AlreadyExists = 'already_exists',\n /** Operation was rejected because the system is not in a state required for the operation's */\n FailedPrecondition = 'failed_precondition',\n /** The operation was aborted, typically due to a concurrency issue. */\n Aborted = 'aborted',\n /** Operation was attempted past the valid range. */\n OutOfRange = 'out_of_range',\n /** Unrecoverable data loss or corruption */\n DataLoss = 'data_loss',\n}\n\nexport type SpanStatusType =\n /** The operation completed successfully. */\n | 'ok'\n /** Deadline expired before operation could complete. */\n | 'deadline_exceeded'\n /** 401 Unauthorized (actually does mean unauthenticated according to RFC 7235) */\n | 'unauthenticated'\n /** 403 Forbidden */\n | 'permission_denied'\n /** 404 Not Found. Some requested entity (file or directory) was not found. */\n | 'not_found'\n /** 429 Too Many Requests */\n | 'resource_exhausted'\n /** Client specified an invalid argument. 4xx. */\n | 'invalid_argument'\n /** 501 Not Implemented */\n | 'unimplemented'\n /** 503 Service Unavailable */\n | 'unavailable'\n /** Other/generic 5xx. */\n | 'internal_error'\n /** Unknown. Any non-standard HTTP status code. */\n | 'unknown_error'\n /** The operation was cancelled (typically by the user). */\n | 'cancelled'\n /** Already exists (409) */\n | 'already_exists'\n /** Operation was rejected because the system is not in a state required for the operation's */\n | 'failed_precondition'\n /** The operation was aborted, typically due to a concurrency issue. */\n | 'aborted'\n /** Operation was attempted past the valid range. */\n | 'out_of_range'\n /** Unrecoverable data loss or corruption */\n | 'data_loss';\n\n/**\n * Converts a HTTP status code into a {@link SpanStatusType}.\n *\n * @param httpStatus The HTTP response status code.\n * @returns The span status or unknown_error.\n */\nexport function getSpanStatusFromHttpCode(httpStatus: number): SpanStatusType {\n if (httpStatus < 400 && httpStatus >= 100) {\n return 'ok';\n }\n\n if (httpStatus >= 400 && httpStatus < 500) {\n switch (httpStatus) {\n case 401:\n return 'unauthenticated';\n case 403:\n return 'permission_denied';\n case 404:\n return 'not_found';\n case 409:\n return 'already_exists';\n case 413:\n return 'failed_precondition';\n case 429:\n return 'resource_exhausted';\n default:\n return 'invalid_argument';\n }\n }\n\n if (httpStatus >= 500 && httpStatus < 600) {\n switch (httpStatus) {\n case 501:\n return 'unimplemented';\n case 503:\n return 'unavailable';\n case 504:\n return 'deadline_exceeded';\n default:\n return 'internal_error';\n }\n }\n\n return 'unknown_error';\n}\n\n/**\n * Converts a HTTP status code into a {@link SpanStatusType}.\n *\n * @deprecated Use {@link spanStatusFromHttpCode} instead.\n * This export will be removed in v8 as the signature contains a typo.\n *\n * @param httpStatus The HTTP response status code.\n * @returns The span status or unknown_error.\n */\nexport const spanStatusfromHttpCode = getSpanStatusFromHttpCode;\n\n/**\n * Sets the Http status attributes on the current span based on the http code.\n * Additionally, the span's status is updated, depending on the http code.\n */\nexport function setHttpStatus(span: Span, httpStatus: number): void {\n // TODO (v8): Remove these calls\n // Relay does not require us to send the status code as a tag\n // For now, just because users might expect it to land as a tag we keep sending it.\n // Same with data.\n // In v8, we replace both, simply with\n // span.setAttribute('http.response.status_code', httpStatus);\n\n // eslint-disable-next-line deprecation/deprecation\n span.setTag('http.status_code', String(httpStatus));\n // eslint-disable-next-line deprecation/deprecation\n span.setData('http.response.status_code', httpStatus);\n\n const spanStatus = getSpanStatusFromHttpCode(httpStatus);\n if (spanStatus !== 'unknown_error') {\n span.setStatus(spanStatus);\n }\n}\n", "import { isThenable } from '@sentry/utils';\n\n/**\n * Wrap a callback function with error handling.\n * If an error is thrown, it will be passed to the `onError` callback and re-thrown.\n *\n * If the return value of the function is a promise, it will be handled with `maybeHandlePromiseRejection`.\n *\n * If an `onFinally` callback is provided, this will be called when the callback has finished\n * - so if it returns a promise, once the promise resolved/rejected,\n * else once the callback has finished executing.\n * The `onFinally` callback will _always_ be called, no matter if an error was thrown or not.\n */\nexport function handleCallbackErrors<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n Fn extends () => any,\n>(\n fn: Fn,\n onError: (error: unknown) => void,\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n onFinally: () => void = () => {},\n): ReturnType {\n let maybePromiseResult: ReturnType;\n try {\n maybePromiseResult = fn();\n } catch (e) {\n onError(e);\n onFinally();\n throw e;\n }\n\n return maybeHandlePromiseRejection(maybePromiseResult, onError, onFinally);\n}\n\n/**\n * Maybe handle a promise rejection.\n * This expects to be given a value that _may_ be a promise, or any other value.\n * If it is a promise, and it rejects, it will call the `onError` callback.\n * Other than this, it will generally return the given value as-is.\n */\nfunction maybeHandlePromiseRejection(\n value: MaybePromise,\n onError: (error: unknown) => void,\n onFinally: () => void,\n): MaybePromise {\n if (isThenable(value)) {\n // @ts-expect-error - the isThenable check returns the \"wrong\" type here\n return value.then(\n res => {\n onFinally();\n return res;\n },\n e => {\n onError(e);\n onFinally();\n throw e;\n },\n );\n }\n\n onFinally();\n return value;\n}\n", "import type { Options } from '@sentry/types';\n\nimport { getClient } from '../exports';\n\n// Treeshakable guard to remove all code related to tracing\ndeclare const __SENTRY_TRACING__: boolean | undefined;\n\n/**\n * Determines if tracing is currently enabled.\n *\n * Tracing is enabled when at least one of `tracesSampleRate` and `tracesSampler` is defined in the SDK config.\n */\nexport function hasTracingEnabled(\n maybeOptions?: Pick | undefined,\n): boolean {\n if (typeof __SENTRY_TRACING__ === 'boolean' && !__SENTRY_TRACING__) {\n return false;\n }\n\n const client = getClient();\n const options = maybeOptions || (client && client.getOptions());\n return !!options && (options.enableTracing || 'tracesSampleRate' in options || 'tracesSampler' in options);\n}\n", "import type { Scope, Span, SpanTimeInput, StartSpanOptions, TransactionContext } from '@sentry/types';\n\nimport { addNonEnumerableProperty, dropUndefinedKeys, logger, tracingContextFromHeaders } from '@sentry/utils';\nimport { getDynamicSamplingContextFromSpan } from '.';\n\nimport { DEBUG_BUILD } from '../debug-build';\nimport { getCurrentScope, withScope } from '../exports';\nimport type { Hub } from '../hub';\nimport { runWithAsyncContext } from '../hub';\nimport { getIsolationScope } from '../hub';\nimport { getCurrentHub } from '../hub';\nimport type { Scope as ScopeClass } from '../scope';\nimport { handleCallbackErrors } from '../utils/handleCallbackErrors';\nimport { hasTracingEnabled } from '../utils/hasTracingEnabled';\nimport { spanIsSampled, spanTimeInputToSeconds, spanToJSON } from '../utils/spanUtils';\n\n/**\n * Wraps a function with a transaction/span and finishes the span after the function is done.\n *\n * Note that if you have not enabled tracing extensions via `addTracingExtensions`\n * or you didn't set `tracesSampleRate`, this function will not generate spans\n * and the `span` returned from the callback will be undefined.\n *\n * This function is meant to be used internally and may break at any time. Use at your own risk.\n *\n * @internal\n * @private\n *\n * @deprecated Use `startSpan` instead.\n */\nexport function trace(\n context: TransactionContext,\n callback: (span?: Span) => T,\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n onError: (error: unknown, span?: Span) => void = () => {},\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n afterFinish: () => void = () => {},\n): T {\n // eslint-disable-next-line deprecation/deprecation\n const hub = getCurrentHub();\n const scope = getCurrentScope();\n // eslint-disable-next-line deprecation/deprecation\n const parentSpan = scope.getSpan();\n\n const spanContext = normalizeContext(context);\n const activeSpan = createChildSpanOrTransaction(hub, {\n parentSpan,\n spanContext,\n forceTransaction: false,\n scope,\n });\n\n // eslint-disable-next-line deprecation/deprecation\n scope.setSpan(activeSpan);\n\n return handleCallbackErrors(\n () => callback(activeSpan),\n error => {\n activeSpan && activeSpan.setStatus('internal_error');\n onError(error, activeSpan);\n },\n () => {\n activeSpan && activeSpan.end();\n // eslint-disable-next-line deprecation/deprecation\n scope.setSpan(parentSpan);\n afterFinish();\n },\n );\n}\n\n/**\n * Wraps a function with a transaction/span and finishes the span after the function is done.\n * The created span is the active span and will be used as parent by other spans created inside the function\n * and can be accessed via `Sentry.getSpan()`, as long as the function is executed while the scope is active.\n *\n * If you want to create a span that is not set as active, use {@link startInactiveSpan}.\n *\n * Note that if you have not enabled tracing extensions via `addTracingExtensions`\n * or you didn't set `tracesSampleRate`, this function will not generate spans\n * and the `span` returned from the callback will be undefined.\n */\nexport function startSpan(context: StartSpanOptions, callback: (span: Span | undefined) => T): T {\n const spanContext = normalizeContext(context);\n\n return runWithAsyncContext(() => {\n return withScope(context.scope, scope => {\n // eslint-disable-next-line deprecation/deprecation\n const hub = getCurrentHub();\n // eslint-disable-next-line deprecation/deprecation\n const parentSpan = scope.getSpan();\n\n const shouldSkipSpan = context.onlyIfParent && !parentSpan;\n const activeSpan = shouldSkipSpan\n ? undefined\n : createChildSpanOrTransaction(hub, {\n parentSpan,\n spanContext,\n forceTransaction: context.forceTransaction,\n scope,\n });\n\n return handleCallbackErrors(\n () => callback(activeSpan),\n () => {\n // Only update the span status if it hasn't been changed yet\n if (activeSpan) {\n const { status } = spanToJSON(activeSpan);\n if (!status || status === 'ok') {\n activeSpan.setStatus('internal_error');\n }\n }\n },\n () => activeSpan && activeSpan.end(),\n );\n });\n });\n}\n\n/**\n * @deprecated Use {@link startSpan} instead.\n */\nexport const startActiveSpan = startSpan;\n\n/**\n * Similar to `Sentry.startSpan`. Wraps a function with a transaction/span, but does not finish the span\n * after the function is done automatically. You'll have to call `span.end()` manually.\n *\n * The created span is the active span and will be used as parent by other spans created inside the function\n * and can be accessed via `Sentry.getActiveSpan()`, as long as the function is executed while the scope is active.\n *\n * Note that if you have not enabled tracing extensions via `addTracingExtensions`\n * or you didn't set `tracesSampleRate`, this function will not generate spans\n * and the `span` returned from the callback will be undefined.\n */\nexport function startSpanManual(\n context: StartSpanOptions,\n callback: (span: Span | undefined, finish: () => void) => T,\n): T {\n const spanContext = normalizeContext(context);\n\n return runWithAsyncContext(() => {\n return withScope(context.scope, scope => {\n // eslint-disable-next-line deprecation/deprecation\n const hub = getCurrentHub();\n // eslint-disable-next-line deprecation/deprecation\n const parentSpan = scope.getSpan();\n\n const shouldSkipSpan = context.onlyIfParent && !parentSpan;\n const activeSpan = shouldSkipSpan\n ? undefined\n : createChildSpanOrTransaction(hub, {\n parentSpan,\n spanContext,\n forceTransaction: context.forceTransaction,\n scope,\n });\n\n function finishAndSetSpan(): void {\n activeSpan && activeSpan.end();\n }\n\n return handleCallbackErrors(\n () => callback(activeSpan, finishAndSetSpan),\n () => {\n // Only update the span status if it hasn't been changed yet, and the span is not yet finished\n if (activeSpan && activeSpan.isRecording()) {\n const { status } = spanToJSON(activeSpan);\n if (!status || status === 'ok') {\n activeSpan.setStatus('internal_error');\n }\n }\n },\n );\n });\n });\n}\n\n/**\n * Creates a span. This span is not set as active, so will not get automatic instrumentation spans\n * as children or be able to be accessed via `Sentry.getSpan()`.\n *\n * If you want to create a span that is set as active, use {@link startSpan}.\n *\n * Note that if you have not enabled tracing extensions via `addTracingExtensions`\n * or you didn't set `tracesSampleRate` or `tracesSampler`, this function will not generate spans\n * and the `span` returned from the callback will be undefined.\n */\nexport function startInactiveSpan(context: StartSpanOptions): Span | undefined {\n if (!hasTracingEnabled()) {\n return undefined;\n }\n\n const spanContext = normalizeContext(context);\n // eslint-disable-next-line deprecation/deprecation\n const hub = getCurrentHub();\n const parentSpan = context.scope\n ? // eslint-disable-next-line deprecation/deprecation\n context.scope.getSpan()\n : getActiveSpan();\n\n const shouldSkipSpan = context.onlyIfParent && !parentSpan;\n\n if (shouldSkipSpan) {\n return undefined;\n }\n\n const scope = context.scope || getCurrentScope();\n\n // Even though we don't actually want to make this span active on the current scope,\n // we need to make it active on a temporary scope that we use for event processing\n // as otherwise, it won't pick the correct span for the event when processing it\n const temporaryScope = (scope as ScopeClass).clone();\n\n return createChildSpanOrTransaction(hub, {\n parentSpan,\n spanContext,\n forceTransaction: context.forceTransaction,\n scope: temporaryScope,\n });\n}\n\n/**\n * Returns the currently active span.\n */\nexport function getActiveSpan(): Span | undefined {\n // eslint-disable-next-line deprecation/deprecation\n return getCurrentScope().getSpan();\n}\n\ninterface ContinueTrace {\n /**\n * Continue a trace from `sentry-trace` and `baggage` values.\n * These values can be obtained from incoming request headers,\n * or in the browser from `` and `` HTML tags.\n *\n * @deprecated Use the version of this function taking a callback as second parameter instead:\n *\n * ```\n * Sentry.continueTrace(sentryTrace: '...', baggage: '...' }, () => {\n * // ...\n * })\n * ```\n *\n */\n ({\n sentryTrace,\n baggage,\n }: {\n // eslint-disable-next-line deprecation/deprecation\n sentryTrace: Parameters[0];\n // eslint-disable-next-line deprecation/deprecation\n baggage: Parameters[1];\n }): Partial;\n\n /**\n * Continue a trace from `sentry-trace` and `baggage` values.\n * These values can be obtained from incoming request headers, or in the browser from ``\n * and `` HTML tags.\n *\n * Spans started with `startSpan`, `startSpanManual` and `startInactiveSpan`, within the callback will automatically\n * be attached to the incoming trace.\n *\n * Deprecation notice: In the next major version of the SDK the provided callback will not receive a transaction\n * context argument.\n */\n (\n {\n sentryTrace,\n baggage,\n }: {\n // eslint-disable-next-line deprecation/deprecation\n sentryTrace: Parameters[0];\n // eslint-disable-next-line deprecation/deprecation\n baggage: Parameters[1];\n },\n // TODO(v8): Remove parameter from this callback.\n callback: (transactionContext: Partial) => V,\n ): V;\n}\n\nexport const continueTrace: ContinueTrace = (\n {\n sentryTrace,\n baggage,\n }: {\n // eslint-disable-next-line deprecation/deprecation\n sentryTrace: Parameters[0];\n // eslint-disable-next-line deprecation/deprecation\n baggage: Parameters[1];\n },\n callback?: (transactionContext: Partial) => V,\n): V | Partial => {\n // TODO(v8): Change this function so it doesn't do anything besides setting the propagation context on the current scope:\n /*\n return withScope((scope) => {\n const propagationContext = propagationContextFromHeaders(sentryTrace, baggage);\n scope.setPropagationContext(propagationContext);\n return callback();\n })\n */\n\n const currentScope = getCurrentScope();\n\n // eslint-disable-next-line deprecation/deprecation\n const { traceparentData, dynamicSamplingContext, propagationContext } = tracingContextFromHeaders(\n sentryTrace,\n baggage,\n );\n\n currentScope.setPropagationContext(propagationContext);\n\n if (DEBUG_BUILD && traceparentData) {\n logger.log(`[Tracing] Continuing trace ${traceparentData.traceId}.`);\n }\n\n const transactionContext: Partial = {\n ...traceparentData,\n metadata: dropUndefinedKeys({\n dynamicSamplingContext,\n }),\n };\n\n if (!callback) {\n return transactionContext;\n }\n\n return runWithAsyncContext(() => {\n return callback(transactionContext);\n });\n};\n\nfunction createChildSpanOrTransaction(\n // eslint-disable-next-line deprecation/deprecation\n hub: Hub,\n {\n parentSpan,\n spanContext,\n forceTransaction,\n scope,\n }: {\n parentSpan: Span | undefined;\n spanContext: TransactionContext;\n forceTransaction?: boolean;\n scope: Scope;\n },\n): Span | undefined {\n if (!hasTracingEnabled()) {\n return undefined;\n }\n\n const isolationScope = getIsolationScope();\n\n let span: Span | undefined;\n if (parentSpan && !forceTransaction) {\n // eslint-disable-next-line deprecation/deprecation\n span = parentSpan.startChild(spanContext);\n } else if (parentSpan) {\n // If we forced a transaction but have a parent span, make sure to continue from the parent span, not the scope\n const dsc = getDynamicSamplingContextFromSpan(parentSpan);\n const { traceId, spanId: parentSpanId } = parentSpan.spanContext();\n const sampled = spanIsSampled(parentSpan);\n\n // eslint-disable-next-line deprecation/deprecation\n span = hub.startTransaction({\n traceId,\n parentSpanId,\n parentSampled: sampled,\n ...spanContext,\n metadata: {\n dynamicSamplingContext: dsc,\n // eslint-disable-next-line deprecation/deprecation\n ...spanContext.metadata,\n },\n });\n } else {\n const { traceId, dsc, parentSpanId, sampled } = {\n ...isolationScope.getPropagationContext(),\n ...scope.getPropagationContext(),\n };\n\n // eslint-disable-next-line deprecation/deprecation\n span = hub.startTransaction({\n traceId,\n parentSpanId,\n parentSampled: sampled,\n ...spanContext,\n metadata: {\n dynamicSamplingContext: dsc,\n // eslint-disable-next-line deprecation/deprecation\n ...spanContext.metadata,\n },\n });\n }\n\n // We always set this as active span on the scope\n // In the case of this being an inactive span, we ensure to pass a detached scope in here in the first place\n // But by having this here, we can ensure that the lookup through `getCapturedScopesOnSpan` results in the correct scope & span combo\n // eslint-disable-next-line deprecation/deprecation\n scope.setSpan(span);\n\n setCapturedScopesOnSpan(span, scope, isolationScope);\n\n return span;\n}\n\n/**\n * This converts StartSpanOptions to TransactionContext.\n * For the most part (for now) we accept the same options,\n * but some of them need to be transformed.\n *\n * Eventually the StartSpanOptions will be more aligned with OpenTelemetry.\n */\nfunction normalizeContext(context: StartSpanOptions): TransactionContext {\n if (context.startTime) {\n const ctx: TransactionContext & { startTime?: SpanTimeInput } = { ...context };\n ctx.startTimestamp = spanTimeInputToSeconds(context.startTime);\n delete ctx.startTime;\n return ctx;\n }\n\n return context;\n}\n\nconst SCOPE_ON_START_SPAN_FIELD = '_sentryScope';\nconst ISOLATION_SCOPE_ON_START_SPAN_FIELD = '_sentryIsolationScope';\n\ntype SpanWithScopes = Span & {\n [SCOPE_ON_START_SPAN_FIELD]?: Scope;\n [ISOLATION_SCOPE_ON_START_SPAN_FIELD]?: Scope;\n};\n\nfunction setCapturedScopesOnSpan(span: Span | undefined, scope: Scope, isolationScope: Scope): void {\n if (span) {\n addNonEnumerableProperty(span, ISOLATION_SCOPE_ON_START_SPAN_FIELD, isolationScope);\n addNonEnumerableProperty(span, SCOPE_ON_START_SPAN_FIELD, scope);\n }\n}\n\n/**\n * Grabs the scope and isolation scope off a span that were active when the span was started.\n */\nexport function getCapturedScopesOnSpan(span: Span): { scope?: Scope; isolationScope?: Scope } {\n return {\n scope: (span as SpanWithScopes)[SCOPE_ON_START_SPAN_FIELD],\n isolationScope: (span as SpanWithScopes)[ISOLATION_SCOPE_ON_START_SPAN_FIELD],\n };\n}\n", "import type { MeasurementUnit, Span } from '@sentry/types';\nimport type { MetricSummary } from '@sentry/types';\nimport type { Primitive } from '@sentry/types';\nimport { dropUndefinedKeys } from '@sentry/utils';\nimport { getActiveSpan } from '../tracing';\nimport type { MetricType } from './types';\n\n/**\n * key: bucketKey\n * value: [exportKey, MetricSummary]\n */\ntype MetricSummaryStorage = Map;\n\nlet SPAN_METRIC_SUMMARY: WeakMap | undefined;\n\nfunction getMetricStorageForSpan(span: Span): MetricSummaryStorage | undefined {\n return SPAN_METRIC_SUMMARY ? SPAN_METRIC_SUMMARY.get(span) : undefined;\n}\n\n/**\n * Fetches the metric summary if it exists for the passed span\n */\nexport function getMetricSummaryJsonForSpan(span: Span): Record> | undefined {\n const storage = getMetricStorageForSpan(span);\n\n if (!storage) {\n return undefined;\n }\n const output: Record> = {};\n\n for (const [, [exportKey, summary]] of storage) {\n if (!output[exportKey]) {\n output[exportKey] = [];\n }\n\n output[exportKey].push(dropUndefinedKeys(summary));\n }\n\n return output;\n}\n\n/**\n * Updates the metric summary on the currently active span\n */\nexport function updateMetricSummaryOnActiveSpan(\n metricType: MetricType,\n sanitizedName: string,\n value: number,\n unit: MeasurementUnit,\n tags: Record,\n bucketKey: string,\n): void {\n const span = getActiveSpan();\n if (span) {\n const storage = getMetricStorageForSpan(span) || new Map();\n\n const exportKey = `${metricType}:${sanitizedName}@${unit}`;\n const bucketItem = storage.get(bucketKey);\n\n if (bucketItem) {\n const [, summary] = bucketItem;\n storage.set(bucketKey, [\n exportKey,\n {\n min: Math.min(summary.min, value),\n max: Math.max(summary.max, value),\n count: (summary.count += 1),\n sum: (summary.sum += value),\n tags: summary.tags,\n },\n ]);\n } else {\n storage.set(bucketKey, [\n exportKey,\n {\n min: value,\n max: value,\n count: 1,\n sum: value,\n tags,\n },\n ]);\n }\n\n if (!SPAN_METRIC_SUMMARY) {\n SPAN_METRIC_SUMMARY = new WeakMap();\n }\n\n SPAN_METRIC_SUMMARY.set(span, storage);\n }\n}\n", "/**\n * Use this attribute to represent the source of a span.\n * Should be one of: custom, url, route, view, component, task, unknown\n *\n */\nexport const SEMANTIC_ATTRIBUTE_SENTRY_SOURCE = 'sentry.source';\n\n/**\n * Use this attribute to represent the sample rate used for a span.\n */\nexport const SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE = 'sentry.sample_rate';\n\n/**\n * Use this attribute to represent the operation of a span.\n */\nexport const SEMANTIC_ATTRIBUTE_SENTRY_OP = 'sentry.op';\n\n/**\n * Use this attribute to represent the origin of a span.\n */\nexport const SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN = 'sentry.origin';\n\n/**\n * The id of the profile that this span occured in.\n */\nexport const SEMANTIC_ATTRIBUTE_PROFILE_ID = 'profile_id';\n", "/* eslint-disable max-lines */\nimport type {\n Instrumenter,\n Measurements,\n Primitive,\n Span as SpanInterface,\n SpanAttributeValue,\n SpanAttributes,\n SpanContext,\n SpanContextData,\n SpanJSON,\n SpanOrigin,\n SpanTimeInput,\n TraceContext,\n Transaction,\n} from '@sentry/types';\nimport { dropUndefinedKeys, logger, timestampInSeconds, uuid4 } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\nimport { getMetricSummaryJsonForSpan } from '../metrics/metric-summary';\nimport {\n SEMANTIC_ATTRIBUTE_PROFILE_ID,\n SEMANTIC_ATTRIBUTE_SENTRY_OP,\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n} from '../semanticAttributes';\nimport { getRootSpan } from '../utils/getRootSpan';\nimport {\n TRACE_FLAG_NONE,\n TRACE_FLAG_SAMPLED,\n spanTimeInputToSeconds,\n spanToJSON,\n spanToTraceContext,\n spanToTraceHeader,\n} from '../utils/spanUtils';\nimport type { SpanStatusType } from './spanstatus';\nimport { setHttpStatus } from './spanstatus';\n\n/**\n * Keeps track of finished spans for a given transaction\n * @internal\n * @hideconstructor\n * @hidden\n */\nexport class SpanRecorder {\n public spans: Span[];\n\n private readonly _maxlen: number;\n\n public constructor(maxlen: number = 1000) {\n this._maxlen = maxlen;\n this.spans = [];\n }\n\n /**\n * This is just so that we don't run out of memory while recording a lot\n * of spans. At some point we just stop and flush out the start of the\n * trace tree (i.e.the first n spans with the smallest\n * start_timestamp).\n */\n public add(span: Span): void {\n if (this.spans.length > this._maxlen) {\n // eslint-disable-next-line deprecation/deprecation\n span.spanRecorder = undefined;\n } else {\n this.spans.push(span);\n }\n }\n}\n\n/**\n * Span contains all data about a span\n */\nexport class Span implements SpanInterface {\n /**\n * Tags for the span.\n * @deprecated Use `spanToJSON(span).atttributes` instead.\n */\n public tags: { [key: string]: Primitive };\n\n /**\n * Data for the span.\n * @deprecated Use `spanToJSON(span).atttributes` instead.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n public data: { [key: string]: any };\n\n /**\n * List of spans that were finalized\n *\n * @deprecated This property will no longer be public. Span recording will be handled internally.\n */\n public spanRecorder?: SpanRecorder;\n\n /**\n * @inheritDoc\n * @deprecated Use top level `Sentry.getRootSpan()` instead\n */\n public transaction?: Transaction;\n\n /**\n * The instrumenter that created this span.\n *\n * TODO (v8): This can probably be replaced by an `instanceOf` check of the span class.\n * the instrumenter can only be sentry or otel so we can check the span instance\n * to verify which one it is and remove this field entirely.\n *\n * @deprecated This field will be removed.\n */\n public instrumenter: Instrumenter;\n\n protected _traceId: string;\n protected _spanId: string;\n protected _parentSpanId?: string | undefined;\n protected _sampled: boolean | undefined;\n protected _name?: string | undefined;\n protected _attributes: SpanAttributes;\n /** Epoch timestamp in seconds when the span started. */\n protected _startTime: number;\n /** Epoch timestamp in seconds when the span ended. */\n protected _endTime?: number | undefined;\n /** Internal keeper of the status */\n protected _status?: SpanStatusType | string | undefined;\n protected _exclusiveTime?: number;\n\n protected _measurements: Measurements;\n\n private _logMessage?: string;\n\n /**\n * You should never call the constructor manually, always use `Sentry.startTransaction()`\n * or call `startChild()` on an existing span.\n * @internal\n * @hideconstructor\n * @hidden\n */\n public constructor(spanContext: SpanContext = {}) {\n this._traceId = spanContext.traceId || uuid4();\n this._spanId = spanContext.spanId || uuid4().substring(16);\n this._startTime = spanContext.startTimestamp || timestampInSeconds();\n // eslint-disable-next-line deprecation/deprecation\n this.tags = spanContext.tags ? { ...spanContext.tags } : {};\n // eslint-disable-next-line deprecation/deprecation\n this.data = spanContext.data ? { ...spanContext.data } : {};\n // eslint-disable-next-line deprecation/deprecation\n this.instrumenter = spanContext.instrumenter || 'sentry';\n\n this._attributes = {};\n this.setAttributes({\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: spanContext.origin || 'manual',\n [SEMANTIC_ATTRIBUTE_SENTRY_OP]: spanContext.op,\n ...spanContext.attributes,\n });\n\n // eslint-disable-next-line deprecation/deprecation\n this._name = spanContext.name || spanContext.description;\n\n if (spanContext.parentSpanId) {\n this._parentSpanId = spanContext.parentSpanId;\n }\n // We want to include booleans as well here\n if ('sampled' in spanContext) {\n this._sampled = spanContext.sampled;\n }\n if (spanContext.status) {\n this._status = spanContext.status;\n }\n if (spanContext.endTimestamp) {\n this._endTime = spanContext.endTimestamp;\n }\n if (spanContext.exclusiveTime !== undefined) {\n this._exclusiveTime = spanContext.exclusiveTime;\n }\n this._measurements = spanContext.measurements ? { ...spanContext.measurements } : {};\n }\n\n // This rule conflicts with another eslint rule :(\n /* eslint-disable @typescript-eslint/member-ordering */\n\n /**\n * An alias for `description` of the Span.\n * @deprecated Use `spanToJSON(span).description` instead.\n */\n public get name(): string {\n return this._name || '';\n }\n\n /**\n * Update the name of the span.\n * @deprecated Use `spanToJSON(span).description` instead.\n */\n public set name(name: string) {\n this.updateName(name);\n }\n\n /**\n * Get the description of the Span.\n * @deprecated Use `spanToJSON(span).description` instead.\n */\n public get description(): string | undefined {\n return this._name;\n }\n\n /**\n * Get the description of the Span.\n * @deprecated Use `spanToJSON(span).description` instead.\n */\n public set description(description: string | undefined) {\n this._name = description;\n }\n\n /**\n * The ID of the trace.\n * @deprecated Use `spanContext().traceId` instead.\n */\n public get traceId(): string {\n return this._traceId;\n }\n\n /**\n * The ID of the trace.\n * @deprecated You cannot update the traceId of a span after span creation.\n */\n public set traceId(traceId: string) {\n this._traceId = traceId;\n }\n\n /**\n * The ID of the span.\n * @deprecated Use `spanContext().spanId` instead.\n */\n public get spanId(): string {\n return this._spanId;\n }\n\n /**\n * The ID of the span.\n * @deprecated You cannot update the spanId of a span after span creation.\n */\n public set spanId(spanId: string) {\n this._spanId = spanId;\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `startSpan` functions instead.\n */\n public set parentSpanId(string) {\n this._parentSpanId = string;\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `spanToJSON(span).parent_span_id` instead.\n */\n public get parentSpanId(): string | undefined {\n return this._parentSpanId;\n }\n\n /**\n * Was this span chosen to be sent as part of the sample?\n * @deprecated Use `isRecording()` instead.\n */\n public get sampled(): boolean | undefined {\n return this._sampled;\n }\n\n /**\n * Was this span chosen to be sent as part of the sample?\n * @deprecated You cannot update the sampling decision of a span after span creation.\n */\n public set sampled(sampled: boolean | undefined) {\n this._sampled = sampled;\n }\n\n /**\n * Attributes for the span.\n * @deprecated Use `spanToJSON(span).atttributes` instead.\n */\n public get attributes(): SpanAttributes {\n return this._attributes;\n }\n\n /**\n * Attributes for the span.\n * @deprecated Use `setAttributes()` instead.\n */\n public set attributes(attributes: SpanAttributes) {\n this._attributes = attributes;\n }\n\n /**\n * Timestamp in seconds (epoch time) indicating when the span started.\n * @deprecated Use `spanToJSON()` instead.\n */\n public get startTimestamp(): number {\n return this._startTime;\n }\n\n /**\n * Timestamp in seconds (epoch time) indicating when the span started.\n * @deprecated In v8, you will not be able to update the span start time after creation.\n */\n public set startTimestamp(startTime: number) {\n this._startTime = startTime;\n }\n\n /**\n * Timestamp in seconds when the span ended.\n * @deprecated Use `spanToJSON()` instead.\n */\n public get endTimestamp(): number | undefined {\n return this._endTime;\n }\n\n /**\n * Timestamp in seconds when the span ended.\n * @deprecated Set the end time via `span.end()` instead.\n */\n public set endTimestamp(endTime: number | undefined) {\n this._endTime = endTime;\n }\n\n /**\n * The status of the span.\n *\n * @deprecated Use `spanToJSON().status` instead to get the status.\n */\n public get status(): SpanStatusType | string | undefined {\n return this._status;\n }\n\n /**\n * The status of the span.\n *\n * @deprecated Use `.setStatus()` instead to set or update the status.\n */\n public set status(status: SpanStatusType | string | undefined) {\n this._status = status;\n }\n\n /**\n * Operation of the span\n *\n * @deprecated Use `spanToJSON().op` to read the op instead.\n */\n public get op(): string | undefined {\n return this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_OP] as string | undefined;\n }\n\n /**\n * Operation of the span\n *\n * @deprecated Use `startSpan()` functions to set or `span.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_OP, 'op')\n * to update the span instead.\n */\n public set op(op: string | undefined) {\n this.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_OP, op);\n }\n\n /**\n * The origin of the span, giving context about what created the span.\n *\n * @deprecated Use `spanToJSON().origin` to read the origin instead.\n */\n public get origin(): SpanOrigin | undefined {\n return this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN] as SpanOrigin | undefined;\n }\n\n /**\n * The origin of the span, giving context about what created the span.\n *\n * @deprecated Use `startSpan()` functions to set the origin instead.\n */\n public set origin(origin: SpanOrigin | undefined) {\n this.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, origin);\n }\n\n /* eslint-enable @typescript-eslint/member-ordering */\n\n /** @inheritdoc */\n public spanContext(): SpanContextData {\n const { _spanId: spanId, _traceId: traceId, _sampled: sampled } = this;\n return {\n spanId,\n traceId,\n traceFlags: sampled ? TRACE_FLAG_SAMPLED : TRACE_FLAG_NONE,\n };\n }\n\n /**\n * Creates a new `Span` while setting the current `Span.id` as `parentSpanId`.\n * Also the `sampled` decision will be inherited.\n *\n * @deprecated Use `startSpan()`, `startSpanManual()` or `startInactiveSpan()` instead.\n */\n public startChild(\n spanContext?: Pick>,\n ): SpanInterface {\n const childSpan = new Span({\n ...spanContext,\n parentSpanId: this._spanId,\n sampled: this._sampled,\n traceId: this._traceId,\n });\n\n // eslint-disable-next-line deprecation/deprecation\n childSpan.spanRecorder = this.spanRecorder;\n // eslint-disable-next-line deprecation/deprecation\n if (childSpan.spanRecorder) {\n // eslint-disable-next-line deprecation/deprecation\n childSpan.spanRecorder.add(childSpan);\n }\n\n const rootSpan = getRootSpan(this);\n // TODO: still set span.transaction here until we have a more permanent solution\n // Probably similarly to the weakmap we hold in node-experimental\n // eslint-disable-next-line deprecation/deprecation\n childSpan.transaction = rootSpan as Transaction;\n\n if (DEBUG_BUILD && rootSpan) {\n const opStr = (spanContext && spanContext.op) || '< unknown op >';\n const nameStr = spanToJSON(childSpan).description || '< unknown name >';\n const idStr = rootSpan.spanContext().spanId;\n\n const logMessage = `[Tracing] Starting '${opStr}' span on transaction '${nameStr}' (${idStr}).`;\n logger.log(logMessage);\n this._logMessage = logMessage;\n }\n\n return childSpan;\n }\n\n /**\n * Sets the tag attribute on the current span.\n *\n * Can also be used to unset a tag, by passing `undefined`.\n *\n * @param key Tag key\n * @param value Tag value\n * @deprecated Use `setAttribute()` instead.\n */\n public setTag(key: string, value: Primitive): this {\n // eslint-disable-next-line deprecation/deprecation\n this.tags = { ...this.tags, [key]: value };\n return this;\n }\n\n /**\n * Sets the data attribute on the current span\n * @param key Data key\n * @param value Data value\n * @deprecated Use `setAttribute()` instead.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n public setData(key: string, value: any): this {\n // eslint-disable-next-line deprecation/deprecation\n this.data = { ...this.data, [key]: value };\n return this;\n }\n\n /** @inheritdoc */\n public setAttribute(key: string, value: SpanAttributeValue | undefined): void {\n if (value === undefined) {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete this._attributes[key];\n } else {\n this._attributes[key] = value;\n }\n }\n\n /** @inheritdoc */\n public setAttributes(attributes: SpanAttributes): void {\n Object.keys(attributes).forEach(key => this.setAttribute(key, attributes[key]));\n }\n\n /**\n * @inheritDoc\n */\n public setStatus(value: SpanStatusType): this {\n this._status = value;\n return this;\n }\n\n /**\n * @inheritDoc\n * @deprecated Use top-level `setHttpStatus()` instead.\n */\n public setHttpStatus(httpStatus: number): this {\n setHttpStatus(this, httpStatus);\n return this;\n }\n\n /**\n * @inheritdoc\n *\n * @deprecated Use `.updateName()` instead.\n */\n public setName(name: string): void {\n this.updateName(name);\n }\n\n /**\n * @inheritDoc\n */\n public updateName(name: string): this {\n this._name = name;\n return this;\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `spanToJSON(span).status === 'ok'` instead.\n */\n public isSuccess(): boolean {\n return this._status === 'ok';\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `.end()` instead.\n */\n public finish(endTimestamp?: number): void {\n return this.end(endTimestamp);\n }\n\n /** @inheritdoc */\n public end(endTimestamp?: SpanTimeInput): void {\n // If already ended, skip\n if (this._endTime) {\n return;\n }\n const rootSpan = getRootSpan(this);\n if (\n DEBUG_BUILD &&\n // Don't call this for transactions\n rootSpan &&\n rootSpan.spanContext().spanId !== this._spanId\n ) {\n const logMessage = this._logMessage;\n if (logMessage) {\n logger.log((logMessage as string).replace('Starting', 'Finishing'));\n }\n }\n\n this._endTime = spanTimeInputToSeconds(endTimestamp);\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `spanToTraceHeader()` instead.\n */\n public toTraceparent(): string {\n return spanToTraceHeader(this);\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `spanToJSON()` or access the fields directly instead.\n */\n public toContext(): SpanContext {\n return dropUndefinedKeys({\n data: this._getData(),\n description: this._name,\n endTimestamp: this._endTime,\n // eslint-disable-next-line deprecation/deprecation\n op: this.op,\n parentSpanId: this._parentSpanId,\n sampled: this._sampled,\n spanId: this._spanId,\n startTimestamp: this._startTime,\n status: this._status,\n // eslint-disable-next-line deprecation/deprecation\n tags: this.tags,\n traceId: this._traceId,\n });\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Update the fields directly instead.\n */\n public updateWithContext(spanContext: SpanContext): this {\n // eslint-disable-next-line deprecation/deprecation\n this.data = spanContext.data || {};\n // eslint-disable-next-line deprecation/deprecation\n this._name = spanContext.name || spanContext.description;\n this._endTime = spanContext.endTimestamp;\n // eslint-disable-next-line deprecation/deprecation\n this.op = spanContext.op;\n this._parentSpanId = spanContext.parentSpanId;\n this._sampled = spanContext.sampled;\n this._spanId = spanContext.spanId || this._spanId;\n this._startTime = spanContext.startTimestamp || this._startTime;\n this._status = spanContext.status;\n // eslint-disable-next-line deprecation/deprecation\n this.tags = spanContext.tags || {};\n this._traceId = spanContext.traceId || this._traceId;\n\n return this;\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `spanToTraceContext()` util function instead.\n */\n public getTraceContext(): TraceContext {\n return spanToTraceContext(this);\n }\n\n /**\n * Get JSON representation of this span.\n *\n * @hidden\n * @internal This method is purely for internal purposes and should not be used outside\n * of SDK code. If you need to get a JSON representation of a span,\n * use `spanToJSON(span)` instead.\n */\n public getSpanJSON(): SpanJSON {\n return dropUndefinedKeys({\n data: this._getData(),\n description: this._name,\n op: this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_OP] as string | undefined,\n parent_span_id: this._parentSpanId,\n span_id: this._spanId,\n start_timestamp: this._startTime,\n status: this._status,\n // eslint-disable-next-line deprecation/deprecation\n tags: Object.keys(this.tags).length > 0 ? this.tags : undefined,\n timestamp: this._endTime,\n trace_id: this._traceId,\n origin: this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN] as SpanOrigin | undefined,\n _metrics_summary: getMetricSummaryJsonForSpan(this),\n profile_id: this._attributes[SEMANTIC_ATTRIBUTE_PROFILE_ID] as string | undefined,\n exclusive_time: this._exclusiveTime,\n measurements: Object.keys(this._measurements).length > 0 ? this._measurements : undefined,\n });\n }\n\n /** @inheritdoc */\n public isRecording(): boolean {\n return !this._endTime && !!this._sampled;\n }\n\n /**\n * Convert the object to JSON.\n * @deprecated Use `spanToJSON(span)` instead.\n */\n public toJSON(): SpanJSON {\n return this.getSpanJSON();\n }\n\n /**\n * Get the merged data for this span.\n * For now, this combines `data` and `attributes` together,\n * until eventually we can ingest `attributes` directly.\n */\n private _getData():\n | {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [key: string]: any;\n }\n | undefined {\n // eslint-disable-next-line deprecation/deprecation\n const { data, _attributes: attributes } = this;\n\n const hasData = Object.keys(data).length > 0;\n const hasAttributes = Object.keys(attributes).length > 0;\n\n if (!hasData && !hasAttributes) {\n return undefined;\n }\n\n if (hasData && hasAttributes) {\n return {\n ...data,\n ...attributes,\n };\n }\n\n return hasData ? data : attributes;\n }\n}\n", "import type {\n Context,\n Contexts,\n DynamicSamplingContext,\n MeasurementUnit,\n SpanTimeInput,\n Transaction as TransactionInterface,\n TransactionContext,\n TransactionEvent,\n TransactionMetadata,\n} from '@sentry/types';\nimport { dropUndefinedKeys, logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { Hub } from '../hub';\nimport { getCurrentHub } from '../hub';\nimport { getMetricSummaryJsonForSpan } from '../metrics/metric-summary';\nimport { SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE } from '../semanticAttributes';\nimport { spanTimeInputToSeconds, spanToJSON, spanToTraceContext } from '../utils/spanUtils';\nimport { getDynamicSamplingContextFromSpan } from './dynamicSamplingContext';\nimport { Span as SpanClass, SpanRecorder } from './span';\nimport { getCapturedScopesOnSpan } from './trace';\n\n/** JSDoc */\nexport class Transaction extends SpanClass implements TransactionInterface {\n /**\n * The reference to the current hub.\n */\n // eslint-disable-next-line deprecation/deprecation\n public _hub: Hub;\n\n protected _name: string;\n\n private _contexts: Contexts;\n\n private _trimEnd?: boolean | undefined;\n\n // DO NOT yet remove this property, it is used in a hack for v7 backwards compatibility.\n private _frozenDynamicSamplingContext: Readonly> | undefined;\n\n private _metadata: Partial;\n\n /**\n * This constructor should never be called manually. Those instrumenting tracing should use\n * `Sentry.startTransaction()`, and internal methods should use `hub.startTransaction()`.\n * @internal\n * @hideconstructor\n * @hidden\n *\n * @deprecated Transactions will be removed in v8. Use spans instead.\n */\n // eslint-disable-next-line deprecation/deprecation\n public constructor(transactionContext: TransactionContext, hub?: Hub) {\n super(transactionContext);\n this._contexts = {};\n\n // eslint-disable-next-line deprecation/deprecation\n this._hub = hub || getCurrentHub();\n\n this._name = transactionContext.name || '';\n\n this._metadata = {\n // eslint-disable-next-line deprecation/deprecation\n ...transactionContext.metadata,\n };\n\n this._trimEnd = transactionContext.trimEnd;\n\n // this is because transactions are also spans, and spans have a transaction pointer\n // TODO (v8): Replace this with another way to set the root span\n // eslint-disable-next-line deprecation/deprecation\n this.transaction = this;\n\n // If Dynamic Sampling Context is provided during the creation of the transaction, we freeze it as it usually means\n // there is incoming Dynamic Sampling Context. (Either through an incoming request, a baggage meta-tag, or other means)\n const incomingDynamicSamplingContext = this._metadata.dynamicSamplingContext;\n if (incomingDynamicSamplingContext) {\n // We shallow copy this in case anything writes to the original reference of the passed in `dynamicSamplingContext`\n this._frozenDynamicSamplingContext = { ...incomingDynamicSamplingContext };\n }\n }\n\n // This sadly conflicts with the getter/setter ordering :(\n /* eslint-disable @typescript-eslint/member-ordering */\n\n /**\n * Getter for `name` property.\n * @deprecated Use `spanToJSON(span).description` instead.\n */\n public get name(): string {\n return this._name;\n }\n\n /**\n * Setter for `name` property, which also sets `source` as custom.\n * @deprecated Use `updateName()` and `setMetadata()` instead.\n */\n public set name(newName: string) {\n // eslint-disable-next-line deprecation/deprecation\n this.setName(newName);\n }\n\n /**\n * Get the metadata for this transaction.\n * @deprecated Use `spanGetMetadata(transaction)` instead.\n */\n public get metadata(): TransactionMetadata {\n // We merge attributes in for backwards compatibility\n return {\n // Defaults\n // eslint-disable-next-line deprecation/deprecation\n source: 'custom',\n spanMetadata: {},\n\n // Legacy metadata\n ...this._metadata,\n\n // From attributes\n ...(this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE] && {\n source: this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE] as TransactionMetadata['source'],\n }),\n ...(this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE] && {\n sampleRate: this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE] as TransactionMetadata['sampleRate'],\n }),\n };\n }\n\n /**\n * Update the metadata for this transaction.\n * @deprecated Use `spanGetMetadata(transaction)` instead.\n */\n public set metadata(metadata: TransactionMetadata) {\n this._metadata = metadata;\n }\n\n /* eslint-enable @typescript-eslint/member-ordering */\n\n /**\n * Setter for `name` property, which also sets `source` on the metadata.\n *\n * @deprecated Use `.updateName()` and `.setAttribute()` instead.\n */\n public setName(name: string, source: TransactionMetadata['source'] = 'custom'): void {\n this._name = name;\n this.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, source);\n }\n\n /** @inheritdoc */\n public updateName(name: string): this {\n this._name = name;\n return this;\n }\n\n /**\n * Attaches SpanRecorder to the span itself\n * @param maxlen maximum number of spans that can be recorded\n */\n public initSpanRecorder(maxlen: number = 1000): void {\n // eslint-disable-next-line deprecation/deprecation\n if (!this.spanRecorder) {\n // eslint-disable-next-line deprecation/deprecation\n this.spanRecorder = new SpanRecorder(maxlen);\n }\n // eslint-disable-next-line deprecation/deprecation\n this.spanRecorder.add(this);\n }\n\n /**\n * Set the context of a transaction event.\n * @deprecated Use either `.setAttribute()`, or set the context on the scope before creating the transaction.\n */\n public setContext(key: string, context: Context | null): void {\n if (context === null) {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete this._contexts[key];\n } else {\n this._contexts[key] = context;\n }\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use top-level `setMeasurement()` instead.\n */\n public setMeasurement(name: string, value: number, unit: MeasurementUnit = ''): void {\n this._measurements[name] = { value, unit };\n }\n\n /**\n * Store metadata on this transaction.\n * @deprecated Use attributes or store data on the scope instead.\n */\n public setMetadata(newMetadata: Partial): void {\n this._metadata = { ...this._metadata, ...newMetadata };\n }\n\n /**\n * @inheritDoc\n */\n public end(endTimestamp?: SpanTimeInput): string | undefined {\n const timestampInS = spanTimeInputToSeconds(endTimestamp);\n const transaction = this._finishTransaction(timestampInS);\n if (!transaction) {\n return undefined;\n }\n // eslint-disable-next-line deprecation/deprecation\n return this._hub.captureEvent(transaction);\n }\n\n /**\n * @inheritDoc\n */\n public toContext(): TransactionContext {\n // eslint-disable-next-line deprecation/deprecation\n const spanContext = super.toContext();\n\n return dropUndefinedKeys({\n ...spanContext,\n name: this._name,\n trimEnd: this._trimEnd,\n });\n }\n\n /**\n * @inheritDoc\n */\n public updateWithContext(transactionContext: TransactionContext): this {\n // eslint-disable-next-line deprecation/deprecation\n super.updateWithContext(transactionContext);\n\n this._name = transactionContext.name || '';\n this._trimEnd = transactionContext.trimEnd;\n\n return this;\n }\n\n /**\n * @inheritdoc\n *\n * @experimental\n *\n * @deprecated Use top-level `getDynamicSamplingContextFromSpan` instead.\n */\n public getDynamicSamplingContext(): Readonly> {\n return getDynamicSamplingContextFromSpan(this);\n }\n\n /**\n * Override the current hub with a new one.\n * Used if you want another hub to finish the transaction.\n *\n * @internal\n */\n // eslint-disable-next-line deprecation/deprecation\n public setHub(hub: Hub): void {\n this._hub = hub;\n }\n\n /**\n * Get the profile id of the transaction.\n */\n public getProfileId(): string | undefined {\n if (this._contexts !== undefined && this._contexts['profile'] !== undefined) {\n return this._contexts['profile'].profile_id as string;\n }\n return undefined;\n }\n\n /**\n * Finish the transaction & prepare the event to send to Sentry.\n */\n protected _finishTransaction(endTimestamp?: number): TransactionEvent | undefined {\n // This transaction is already finished, so we should not flush it again.\n if (this._endTime !== undefined) {\n return undefined;\n }\n\n if (!this._name) {\n DEBUG_BUILD && logger.warn('Transaction has no name, falling back to ``.');\n this._name = '';\n }\n\n // just sets the end timestamp\n super.end(endTimestamp);\n\n // eslint-disable-next-line deprecation/deprecation\n const client = this._hub.getClient();\n if (client && client.emit) {\n client.emit('finishTransaction', this);\n }\n\n if (this._sampled !== true) {\n // At this point if `sampled !== true` we want to discard the transaction.\n DEBUG_BUILD && logger.log('[Tracing] Discarding transaction because its trace was not chosen to be sampled.');\n\n if (client) {\n client.recordDroppedEvent('sample_rate', 'transaction');\n }\n\n return undefined;\n }\n\n // eslint-disable-next-line deprecation/deprecation\n const finishedSpans = this.spanRecorder\n ? // eslint-disable-next-line deprecation/deprecation\n this.spanRecorder.spans.filter(span => span !== this && spanToJSON(span).timestamp)\n : [];\n\n if (this._trimEnd && finishedSpans.length > 0) {\n const endTimes = finishedSpans.map(span => spanToJSON(span).timestamp).filter(Boolean) as number[];\n this._endTime = endTimes.reduce((prev, current) => {\n return prev > current ? prev : current;\n });\n }\n\n const { scope: capturedSpanScope, isolationScope: capturedSpanIsolationScope } = getCapturedScopesOnSpan(this);\n\n // eslint-disable-next-line deprecation/deprecation\n const { metadata } = this;\n // eslint-disable-next-line deprecation/deprecation\n const { source } = metadata;\n\n const transaction: TransactionEvent = {\n contexts: {\n ...this._contexts,\n // We don't want to override trace context\n trace: spanToTraceContext(this),\n },\n // TODO: Pass spans serialized via `spanToJSON()` here instead in v8.\n spans: finishedSpans,\n start_timestamp: this._startTime,\n // eslint-disable-next-line deprecation/deprecation\n tags: this.tags,\n timestamp: this._endTime,\n transaction: this._name,\n type: 'transaction',\n sdkProcessingMetadata: {\n ...metadata,\n capturedSpanScope,\n capturedSpanIsolationScope,\n ...dropUndefinedKeys({\n dynamicSamplingContext: getDynamicSamplingContextFromSpan(this),\n }),\n },\n _metrics_summary: getMetricSummaryJsonForSpan(this),\n ...(source && {\n transaction_info: {\n source,\n },\n }),\n };\n\n const hasMeasurements = Object.keys(this._measurements).length > 0;\n\n if (hasMeasurements) {\n DEBUG_BUILD &&\n logger.log(\n '[Measurements] Adding measurements to transaction',\n JSON.stringify(this._measurements, undefined, 2),\n );\n transaction.measurements = this._measurements;\n }\n\n // eslint-disable-next-line deprecation/deprecation\n DEBUG_BUILD && logger.log(`[Tracing] Finishing ${this.op} transaction: ${this._name}.`);\n\n return transaction;\n }\n}\n", "/* eslint-disable max-lines */\nimport type { SpanTimeInput, TransactionContext } from '@sentry/types';\nimport { logger, timestampInSeconds } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { Hub } from '../hub';\nimport { spanTimeInputToSeconds, spanToJSON } from '../utils/spanUtils';\nimport type { Span } from './span';\nimport { SpanRecorder } from './span';\nimport { Transaction } from './transaction';\n\nexport const TRACING_DEFAULTS = {\n idleTimeout: 1000,\n finalTimeout: 30000,\n heartbeatInterval: 5000,\n};\n\nconst FINISH_REASON_TAG = 'finishReason';\n\nconst IDLE_TRANSACTION_FINISH_REASONS = [\n 'heartbeatFailed',\n 'idleTimeout',\n 'documentHidden',\n 'finalTimeout',\n 'externalFinish',\n 'cancelled',\n];\n\n/**\n * @inheritDoc\n */\nexport class IdleTransactionSpanRecorder extends SpanRecorder {\n public constructor(\n private readonly _pushActivity: (id: string) => void,\n private readonly _popActivity: (id: string) => void,\n public transactionSpanId: string,\n maxlen?: number,\n ) {\n super(maxlen);\n }\n\n /**\n * @inheritDoc\n */\n public add(span: Span): void {\n // We should make sure we do not push and pop activities for\n // the transaction that this span recorder belongs to.\n if (span.spanContext().spanId !== this.transactionSpanId) {\n // We patch span.end() to pop an activity after setting an endTimestamp.\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const originalEnd = span.end;\n span.end = (...rest: unknown[]) => {\n this._popActivity(span.spanContext().spanId);\n return originalEnd.apply(span, rest);\n };\n\n // We should only push new activities if the span does not have an end timestamp.\n if (spanToJSON(span).timestamp === undefined) {\n this._pushActivity(span.spanContext().spanId);\n }\n }\n\n super.add(span);\n }\n}\n\nexport type BeforeFinishCallback = (transactionSpan: IdleTransaction, endTimestamp: number) => void;\n\n/**\n * An IdleTransaction is a transaction that automatically finishes. It does this by tracking child spans as activities.\n * You can have multiple IdleTransactions active, but if the `onScope` option is specified, the idle transaction will\n * put itself on the scope on creation.\n */\nexport class IdleTransaction extends Transaction {\n // Activities store a list of active spans\n public activities: Record;\n // Track state of activities in previous heartbeat\n private _prevHeartbeatString: string | undefined;\n\n // Amount of times heartbeat has counted. Will cause transaction to finish after 3 beats.\n private _heartbeatCounter: number;\n\n // We should not use heartbeat if we finished a transaction\n private _finished: boolean;\n\n // Idle timeout was canceled and we should finish the transaction with the last span end.\n private _idleTimeoutCanceledPermanently: boolean;\n\n private readonly _beforeFinishCallbacks: BeforeFinishCallback[];\n\n /**\n * Timer that tracks Transaction idleTimeout\n */\n private _idleTimeoutID: ReturnType | undefined;\n\n private _finishReason: (typeof IDLE_TRANSACTION_FINISH_REASONS)[number];\n\n private _autoFinishAllowed: boolean;\n\n /**\n * @deprecated Transactions will be removed in v8. Use spans instead.\n */\n public constructor(\n transactionContext: TransactionContext,\n // eslint-disable-next-line deprecation/deprecation\n private readonly _idleHub: Hub,\n /**\n * The time to wait in ms until the idle transaction will be finished. This timer is started each time\n * there are no active spans on this transaction.\n */\n private readonly _idleTimeout: number = TRACING_DEFAULTS.idleTimeout,\n /**\n * The final value in ms that a transaction cannot exceed\n */\n private readonly _finalTimeout: number = TRACING_DEFAULTS.finalTimeout,\n private readonly _heartbeatInterval: number = TRACING_DEFAULTS.heartbeatInterval,\n // Whether or not the transaction should put itself on the scope when it starts and pop itself off when it ends\n private readonly _onScope: boolean = false,\n /**\n * When set to `true`, will disable the idle timeout (`_idleTimeout` option) and heartbeat mechanisms (`_heartbeatInterval`\n * option) until the `sendAutoFinishSignal()` method is called. The final timeout mechanism (`_finalTimeout` option)\n * will not be affected by this option, meaning the transaction will definitely be finished when the final timeout is\n * reached, no matter what this option is configured to.\n *\n * Defaults to `false`.\n */\n delayAutoFinishUntilSignal: boolean = false,\n ) {\n super(transactionContext, _idleHub);\n\n this.activities = {};\n this._heartbeatCounter = 0;\n this._finished = false;\n this._idleTimeoutCanceledPermanently = false;\n this._beforeFinishCallbacks = [];\n this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[4];\n this._autoFinishAllowed = !delayAutoFinishUntilSignal;\n\n if (_onScope) {\n // We set the transaction here on the scope so error events pick up the trace\n // context and attach it to the error.\n DEBUG_BUILD && logger.log(`Setting idle transaction on scope. Span ID: ${this.spanContext().spanId}`);\n // eslint-disable-next-line deprecation/deprecation\n _idleHub.getScope().setSpan(this);\n }\n\n if (!delayAutoFinishUntilSignal) {\n this._restartIdleTimeout();\n }\n\n setTimeout(() => {\n if (!this._finished) {\n this.setStatus('deadline_exceeded');\n this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[3];\n this.end();\n }\n }, this._finalTimeout);\n }\n\n /** {@inheritDoc} */\n public end(endTimestamp?: SpanTimeInput): string | undefined {\n const endTimestampInS = spanTimeInputToSeconds(endTimestamp);\n\n this._finished = true;\n this.activities = {};\n\n // eslint-disable-next-line deprecation/deprecation\n if (this.op === 'ui.action.click') {\n this.setAttribute(FINISH_REASON_TAG, this._finishReason);\n }\n\n // eslint-disable-next-line deprecation/deprecation\n if (this.spanRecorder) {\n DEBUG_BUILD &&\n // eslint-disable-next-line deprecation/deprecation\n logger.log('[Tracing] finishing IdleTransaction', new Date(endTimestampInS * 1000).toISOString(), this.op);\n\n for (const callback of this._beforeFinishCallbacks) {\n callback(this, endTimestampInS);\n }\n\n // eslint-disable-next-line deprecation/deprecation\n this.spanRecorder.spans = this.spanRecorder.spans.filter((span: Span) => {\n // If we are dealing with the transaction itself, we just return it\n if (span.spanContext().spanId === this.spanContext().spanId) {\n return true;\n }\n\n // We cancel all pending spans with status \"cancelled\" to indicate the idle transaction was finished early\n if (!spanToJSON(span).timestamp) {\n span.setStatus('cancelled');\n span.end(endTimestampInS);\n DEBUG_BUILD &&\n logger.log('[Tracing] cancelling span since transaction ended early', JSON.stringify(span, undefined, 2));\n }\n\n const { start_timestamp: startTime, timestamp: endTime } = spanToJSON(span);\n const spanStartedBeforeTransactionFinish = startTime && startTime < endTimestampInS;\n\n // Add a delta with idle timeout so that we prevent false positives\n const timeoutWithMarginOfError = (this._finalTimeout + this._idleTimeout) / 1000;\n const spanEndedBeforeFinalTimeout = endTime && startTime && endTime - startTime < timeoutWithMarginOfError;\n\n if (DEBUG_BUILD) {\n const stringifiedSpan = JSON.stringify(span, undefined, 2);\n if (!spanStartedBeforeTransactionFinish) {\n logger.log('[Tracing] discarding Span since it happened after Transaction was finished', stringifiedSpan);\n } else if (!spanEndedBeforeFinalTimeout) {\n logger.log('[Tracing] discarding Span since it finished after Transaction final timeout', stringifiedSpan);\n }\n }\n\n return spanStartedBeforeTransactionFinish && spanEndedBeforeFinalTimeout;\n });\n\n DEBUG_BUILD && logger.log('[Tracing] flushing IdleTransaction');\n } else {\n DEBUG_BUILD && logger.log('[Tracing] No active IdleTransaction');\n }\n\n // if `this._onScope` is `true`, the transaction put itself on the scope when it started\n if (this._onScope) {\n // eslint-disable-next-line deprecation/deprecation\n const scope = this._idleHub.getScope();\n // eslint-disable-next-line deprecation/deprecation\n if (scope.getTransaction() === this) {\n // eslint-disable-next-line deprecation/deprecation\n scope.setSpan(undefined);\n }\n }\n\n return super.end(endTimestamp);\n }\n\n /**\n * Register a callback function that gets executed before the transaction finishes.\n * Useful for cleanup or if you want to add any additional spans based on current context.\n *\n * This is exposed because users have no other way of running something before an idle transaction\n * finishes.\n */\n public registerBeforeFinishCallback(callback: BeforeFinishCallback): void {\n this._beforeFinishCallbacks.push(callback);\n }\n\n /**\n * @inheritDoc\n */\n public initSpanRecorder(maxlen?: number): void {\n // eslint-disable-next-line deprecation/deprecation\n if (!this.spanRecorder) {\n const pushActivity = (id: string): void => {\n if (this._finished) {\n return;\n }\n this._pushActivity(id);\n };\n const popActivity = (id: string): void => {\n if (this._finished) {\n return;\n }\n this._popActivity(id);\n };\n\n // eslint-disable-next-line deprecation/deprecation\n this.spanRecorder = new IdleTransactionSpanRecorder(pushActivity, popActivity, this.spanContext().spanId, maxlen);\n\n // Start heartbeat so that transactions do not run forever.\n DEBUG_BUILD && logger.log('Starting heartbeat');\n this._pingHeartbeat();\n }\n // eslint-disable-next-line deprecation/deprecation\n this.spanRecorder.add(this);\n }\n\n /**\n * Cancels the existing idle timeout, if there is one.\n * @param restartOnChildSpanChange Default is `true`.\n * If set to false the transaction will end\n * with the last child span.\n */\n public cancelIdleTimeout(\n endTimestamp?: Parameters[0],\n {\n restartOnChildSpanChange,\n }: {\n restartOnChildSpanChange?: boolean;\n } = {\n restartOnChildSpanChange: true,\n },\n ): void {\n this._idleTimeoutCanceledPermanently = restartOnChildSpanChange === false;\n if (this._idleTimeoutID) {\n clearTimeout(this._idleTimeoutID);\n this._idleTimeoutID = undefined;\n\n if (Object.keys(this.activities).length === 0 && this._idleTimeoutCanceledPermanently) {\n this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[5];\n this.end(endTimestamp);\n }\n }\n }\n\n /**\n * Temporary method used to externally set the transaction's `finishReason`\n *\n * ** WARNING**\n * This is for the purpose of experimentation only and will be removed in the near future, do not use!\n *\n * @internal\n *\n */\n public setFinishReason(reason: string): void {\n this._finishReason = reason;\n }\n\n /**\n * Permits the IdleTransaction to automatically end itself via the idle timeout and heartbeat mechanisms when the `delayAutoFinishUntilSignal` option was set to `true`.\n */\n public sendAutoFinishSignal(): void {\n if (!this._autoFinishAllowed) {\n DEBUG_BUILD && logger.log('[Tracing] Received finish signal for idle transaction.');\n this._restartIdleTimeout();\n this._autoFinishAllowed = true;\n }\n }\n\n /**\n * Restarts idle timeout, if there is no running idle timeout it will start one.\n */\n private _restartIdleTimeout(endTimestamp?: Parameters[0]): void {\n this.cancelIdleTimeout();\n this._idleTimeoutID = setTimeout(() => {\n if (!this._finished && Object.keys(this.activities).length === 0) {\n this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[1];\n this.end(endTimestamp);\n }\n }, this._idleTimeout);\n }\n\n /**\n * Start tracking a specific activity.\n * @param spanId The span id that represents the activity\n */\n private _pushActivity(spanId: string): void {\n this.cancelIdleTimeout(undefined, { restartOnChildSpanChange: !this._idleTimeoutCanceledPermanently });\n DEBUG_BUILD && logger.log(`[Tracing] pushActivity: ${spanId}`);\n this.activities[spanId] = true;\n DEBUG_BUILD && logger.log('[Tracing] new activities count', Object.keys(this.activities).length);\n }\n\n /**\n * Remove an activity from usage\n * @param spanId The span id that represents the activity\n */\n private _popActivity(spanId: string): void {\n if (this.activities[spanId]) {\n DEBUG_BUILD && logger.log(`[Tracing] popActivity ${spanId}`);\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete this.activities[spanId];\n DEBUG_BUILD && logger.log('[Tracing] new activities count', Object.keys(this.activities).length);\n }\n\n if (Object.keys(this.activities).length === 0) {\n const endTimestamp = timestampInSeconds();\n if (this._idleTimeoutCanceledPermanently) {\n if (this._autoFinishAllowed) {\n this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[5];\n this.end(endTimestamp);\n }\n } else {\n // We need to add the timeout here to have the real endtimestamp of the transaction\n // Remember timestampInSeconds is in seconds, timeout is in ms\n this._restartIdleTimeout(endTimestamp + this._idleTimeout / 1000);\n }\n }\n }\n\n /**\n * Checks when entries of this.activities are not changing for 3 beats.\n * If this occurs we finish the transaction.\n */\n private _beat(): void {\n // We should not be running heartbeat if the idle transaction is finished.\n if (this._finished) {\n return;\n }\n\n const heartbeatString = Object.keys(this.activities).join('');\n\n if (heartbeatString === this._prevHeartbeatString) {\n this._heartbeatCounter++;\n } else {\n this._heartbeatCounter = 1;\n }\n\n this._prevHeartbeatString = heartbeatString;\n\n if (this._heartbeatCounter >= 3) {\n if (this._autoFinishAllowed) {\n DEBUG_BUILD && logger.log('[Tracing] Transaction finished because of no change for 3 heart beats');\n this.setStatus('deadline_exceeded');\n this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[0];\n this.end();\n }\n } else {\n this._pingHeartbeat();\n }\n }\n\n /**\n * Pings the heartbeat\n */\n private _pingHeartbeat(): void {\n DEBUG_BUILD && logger.log(`pinging Heartbeat -> current counter: ${this._heartbeatCounter}`);\n setTimeout(() => {\n this._beat();\n }, this._heartbeatInterval);\n }\n}\n", "import type { Options, SamplingContext } from '@sentry/types';\nimport { isNaN, logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\nimport { SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE } from '../semanticAttributes';\nimport { hasTracingEnabled } from '../utils/hasTracingEnabled';\nimport { spanToJSON } from '../utils/spanUtils';\nimport type { Transaction } from './transaction';\n\n/**\n * Makes a sampling decision for the given transaction and stores it on the transaction.\n *\n * Called every time a transaction is created. Only transactions which emerge with a `sampled` value of `true` will be\n * sent to Sentry.\n *\n * This method muttes the given `transaction` and will set the `sampled` value on it.\n * It returns the same transaction, for convenience.\n */\nexport function sampleTransaction(\n transaction: T,\n options: Pick,\n samplingContext: SamplingContext,\n): T {\n // nothing to do if tracing is not enabled\n if (!hasTracingEnabled(options)) {\n // eslint-disable-next-line deprecation/deprecation\n transaction.sampled = false;\n return transaction;\n }\n\n // if the user has forced a sampling decision by passing a `sampled` value in their transaction context, go with that\n // eslint-disable-next-line deprecation/deprecation\n if (transaction.sampled !== undefined) {\n // eslint-disable-next-line deprecation/deprecation\n transaction.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, Number(transaction.sampled));\n return transaction;\n }\n\n // we would have bailed already if neither `tracesSampler` nor `tracesSampleRate` nor `enableTracing` were defined, so one of these should\n // work; prefer the hook if so\n let sampleRate;\n if (typeof options.tracesSampler === 'function') {\n sampleRate = options.tracesSampler(samplingContext);\n transaction.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, Number(sampleRate));\n } else if (samplingContext.parentSampled !== undefined) {\n sampleRate = samplingContext.parentSampled;\n } else if (typeof options.tracesSampleRate !== 'undefined') {\n sampleRate = options.tracesSampleRate;\n transaction.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, Number(sampleRate));\n } else {\n // When `enableTracing === true`, we use a sample rate of 100%\n sampleRate = 1;\n transaction.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, sampleRate);\n }\n\n // Since this is coming from the user (or from a function provided by the user), who knows what we might get. (The\n // only valid values are booleans or numbers between 0 and 1.)\n if (!isValidSampleRate(sampleRate)) {\n DEBUG_BUILD && logger.warn('[Tracing] Discarding transaction because of invalid sample rate.');\n // eslint-disable-next-line deprecation/deprecation\n transaction.sampled = false;\n return transaction;\n }\n\n // if the function returned 0 (or false), or if `tracesSampleRate` is 0, it's a sign the transaction should be dropped\n if (!sampleRate) {\n DEBUG_BUILD &&\n logger.log(\n `[Tracing] Discarding transaction because ${\n typeof options.tracesSampler === 'function'\n ? 'tracesSampler returned 0 or false'\n : 'a negative sampling decision was inherited or tracesSampleRate is set to 0'\n }`,\n );\n // eslint-disable-next-line deprecation/deprecation\n transaction.sampled = false;\n return transaction;\n }\n\n // Now we roll the dice. Math.random is inclusive of 0, but not of 1, so strict < is safe here. In case sampleRate is\n // a boolean, the < comparison will cause it to be automatically cast to 1 if it's true and 0 if it's false.\n // eslint-disable-next-line deprecation/deprecation\n transaction.sampled = Math.random() < (sampleRate as number | boolean);\n\n // if we're not going to keep it, we're done\n // eslint-disable-next-line deprecation/deprecation\n if (!transaction.sampled) {\n DEBUG_BUILD &&\n logger.log(\n `[Tracing] Discarding transaction because it's not included in the random sample (sampling rate = ${Number(\n sampleRate,\n )})`,\n );\n return transaction;\n }\n\n DEBUG_BUILD &&\n // eslint-disable-next-line deprecation/deprecation\n logger.log(`[Tracing] starting ${transaction.op} transaction - ${spanToJSON(transaction).description}`);\n return transaction;\n}\n\n/**\n * Checks the given sample rate to make sure it is valid type and value (a boolean, or a number between 0 and 1).\n */\nexport function isValidSampleRate(rate: unknown): boolean {\n // we need to check NaN explicitly because it's of type 'number' and therefore wouldn't get caught by this typecheck\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n if (isNaN(rate) || !(typeof rate === 'number' || typeof rate === 'boolean')) {\n DEBUG_BUILD &&\n logger.warn(\n `[Tracing] Given sample rate is invalid. Sample rate must be a boolean or a number between 0 and 1. Got ${JSON.stringify(\n rate,\n )} of type ${JSON.stringify(typeof rate)}.`,\n );\n return false;\n }\n\n // in case sampleRate is a boolean, it will get automatically cast to 1 if it's true and 0 if it's false\n if (rate < 0 || rate > 1) {\n DEBUG_BUILD &&\n logger.warn(`[Tracing] Given sample rate is invalid. Sample rate must be between 0 and 1. Got ${rate}.`);\n return false;\n }\n return true;\n}\n", "import type { ClientOptions, CustomSamplingContext, TransactionContext } from '@sentry/types';\nimport { logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { Hub } from '../hub';\nimport { getMainCarrier } from '../hub';\nimport { spanToTraceHeader } from '../utils/spanUtils';\nimport { registerErrorInstrumentation } from './errors';\nimport { IdleTransaction } from './idletransaction';\nimport { sampleTransaction } from './sampling';\nimport { Transaction } from './transaction';\n\n/** Returns all trace headers that are currently on the top scope. */\n// eslint-disable-next-line deprecation/deprecation\nfunction traceHeaders(this: Hub): { [key: string]: string } {\n // eslint-disable-next-line deprecation/deprecation\n const scope = this.getScope();\n // eslint-disable-next-line deprecation/deprecation\n const span = scope.getSpan();\n\n return span\n ? {\n 'sentry-trace': spanToTraceHeader(span),\n }\n : {};\n}\n\n/**\n * Creates a new transaction and adds a sampling decision if it doesn't yet have one.\n *\n * The Hub.startTransaction method delegates to this method to do its work, passing the Hub instance in as `this`, as if\n * it had been called on the hub directly. Exists as a separate function so that it can be injected into the class as an\n * \"extension method.\"\n *\n * @param this: The Hub starting the transaction\n * @param transactionContext: Data used to configure the transaction\n * @param CustomSamplingContext: Optional data to be provided to the `tracesSampler` function (if any)\n *\n * @returns The new transaction\n *\n * @see {@link Hub.startTransaction}\n */\nfunction _startTransaction(\n // eslint-disable-next-line deprecation/deprecation\n this: Hub,\n transactionContext: TransactionContext,\n customSamplingContext?: CustomSamplingContext,\n): Transaction {\n // eslint-disable-next-line deprecation/deprecation\n const client = this.getClient();\n const options: Partial = (client && client.getOptions()) || {};\n\n const configInstrumenter = options.instrumenter || 'sentry';\n const transactionInstrumenter = transactionContext.instrumenter || 'sentry';\n\n if (configInstrumenter !== transactionInstrumenter) {\n DEBUG_BUILD &&\n logger.error(\n `A transaction was started with instrumenter=\\`${transactionInstrumenter}\\`, but the SDK is configured with the \\`${configInstrumenter}\\` instrumenter.\nThe transaction will not be sampled. Please use the ${configInstrumenter} instrumentation to start transactions.`,\n );\n\n // eslint-disable-next-line deprecation/deprecation\n transactionContext.sampled = false;\n }\n\n // eslint-disable-next-line deprecation/deprecation\n let transaction = new Transaction(transactionContext, this);\n transaction = sampleTransaction(transaction, options, {\n name: transactionContext.name,\n parentSampled: transactionContext.parentSampled,\n transactionContext,\n attributes: {\n // eslint-disable-next-line deprecation/deprecation\n ...transactionContext.data,\n ...transactionContext.attributes,\n },\n ...customSamplingContext,\n });\n if (transaction.isRecording()) {\n transaction.initSpanRecorder(options._experiments && (options._experiments.maxSpans as number));\n }\n if (client && client.emit) {\n client.emit('startTransaction', transaction);\n }\n return transaction;\n}\n\n/**\n * Create new idle transaction.\n */\nexport function startIdleTransaction(\n // eslint-disable-next-line deprecation/deprecation\n hub: Hub,\n transactionContext: TransactionContext,\n idleTimeout: number,\n finalTimeout: number,\n onScope?: boolean,\n customSamplingContext?: CustomSamplingContext,\n heartbeatInterval?: number,\n delayAutoFinishUntilSignal: boolean = false,\n): IdleTransaction {\n // eslint-disable-next-line deprecation/deprecation\n const client = hub.getClient();\n const options: Partial = (client && client.getOptions()) || {};\n\n // eslint-disable-next-line deprecation/deprecation\n let transaction = new IdleTransaction(\n transactionContext,\n hub,\n idleTimeout,\n finalTimeout,\n heartbeatInterval,\n onScope,\n delayAutoFinishUntilSignal,\n );\n transaction = sampleTransaction(transaction, options, {\n name: transactionContext.name,\n parentSampled: transactionContext.parentSampled,\n transactionContext,\n attributes: {\n // eslint-disable-next-line deprecation/deprecation\n ...transactionContext.data,\n ...transactionContext.attributes,\n },\n ...customSamplingContext,\n });\n if (transaction.isRecording()) {\n transaction.initSpanRecorder(options._experiments && (options._experiments.maxSpans as number));\n }\n if (client && client.emit) {\n client.emit('startTransaction', transaction);\n }\n return transaction;\n}\n\n/**\n * Adds tracing extensions to the global hub.\n */\nexport function addTracingExtensions(): void {\n const carrier = getMainCarrier();\n if (!carrier.__SENTRY__) {\n return;\n }\n carrier.__SENTRY__.extensions = carrier.__SENTRY__.extensions || {};\n if (!carrier.__SENTRY__.extensions.startTransaction) {\n carrier.__SENTRY__.extensions.startTransaction = _startTransaction;\n }\n if (!carrier.__SENTRY__.extensions.traceHeaders) {\n carrier.__SENTRY__.extensions.traceHeaders = traceHeaders;\n }\n\n registerErrorInstrumentation();\n}\n", "import type { MeasurementUnit } from '@sentry/types';\n\nimport { getActiveTransaction } from './utils';\n\n/**\n * Adds a measurement to the current active transaction.\n */\nexport function setMeasurement(name: string, value: number, unit: MeasurementUnit): void {\n // eslint-disable-next-line deprecation/deprecation\n const transaction = getActiveTransaction();\n if (transaction) {\n // eslint-disable-next-line deprecation/deprecation\n transaction.setMeasurement(name, value, unit);\n }\n}\n", "import type {\n DsnComponents,\n Event,\n EventEnvelope,\n EventItem,\n SdkInfo,\n SdkMetadata,\n Session,\n SessionAggregates,\n SessionEnvelope,\n SessionItem,\n} from '@sentry/types';\nimport {\n createEnvelope,\n createEventEnvelopeHeaders,\n dsnToString,\n getSdkMetadataForEnvelopeHeader,\n} from '@sentry/utils';\n\n/**\n * Apply SdkInfo (name, version, packages, integrations) to the corresponding event key.\n * Merge with existing data if any.\n **/\nfunction enhanceEventWithSdkInfo(event: Event, sdkInfo?: SdkInfo): Event {\n if (!sdkInfo) {\n return event;\n }\n event.sdk = event.sdk || {};\n event.sdk.name = event.sdk.name || sdkInfo.name;\n event.sdk.version = event.sdk.version || sdkInfo.version;\n event.sdk.integrations = [...(event.sdk.integrations || []), ...(sdkInfo.integrations || [])];\n event.sdk.packages = [...(event.sdk.packages || []), ...(sdkInfo.packages || [])];\n return event;\n}\n\n/** Creates an envelope from a Session */\nexport function createSessionEnvelope(\n session: Session | SessionAggregates,\n dsn?: DsnComponents,\n metadata?: SdkMetadata,\n tunnel?: string,\n): SessionEnvelope {\n const sdkInfo = getSdkMetadataForEnvelopeHeader(metadata);\n const envelopeHeaders = {\n sent_at: new Date().toISOString(),\n ...(sdkInfo && { sdk: sdkInfo }),\n ...(!!tunnel && dsn && { dsn: dsnToString(dsn) }),\n };\n\n const envelopeItem: SessionItem =\n 'aggregates' in session ? [{ type: 'sessions' }, session] : [{ type: 'session' }, session.toJSON()];\n\n return createEnvelope(envelopeHeaders, [envelopeItem]);\n}\n\n/**\n * Create an Envelope from an event.\n */\nexport function createEventEnvelope(\n event: Event,\n dsn?: DsnComponents,\n metadata?: SdkMetadata,\n tunnel?: string,\n): EventEnvelope {\n const sdkInfo = getSdkMetadataForEnvelopeHeader(metadata);\n\n /*\n Note: Due to TS, event.type may be `replay_event`, theoretically.\n In practice, we never call `createEventEnvelope` with `replay_event` type,\n and we'd have to adjut a looot of types to make this work properly.\n We want to avoid casting this around, as that could lead to bugs (e.g. when we add another type)\n So the safe choice is to really guard against the replay_event type here.\n */\n const eventType = event.type && event.type !== 'replay_event' ? event.type : 'event';\n\n enhanceEventWithSdkInfo(event, metadata && metadata.sdk);\n\n const envelopeHeaders = createEventEnvelopeHeaders(event, sdkInfo, tunnel, dsn);\n\n // Prevent this data (which, if it exists, was used in earlier steps in the processing pipeline) from being sent to\n // sentry. (Note: Our use of this property comes and goes with whatever we might be debugging, whatever hacks we may\n // have temporarily added, etc. Even if we don't happen to be using it at some point in the future, let's not get rid\n // of this `delete`, lest we miss putting it back in the next time the property is in use.)\n delete event.sdkProcessingMetadata;\n\n const eventItem: EventItem = [{ type: eventType }, event];\n return createEnvelope(envelopeHeaders, [eventItem]);\n}\n", "import type {\n AggregationCounts,\n Client,\n RequestSessionStatus,\n SessionAggregates,\n SessionFlusherLike,\n} from '@sentry/types';\nimport { dropUndefinedKeys } from '@sentry/utils';\nimport { getCurrentScope } from './exports';\n\ntype ReleaseHealthAttributes = {\n environment?: string;\n release: string;\n};\n\n/**\n * @inheritdoc\n */\nexport class SessionFlusher implements SessionFlusherLike {\n public readonly flushTimeout: number;\n private _pendingAggregates: Record;\n private _sessionAttrs: ReleaseHealthAttributes;\n // Cast to any so that it can use Node.js timeout\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private _intervalId: any;\n private _isEnabled: boolean;\n private _client: Client;\n\n public constructor(client: Client, attrs: ReleaseHealthAttributes) {\n this._client = client;\n this.flushTimeout = 60;\n this._pendingAggregates = {};\n this._isEnabled = true;\n\n // Call to setInterval, so that flush is called every 60 seconds.\n this._intervalId = setInterval(() => this.flush(), this.flushTimeout * 1000);\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n if (this._intervalId.unref) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n this._intervalId.unref();\n }\n this._sessionAttrs = attrs;\n }\n\n /** Checks if `pendingAggregates` has entries, and if it does flushes them by calling `sendSession` */\n public flush(): void {\n const sessionAggregates = this.getSessionAggregates();\n if (sessionAggregates.aggregates.length === 0) {\n return;\n }\n this._pendingAggregates = {};\n this._client.sendSession(sessionAggregates);\n }\n\n /** Massages the entries in `pendingAggregates` and returns aggregated sessions */\n public getSessionAggregates(): SessionAggregates {\n const aggregates: AggregationCounts[] = Object.keys(this._pendingAggregates).map((key: string) => {\n return this._pendingAggregates[parseInt(key)];\n });\n\n const sessionAggregates: SessionAggregates = {\n attrs: this._sessionAttrs,\n aggregates,\n };\n return dropUndefinedKeys(sessionAggregates);\n }\n\n /** JSDoc */\n public close(): void {\n clearInterval(this._intervalId);\n this._isEnabled = false;\n this.flush();\n }\n\n /**\n * Wrapper function for _incrementSessionStatusCount that checks if the instance of SessionFlusher is enabled then\n * fetches the session status of the request from `Scope.getRequestSession().status` on the scope and passes them to\n * `_incrementSessionStatusCount` along with the start date\n */\n public incrementSessionStatusCount(): void {\n if (!this._isEnabled) {\n return;\n }\n const scope = getCurrentScope();\n const requestSession = scope.getRequestSession();\n\n if (requestSession && requestSession.status) {\n this._incrementSessionStatusCount(requestSession.status, new Date());\n // This is not entirely necessarily but is added as a safe guard to indicate the bounds of a request and so in\n // case captureRequestSession is called more than once to prevent double count\n scope.setRequestSession(undefined);\n /* eslint-enable @typescript-eslint/no-unsafe-member-access */\n }\n }\n\n /**\n * Increments status bucket in pendingAggregates buffer (internal state) corresponding to status of\n * the session received\n */\n private _incrementSessionStatusCount(status: RequestSessionStatus, date: Date): number {\n // Truncate minutes and seconds on Session Started attribute to have one minute bucket keys\n const sessionStartedTrunc = new Date(date).setSeconds(0, 0);\n this._pendingAggregates[sessionStartedTrunc] = this._pendingAggregates[sessionStartedTrunc] || {};\n\n // corresponds to aggregated sessions in one specific minute bucket\n // for example, {\"started\":\"2021-03-16T08:00:00.000Z\",\"exited\":4, \"errored\": 1}\n const aggregationCounts: AggregationCounts = this._pendingAggregates[sessionStartedTrunc];\n if (!aggregationCounts.started) {\n aggregationCounts.started = new Date(sessionStartedTrunc).toISOString();\n }\n\n switch (status) {\n case 'errored':\n aggregationCounts.errored = (aggregationCounts.errored || 0) + 1;\n return aggregationCounts.errored;\n case 'ok':\n aggregationCounts.exited = (aggregationCounts.exited || 0) + 1;\n return aggregationCounts.exited;\n default:\n aggregationCounts.crashed = (aggregationCounts.crashed || 0) + 1;\n return aggregationCounts.crashed;\n }\n }\n}\n", "import type { ClientOptions, DsnComponents, DsnLike, SdkInfo } from '@sentry/types';\nimport { dsnToString, makeDsn, urlEncode } from '@sentry/utils';\n\nconst SENTRY_API_VERSION = '7';\n\n/** Returns the prefix to construct Sentry ingestion API endpoints. */\nfunction getBaseApiEndpoint(dsn: DsnComponents): string {\n const protocol = dsn.protocol ? `${dsn.protocol}:` : '';\n const port = dsn.port ? `:${dsn.port}` : '';\n return `${protocol}//${dsn.host}${port}${dsn.path ? `/${dsn.path}` : ''}/api/`;\n}\n\n/** Returns the ingest API endpoint for target. */\nfunction _getIngestEndpoint(dsn: DsnComponents): string {\n return `${getBaseApiEndpoint(dsn)}${dsn.projectId}/envelope/`;\n}\n\n/** Returns a URL-encoded string with auth config suitable for a query string. */\nfunction _encodedAuth(dsn: DsnComponents, sdkInfo: SdkInfo | undefined): string {\n return urlEncode({\n // We send only the minimum set of required information. See\n // https://github.com/getsentry/sentry-javascript/issues/2572.\n sentry_key: dsn.publicKey,\n sentry_version: SENTRY_API_VERSION,\n ...(sdkInfo && { sentry_client: `${sdkInfo.name}/${sdkInfo.version}` }),\n });\n}\n\n/**\n * Returns the envelope endpoint URL with auth in the query string.\n *\n * Sending auth as part of the query string and not as custom HTTP headers avoids CORS preflight requests.\n */\nexport function getEnvelopeEndpointWithUrlEncodedAuth(\n dsn: DsnComponents,\n // TODO (v8): Remove `tunnelOrOptions` in favor of `options`, and use the substitute code below\n // options: ClientOptions = {} as ClientOptions,\n tunnelOrOptions: string | ClientOptions = {} as ClientOptions,\n): string {\n // TODO (v8): Use this code instead\n // const { tunnel, _metadata = {} } = options;\n // return tunnel ? tunnel : `${_getIngestEndpoint(dsn)}?${_encodedAuth(dsn, _metadata.sdk)}`;\n\n const tunnel = typeof tunnelOrOptions === 'string' ? tunnelOrOptions : tunnelOrOptions.tunnel;\n const sdkInfo =\n typeof tunnelOrOptions === 'string' || !tunnelOrOptions._metadata ? undefined : tunnelOrOptions._metadata.sdk;\n\n return tunnel ? tunnel : `${_getIngestEndpoint(dsn)}?${_encodedAuth(dsn, sdkInfo)}`;\n}\n\n/** Returns the url to the report dialog endpoint. */\nexport function getReportDialogEndpoint(\n dsnLike: DsnLike,\n dialogOptions: {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [key: string]: any;\n user?: { name?: string; email?: string };\n },\n): string {\n const dsn = makeDsn(dsnLike);\n if (!dsn) {\n return '';\n }\n\n const endpoint = `${getBaseApiEndpoint(dsn)}embed/error-page/`;\n\n let encodedOptions = `dsn=${dsnToString(dsn)}`;\n for (const key in dialogOptions) {\n if (key === 'dsn') {\n continue;\n }\n\n if (key === 'onClose') {\n continue;\n }\n\n if (key === 'user') {\n const user = dialogOptions.user;\n if (!user) {\n continue;\n }\n if (user.name) {\n encodedOptions += `&name=${encodeURIComponent(user.name)}`;\n }\n if (user.email) {\n encodedOptions += `&email=${encodeURIComponent(user.email)}`;\n }\n } else {\n encodedOptions += `&${encodeURIComponent(key)}=${encodeURIComponent(dialogOptions[key] as string)}`;\n }\n }\n\n return `${endpoint}?${encodedOptions}`;\n}\n", "import type {\n Client,\n Event,\n EventHint,\n Integration,\n IntegrationClass,\n IntegrationFn,\n IntegrationFnResult,\n Options,\n} from '@sentry/types';\nimport { arrayify, logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from './debug-build';\nimport { addGlobalEventProcessor } from './eventProcessors';\nimport { getClient } from './exports';\nimport { getCurrentHub } from './hub';\n\ndeclare module '@sentry/types' {\n interface Integration {\n isDefaultInstance?: boolean;\n }\n}\n\nexport const installedIntegrations: string[] = [];\n\n/** Map of integrations assigned to a client */\nexport type IntegrationIndex = {\n [key: string]: Integration;\n};\n\n/**\n * Remove duplicates from the given array, preferring the last instance of any duplicate. Not guaranteed to\n * preseve the order of integrations in the array.\n *\n * @private\n */\nfunction filterDuplicates(integrations: Integration[]): Integration[] {\n const integrationsByName: { [key: string]: Integration } = {};\n\n integrations.forEach(currentInstance => {\n const { name } = currentInstance;\n\n const existingInstance = integrationsByName[name];\n\n // We want integrations later in the array to overwrite earlier ones of the same type, except that we never want a\n // default instance to overwrite an existing user instance\n if (existingInstance && !existingInstance.isDefaultInstance && currentInstance.isDefaultInstance) {\n return;\n }\n\n integrationsByName[name] = currentInstance;\n });\n\n return Object.keys(integrationsByName).map(k => integrationsByName[k]);\n}\n\n/** Gets integrations to install */\nexport function getIntegrationsToSetup(options: Pick): Integration[] {\n const defaultIntegrations = options.defaultIntegrations || [];\n const userIntegrations = options.integrations;\n\n // We flag default instances, so that later we can tell them apart from any user-created instances of the same class\n defaultIntegrations.forEach(integration => {\n integration.isDefaultInstance = true;\n });\n\n let integrations: Integration[];\n\n if (Array.isArray(userIntegrations)) {\n integrations = [...defaultIntegrations, ...userIntegrations];\n } else if (typeof userIntegrations === 'function') {\n integrations = arrayify(userIntegrations(defaultIntegrations));\n } else {\n integrations = defaultIntegrations;\n }\n\n const finalIntegrations = filterDuplicates(integrations);\n\n // The `Debug` integration prints copies of the `event` and `hint` which will be passed to `beforeSend` or\n // `beforeSendTransaction`. It therefore has to run after all other integrations, so that the changes of all event\n // processors will be reflected in the printed values. For lack of a more elegant way to guarantee that, we therefore\n // locate it and, assuming it exists, pop it out of its current spot and shove it onto the end of the array.\n const debugIndex = findIndex(finalIntegrations, integration => integration.name === 'Debug');\n if (debugIndex !== -1) {\n const [debugInstance] = finalIntegrations.splice(debugIndex, 1);\n finalIntegrations.push(debugInstance);\n }\n\n return finalIntegrations;\n}\n\n/**\n * Given a list of integration instances this installs them all. When `withDefaults` is set to `true` then all default\n * integrations are added unless they were already provided before.\n * @param integrations array of integration instances\n * @param withDefault should enable default integrations\n */\nexport function setupIntegrations(client: Client, integrations: Integration[]): IntegrationIndex {\n const integrationIndex: IntegrationIndex = {};\n\n integrations.forEach(integration => {\n // guard against empty provided integrations\n if (integration) {\n setupIntegration(client, integration, integrationIndex);\n }\n });\n\n return integrationIndex;\n}\n\n/**\n * Execute the `afterAllSetup` hooks of the given integrations.\n */\nexport function afterSetupIntegrations(client: Client, integrations: Integration[]): void {\n for (const integration of integrations) {\n // guard against empty provided integrations\n if (integration && integration.afterAllSetup) {\n integration.afterAllSetup(client);\n }\n }\n}\n\n/** Setup a single integration. */\nexport function setupIntegration(client: Client, integration: Integration, integrationIndex: IntegrationIndex): void {\n if (integrationIndex[integration.name]) {\n DEBUG_BUILD && logger.log(`Integration skipped because it was already installed: ${integration.name}`);\n return;\n }\n integrationIndex[integration.name] = integration;\n\n // `setupOnce` is only called the first time\n if (installedIntegrations.indexOf(integration.name) === -1) {\n // eslint-disable-next-line deprecation/deprecation\n integration.setupOnce(addGlobalEventProcessor, getCurrentHub);\n installedIntegrations.push(integration.name);\n }\n\n // `setup` is run for each client\n if (integration.setup && typeof integration.setup === 'function') {\n integration.setup(client);\n }\n\n if (client.on && typeof integration.preprocessEvent === 'function') {\n const callback = integration.preprocessEvent.bind(integration) as typeof integration.preprocessEvent;\n client.on('preprocessEvent', (event, hint) => callback(event, hint, client));\n }\n\n if (client.addEventProcessor && typeof integration.processEvent === 'function') {\n const callback = integration.processEvent.bind(integration) as typeof integration.processEvent;\n\n const processor = Object.assign((event: Event, hint: EventHint) => callback(event, hint, client), {\n id: integration.name,\n });\n\n client.addEventProcessor(processor);\n }\n\n DEBUG_BUILD && logger.log(`Integration installed: ${integration.name}`);\n}\n\n/** Add an integration to the current hub's client. */\nexport function addIntegration(integration: Integration): void {\n const client = getClient();\n\n if (!client || !client.addIntegration) {\n DEBUG_BUILD && logger.warn(`Cannot add integration \"${integration.name}\" because no SDK Client is available.`);\n return;\n }\n\n client.addIntegration(integration);\n}\n\n// Polyfill for Array.findIndex(), which is not supported in ES5\nfunction findIndex(arr: T[], callback: (item: T) => boolean): number {\n for (let i = 0; i < arr.length; i++) {\n if (callback(arr[i]) === true) {\n return i;\n }\n }\n\n return -1;\n}\n\n/**\n * Convert a new integration function to the legacy class syntax.\n * In v8, we can remove this and instead export the integration functions directly.\n *\n * @deprecated This will be removed in v8!\n */\nexport function convertIntegrationFnToClass(\n name: string,\n fn: Fn,\n): IntegrationClass {\n return Object.assign(\n function ConvertedIntegration(...args: Parameters): Integration {\n return fn(...args);\n },\n { id: name },\n ) as unknown as IntegrationClass;\n}\n\n/**\n * Define an integration function that can be used to create an integration instance.\n * Note that this by design hides the implementation details of the integration, as they are considered internal.\n */\nexport function defineIntegration(fn: Fn): (...args: Parameters) => IntegrationFnResult {\n return fn;\n}\n", "import type { MeasurementUnit, MetricBucketItem, Primitive } from '@sentry/types';\nimport { dropUndefinedKeys } from '@sentry/utils';\nimport type { MetricType } from './types';\n\n/**\n * Generate bucket key from metric properties.\n */\nexport function getBucketKey(\n metricType: MetricType,\n name: string,\n unit: MeasurementUnit,\n tags: Record,\n): string {\n const stringifiedTags = Object.entries(dropUndefinedKeys(tags)).sort((a, b) => a[0].localeCompare(b[0]));\n return `${metricType}${name}${unit}${stringifiedTags}`;\n}\n\n/* eslint-disable no-bitwise */\n/**\n * Simple hash function for strings.\n */\nexport function simpleHash(s: string): number {\n let rv = 0;\n for (let i = 0; i < s.length; i++) {\n const c = s.charCodeAt(i);\n rv = (rv << 5) - rv + c;\n rv &= rv;\n }\n return rv >>> 0;\n}\n/* eslint-enable no-bitwise */\n\n/**\n * Serialize metrics buckets into a string based on statsd format.\n *\n * Example of format:\n * metric.name@second:1:1.2|d|#a:value,b:anothervalue|T12345677\n * Segments:\n * name: metric.name\n * unit: second\n * value: [1, 1.2]\n * type of metric: d (distribution)\n * tags: { a: value, b: anothervalue }\n * timestamp: 12345677\n */\nexport function serializeMetricBuckets(metricBucketItems: MetricBucketItem[]): string {\n let out = '';\n for (const item of metricBucketItems) {\n const tagEntries = Object.entries(item.tags);\n const maybeTags = tagEntries.length > 0 ? `|#${tagEntries.map(([key, value]) => `${key}:${value}`).join(',')}` : '';\n out += `${item.name}@${item.unit}:${item.metric}|${item.metricType}${maybeTags}|T${item.timestamp}\\n`;\n }\n return out;\n}\n\n/** Sanitizes units */\nexport function sanitizeUnit(unit: string): string {\n return unit.replace(/[^\\w]+/gi, '_');\n}\n\n/** Sanitizes metric keys */\nexport function sanitizeMetricKey(key: string): string {\n return key.replace(/[^\\w\\-.]+/gi, '_');\n}\n\nfunction sanitizeTagKey(key: string): string {\n return key.replace(/[^\\w\\-./]+/gi, '');\n}\n\nconst tagValueReplacements: [string, string][] = [\n ['\\n', '\\\\n'],\n ['\\r', '\\\\r'],\n ['\\t', '\\\\t'],\n ['\\\\', '\\\\\\\\'],\n ['|', '\\\\u{7c}'],\n [',', '\\\\u{2c}'],\n];\n\nfunction getCharOrReplacement(input: string): string {\n for (const [search, replacement] of tagValueReplacements) {\n if (input === search) {\n return replacement;\n }\n }\n\n return input;\n}\n\nfunction sanitizeTagValue(value: string): string {\n return [...value].reduce((acc, char) => acc + getCharOrReplacement(char), '');\n}\n\n/**\n * Sanitizes tags.\n */\nexport function sanitizeTags(unsanitizedTags: Record): Record {\n const tags: Record = {};\n for (const key in unsanitizedTags) {\n if (Object.prototype.hasOwnProperty.call(unsanitizedTags, key)) {\n const sanitizedKey = sanitizeTagKey(key);\n tags[sanitizedKey] = sanitizeTagValue(String(unsanitizedTags[key]));\n }\n }\n return tags;\n}\n", "import type { DsnComponents, MetricBucketItem, SdkMetadata, StatsdEnvelope, StatsdItem } from '@sentry/types';\nimport { createEnvelope, dsnToString } from '@sentry/utils';\nimport { serializeMetricBuckets } from './utils';\n\n/**\n * Create envelope from a metric aggregate.\n */\nexport function createMetricEnvelope(\n metricBucketItems: Array,\n dsn?: DsnComponents,\n metadata?: SdkMetadata,\n tunnel?: string,\n): StatsdEnvelope {\n const headers: StatsdEnvelope[0] = {\n sent_at: new Date().toISOString(),\n };\n\n if (metadata && metadata.sdk) {\n headers.sdk = {\n name: metadata.sdk.name,\n version: metadata.sdk.version,\n };\n }\n\n if (!!tunnel && dsn) {\n headers.dsn = dsnToString(dsn);\n }\n\n const item = createMetricEnvelopeItem(metricBucketItems);\n return createEnvelope(headers, [item]);\n}\n\nfunction createMetricEnvelopeItem(metricBucketItems: MetricBucketItem[]): StatsdItem {\n const payload = serializeMetricBuckets(metricBucketItems);\n const metricHeaders: StatsdItem[0] = {\n type: 'statsd',\n length: payload.length,\n };\n return [metricHeaders, payload];\n}\n", "/* eslint-disable max-lines */\nimport type {\n Breadcrumb,\n BreadcrumbHint,\n Client,\n ClientOptions,\n DataCategory,\n DsnComponents,\n DynamicSamplingContext,\n Envelope,\n ErrorEvent,\n Event,\n EventDropReason,\n EventHint,\n EventProcessor,\n FeedbackEvent,\n Integration,\n IntegrationClass,\n MetricBucketItem,\n MetricsAggregator,\n Outcome,\n ParameterizedString,\n SdkMetadata,\n Session,\n SessionAggregates,\n Severity,\n SeverityLevel,\n StartSpanOptions,\n Transaction,\n TransactionEvent,\n Transport,\n TransportMakeRequestResponse,\n} from '@sentry/types';\nimport {\n SentryError,\n SyncPromise,\n addItemToEnvelope,\n checkOrSetAlreadyCaught,\n createAttachmentEnvelopeItem,\n isParameterizedString,\n isPlainObject,\n isPrimitive,\n isThenable,\n logger,\n makeDsn,\n rejectedSyncPromise,\n resolvedSyncPromise,\n} from '@sentry/utils';\n\nimport { getEnvelopeEndpointWithUrlEncodedAuth } from './api';\nimport { DEBUG_BUILD } from './debug-build';\nimport { createEventEnvelope, createSessionEnvelope } from './envelope';\nimport { getClient } from './exports';\nimport { getIsolationScope } from './hub';\nimport type { IntegrationIndex } from './integration';\nimport { afterSetupIntegrations } from './integration';\nimport { setupIntegration, setupIntegrations } from './integration';\nimport { createMetricEnvelope } from './metrics/envelope';\nimport type { Scope } from './scope';\nimport { updateSession } from './session';\nimport { getDynamicSamplingContextFromClient } from './tracing/dynamicSamplingContext';\nimport { prepareEvent } from './utils/prepareEvent';\n\nconst ALREADY_SEEN_ERROR = \"Not capturing exception because it's already been captured.\";\n\n/**\n * Base implementation for all JavaScript SDK clients.\n *\n * Call the constructor with the corresponding options\n * specific to the client subclass. To access these options later, use\n * {@link Client.getOptions}.\n *\n * If a Dsn is specified in the options, it will be parsed and stored. Use\n * {@link Client.getDsn} to retrieve the Dsn at any moment. In case the Dsn is\n * invalid, the constructor will throw a {@link SentryException}. Note that\n * without a valid Dsn, the SDK will not send any events to Sentry.\n *\n * Before sending an event, it is passed through\n * {@link BaseClient._prepareEvent} to add SDK information and scope data\n * (breadcrumbs and context). To add more custom information, override this\n * method and extend the resulting prepared event.\n *\n * To issue automatically created events (e.g. via instrumentation), use\n * {@link Client.captureEvent}. It will prepare the event and pass it through\n * the callback lifecycle. To issue auto-breadcrumbs, use\n * {@link Client.addBreadcrumb}.\n *\n * @example\n * class NodeClient extends BaseClient {\n * public constructor(options: NodeOptions) {\n * super(options);\n * }\n *\n * // ...\n * }\n */\nexport abstract class BaseClient implements Client {\n /**\n * A reference to a metrics aggregator\n *\n * @experimental Note this is alpha API. It may experience breaking changes in the future.\n */\n public metricsAggregator?: MetricsAggregator;\n\n /** Options passed to the SDK. */\n protected readonly _options: O;\n\n /** The client Dsn, if specified in options. Without this Dsn, the SDK will be disabled. */\n protected readonly _dsn?: DsnComponents;\n\n protected readonly _transport?: Transport;\n\n /** Array of set up integrations. */\n protected _integrations: IntegrationIndex;\n\n /** Indicates whether this client's integrations have been set up. */\n protected _integrationsInitialized: boolean;\n\n /** Number of calls being processed */\n protected _numProcessing: number;\n\n protected _eventProcessors: EventProcessor[];\n\n /** Holds flushable */\n private _outcomes: { [key: string]: number };\n\n // eslint-disable-next-line @typescript-eslint/ban-types\n private _hooks: Record;\n\n /**\n * Initializes this client instance.\n *\n * @param options Options for the client.\n */\n protected constructor(options: O) {\n this._options = options;\n this._integrations = {};\n this._integrationsInitialized = false;\n this._numProcessing = 0;\n this._outcomes = {};\n this._hooks = {};\n this._eventProcessors = [];\n\n if (options.dsn) {\n this._dsn = makeDsn(options.dsn);\n } else {\n DEBUG_BUILD && logger.warn('No DSN provided, client will not send events.');\n }\n\n if (this._dsn) {\n const url = getEnvelopeEndpointWithUrlEncodedAuth(this._dsn, options);\n this._transport = options.transport({\n tunnel: this._options.tunnel,\n recordDroppedEvent: this.recordDroppedEvent.bind(this),\n ...options.transportOptions,\n url,\n });\n }\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types\n public captureException(exception: any, hint?: EventHint, scope?: Scope): string | undefined {\n // ensure we haven't captured this very object before\n if (checkOrSetAlreadyCaught(exception)) {\n DEBUG_BUILD && logger.log(ALREADY_SEEN_ERROR);\n return;\n }\n\n let eventId: string | undefined = hint && hint.event_id;\n\n this._process(\n this.eventFromException(exception, hint)\n .then(event => this._captureEvent(event, hint, scope))\n .then(result => {\n eventId = result;\n }),\n );\n\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n public captureMessage(\n message: ParameterizedString,\n // eslint-disable-next-line deprecation/deprecation\n level?: Severity | SeverityLevel,\n hint?: EventHint,\n scope?: Scope,\n ): string | undefined {\n let eventId: string | undefined = hint && hint.event_id;\n\n const eventMessage = isParameterizedString(message) ? message : String(message);\n\n const promisedEvent = isPrimitive(message)\n ? this.eventFromMessage(eventMessage, level, hint)\n : this.eventFromException(message, hint);\n\n this._process(\n promisedEvent\n .then(event => this._captureEvent(event, hint, scope))\n .then(result => {\n eventId = result;\n }),\n );\n\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n public captureEvent(event: Event, hint?: EventHint, scope?: Scope): string | undefined {\n // ensure we haven't captured this very object before\n if (hint && hint.originalException && checkOrSetAlreadyCaught(hint.originalException)) {\n DEBUG_BUILD && logger.log(ALREADY_SEEN_ERROR);\n return;\n }\n\n let eventId: string | undefined = hint && hint.event_id;\n\n const sdkProcessingMetadata = event.sdkProcessingMetadata || {};\n const capturedSpanScope: Scope | undefined = sdkProcessingMetadata.capturedSpanScope;\n\n this._process(\n this._captureEvent(event, hint, capturedSpanScope || scope).then(result => {\n eventId = result;\n }),\n );\n\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n public captureSession(session: Session): void {\n if (!(typeof session.release === 'string')) {\n DEBUG_BUILD && logger.warn('Discarded session because of missing or non-string release');\n } else {\n this.sendSession(session);\n // After sending, we set init false to indicate it's not the first occurrence\n updateSession(session, { init: false });\n }\n }\n\n /**\n * @inheritDoc\n */\n public getDsn(): DsnComponents | undefined {\n return this._dsn;\n }\n\n /**\n * @inheritDoc\n */\n public getOptions(): O {\n return this._options;\n }\n\n /**\n * @see SdkMetadata in @sentry/types\n *\n * @return The metadata of the SDK\n */\n public getSdkMetadata(): SdkMetadata | undefined {\n return this._options._metadata;\n }\n\n /**\n * @inheritDoc\n */\n public getTransport(): Transport | undefined {\n return this._transport;\n }\n\n /**\n * @inheritDoc\n */\n public flush(timeout?: number): PromiseLike {\n const transport = this._transport;\n if (transport) {\n if (this.metricsAggregator) {\n this.metricsAggregator.flush();\n }\n return this._isClientDoneProcessing(timeout).then(clientFinished => {\n return transport.flush(timeout).then(transportFlushed => clientFinished && transportFlushed);\n });\n } else {\n return resolvedSyncPromise(true);\n }\n }\n\n /**\n * @inheritDoc\n */\n public close(timeout?: number): PromiseLike {\n return this.flush(timeout).then(result => {\n this.getOptions().enabled = false;\n if (this.metricsAggregator) {\n this.metricsAggregator.close();\n }\n return result;\n });\n }\n\n /** Get all installed event processors. */\n public getEventProcessors(): EventProcessor[] {\n return this._eventProcessors;\n }\n\n /** @inheritDoc */\n public addEventProcessor(eventProcessor: EventProcessor): void {\n this._eventProcessors.push(eventProcessor);\n }\n\n /**\n * This is an internal function to setup all integrations that should run on the client.\n * @deprecated Use `client.init()` instead.\n */\n public setupIntegrations(forceInitialize?: boolean): void {\n if ((forceInitialize && !this._integrationsInitialized) || (this._isEnabled() && !this._integrationsInitialized)) {\n this._setupIntegrations();\n }\n }\n\n /** @inheritdoc */\n public init(): void {\n if (this._isEnabled()) {\n this._setupIntegrations();\n }\n }\n\n /**\n * Gets an installed integration by its `id`.\n *\n * @returns The installed integration or `undefined` if no integration with that `id` was installed.\n * @deprecated Use `getIntegrationByName()` instead.\n */\n public getIntegrationById(integrationId: string): Integration | undefined {\n return this.getIntegrationByName(integrationId);\n }\n\n /**\n * Gets an installed integration by its name.\n *\n * @returns The installed integration or `undefined` if no integration with that `name` was installed.\n */\n public getIntegrationByName(integrationName: string): T | undefined {\n return this._integrations[integrationName] as T | undefined;\n }\n\n /**\n * Returns the client's instance of the given integration class, it any.\n * @deprecated Use `getIntegrationByName()` instead.\n */\n public getIntegration(integration: IntegrationClass): T | null {\n try {\n return (this._integrations[integration.id] as T) || null;\n } catch (_oO) {\n DEBUG_BUILD && logger.warn(`Cannot retrieve integration ${integration.id} from the current Client`);\n return null;\n }\n }\n\n /**\n * @inheritDoc\n */\n public addIntegration(integration: Integration): void {\n const isAlreadyInstalled = this._integrations[integration.name];\n\n // This hook takes care of only installing if not already installed\n setupIntegration(this, integration, this._integrations);\n // Here we need to check manually to make sure to not run this multiple times\n if (!isAlreadyInstalled) {\n afterSetupIntegrations(this, [integration]);\n }\n }\n\n /**\n * @inheritDoc\n */\n public sendEvent(event: Event, hint: EventHint = {}): void {\n this.emit('beforeSendEvent', event, hint);\n\n let env = createEventEnvelope(event, this._dsn, this._options._metadata, this._options.tunnel);\n\n for (const attachment of hint.attachments || []) {\n env = addItemToEnvelope(\n env,\n createAttachmentEnvelopeItem(\n attachment,\n this._options.transportOptions && this._options.transportOptions.textEncoder,\n ),\n );\n }\n\n const promise = this._sendEnvelope(env);\n if (promise) {\n promise.then(sendResponse => this.emit('afterSendEvent', event, sendResponse), null);\n }\n }\n\n /**\n * @inheritDoc\n */\n public sendSession(session: Session | SessionAggregates): void {\n const env = createSessionEnvelope(session, this._dsn, this._options._metadata, this._options.tunnel);\n\n // _sendEnvelope should not throw\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this._sendEnvelope(env);\n }\n\n /**\n * @inheritDoc\n */\n public recordDroppedEvent(reason: EventDropReason, category: DataCategory, eventOrCount?: Event | number): void {\n if (this._options.sendClientReports) {\n // TODO v9: We do not need the `event` passed as third argument anymore, and can possibly remove this overload\n // If event is passed as third argument, we assume this is a count of 1\n const count = typeof eventOrCount === 'number' ? eventOrCount : 1;\n\n // We want to track each category (error, transaction, session, replay_event) separately\n // but still keep the distinction between different type of outcomes.\n // We could use nested maps, but it's much easier to read and type this way.\n // A correct type for map-based implementation if we want to go that route\n // would be `Partial>>>`\n // With typescript 4.1 we could even use template literal types\n const key = `${reason}:${category}`;\n DEBUG_BUILD && logger.log(`Recording outcome: \"${key}\"${count > 1 ? ` (${count} times)` : ''}`);\n this._outcomes[key] = (this._outcomes[key] || 0) + count;\n }\n }\n\n /**\n * @inheritDoc\n */\n public captureAggregateMetrics(metricBucketItems: Array): void {\n DEBUG_BUILD && logger.log(`Flushing aggregated metrics, number of metrics: ${metricBucketItems.length}`);\n const metricsEnvelope = createMetricEnvelope(\n metricBucketItems,\n this._dsn,\n this._options._metadata,\n this._options.tunnel,\n );\n\n // _sendEnvelope should not throw\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this._sendEnvelope(metricsEnvelope);\n }\n\n // Keep on() & emit() signatures in sync with types' client.ts interface\n /* eslint-disable @typescript-eslint/unified-signatures */\n\n /** @inheritdoc */\n public on(hook: 'startTransaction', callback: (transaction: Transaction) => void): void;\n\n /** @inheritdoc */\n public on(hook: 'finishTransaction', callback: (transaction: Transaction) => void): void;\n\n /** @inheritdoc */\n public on(hook: 'beforeEnvelope', callback: (envelope: Envelope) => void): void;\n\n /** @inheritdoc */\n public on(hook: 'beforeSendEvent', callback: (event: Event, hint?: EventHint) => void): void;\n\n /** @inheritdoc */\n public on(hook: 'preprocessEvent', callback: (event: Event, hint?: EventHint) => void): void;\n\n /** @inheritdoc */\n public on(\n hook: 'afterSendEvent',\n callback: (event: Event, sendResponse: TransportMakeRequestResponse | void) => void,\n ): void;\n\n /** @inheritdoc */\n public on(hook: 'beforeAddBreadcrumb', callback: (breadcrumb: Breadcrumb, hint?: BreadcrumbHint) => void): void;\n\n /** @inheritdoc */\n public on(hook: 'createDsc', callback: (dsc: DynamicSamplingContext) => void): void;\n\n /** @inheritdoc */\n public on(hook: 'otelSpanEnd', callback: (otelSpan: unknown, mutableOptions: { drop: boolean }) => void): void;\n\n /** @inheritdoc */\n public on(\n hook: 'beforeSendFeedback',\n callback: (feedback: FeedbackEvent, options?: { includeReplay: boolean }) => void,\n ): void;\n\n /** @inheritdoc */\n public on(hook: 'startPageLoadSpan', callback: (options: StartSpanOptions) => void): void;\n\n /** @inheritdoc */\n public on(hook: 'startNavigationSpan', callback: (options: StartSpanOptions) => void): void;\n\n /** @inheritdoc */\n public on(hook: string, callback: unknown): void {\n if (!this._hooks[hook]) {\n this._hooks[hook] = [];\n }\n\n // @ts-expect-error We assue the types are correct\n this._hooks[hook].push(callback);\n }\n\n /** @inheritdoc */\n public emit(hook: 'startTransaction', transaction: Transaction): void;\n\n /** @inheritdoc */\n public emit(hook: 'finishTransaction', transaction: Transaction): void;\n\n /** @inheritdoc */\n public emit(hook: 'beforeEnvelope', envelope: Envelope): void;\n\n /** @inheritdoc */\n public emit(hook: 'beforeSendEvent', event: Event, hint?: EventHint): void;\n\n /** @inheritdoc */\n public emit(hook: 'preprocessEvent', event: Event, hint?: EventHint): void;\n\n /** @inheritdoc */\n public emit(hook: 'afterSendEvent', event: Event, sendResponse: TransportMakeRequestResponse | void): void;\n\n /** @inheritdoc */\n public emit(hook: 'beforeAddBreadcrumb', breadcrumb: Breadcrumb, hint?: BreadcrumbHint): void;\n\n /** @inheritdoc */\n public emit(hook: 'createDsc', dsc: DynamicSamplingContext): void;\n\n /** @inheritdoc */\n public emit(hook: 'otelSpanEnd', otelSpan: unknown, mutableOptions: { drop: boolean }): void;\n\n /** @inheritdoc */\n public emit(hook: 'beforeSendFeedback', feedback: FeedbackEvent, options?: { includeReplay: boolean }): void;\n\n /** @inheritdoc */\n public emit(hook: 'startPageLoadSpan', options: StartSpanOptions): void;\n\n /** @inheritdoc */\n public emit(hook: 'startNavigationSpan', options: StartSpanOptions): void;\n\n /** @inheritdoc */\n public emit(hook: string, ...rest: unknown[]): void {\n if (this._hooks[hook]) {\n this._hooks[hook].forEach(callback => callback(...rest));\n }\n }\n\n /* eslint-enable @typescript-eslint/unified-signatures */\n\n /** Setup integrations for this client. */\n protected _setupIntegrations(): void {\n const { integrations } = this._options;\n this._integrations = setupIntegrations(this, integrations);\n afterSetupIntegrations(this, integrations);\n\n // TODO v8: We don't need this flag anymore\n this._integrationsInitialized = true;\n }\n\n /** Updates existing session based on the provided event */\n protected _updateSessionFromEvent(session: Session, event: Event): void {\n let crashed = false;\n let errored = false;\n const exceptions = event.exception && event.exception.values;\n\n if (exceptions) {\n errored = true;\n\n for (const ex of exceptions) {\n const mechanism = ex.mechanism;\n if (mechanism && mechanism.handled === false) {\n crashed = true;\n break;\n }\n }\n }\n\n // A session is updated and that session update is sent in only one of the two following scenarios:\n // 1. Session with non terminal status and 0 errors + an error occurred -> Will set error count to 1 and send update\n // 2. Session with non terminal status and 1 error + a crash occurred -> Will set status crashed and send update\n const sessionNonTerminal = session.status === 'ok';\n const shouldUpdateAndSend = (sessionNonTerminal && session.errors === 0) || (sessionNonTerminal && crashed);\n\n if (shouldUpdateAndSend) {\n updateSession(session, {\n ...(crashed && { status: 'crashed' }),\n errors: session.errors || Number(errored || crashed),\n });\n this.captureSession(session);\n }\n }\n\n /**\n * Determine if the client is finished processing. Returns a promise because it will wait `timeout` ms before saying\n * \"no\" (resolving to `false`) in order to give the client a chance to potentially finish first.\n *\n * @param timeout The time, in ms, after which to resolve to `false` if the client is still busy. Passing `0` (or not\n * passing anything) will make the promise wait as long as it takes for processing to finish before resolving to\n * `true`.\n * @returns A promise which will resolve to `true` if processing is already done or finishes before the timeout, and\n * `false` otherwise\n */\n protected _isClientDoneProcessing(timeout?: number): PromiseLike {\n return new SyncPromise(resolve => {\n let ticked: number = 0;\n const tick: number = 1;\n\n const interval = setInterval(() => {\n if (this._numProcessing == 0) {\n clearInterval(interval);\n resolve(true);\n } else {\n ticked += tick;\n if (timeout && ticked >= timeout) {\n clearInterval(interval);\n resolve(false);\n }\n }\n }, tick);\n });\n }\n\n /** Determines whether this SDK is enabled and a transport is present. */\n protected _isEnabled(): boolean {\n return this.getOptions().enabled !== false && this._transport !== undefined;\n }\n\n /**\n * Adds common information to events.\n *\n * The information includes release and environment from `options`,\n * breadcrumbs and context (extra, tags and user) from the scope.\n *\n * Information that is already present in the event is never overwritten. For\n * nested objects, such as the context, keys are merged.\n *\n * @param event The original event.\n * @param hint May contain additional information about the original exception.\n * @param scope A scope containing event metadata.\n * @returns A new event with more information.\n */\n protected _prepareEvent(\n event: Event,\n hint: EventHint,\n scope?: Scope,\n isolationScope = getIsolationScope(),\n ): PromiseLike {\n const options = this.getOptions();\n const integrations = Object.keys(this._integrations);\n if (!hint.integrations && integrations.length > 0) {\n hint.integrations = integrations;\n }\n\n this.emit('preprocessEvent', event, hint);\n\n return prepareEvent(options, event, hint, scope, this, isolationScope).then(evt => {\n if (evt === null) {\n return evt;\n }\n\n const propagationContext = {\n ...isolationScope.getPropagationContext(),\n ...(scope ? scope.getPropagationContext() : undefined),\n };\n\n const trace = evt.contexts && evt.contexts.trace;\n if (!trace && propagationContext) {\n const { traceId: trace_id, spanId, parentSpanId, dsc } = propagationContext;\n evt.contexts = {\n trace: {\n trace_id,\n span_id: spanId,\n parent_span_id: parentSpanId,\n },\n ...evt.contexts,\n };\n\n const dynamicSamplingContext = dsc ? dsc : getDynamicSamplingContextFromClient(trace_id, this, scope);\n\n evt.sdkProcessingMetadata = {\n dynamicSamplingContext,\n ...evt.sdkProcessingMetadata,\n };\n }\n return evt;\n });\n }\n\n /**\n * Processes the event and logs an error in case of rejection\n * @param event\n * @param hint\n * @param scope\n */\n protected _captureEvent(event: Event, hint: EventHint = {}, scope?: Scope): PromiseLike {\n return this._processEvent(event, hint, scope).then(\n finalEvent => {\n return finalEvent.event_id;\n },\n reason => {\n if (DEBUG_BUILD) {\n // If something's gone wrong, log the error as a warning. If it's just us having used a `SentryError` for\n // control flow, log just the message (no stack) as a log-level log.\n const sentryError = reason as SentryError;\n if (sentryError.logLevel === 'log') {\n logger.log(sentryError.message);\n } else {\n logger.warn(sentryError);\n }\n }\n return undefined;\n },\n );\n }\n\n /**\n * Processes an event (either error or message) and sends it to Sentry.\n *\n * This also adds breadcrumbs and context information to the event. However,\n * platform specific meta data (such as the User's IP address) must be added\n * by the SDK implementor.\n *\n *\n * @param event The event to send to Sentry.\n * @param hint May contain additional information about the original exception.\n * @param scope A scope containing event metadata.\n * @returns A SyncPromise that resolves with the event or rejects in case event was/will not be send.\n */\n protected _processEvent(event: Event, hint: EventHint, scope?: Scope): PromiseLike {\n const options = this.getOptions();\n const { sampleRate } = options;\n\n const isTransaction = isTransactionEvent(event);\n const isError = isErrorEvent(event);\n const eventType = event.type || 'error';\n const beforeSendLabel = `before send for type \\`${eventType}\\``;\n\n // 1.0 === 100% events are sent\n // 0.0 === 0% events are sent\n // Sampling for transaction happens somewhere else\n if (isError && typeof sampleRate === 'number' && Math.random() > sampleRate) {\n this.recordDroppedEvent('sample_rate', 'error', event);\n return rejectedSyncPromise(\n new SentryError(\n `Discarding event because it's not included in the random sample (sampling rate = ${sampleRate})`,\n 'log',\n ),\n );\n }\n\n const dataCategory: DataCategory = eventType === 'replay_event' ? 'replay' : eventType;\n\n const sdkProcessingMetadata = event.sdkProcessingMetadata || {};\n const capturedSpanIsolationScope: Scope | undefined = sdkProcessingMetadata.capturedSpanIsolationScope;\n\n return this._prepareEvent(event, hint, scope, capturedSpanIsolationScope)\n .then(prepared => {\n if (prepared === null) {\n this.recordDroppedEvent('event_processor', dataCategory, event);\n throw new SentryError('An event processor returned `null`, will not send event.', 'log');\n }\n\n const isInternalException = hint.data && (hint.data as { __sentry__: boolean }).__sentry__ === true;\n if (isInternalException) {\n return prepared;\n }\n\n const result = processBeforeSend(options, prepared, hint);\n return _validateBeforeSendResult(result, beforeSendLabel);\n })\n .then(processedEvent => {\n if (processedEvent === null) {\n this.recordDroppedEvent('before_send', dataCategory, event);\n if (isTransaction) {\n const spans = event.spans || [];\n // the transaction itself counts as one span, plus all the child spans that are added\n const spanCount = 1 + spans.length;\n this.recordDroppedEvent('before_send', 'span', spanCount);\n }\n throw new SentryError(`${beforeSendLabel} returned \\`null\\`, will not send event.`, 'log');\n }\n\n const session = scope && scope.getSession();\n if (!isTransaction && session) {\n this._updateSessionFromEvent(session, processedEvent);\n }\n\n if (isTransaction) {\n const spanCountBefore =\n (processedEvent.sdkProcessingMetadata && processedEvent.sdkProcessingMetadata.spanCountBeforeProcessing) ||\n 0;\n const spanCountAfter = processedEvent.spans ? processedEvent.spans.length : 0;\n\n const droppedSpanCount = spanCountBefore - spanCountAfter;\n if (droppedSpanCount > 0) {\n this.recordDroppedEvent('before_send', 'span', droppedSpanCount);\n }\n }\n\n // None of the Sentry built event processor will update transaction name,\n // so if the transaction name has been changed by an event processor, we know\n // it has to come from custom event processor added by a user\n const transactionInfo = processedEvent.transaction_info;\n if (isTransaction && transactionInfo && processedEvent.transaction !== event.transaction) {\n const source = 'custom';\n processedEvent.transaction_info = {\n ...transactionInfo,\n source,\n };\n }\n\n this.sendEvent(processedEvent, hint);\n return processedEvent;\n })\n .then(null, reason => {\n if (reason instanceof SentryError) {\n throw reason;\n }\n\n this.captureException(reason, {\n data: {\n __sentry__: true,\n },\n originalException: reason,\n });\n throw new SentryError(\n `Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event.\\nReason: ${reason}`,\n );\n });\n }\n\n /**\n * Occupies the client with processing and event\n */\n protected _process(promise: PromiseLike): void {\n this._numProcessing++;\n void promise.then(\n value => {\n this._numProcessing--;\n return value;\n },\n reason => {\n this._numProcessing--;\n return reason;\n },\n );\n }\n\n /**\n * @inheritdoc\n */\n protected _sendEnvelope(envelope: Envelope): PromiseLike | void {\n this.emit('beforeEnvelope', envelope);\n\n if (this._isEnabled() && this._transport) {\n return this._transport.send(envelope).then(null, reason => {\n DEBUG_BUILD && logger.error('Error while sending event:', reason);\n });\n } else {\n DEBUG_BUILD && logger.error('Transport disabled');\n }\n }\n\n /**\n * Clears outcomes on this client and returns them.\n */\n protected _clearOutcomes(): Outcome[] {\n const outcomes = this._outcomes;\n this._outcomes = {};\n return Object.keys(outcomes).map(key => {\n const [reason, category] = key.split(':') as [EventDropReason, DataCategory];\n return {\n reason,\n category,\n quantity: outcomes[key],\n };\n });\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types\n public abstract eventFromException(_exception: any, _hint?: EventHint): PromiseLike;\n\n /**\n * @inheritDoc\n */\n public abstract eventFromMessage(\n _message: ParameterizedString,\n // eslint-disable-next-line deprecation/deprecation\n _level?: Severity | SeverityLevel,\n _hint?: EventHint,\n ): PromiseLike;\n}\n\n/**\n * Verifies that return value of configured `beforeSend` or `beforeSendTransaction` is of expected type, and returns the value if so.\n */\nfunction _validateBeforeSendResult(\n beforeSendResult: PromiseLike | Event | null,\n beforeSendLabel: string,\n): PromiseLike | Event | null {\n const invalidValueError = `${beforeSendLabel} must return \\`null\\` or a valid event.`;\n if (isThenable(beforeSendResult)) {\n return beforeSendResult.then(\n event => {\n if (!isPlainObject(event) && event !== null) {\n throw new SentryError(invalidValueError);\n }\n return event;\n },\n e => {\n throw new SentryError(`${beforeSendLabel} rejected with ${e}`);\n },\n );\n } else if (!isPlainObject(beforeSendResult) && beforeSendResult !== null) {\n throw new SentryError(invalidValueError);\n }\n return beforeSendResult;\n}\n\n/**\n * Process the matching `beforeSendXXX` callback.\n */\nfunction processBeforeSend(\n options: ClientOptions,\n event: Event,\n hint: EventHint,\n): PromiseLike | Event | null {\n const { beforeSend, beforeSendTransaction } = options;\n\n if (isErrorEvent(event) && beforeSend) {\n return beforeSend(event, hint);\n }\n\n if (isTransactionEvent(event) && beforeSendTransaction) {\n if (event.spans) {\n // We store the # of spans before processing in SDK metadata,\n // so we can compare it afterwards to determine how many spans were dropped\n const spanCountBefore = event.spans.length;\n event.sdkProcessingMetadata = {\n ...event.sdkProcessingMetadata,\n spanCountBeforeProcessing: spanCountBefore,\n };\n }\n return beforeSendTransaction(event, hint);\n }\n\n return event;\n}\n\nfunction isErrorEvent(event: Event): event is ErrorEvent {\n return event.type === undefined;\n}\n\nfunction isTransactionEvent(event: Event): event is TransactionEvent {\n return event.type === 'transaction';\n}\n\n/**\n * Add an event processor to the current client.\n * This event processor will run for all events processed by this client.\n */\nexport function addEventProcessor(callback: EventProcessor): void {\n const client = getClient();\n\n if (!client || !client.addEventProcessor) {\n return;\n }\n\n client.addEventProcessor(callback);\n}\n", "import type {\n CheckInEnvelope,\n CheckInItem,\n DsnComponents,\n DynamicSamplingContext,\n SdkMetadata,\n SerializedCheckIn,\n} from '@sentry/types';\nimport { createEnvelope, dropUndefinedKeys, dsnToString } from '@sentry/utils';\n\n/**\n * Create envelope from check in item.\n */\nexport function createCheckInEnvelope(\n checkIn: SerializedCheckIn,\n dynamicSamplingContext?: Partial,\n metadata?: SdkMetadata,\n tunnel?: string,\n dsn?: DsnComponents,\n): CheckInEnvelope {\n const headers: CheckInEnvelope[0] = {\n sent_at: new Date().toISOString(),\n };\n\n if (metadata && metadata.sdk) {\n headers.sdk = {\n name: metadata.sdk.name,\n version: metadata.sdk.version,\n };\n }\n\n if (!!tunnel && !!dsn) {\n headers.dsn = dsnToString(dsn);\n }\n\n if (dynamicSamplingContext) {\n headers.trace = dropUndefinedKeys(dynamicSamplingContext) as DynamicSamplingContext;\n }\n\n const item = createCheckInEnvelopeItem(checkIn);\n return createEnvelope(headers, [item]);\n}\n\nfunction createCheckInEnvelopeItem(checkIn: SerializedCheckIn): CheckInItem {\n const checkInHeaders: CheckInItem[0] = {\n type: 'check_in',\n };\n return [checkInHeaders, checkIn];\n}\n", "export const COUNTER_METRIC_TYPE = 'c' as const;\nexport const GAUGE_METRIC_TYPE = 'g' as const;\nexport const SET_METRIC_TYPE = 's' as const;\nexport const DISTRIBUTION_METRIC_TYPE = 'd' as const;\n\n/**\n * This does not match spec in https://develop.sentry.dev/sdk/metrics\n * but was chosen to optimize for the most common case in browser environments.\n */\nexport const DEFAULT_BROWSER_FLUSH_INTERVAL = 5000;\n\n/**\n * SDKs are required to bucket into 10 second intervals (rollup in seconds)\n * which is the current lower bound of metric accuracy.\n */\nexport const DEFAULT_FLUSH_INTERVAL = 10000;\n\n/**\n * The maximum number of metrics that should be stored in memory.\n */\nexport const MAX_WEIGHT = 10000;\n", "import type { MetricInstance } from '@sentry/types';\nimport { COUNTER_METRIC_TYPE, DISTRIBUTION_METRIC_TYPE, GAUGE_METRIC_TYPE, SET_METRIC_TYPE } from './constants';\nimport { simpleHash } from './utils';\n\n/**\n * A metric instance representing a counter.\n */\nexport class CounterMetric implements MetricInstance {\n public constructor(private _value: number) {}\n\n /** @inheritDoc */\n public get weight(): number {\n return 1;\n }\n\n /** @inheritdoc */\n public add(value: number): void {\n this._value += value;\n }\n\n /** @inheritdoc */\n public toString(): string {\n return `${this._value}`;\n }\n}\n\n/**\n * A metric instance representing a gauge.\n */\nexport class GaugeMetric implements MetricInstance {\n private _last: number;\n private _min: number;\n private _max: number;\n private _sum: number;\n private _count: number;\n\n public constructor(value: number) {\n this._last = value;\n this._min = value;\n this._max = value;\n this._sum = value;\n this._count = 1;\n }\n\n /** @inheritDoc */\n public get weight(): number {\n return 5;\n }\n\n /** @inheritdoc */\n public add(value: number): void {\n this._last = value;\n if (value < this._min) {\n this._min = value;\n }\n if (value > this._max) {\n this._max = value;\n }\n this._sum += value;\n this._count++;\n }\n\n /** @inheritdoc */\n public toString(): string {\n return `${this._last}:${this._min}:${this._max}:${this._sum}:${this._count}`;\n }\n}\n\n/**\n * A metric instance representing a distribution.\n */\nexport class DistributionMetric implements MetricInstance {\n private _value: number[];\n\n public constructor(first: number) {\n this._value = [first];\n }\n\n /** @inheritDoc */\n public get weight(): number {\n return this._value.length;\n }\n\n /** @inheritdoc */\n public add(value: number): void {\n this._value.push(value);\n }\n\n /** @inheritdoc */\n public toString(): string {\n return this._value.join(':');\n }\n}\n\n/**\n * A metric instance representing a set.\n */\nexport class SetMetric implements MetricInstance {\n private _value: Set;\n\n public constructor(public first: number | string) {\n this._value = new Set([first]);\n }\n\n /** @inheritDoc */\n public get weight(): number {\n return this._value.size;\n }\n\n /** @inheritdoc */\n public add(value: number | string): void {\n this._value.add(value);\n }\n\n /** @inheritdoc */\n public toString(): string {\n return Array.from(this._value)\n .map(val => (typeof val === 'string' ? simpleHash(val) : val))\n .join(':');\n }\n}\n\nexport const METRIC_MAP = {\n [COUNTER_METRIC_TYPE]: CounterMetric,\n [GAUGE_METRIC_TYPE]: GaugeMetric,\n [DISTRIBUTION_METRIC_TYPE]: DistributionMetric,\n [SET_METRIC_TYPE]: SetMetric,\n};\n", "import type {\n Client,\n ClientOptions,\n MeasurementUnit,\n MetricsAggregator as MetricsAggregatorBase,\n Primitive,\n} from '@sentry/types';\nimport { timestampInSeconds } from '@sentry/utils';\nimport { DEFAULT_FLUSH_INTERVAL, MAX_WEIGHT, SET_METRIC_TYPE } from './constants';\nimport { METRIC_MAP } from './instance';\nimport { updateMetricSummaryOnActiveSpan } from './metric-summary';\nimport type { MetricBucket, MetricType } from './types';\nimport { getBucketKey, sanitizeMetricKey, sanitizeTags, sanitizeUnit } from './utils';\n\n/**\n * A metrics aggregator that aggregates metrics in memory and flushes them periodically.\n */\nexport class MetricsAggregator implements MetricsAggregatorBase {\n // TODO(@anonrig): Use FinalizationRegistry to have a proper way of flushing the buckets\n // when the aggregator is garbage collected.\n // Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry\n private _buckets: MetricBucket;\n\n // Different metrics have different weights. We use this to limit the number of metrics\n // that we store in memory.\n private _bucketsTotalWeight;\n\n // Cast to any so that it can use Node.js timeout\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private readonly _interval: any;\n\n // SDKs are required to shift the flush interval by random() * rollup_in_seconds.\n // That shift is determined once per startup to create jittering.\n private readonly _flushShift: number;\n\n // An SDK is required to perform force flushing ahead of scheduled time if the memory\n // pressure is too high. There is no rule for this other than that SDKs should be tracking\n // abstract aggregation complexity (eg: a counter only carries a single float, whereas a\n // distribution is a float per emission).\n //\n // Force flush is used on either shutdown, flush() or when we exceed the max weight.\n private _forceFlush: boolean;\n\n public constructor(private readonly _client: Client) {\n this._buckets = new Map();\n this._bucketsTotalWeight = 0;\n\n this._interval = setInterval(() => this._flush(), DEFAULT_FLUSH_INTERVAL) as any;\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n if (this._interval.unref) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n this._interval.unref();\n }\n\n this._flushShift = Math.floor((Math.random() * DEFAULT_FLUSH_INTERVAL) / 1000);\n this._forceFlush = false;\n }\n\n /**\n * @inheritDoc\n */\n public add(\n metricType: MetricType,\n unsanitizedName: string,\n value: number | string,\n unsanitizedUnit: MeasurementUnit = 'none',\n unsanitizedTags: Record = {},\n maybeFloatTimestamp = timestampInSeconds(),\n ): void {\n const timestamp = Math.floor(maybeFloatTimestamp);\n const name = sanitizeMetricKey(unsanitizedName);\n const tags = sanitizeTags(unsanitizedTags);\n const unit = sanitizeUnit(unsanitizedUnit as string);\n\n const bucketKey = getBucketKey(metricType, name, unit, tags);\n\n let bucketItem = this._buckets.get(bucketKey);\n // If this is a set metric, we need to calculate the delta from the previous weight.\n const previousWeight = bucketItem && metricType === SET_METRIC_TYPE ? bucketItem.metric.weight : 0;\n\n if (bucketItem) {\n bucketItem.metric.add(value);\n // TODO(abhi): Do we need this check?\n if (bucketItem.timestamp < timestamp) {\n bucketItem.timestamp = timestamp;\n }\n } else {\n bucketItem = {\n // @ts-expect-error we don't need to narrow down the type of value here, saves bundle size.\n metric: new METRIC_MAP[metricType](value),\n timestamp,\n metricType,\n name,\n unit,\n tags,\n };\n this._buckets.set(bucketKey, bucketItem);\n }\n\n // If value is a string, it's a set metric so calculate the delta from the previous weight.\n const val = typeof value === 'string' ? bucketItem.metric.weight - previousWeight : value;\n updateMetricSummaryOnActiveSpan(metricType, name, val, unit, unsanitizedTags, bucketKey);\n\n // We need to keep track of the total weight of the buckets so that we can\n // flush them when we exceed the max weight.\n this._bucketsTotalWeight += bucketItem.metric.weight;\n\n if (this._bucketsTotalWeight >= MAX_WEIGHT) {\n this.flush();\n }\n }\n\n /**\n * Flushes the current metrics to the transport via the transport.\n */\n public flush(): void {\n this._forceFlush = true;\n this._flush();\n }\n\n /**\n * Shuts down metrics aggregator and clears all metrics.\n */\n public close(): void {\n this._forceFlush = true;\n clearInterval(this._interval);\n this._flush();\n }\n\n /**\n * Flushes the buckets according to the internal state of the aggregator.\n * If it is a force flush, which happens on shutdown, it will flush all buckets.\n * Otherwise, it will only flush buckets that are older than the flush interval,\n * and according to the flush shift.\n *\n * This function mutates `_forceFlush` and `_bucketsTotalWeight` properties.\n */\n private _flush(): void {\n // TODO(@anonrig): Add Atomics for locking to avoid having force flush and regular flush\n // running at the same time.\n // Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Atomics\n\n // This path eliminates the need for checking for timestamps since we're forcing a flush.\n // Remember to reset the flag, or it will always flush all metrics.\n if (this._forceFlush) {\n this._forceFlush = false;\n this._bucketsTotalWeight = 0;\n this._captureMetrics(this._buckets);\n this._buckets.clear();\n return;\n }\n const cutoffSeconds = Math.floor(timestampInSeconds()) - DEFAULT_FLUSH_INTERVAL / 1000 - this._flushShift;\n // TODO(@anonrig): Optimization opportunity.\n // Convert this map to an array and store key in the bucketItem.\n const flushedBuckets: MetricBucket = new Map();\n for (const [key, bucket] of this._buckets) {\n if (bucket.timestamp <= cutoffSeconds) {\n flushedBuckets.set(key, bucket);\n this._bucketsTotalWeight -= bucket.metric.weight;\n }\n }\n\n for (const [key] of flushedBuckets) {\n this._buckets.delete(key);\n }\n\n this._captureMetrics(flushedBuckets);\n }\n\n /**\n * Only captures a subset of the buckets passed to this function.\n * @param flushedBuckets\n */\n private _captureMetrics(flushedBuckets: MetricBucket): void {\n if (flushedBuckets.size > 0 && this._client.captureAggregateMetrics) {\n // TODO(@anonrig): Optimization opportunity.\n // This copy operation can be avoided if we store the key in the bucketItem.\n const buckets = Array.from(flushedBuckets).map(([, bucketItem]) => bucketItem);\n this._client.captureAggregateMetrics(buckets);\n }\n }\n}\n", "import type {\n BaseTransportOptions,\n CheckIn,\n ClientOptions,\n DynamicSamplingContext,\n Event,\n EventHint,\n MonitorConfig,\n ParameterizedString,\n SerializedCheckIn,\n Severity,\n SeverityLevel,\n TraceContext,\n} from '@sentry/types';\nimport { eventFromMessage, eventFromUnknownInput, logger, resolvedSyncPromise, uuid4 } from '@sentry/utils';\n\nimport { BaseClient } from './baseclient';\nimport { createCheckInEnvelope } from './checkin';\nimport { DEBUG_BUILD } from './debug-build';\nimport { getClient } from './exports';\nimport { MetricsAggregator } from './metrics/aggregator';\nimport type { Scope } from './scope';\nimport { SessionFlusher } from './sessionflusher';\nimport {\n addTracingExtensions,\n getDynamicSamplingContextFromClient,\n getDynamicSamplingContextFromSpan,\n} from './tracing';\nimport { getRootSpan } from './utils/getRootSpan';\nimport { spanToTraceContext } from './utils/spanUtils';\n\nexport interface ServerRuntimeClientOptions extends ClientOptions {\n platform?: string;\n runtime?: { name: string; version?: string };\n serverName?: string;\n}\n\n/**\n * The Sentry Server Runtime Client SDK.\n */\nexport class ServerRuntimeClient<\n O extends ClientOptions & ServerRuntimeClientOptions = ServerRuntimeClientOptions,\n> extends BaseClient {\n protected _sessionFlusher: SessionFlusher | undefined;\n\n /**\n * Creates a new Edge SDK instance.\n * @param options Configuration options for this SDK.\n */\n public constructor(options: O) {\n // Server clients always support tracing\n addTracingExtensions();\n\n super(options);\n\n if (options._experiments && options._experiments['metricsAggregator']) {\n this.metricsAggregator = new MetricsAggregator(this);\n }\n }\n\n /**\n * @inheritDoc\n */\n public eventFromException(exception: unknown, hint?: EventHint): PromiseLike {\n return resolvedSyncPromise(eventFromUnknownInput(getClient(), this._options.stackParser, exception, hint));\n }\n\n /**\n * @inheritDoc\n */\n public eventFromMessage(\n message: ParameterizedString,\n // eslint-disable-next-line deprecation/deprecation\n level: Severity | SeverityLevel = 'info',\n hint?: EventHint,\n ): PromiseLike {\n return resolvedSyncPromise(\n eventFromMessage(this._options.stackParser, message, level, hint, this._options.attachStacktrace),\n );\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types\n public captureException(exception: any, hint?: EventHint, scope?: Scope): string | undefined {\n // Check if the flag `autoSessionTracking` is enabled, and if `_sessionFlusher` exists because it is initialised only\n // when the `requestHandler` middleware is used, and hence the expectation is to have SessionAggregates payload\n // sent to the Server only when the `requestHandler` middleware is used\n if (this._options.autoSessionTracking && this._sessionFlusher && scope) {\n const requestSession = scope.getRequestSession();\n\n // Necessary checks to ensure this is code block is executed only within a request\n // Should override the status only if `requestSession.status` is `Ok`, which is its initial stage\n if (requestSession && requestSession.status === 'ok') {\n requestSession.status = 'errored';\n }\n }\n\n return super.captureException(exception, hint, scope);\n }\n\n /**\n * @inheritDoc\n */\n public captureEvent(event: Event, hint?: EventHint, scope?: Scope): string | undefined {\n // Check if the flag `autoSessionTracking` is enabled, and if `_sessionFlusher` exists because it is initialised only\n // when the `requestHandler` middleware is used, and hence the expectation is to have SessionAggregates payload\n // sent to the Server only when the `requestHandler` middleware is used\n if (this._options.autoSessionTracking && this._sessionFlusher && scope) {\n const eventType = event.type || 'exception';\n const isException =\n eventType === 'exception' && event.exception && event.exception.values && event.exception.values.length > 0;\n\n // If the event is of type Exception, then a request session should be captured\n if (isException) {\n const requestSession = scope.getRequestSession();\n\n // Ensure that this is happening within the bounds of a request, and make sure not to override\n // Session Status if Errored / Crashed\n if (requestSession && requestSession.status === 'ok') {\n requestSession.status = 'errored';\n }\n }\n }\n\n return super.captureEvent(event, hint, scope);\n }\n\n /**\n *\n * @inheritdoc\n */\n public close(timeout?: number): PromiseLike {\n if (this._sessionFlusher) {\n this._sessionFlusher.close();\n }\n return super.close(timeout);\n }\n\n /** Method that initialises an instance of SessionFlusher on Client */\n public initSessionFlusher(): void {\n const { release, environment } = this._options;\n if (!release) {\n DEBUG_BUILD && logger.warn('Cannot initialise an instance of SessionFlusher if no release is provided!');\n } else {\n this._sessionFlusher = new SessionFlusher(this, {\n release,\n environment,\n });\n }\n }\n\n /**\n * Create a cron monitor check in and send it to Sentry.\n *\n * @param checkIn An object that describes a check in.\n * @param upsertMonitorConfig An optional object that describes a monitor config. Use this if you want\n * to create a monitor automatically when sending a check in.\n */\n public captureCheckIn(checkIn: CheckIn, monitorConfig?: MonitorConfig, scope?: Scope): string {\n const id = 'checkInId' in checkIn && checkIn.checkInId ? checkIn.checkInId : uuid4();\n if (!this._isEnabled()) {\n DEBUG_BUILD && logger.warn('SDK not enabled, will not capture checkin.');\n return id;\n }\n\n const options = this.getOptions();\n const { release, environment, tunnel } = options;\n\n const serializedCheckIn: SerializedCheckIn = {\n check_in_id: id,\n monitor_slug: checkIn.monitorSlug,\n status: checkIn.status,\n release,\n environment,\n };\n\n if ('duration' in checkIn) {\n serializedCheckIn.duration = checkIn.duration;\n }\n\n if (monitorConfig) {\n serializedCheckIn.monitor_config = {\n schedule: monitorConfig.schedule,\n checkin_margin: monitorConfig.checkinMargin,\n max_runtime: monitorConfig.maxRuntime,\n timezone: monitorConfig.timezone,\n };\n }\n\n const [dynamicSamplingContext, traceContext] = this._getTraceInfoFromScope(scope);\n if (traceContext) {\n serializedCheckIn.contexts = {\n trace: traceContext,\n };\n }\n\n const envelope = createCheckInEnvelope(\n serializedCheckIn,\n dynamicSamplingContext,\n this.getSdkMetadata(),\n tunnel,\n this.getDsn(),\n );\n\n DEBUG_BUILD && logger.info('Sending checkin:', checkIn.monitorSlug, checkIn.status);\n\n // _sendEnvelope should not throw\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this._sendEnvelope(envelope);\n\n return id;\n }\n\n /**\n * Method responsible for capturing/ending a request session by calling `incrementSessionStatusCount` to increment\n * appropriate session aggregates bucket\n */\n protected _captureRequestSession(): void {\n if (!this._sessionFlusher) {\n DEBUG_BUILD && logger.warn('Discarded request mode session because autoSessionTracking option was disabled');\n } else {\n this._sessionFlusher.incrementSessionStatusCount();\n }\n }\n\n /**\n * @inheritDoc\n */\n protected _prepareEvent(\n event: Event,\n hint: EventHint,\n scope?: Scope,\n isolationScope?: Scope,\n ): PromiseLike {\n if (this._options.platform) {\n event.platform = event.platform || this._options.platform;\n }\n\n if (this._options.runtime) {\n event.contexts = {\n ...event.contexts,\n runtime: (event.contexts || {}).runtime || this._options.runtime,\n };\n }\n\n if (this._options.serverName) {\n event.server_name = event.server_name || this._options.serverName;\n }\n\n return super._prepareEvent(event, hint, scope, isolationScope);\n }\n\n /** Extract trace information from scope */\n private _getTraceInfoFromScope(\n scope: Scope | undefined,\n ): [dynamicSamplingContext: Partial | undefined, traceContext: TraceContext | undefined] {\n if (!scope) {\n return [undefined, undefined];\n }\n\n // eslint-disable-next-line deprecation/deprecation\n const span = scope.getSpan();\n if (span) {\n const samplingContext = getRootSpan(span) ? getDynamicSamplingContextFromSpan(span) : undefined;\n return [samplingContext, spanToTraceContext(span)];\n }\n\n const { traceId, spanId, parentSpanId, dsc } = scope.getPropagationContext();\n const traceContext: TraceContext = {\n trace_id: traceId,\n span_id: spanId,\n parent_span_id: parentSpanId,\n };\n if (dsc) {\n return [dsc, traceContext];\n }\n\n return [getDynamicSamplingContextFromClient(traceId, this, scope), traceContext];\n }\n}\n", "import type { Client, ClientOptions } from '@sentry/types';\nimport { consoleSandbox, logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from './debug-build';\nimport { getCurrentScope } from './exports';\nimport { getCurrentHub } from './hub';\n\n/** A class object that can instantiate Client objects. */\nexport type ClientClass = new (options: O) => F;\n\n/**\n * Internal function to create a new SDK client instance. The client is\n * installed and then bound to the current scope.\n *\n * @param clientClass The client class to instantiate.\n * @param options Options to pass to the client.\n */\nexport function initAndBind(\n clientClass: ClientClass,\n options: O,\n): void {\n if (options.debug === true) {\n if (DEBUG_BUILD) {\n logger.enable();\n } else {\n // use `console.warn` rather than `logger.warn` since by non-debug bundles have all `logger.x` statements stripped\n consoleSandbox(() => {\n // eslint-disable-next-line no-console\n console.warn('[Sentry] Cannot initialize SDK with `debug` option using a non-debug bundle.');\n });\n }\n }\n const scope = getCurrentScope();\n scope.update(options.initialScope);\n\n const client = new clientClass(options);\n setCurrentClient(client);\n initializeClient(client);\n}\n\n/**\n * Make the given client the current client.\n */\nexport function setCurrentClient(client: Client): void {\n // eslint-disable-next-line deprecation/deprecation\n const hub = getCurrentHub();\n // eslint-disable-next-line deprecation/deprecation\n const top = hub.getStackTop();\n top.client = client;\n top.scope.setClient(client);\n}\n\n/**\n * Initialize the client for the current scope.\n * Make sure to call this after `setCurrentClient()`.\n */\nfunction initializeClient(client: Client): void {\n if (client.init) {\n client.init();\n // TODO v8: Remove this fallback\n // eslint-disable-next-line deprecation/deprecation\n } else if (client.setupIntegrations) {\n // eslint-disable-next-line deprecation/deprecation\n client.setupIntegrations();\n }\n}\n", "import type {\n Envelope,\n EnvelopeItem,\n EnvelopeItemType,\n Event,\n EventDropReason,\n EventItem,\n InternalBaseTransportOptions,\n Transport,\n TransportMakeRequestResponse,\n TransportRequestExecutor,\n} from '@sentry/types';\nimport type { PromiseBuffer, RateLimits } from '@sentry/utils';\nimport {\n SentryError,\n createEnvelope,\n envelopeItemTypeToDataCategory,\n forEachEnvelopeItem,\n isRateLimited,\n logger,\n makePromiseBuffer,\n resolvedSyncPromise,\n serializeEnvelope,\n updateRateLimits,\n} from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\n\nexport const DEFAULT_TRANSPORT_BUFFER_SIZE = 30;\n\n/**\n * Creates an instance of a Sentry `Transport`\n *\n * @param options\n * @param makeRequest\n */\nexport function createTransport(\n options: InternalBaseTransportOptions,\n makeRequest: TransportRequestExecutor,\n buffer: PromiseBuffer = makePromiseBuffer(\n options.bufferSize || DEFAULT_TRANSPORT_BUFFER_SIZE,\n ),\n): Transport {\n let rateLimits: RateLimits = {};\n const flush = (timeout?: number): PromiseLike => buffer.drain(timeout);\n\n function send(envelope: Envelope): PromiseLike {\n const filteredEnvelopeItems: EnvelopeItem[] = [];\n\n // Drop rate limited items from envelope\n forEachEnvelopeItem(envelope, (item, type) => {\n const dataCategory = envelopeItemTypeToDataCategory(type);\n if (isRateLimited(rateLimits, dataCategory)) {\n const event: Event | undefined = getEventForEnvelopeItem(item, type);\n options.recordDroppedEvent('ratelimit_backoff', dataCategory, event);\n } else {\n filteredEnvelopeItems.push(item);\n }\n });\n\n // Skip sending if envelope is empty after filtering out rate limited events\n if (filteredEnvelopeItems.length === 0) {\n return resolvedSyncPromise();\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const filteredEnvelope: Envelope = createEnvelope(envelope[0], filteredEnvelopeItems as any);\n\n // Creates client report for each item in an envelope\n const recordEnvelopeLoss = (reason: EventDropReason): void => {\n forEachEnvelopeItem(filteredEnvelope, (item, type) => {\n const event: Event | undefined = getEventForEnvelopeItem(item, type);\n options.recordDroppedEvent(reason, envelopeItemTypeToDataCategory(type), event);\n });\n };\n\n const requestTask = (): PromiseLike =>\n makeRequest({ body: serializeEnvelope(filteredEnvelope, options.textEncoder) }).then(\n response => {\n // We don't want to throw on NOK responses, but we want to at least log them\n if (response.statusCode !== undefined && (response.statusCode < 200 || response.statusCode >= 300)) {\n DEBUG_BUILD && logger.warn(`Sentry responded with status code ${response.statusCode} to sent event.`);\n }\n\n rateLimits = updateRateLimits(rateLimits, response);\n return response;\n },\n error => {\n recordEnvelopeLoss('network_error');\n throw error;\n },\n );\n\n return buffer.add(requestTask).then(\n result => result,\n error => {\n if (error instanceof SentryError) {\n DEBUG_BUILD && logger.error('Skipped sending event because buffer is full.');\n recordEnvelopeLoss('queue_overflow');\n return resolvedSyncPromise();\n } else {\n throw error;\n }\n },\n );\n }\n\n // We use this to identifify if the transport is the base transport\n // TODO (v8): Remove this again as we'll no longer need it\n send.__sentry__baseTransport__ = true;\n\n return {\n send,\n flush,\n };\n}\n\nfunction getEventForEnvelopeItem(item: Envelope[1][number], type: EnvelopeItemType): Event | undefined {\n if (type !== 'event' && type !== 'transaction') {\n return undefined;\n }\n\n return Array.isArray(item) ? (item as EventItem)[1] : undefined;\n}\n", "import type { Envelope, InternalBaseTransportOptions, Transport, TransportMakeRequestResponse } from '@sentry/types';\nimport { envelopeContainsItemType, logger, parseRetryAfterHeader } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\n\nexport const MIN_DELAY = 100; // 100 ms\nexport const START_DELAY = 5_000; // 5 seconds\nconst MAX_DELAY = 3.6e6; // 1 hour\n\nfunction log(msg: string, error?: Error): void {\n DEBUG_BUILD && logger.info(`[Offline]: ${msg}`, error);\n}\n\nexport interface OfflineStore {\n insert(env: Envelope): Promise;\n pop(): Promise;\n}\n\nexport type CreateOfflineStore = (options: OfflineTransportOptions) => OfflineStore;\n\nexport interface OfflineTransportOptions extends InternalBaseTransportOptions {\n /**\n * A function that creates the offline store instance.\n */\n createStore?: CreateOfflineStore;\n\n /**\n * Flush the offline store shortly after startup.\n *\n * Defaults: false\n */\n flushAtStartup?: boolean;\n\n /**\n * Called before an event is stored.\n *\n * Return false to drop the envelope rather than store it.\n *\n * @param envelope The envelope that failed to send.\n * @param error The error that occurred.\n * @param retryDelay The current retry delay in milliseconds.\n */\n shouldStore?: (envelope: Envelope, error: Error, retryDelay: number) => boolean | Promise;\n}\n\ntype Timer = number | { unref?: () => void };\n\n/**\n * Wraps a transport and stores and retries events when they fail to send.\n *\n * @param createTransport The transport to wrap.\n */\nexport function makeOfflineTransport(\n createTransport: (options: TO) => Transport,\n): (options: TO & OfflineTransportOptions) => Transport {\n return options => {\n const transport = createTransport(options);\n const store = options.createStore ? options.createStore(options) : undefined;\n\n let retryDelay = START_DELAY;\n let flushTimer: Timer | undefined;\n\n function shouldQueue(env: Envelope, error: Error, retryDelay: number): boolean | Promise {\n // We don't queue Session Replay envelopes because they are:\n // - Ordered and Replay relies on the response status to know when they're successfully sent.\n // - Likely to fill the queue quickly and block other events from being sent.\n // We also want to drop client reports because they can be generated when we retry sending events while offline.\n if (envelopeContainsItemType(env, ['replay_event', 'replay_recording', 'client_report'])) {\n return false;\n }\n\n if (options.shouldStore) {\n return options.shouldStore(env, error, retryDelay);\n }\n\n return true;\n }\n\n function flushIn(delay: number): void {\n if (!store) {\n return;\n }\n\n if (flushTimer) {\n clearTimeout(flushTimer as ReturnType);\n }\n\n flushTimer = setTimeout(async () => {\n flushTimer = undefined;\n\n const found = await store.pop();\n if (found) {\n log('Attempting to send previously queued event');\n void send(found).catch(e => {\n log('Failed to retry sending', e);\n });\n }\n }, delay) as Timer;\n\n // We need to unref the timer in node.js, otherwise the node process never exit.\n if (typeof flushTimer !== 'number' && flushTimer.unref) {\n flushTimer.unref();\n }\n }\n\n function flushWithBackOff(): void {\n if (flushTimer) {\n return;\n }\n\n flushIn(retryDelay);\n\n retryDelay = Math.min(retryDelay * 2, MAX_DELAY);\n }\n\n async function send(envelope: Envelope): Promise {\n try {\n const result = await transport.send(envelope);\n\n let delay = MIN_DELAY;\n\n if (result) {\n // If there's a retry-after header, use that as the next delay.\n if (result.headers && result.headers['retry-after']) {\n delay = parseRetryAfterHeader(result.headers['retry-after']);\n } // If we have a server error, return now so we don't flush the queue.\n else if ((result.statusCode || 0) >= 400) {\n return result;\n }\n }\n\n flushIn(delay);\n retryDelay = START_DELAY;\n return result;\n } catch (e) {\n if (store && (await shouldQueue(envelope, e as Error, retryDelay))) {\n await store.insert(envelope);\n flushWithBackOff();\n log('Error sending. Event queued', e as Error);\n return {};\n } else {\n throw e;\n }\n }\n }\n\n if (options.flushAtStartup) {\n flushWithBackOff();\n }\n\n return {\n send,\n flush: t => transport.flush(t),\n };\n };\n}\n", "import type {\n BaseTransportOptions,\n Envelope,\n EnvelopeItemType,\n Event,\n EventItem,\n Transport,\n TransportMakeRequestResponse,\n} from '@sentry/types';\nimport { createEnvelope, dsnFromString, forEachEnvelopeItem } from '@sentry/utils';\n\nimport { getEnvelopeEndpointWithUrlEncodedAuth } from '../api';\n\ninterface MatchParam {\n /** The envelope to be sent */\n envelope: Envelope;\n /**\n * A function that returns an event from the envelope if one exists. You can optionally pass an array of envelope item\n * types to filter by - only envelopes matching the given types will be multiplexed.\n * Allowed values are: 'event', 'transaction', 'profile', 'replay_event'\n *\n * @param types Defaults to ['event']\n */\n getEvent(types?: EnvelopeItemType[]): Event | undefined;\n}\n\ntype RouteTo = { dsn: string; release: string };\ntype Matcher = (param: MatchParam) => (string | RouteTo)[];\n\n/**\n * Gets an event from an envelope.\n *\n * This is only exported for use in the tests\n */\nexport function eventFromEnvelope(env: Envelope, types: EnvelopeItemType[]): Event | undefined {\n let event: Event | undefined;\n\n forEachEnvelopeItem(env, (item, type) => {\n if (types.includes(type)) {\n event = Array.isArray(item) ? (item as EventItem)[1] : undefined;\n }\n // bail out if we found an event\n return !!event;\n });\n\n return event;\n}\n\n/**\n * Creates a transport that overrides the release on all events.\n */\nfunction makeOverrideReleaseTransport(\n createTransport: (options: TO) => Transport,\n release: string,\n): (options: TO) => Transport {\n return options => {\n const transport = createTransport(options);\n\n return {\n ...transport,\n send: async (envelope: Envelope): Promise => {\n const event = eventFromEnvelope(envelope, ['event', 'transaction', 'profile', 'replay_event']);\n\n if (event) {\n event.release = release;\n }\n return transport.send(envelope);\n },\n };\n };\n}\n\n/** Overrides the DSN in the envelope header */\nfunction overrideDsn(envelope: Envelope, dsn: string): Envelope {\n return createEnvelope(\n dsn\n ? {\n ...envelope[0],\n dsn,\n }\n : envelope[0],\n envelope[1],\n );\n}\n\n/**\n * Creates a transport that can send events to different DSNs depending on the envelope contents.\n */\nexport function makeMultiplexedTransport(\n createTransport: (options: TO) => Transport,\n matcher: Matcher,\n): (options: TO) => Transport {\n return options => {\n const fallbackTransport = createTransport(options);\n const otherTransports = new Map();\n\n function getTransport(dsn: string, release: string | undefined): [string, Transport] | undefined {\n // We create a transport for every unique dsn/release combination as there may be code from multiple releases in\n // use at the same time\n const key = release ? `${dsn}:${release}` : dsn;\n\n let transport = otherTransports.get(key);\n\n if (!transport) {\n const validatedDsn = dsnFromString(dsn);\n if (!validatedDsn) {\n return undefined;\n }\n\n const url = getEnvelopeEndpointWithUrlEncodedAuth(validatedDsn, options.tunnel);\n\n transport = release\n ? makeOverrideReleaseTransport(createTransport, release)({ ...options, url })\n : createTransport({ ...options, url });\n\n otherTransports.set(key, transport);\n }\n\n return [dsn, transport];\n }\n\n async function send(envelope: Envelope): Promise {\n function getEvent(types?: EnvelopeItemType[]): Event | undefined {\n const eventTypes: EnvelopeItemType[] = types && types.length ? types : ['event'];\n return eventFromEnvelope(envelope, eventTypes);\n }\n\n const transports = matcher({ envelope, getEvent })\n .map(result => {\n if (typeof result === 'string') {\n return getTransport(result, undefined);\n } else {\n return getTransport(result.dsn, result.release);\n }\n })\n .filter((t): t is [string, Transport] => !!t);\n\n // If we have no transports to send to, use the fallback transport\n if (transports.length === 0) {\n // Don't override the DSN in the header for the fallback transport. '' is falsy\n transports.push(['', fallbackTransport]);\n }\n\n const results = await Promise.all(\n transports.map(([dsn, transport]) => transport.send(overrideDsn(envelope, dsn))),\n );\n\n return results[0];\n }\n\n async function flush(timeout: number | undefined): Promise {\n const promises = [await fallbackTransport.flush(timeout)];\n for (const [, transport] of otherTransports) {\n promises.push(await transport.flush(timeout));\n }\n\n return promises.every(r => r);\n }\n\n return {\n send,\n flush,\n };\n };\n}\n", "import type { DsnComponents, SpanEnvelope, SpanItem } from '@sentry/types';\nimport type { Span } from '@sentry/types';\nimport { createEnvelope, dsnToString } from '@sentry/utils';\n\n/**\n * Create envelope from Span item.\n */\nexport function createSpanEnvelope(spans: Span[], dsn?: DsnComponents): SpanEnvelope {\n const headers: SpanEnvelope[0] = {\n sent_at: new Date().toISOString(),\n };\n\n if (dsn) {\n headers.dsn = dsnToString(dsn);\n }\n\n const items = spans.map(createSpanItem);\n return createEnvelope(headers, items);\n}\n\nfunction createSpanItem(span: Span): SpanItem {\n const spanHeaders: SpanItem[0] = {\n type: 'span',\n };\n return [spanHeaders, span];\n}\n", "import type { Client, DsnComponents, Hub } from '@sentry/types';\n\n/**\n * Checks whether given url points to Sentry server\n * @param url url to verify\n *\n * TODO(v8): Remove Hub fallback type\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function isSentryRequestUrl(url: string, hubOrClient: Hub | Client | undefined): boolean {\n const client =\n hubOrClient && isHub(hubOrClient)\n ? // eslint-disable-next-line deprecation/deprecation\n hubOrClient.getClient()\n : hubOrClient;\n const dsn = client && client.getDsn();\n const tunnel = client && client.getOptions().tunnel;\n\n return checkDsn(url, dsn) || checkTunnel(url, tunnel);\n}\n\nfunction checkTunnel(url: string, tunnel: string | undefined): boolean {\n if (!tunnel) {\n return false;\n }\n\n return removeTrailingSlash(url) === removeTrailingSlash(tunnel);\n}\n\nfunction checkDsn(url: string, dsn: DsnComponents | undefined): boolean {\n return dsn ? url.includes(dsn.host) : false;\n}\n\nfunction removeTrailingSlash(str: string): string {\n return str[str.length - 1] === '/' ? str.slice(0, -1) : str;\n}\n\n// eslint-disable-next-line deprecation/deprecation\nfunction isHub(hubOrClient: Hub | Client | undefined): hubOrClient is Hub {\n // eslint-disable-next-line deprecation/deprecation\n return (hubOrClient as Hub).getClient !== undefined;\n}\n", "import type { ParameterizedString } from '@sentry/types';\n\n/**\n * Tagged template function which returns paramaterized representation of the message\n * For example: parameterize`This is a log statement with ${x} and ${y} params`, would return:\n * \"__sentry_template_string__\": 'This is a log statement with %s and %s params',\n * \"__sentry_template_values__\": ['first', 'second']\n * @param strings An array of string values splitted between expressions\n * @param values Expressions extracted from template string\n * @returns String with template information in __sentry_template_string__ and __sentry_template_values__ properties\n */\nexport function parameterize(strings: TemplateStringsArray, ...values: string[]): ParameterizedString {\n const formatted = new String(String.raw(strings, ...values)) as ParameterizedString;\n formatted.__sentry_template_string__ = strings.join('\\x00').replace(/%/g, '%%').replace(/\\0/g, '%s');\n formatted.__sentry_template_values__ = values;\n return formatted;\n}\n", "import type { Options } from '@sentry/types';\nimport { SDK_VERSION } from '../version';\n\n/**\n * A builder for the SDK metadata in the options for the SDK initialization.\n *\n * Note: This function is identical to `buildMetadata` in Remix and NextJS and SvelteKit.\n * We don't extract it for bundle size reasons.\n * @see https://github.com/getsentry/sentry-javascript/pull/7404\n * @see https://github.com/getsentry/sentry-javascript/pull/4196\n *\n * If you make changes to this function consider updating the others as well.\n *\n * @param options SDK options object that gets mutated\n * @param names list of package names\n */\nexport function applySdkMetadata(options: Options, name: string, names = [name], source = 'npm'): void {\n const metadata = options._metadata || {};\n\n if (!metadata.sdk) {\n metadata.sdk = {\n name: `sentry.javascript.${name}`,\n packages: names.map(name => ({\n name: `${source}:@sentry/${name}`,\n version: SDK_VERSION,\n })),\n version: SDK_VERSION,\n };\n }\n\n options._metadata = metadata;\n}\n", "import type { Event, StackParser } from '@sentry/types';\nimport { GLOBAL_OBJ } from '@sentry/utils';\n\n/** Keys are source filename/url, values are metadata objects. */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst filenameMetadataMap = new Map();\n/** Set of stack strings that have already been parsed. */\nconst parsedStacks = new Set();\n\nfunction ensureMetadataStacksAreParsed(parser: StackParser): void {\n if (!GLOBAL_OBJ._sentryModuleMetadata) {\n return;\n }\n\n for (const stack of Object.keys(GLOBAL_OBJ._sentryModuleMetadata)) {\n const metadata = GLOBAL_OBJ._sentryModuleMetadata[stack];\n\n if (parsedStacks.has(stack)) {\n continue;\n }\n\n // Ensure this stack doesn't get parsed again\n parsedStacks.add(stack);\n\n const frames = parser(stack);\n\n // Go through the frames starting from the top of the stack and find the first one with a filename\n for (const frame of frames.reverse()) {\n if (frame.filename) {\n // Save the metadata for this filename\n filenameMetadataMap.set(frame.filename, metadata);\n break;\n }\n }\n }\n}\n\n/**\n * Retrieve metadata for a specific JavaScript file URL.\n *\n * Metadata is injected by the Sentry bundler plugins using the `_experiments.moduleMetadata` config option.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function getMetadataForUrl(parser: StackParser, filename: string): any | undefined {\n ensureMetadataStacksAreParsed(parser);\n return filenameMetadataMap.get(filename);\n}\n\n/**\n * Adds metadata to stack frames.\n *\n * Metadata is injected by the Sentry bundler plugins using the `_experiments.moduleMetadata` config option.\n */\nexport function addMetadataToStackFrames(parser: StackParser, event: Event): void {\n try {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n event.exception!.values!.forEach(exception => {\n if (!exception.stacktrace) {\n return;\n }\n\n for (const frame of exception.stacktrace.frames || []) {\n if (!frame.filename) {\n continue;\n }\n\n const metadata = getMetadataForUrl(parser, frame.filename);\n\n if (metadata) {\n frame.module_metadata = metadata;\n }\n }\n });\n } catch (_) {\n // To save bundle size we're just try catching here instead of checking for the existence of all the different objects.\n }\n}\n\n/**\n * Strips metadata from stack frames.\n */\nexport function stripMetadataFromStackFrames(event: Event): void {\n try {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n event.exception!.values!.forEach(exception => {\n if (!exception.stacktrace) {\n return;\n }\n\n for (const frame of exception.stacktrace.frames || []) {\n delete frame.module_metadata;\n }\n });\n } catch (_) {\n // To save bundle size we're just try catching here instead of checking for the existence of all the different objects.\n }\n}\n", "import type { Client, Event, EventHint, EventItem, Integration, IntegrationClass, IntegrationFn } from '@sentry/types';\nimport { forEachEnvelopeItem } from '@sentry/utils';\nimport { convertIntegrationFnToClass, defineIntegration } from '../integration';\n\nimport { addMetadataToStackFrames, stripMetadataFromStackFrames } from '../metadata';\n\nconst INTEGRATION_NAME = 'ModuleMetadata';\n\nconst _moduleMetadataIntegration = (() => {\n return {\n name: INTEGRATION_NAME,\n // TODO v8: Remove this\n setupOnce() {}, // eslint-disable-line @typescript-eslint/no-empty-function\n setup(client) {\n if (typeof client.on !== 'function') {\n return;\n }\n\n // We need to strip metadata from stack frames before sending them to Sentry since these are client side only.\n client.on('beforeEnvelope', envelope => {\n forEachEnvelopeItem(envelope, (item, type) => {\n if (type === 'event') {\n const event = Array.isArray(item) ? (item as EventItem)[1] : undefined;\n\n if (event) {\n stripMetadataFromStackFrames(event);\n item[1] = event;\n }\n }\n });\n });\n },\n\n processEvent(event, _hint, client) {\n const stackParser = client.getOptions().stackParser;\n addMetadataToStackFrames(stackParser, event);\n return event;\n },\n };\n}) satisfies IntegrationFn;\n\nexport const moduleMetadataIntegration = defineIntegration(_moduleMetadataIntegration);\n\n/**\n * Adds module metadata to stack frames.\n *\n * Metadata can be injected by the Sentry bundler plugins using the `_experiments.moduleMetadata` config option.\n *\n * When this integration is added, the metadata passed to the bundler plugin is added to the stack frames of all events\n * under the `module_metadata` property. This can be used to help in tagging or routing of events from different teams\n * our sources\n *\n * @deprecated Use `moduleMetadataIntegration()` instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport const ModuleMetadata = convertIntegrationFnToClass(\n INTEGRATION_NAME,\n moduleMetadataIntegration,\n) as IntegrationClass<\n Integration & {\n setup: (client: Client) => void;\n processEvent: (event: Event, hint: EventHint, client: Client) => Event;\n }\n>;\n", "import type {\n Client,\n Event,\n EventHint,\n Integration,\n IntegrationClass,\n IntegrationFn,\n Transaction,\n} from '@sentry/types';\nimport type { AddRequestDataToEventOptions, TransactionNamingScheme } from '@sentry/utils';\nimport { addRequestDataToEvent, extractPathForTransaction } from '@sentry/utils';\nimport { convertIntegrationFnToClass, defineIntegration } from '../integration';\nimport { spanToJSON } from '../utils/spanUtils';\n\nexport type RequestDataIntegrationOptions = {\n /**\n * Controls what data is pulled from the request and added to the event\n */\n include?: {\n cookies?: boolean;\n data?: boolean;\n headers?: boolean;\n ip?: boolean;\n query_string?: boolean;\n url?: boolean;\n user?:\n | boolean\n | {\n id?: boolean;\n username?: boolean;\n email?: boolean;\n };\n };\n\n /** Whether to identify transactions by parameterized path, parameterized path with method, or handler name */\n transactionNamingScheme?: TransactionNamingScheme;\n};\n\nconst DEFAULT_OPTIONS = {\n include: {\n cookies: true,\n data: true,\n headers: true,\n ip: false,\n query_string: true,\n url: true,\n user: {\n id: true,\n username: true,\n email: true,\n },\n },\n transactionNamingScheme: 'methodPath',\n};\n\nconst INTEGRATION_NAME = 'RequestData';\n\nconst _requestDataIntegration = ((options: RequestDataIntegrationOptions = {}) => {\n const _addRequestData = addRequestDataToEvent;\n const _options: Required = {\n ...DEFAULT_OPTIONS,\n ...options,\n include: {\n // @ts-expect-error It's mad because `method` isn't a known `include` key. (It's only here and not set by default in\n // `addRequestDataToEvent` for legacy reasons. TODO (v8): Change that.)\n method: true,\n ...DEFAULT_OPTIONS.include,\n ...options.include,\n user:\n options.include && typeof options.include.user === 'boolean'\n ? options.include.user\n : {\n ...DEFAULT_OPTIONS.include.user,\n // Unclear why TS still thinks `options.include.user` could be a boolean at this point\n ...((options.include || {}).user as Record),\n },\n },\n };\n\n return {\n name: INTEGRATION_NAME,\n // TODO v8: Remove this\n setupOnce() {}, // eslint-disable-line @typescript-eslint/no-empty-function\n processEvent(event, _hint, client) {\n // Note: In the long run, most of the logic here should probably move into the request data utility functions. For\n // the moment it lives here, though, until https://github.com/getsentry/sentry-javascript/issues/5718 is addressed.\n // (TL;DR: Those functions touch many parts of the repo in many different ways, and need to be clened up. Once\n // that's happened, it will be easier to add this logic in without worrying about unexpected side effects.)\n const { transactionNamingScheme } = _options;\n\n const { sdkProcessingMetadata = {} } = event;\n const req = sdkProcessingMetadata.request;\n\n if (!req) {\n return event;\n }\n\n // The Express request handler takes a similar `include` option to that which can be passed to this integration.\n // If passed there, we store it in `sdkProcessingMetadata`. TODO(v8): Force express and GCP people to use this\n // integration, so that all of this passing and conversion isn't necessary\n const addRequestDataOptions =\n sdkProcessingMetadata.requestDataOptionsFromExpressHandler ||\n sdkProcessingMetadata.requestDataOptionsFromGCPWrapper ||\n convertReqDataIntegrationOptsToAddReqDataOpts(_options);\n\n const processedEvent = _addRequestData(event, req, addRequestDataOptions);\n\n // Transaction events already have the right `transaction` value\n if (event.type === 'transaction' || transactionNamingScheme === 'handler') {\n return processedEvent;\n }\n\n // In all other cases, use the request's associated transaction (if any) to overwrite the event's `transaction`\n // value with a high-quality one\n const reqWithTransaction = req as { _sentryTransaction?: Transaction };\n const transaction = reqWithTransaction._sentryTransaction;\n if (transaction) {\n const name = spanToJSON(transaction).description || '';\n\n // TODO (v8): Remove the nextjs check and just base it on `transactionNamingScheme` for all SDKs. (We have to\n // keep it the way it is for the moment, because changing the names of transactions in Sentry has the potential\n // to break things like alert rules.)\n const shouldIncludeMethodInTransactionName =\n getSDKName(client) === 'sentry.javascript.nextjs'\n ? name.startsWith('/api')\n : transactionNamingScheme !== 'path';\n\n const [transactionValue] = extractPathForTransaction(req, {\n path: true,\n method: shouldIncludeMethodInTransactionName,\n customRoute: name,\n });\n\n processedEvent.transaction = transactionValue;\n }\n\n return processedEvent;\n },\n };\n}) satisfies IntegrationFn;\n\nexport const requestDataIntegration = defineIntegration(_requestDataIntegration);\n\n/**\n * Add data about a request to an event. Primarily for use in Node-based SDKs, but included in `@sentry/integrations`\n * so it can be used in cross-platform SDKs like `@sentry/nextjs`.\n * @deprecated Use `requestDataIntegration()` instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport const RequestData = convertIntegrationFnToClass(INTEGRATION_NAME, requestDataIntegration) as IntegrationClass<\n Integration & { processEvent: (event: Event, hint: EventHint, client: Client) => Event }\n> & {\n new (options?: {\n /**\n * Controls what data is pulled from the request and added to the event\n */\n include?: {\n cookies?: boolean;\n data?: boolean;\n headers?: boolean;\n ip?: boolean;\n query_string?: boolean;\n url?: boolean;\n user?:\n | boolean\n | {\n id?: boolean;\n username?: boolean;\n email?: boolean;\n };\n };\n\n /** Whether to identify transactions by parameterized path, parameterized path with method, or handler name */\n transactionNamingScheme?: TransactionNamingScheme;\n }): Integration;\n};\n\n/** Convert this integration's options to match what `addRequestDataToEvent` expects */\n/** TODO: Can possibly be deleted once https://github.com/getsentry/sentry-javascript/issues/5718 is fixed */\nfunction convertReqDataIntegrationOptsToAddReqDataOpts(\n integrationOptions: Required,\n): AddRequestDataToEventOptions {\n const {\n transactionNamingScheme,\n include: { ip, user, ...requestOptions },\n } = integrationOptions;\n\n const requestIncludeKeys: string[] = [];\n for (const [key, value] of Object.entries(requestOptions)) {\n if (value) {\n requestIncludeKeys.push(key);\n }\n }\n\n let addReqDataUserOpt;\n if (user === undefined) {\n addReqDataUserOpt = true;\n } else if (typeof user === 'boolean') {\n addReqDataUserOpt = user;\n } else {\n const userIncludeKeys: string[] = [];\n for (const [key, value] of Object.entries(user)) {\n if (value) {\n userIncludeKeys.push(key);\n }\n }\n addReqDataUserOpt = userIncludeKeys;\n }\n\n return {\n include: {\n ip,\n user: addReqDataUserOpt,\n request: requestIncludeKeys.length !== 0 ? requestIncludeKeys : undefined,\n transaction: transactionNamingScheme,\n },\n };\n}\n\nfunction getSDKName(client: Client): string | undefined {\n try {\n // For a long chain like this, it's fewer bytes to combine a try-catch with assuming everything is there than to\n // write out a long chain of `a && a.b && a.b.c && ...`\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n return client.getOptions()._metadata!.sdk!.name;\n } catch (err) {\n // In theory we should never get here\n return undefined;\n }\n}\n", "import type { Client, Event, EventHint, Integration, IntegrationClass, IntegrationFn, StackFrame } from '@sentry/types';\nimport { getEventDescription, logger, stringMatchesSomePattern } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\nimport { convertIntegrationFnToClass, defineIntegration } from '../integration';\n\n// \"Script error.\" is hard coded into browsers for errors that it can't read.\n// this is the result of a script being pulled in from an external domain and CORS.\nconst DEFAULT_IGNORE_ERRORS = [\n /^Script error\\.?$/,\n /^Javascript error: Script error\\.? on line 0$/,\n /^ResizeObserver loop completed with undelivered notifications.$/,\n /^Cannot redefine property: googletag$/,\n];\n\nconst DEFAULT_IGNORE_TRANSACTIONS = [\n /^.*\\/healthcheck$/,\n /^.*\\/healthy$/,\n /^.*\\/live$/,\n /^.*\\/ready$/,\n /^.*\\/heartbeat$/,\n /^.*\\/health$/,\n /^.*\\/healthz$/,\n];\n\n/** Options for the InboundFilters integration */\nexport interface InboundFiltersOptions {\n allowUrls: Array;\n denyUrls: Array;\n ignoreErrors: Array;\n ignoreTransactions: Array;\n ignoreInternal: boolean;\n disableErrorDefaults: boolean;\n disableTransactionDefaults: boolean;\n}\n\nconst INTEGRATION_NAME = 'InboundFilters';\nconst _inboundFiltersIntegration = ((options: Partial = {}) => {\n return {\n name: INTEGRATION_NAME,\n // TODO v8: Remove this\n setupOnce() {}, // eslint-disable-line @typescript-eslint/no-empty-function\n processEvent(event, _hint, client) {\n const clientOptions = client.getOptions();\n const mergedOptions = _mergeOptions(options, clientOptions);\n return _shouldDropEvent(event, mergedOptions) ? null : event;\n },\n };\n}) satisfies IntegrationFn;\n\nexport const inboundFiltersIntegration = defineIntegration(_inboundFiltersIntegration);\n\n/**\n * Inbound filters configurable by the user.\n * @deprecated Use `inboundFiltersIntegration()` instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport const InboundFilters = convertIntegrationFnToClass(\n INTEGRATION_NAME,\n inboundFiltersIntegration,\n) as IntegrationClass void }> & {\n new (\n options?: Partial<{\n allowUrls: Array;\n denyUrls: Array;\n ignoreErrors: Array;\n ignoreTransactions: Array;\n ignoreInternal: boolean;\n disableErrorDefaults: boolean;\n disableTransactionDefaults: boolean;\n }>,\n ): Integration;\n};\n\nfunction _mergeOptions(\n internalOptions: Partial = {},\n clientOptions: Partial = {},\n): Partial {\n return {\n allowUrls: [...(internalOptions.allowUrls || []), ...(clientOptions.allowUrls || [])],\n denyUrls: [...(internalOptions.denyUrls || []), ...(clientOptions.denyUrls || [])],\n ignoreErrors: [\n ...(internalOptions.ignoreErrors || []),\n ...(clientOptions.ignoreErrors || []),\n ...(internalOptions.disableErrorDefaults ? [] : DEFAULT_IGNORE_ERRORS),\n ],\n ignoreTransactions: [\n ...(internalOptions.ignoreTransactions || []),\n ...(clientOptions.ignoreTransactions || []),\n ...(internalOptions.disableTransactionDefaults ? [] : DEFAULT_IGNORE_TRANSACTIONS),\n ],\n ignoreInternal: internalOptions.ignoreInternal !== undefined ? internalOptions.ignoreInternal : true,\n };\n}\n\nfunction _shouldDropEvent(event: Event, options: Partial): boolean {\n if (options.ignoreInternal && _isSentryError(event)) {\n DEBUG_BUILD &&\n logger.warn(`Event dropped due to being internal Sentry Error.\\nEvent: ${getEventDescription(event)}`);\n return true;\n }\n if (_isIgnoredError(event, options.ignoreErrors)) {\n DEBUG_BUILD &&\n logger.warn(\n `Event dropped due to being matched by \\`ignoreErrors\\` option.\\nEvent: ${getEventDescription(event)}`,\n );\n return true;\n }\n if (_isIgnoredTransaction(event, options.ignoreTransactions)) {\n DEBUG_BUILD &&\n logger.warn(\n `Event dropped due to being matched by \\`ignoreTransactions\\` option.\\nEvent: ${getEventDescription(event)}`,\n );\n return true;\n }\n if (_isDeniedUrl(event, options.denyUrls)) {\n DEBUG_BUILD &&\n logger.warn(\n `Event dropped due to being matched by \\`denyUrls\\` option.\\nEvent: ${getEventDescription(\n event,\n )}.\\nUrl: ${_getEventFilterUrl(event)}`,\n );\n return true;\n }\n if (!_isAllowedUrl(event, options.allowUrls)) {\n DEBUG_BUILD &&\n logger.warn(\n `Event dropped due to not being matched by \\`allowUrls\\` option.\\nEvent: ${getEventDescription(\n event,\n )}.\\nUrl: ${_getEventFilterUrl(event)}`,\n );\n return true;\n }\n return false;\n}\n\nfunction _isIgnoredError(event: Event, ignoreErrors?: Array): boolean {\n // If event.type, this is not an error\n if (event.type || !ignoreErrors || !ignoreErrors.length) {\n return false;\n }\n\n return _getPossibleEventMessages(event).some(message => stringMatchesSomePattern(message, ignoreErrors));\n}\n\nfunction _isIgnoredTransaction(event: Event, ignoreTransactions?: Array): boolean {\n if (event.type !== 'transaction' || !ignoreTransactions || !ignoreTransactions.length) {\n return false;\n }\n\n const name = event.transaction;\n return name ? stringMatchesSomePattern(name, ignoreTransactions) : false;\n}\n\nfunction _isDeniedUrl(event: Event, denyUrls?: Array): boolean {\n // TODO: Use Glob instead?\n if (!denyUrls || !denyUrls.length) {\n return false;\n }\n const url = _getEventFilterUrl(event);\n return !url ? false : stringMatchesSomePattern(url, denyUrls);\n}\n\nfunction _isAllowedUrl(event: Event, allowUrls?: Array): boolean {\n // TODO: Use Glob instead?\n if (!allowUrls || !allowUrls.length) {\n return true;\n }\n const url = _getEventFilterUrl(event);\n return !url ? true : stringMatchesSomePattern(url, allowUrls);\n}\n\nfunction _getPossibleEventMessages(event: Event): string[] {\n const possibleMessages: string[] = [];\n\n if (event.message) {\n possibleMessages.push(event.message);\n }\n\n let lastException;\n try {\n // @ts-expect-error Try catching to save bundle size\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n lastException = event.exception.values[event.exception.values.length - 1];\n } catch (e) {\n // try catching to save bundle size checking existence of variables\n }\n\n if (lastException) {\n if (lastException.value) {\n possibleMessages.push(lastException.value);\n if (lastException.type) {\n possibleMessages.push(`${lastException.type}: ${lastException.value}`);\n }\n }\n }\n\n if (DEBUG_BUILD && possibleMessages.length === 0) {\n logger.error(`Could not extract message for event ${getEventDescription(event)}`);\n }\n\n return possibleMessages;\n}\n\nfunction _isSentryError(event: Event): boolean {\n try {\n // @ts-expect-error can't be a sentry error if undefined\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return event.exception.values[0].type === 'SentryError';\n } catch (e) {\n // ignore\n }\n return false;\n}\n\nfunction _getLastValidUrl(frames: StackFrame[] = []): string | null {\n for (let i = frames.length - 1; i >= 0; i--) {\n const frame = frames[i];\n\n if (frame && frame.filename !== '' && frame.filename !== '[native code]') {\n return frame.filename || null;\n }\n }\n\n return null;\n}\n\nfunction _getEventFilterUrl(event: Event): string | null {\n try {\n let frames;\n try {\n // @ts-expect-error we only care about frames if the whole thing here is defined\n frames = event.exception.values[0].stacktrace.frames;\n } catch (e) {\n // ignore\n }\n return frames ? _getLastValidUrl(frames) : null;\n } catch (oO) {\n DEBUG_BUILD && logger.error(`Cannot extract url for event ${getEventDescription(event)}`);\n return null;\n }\n}\n", "import type { Client, Integration, IntegrationClass, IntegrationFn, WrappedFunction } from '@sentry/types';\nimport { getOriginalFunction } from '@sentry/utils';\nimport { getClient } from '../exports';\nimport { convertIntegrationFnToClass, defineIntegration } from '../integration';\n\nlet originalFunctionToString: () => void;\n\nconst INTEGRATION_NAME = 'FunctionToString';\n\nconst SETUP_CLIENTS = new WeakMap();\n\nconst _functionToStringIntegration = (() => {\n return {\n name: INTEGRATION_NAME,\n setupOnce() {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n originalFunctionToString = Function.prototype.toString;\n\n // intrinsics (like Function.prototype) might be immutable in some environments\n // e.g. Node with --frozen-intrinsics, XS (an embedded JavaScript engine) or SES (a JavaScript proposal)\n try {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n Function.prototype.toString = function (this: WrappedFunction, ...args: any[]): string {\n const originalFunction = getOriginalFunction(this);\n const context =\n SETUP_CLIENTS.has(getClient() as Client) && originalFunction !== undefined ? originalFunction : this;\n return originalFunctionToString.apply(context, args);\n };\n } catch {\n // ignore errors here, just don't patch this\n }\n },\n setup(client) {\n SETUP_CLIENTS.set(client, true);\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * Patch toString calls to return proper name for wrapped functions.\n *\n * ```js\n * Sentry.init({\n * integrations: [\n * functionToStringIntegration(),\n * ],\n * });\n * ```\n */\nexport const functionToStringIntegration = defineIntegration(_functionToStringIntegration);\n\n/**\n * Patch toString calls to return proper name for wrapped functions.\n *\n * @deprecated Use `functionToStringIntegration()` instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport const FunctionToString = convertIntegrationFnToClass(\n INTEGRATION_NAME,\n functionToStringIntegration,\n) as IntegrationClass void }>;\n\n// eslint-disable-next-line deprecation/deprecation\nexport type FunctionToString = typeof FunctionToString;\n", "import type { Client, Event, EventHint, Integration, IntegrationClass, IntegrationFn } from '@sentry/types';\nimport { applyAggregateErrorsToEvent, exceptionFromError } from '@sentry/utils';\nimport { convertIntegrationFnToClass, defineIntegration } from '../integration';\n\ninterface LinkedErrorsOptions {\n key?: string;\n limit?: number;\n}\n\nconst DEFAULT_KEY = 'cause';\nconst DEFAULT_LIMIT = 5;\n\nconst INTEGRATION_NAME = 'LinkedErrors';\n\nconst _linkedErrorsIntegration = ((options: LinkedErrorsOptions = {}) => {\n const limit = options.limit || DEFAULT_LIMIT;\n const key = options.key || DEFAULT_KEY;\n\n return {\n name: INTEGRATION_NAME,\n // TODO v8: Remove this\n setupOnce() {}, // eslint-disable-line @typescript-eslint/no-empty-function\n preprocessEvent(event, hint, client) {\n const options = client.getOptions();\n\n applyAggregateErrorsToEvent(\n exceptionFromError,\n options.stackParser,\n options.maxValueLength,\n key,\n limit,\n event,\n hint,\n );\n },\n };\n}) satisfies IntegrationFn;\n\nexport const linkedErrorsIntegration = defineIntegration(_linkedErrorsIntegration);\n\n/**\n * Adds SDK info to an event.\n * @deprecated Use `linkedErrorsIntegration()` instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport const LinkedErrors = convertIntegrationFnToClass(INTEGRATION_NAME, linkedErrorsIntegration) as IntegrationClass<\n Integration & { preprocessEvent: (event: Event, hint: EventHint, client: Client) => void }\n> & { new (options?: { key?: string; limit?: number }): Integration };\n", "import type { Client, ClientOptions, MeasurementUnit, MetricsAggregator, Primitive } from '@sentry/types';\nimport { timestampInSeconds } from '@sentry/utils';\nimport { DEFAULT_BROWSER_FLUSH_INTERVAL, SET_METRIC_TYPE } from './constants';\nimport { METRIC_MAP } from './instance';\nimport { updateMetricSummaryOnActiveSpan } from './metric-summary';\nimport type { MetricBucket, MetricType } from './types';\nimport { getBucketKey, sanitizeMetricKey, sanitizeTags, sanitizeUnit } from './utils';\n\n/**\n * A simple metrics aggregator that aggregates metrics in memory and flushes them periodically.\n * Default flush interval is 5 seconds.\n *\n * @experimental This API is experimental and might change in the future.\n */\nexport class BrowserMetricsAggregator implements MetricsAggregator {\n // TODO(@anonrig): Use FinalizationRegistry to have a proper way of flushing the buckets\n // when the aggregator is garbage collected.\n // Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry\n private _buckets: MetricBucket;\n private readonly _interval: ReturnType;\n\n public constructor(private readonly _client: Client) {\n this._buckets = new Map();\n this._interval = setInterval(() => this.flush(), DEFAULT_BROWSER_FLUSH_INTERVAL);\n }\n\n /**\n * @inheritDoc\n */\n public add(\n metricType: MetricType,\n unsanitizedName: string,\n value: number | string,\n unsanitizedUnit: MeasurementUnit | undefined = 'none',\n unsanitizedTags: Record | undefined = {},\n maybeFloatTimestamp: number | undefined = timestampInSeconds(),\n ): void {\n const timestamp = Math.floor(maybeFloatTimestamp);\n const name = sanitizeMetricKey(unsanitizedName);\n const tags = sanitizeTags(unsanitizedTags);\n const unit = sanitizeUnit(unsanitizedUnit as string);\n\n const bucketKey = getBucketKey(metricType, name, unit, tags);\n\n let bucketItem = this._buckets.get(bucketKey);\n // If this is a set metric, we need to calculate the delta from the previous weight.\n const previousWeight = bucketItem && metricType === SET_METRIC_TYPE ? bucketItem.metric.weight : 0;\n\n if (bucketItem) {\n bucketItem.metric.add(value);\n // TODO(abhi): Do we need this check?\n if (bucketItem.timestamp < timestamp) {\n bucketItem.timestamp = timestamp;\n }\n } else {\n bucketItem = {\n // @ts-expect-error we don't need to narrow down the type of value here, saves bundle size.\n metric: new METRIC_MAP[metricType](value),\n timestamp,\n metricType,\n name,\n unit,\n tags,\n };\n this._buckets.set(bucketKey, bucketItem);\n }\n\n // If value is a string, it's a set metric so calculate the delta from the previous weight.\n const val = typeof value === 'string' ? bucketItem.metric.weight - previousWeight : value;\n updateMetricSummaryOnActiveSpan(metricType, name, val, unit, unsanitizedTags, bucketKey);\n }\n\n /**\n * @inheritDoc\n */\n public flush(): void {\n // short circuit if buckets are empty.\n if (this._buckets.size === 0) {\n return;\n }\n\n if (this._client.captureAggregateMetrics) {\n // TODO(@anonrig): Use Object.values() when we support ES6+\n const metricBuckets = Array.from(this._buckets).map(([, bucketItem]) => bucketItem);\n this._client.captureAggregateMetrics(metricBuckets);\n }\n\n this._buckets.clear();\n }\n\n /**\n * @inheritDoc\n */\n public close(): void {\n clearInterval(this._interval);\n this.flush();\n }\n}\n", "import type { Client, ClientOptions, Integration, IntegrationClass, IntegrationFn } from '@sentry/types';\nimport type { BaseClient } from '../baseclient';\nimport { convertIntegrationFnToClass, defineIntegration } from '../integration';\nimport { BrowserMetricsAggregator } from './browser-aggregator';\n\nconst INTEGRATION_NAME = 'MetricsAggregator';\n\nconst _metricsAggregatorIntegration = (() => {\n return {\n name: INTEGRATION_NAME,\n // TODO v8: Remove this\n setupOnce() {}, // eslint-disable-line @typescript-eslint/no-empty-function\n setup(client: BaseClient) {\n client.metricsAggregator = new BrowserMetricsAggregator(client);\n },\n };\n}) satisfies IntegrationFn;\n\nexport const metricsAggregatorIntegration = defineIntegration(_metricsAggregatorIntegration);\n\n/**\n * Enables Sentry metrics monitoring.\n *\n * @experimental This API is experimental and might having breaking changes in the future.\n * @deprecated Use `metricsAggegratorIntegration()` instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport const MetricsAggregator = convertIntegrationFnToClass(\n INTEGRATION_NAME,\n metricsAggregatorIntegration,\n) as IntegrationClass void }>;\n", "import type { ClientOptions, MeasurementUnit, Primitive } from '@sentry/types';\nimport { logger } from '@sentry/utils';\nimport type { BaseClient } from '../baseclient';\nimport { DEBUG_BUILD } from '../debug-build';\nimport { getClient, getCurrentScope } from '../exports';\nimport { spanToJSON } from '../utils/spanUtils';\nimport { COUNTER_METRIC_TYPE, DISTRIBUTION_METRIC_TYPE, GAUGE_METRIC_TYPE, SET_METRIC_TYPE } from './constants';\nimport { MetricsAggregator, metricsAggregatorIntegration } from './integration';\nimport type { MetricType } from './types';\n\ninterface MetricData {\n unit?: MeasurementUnit;\n tags?: Record;\n timestamp?: number;\n}\n\nfunction addToMetricsAggregator(\n metricType: MetricType,\n name: string,\n value: number | string,\n data: MetricData | undefined = {},\n): void {\n const client = getClient>();\n const scope = getCurrentScope();\n if (client) {\n if (!client.metricsAggregator) {\n DEBUG_BUILD &&\n logger.warn('No metrics aggregator enabled. Please add the MetricsAggregator integration to use metrics APIs');\n return;\n }\n const { unit, tags, timestamp } = data;\n const { release, environment } = client.getOptions();\n // eslint-disable-next-line deprecation/deprecation\n const transaction = scope.getTransaction();\n const metricTags: Record = {};\n if (release) {\n metricTags.release = release;\n }\n if (environment) {\n metricTags.environment = environment;\n }\n if (transaction) {\n metricTags.transaction = spanToJSON(transaction).description || '';\n }\n\n DEBUG_BUILD && logger.log(`Adding value of ${value} to ${metricType} metric ${name}`);\n client.metricsAggregator.add(metricType, name, value, unit, { ...metricTags, ...tags }, timestamp);\n }\n}\n\n/**\n * Adds a value to a counter metric\n *\n * @experimental This API is experimental and might have breaking changes in the future.\n */\nexport function increment(name: string, value: number = 1, data?: MetricData): void {\n addToMetricsAggregator(COUNTER_METRIC_TYPE, name, value, data);\n}\n\n/**\n * Adds a value to a distribution metric\n *\n * @experimental This API is experimental and might have breaking changes in the future.\n */\nexport function distribution(name: string, value: number, data?: MetricData): void {\n addToMetricsAggregator(DISTRIBUTION_METRIC_TYPE, name, value, data);\n}\n\n/**\n * Adds a value to a set metric. Value must be a string or integer.\n *\n * @experimental This API is experimental and might have breaking changes in the future.\n */\nexport function set(name: string, value: number | string, data?: MetricData): void {\n addToMetricsAggregator(SET_METRIC_TYPE, name, value, data);\n}\n\n/**\n * Adds a value to a gauge metric\n *\n * @experimental This API is experimental and might have breaking changes in the future.\n */\nexport function gauge(name: string, value: number, data?: MetricData): void {\n addToMetricsAggregator(GAUGE_METRIC_TYPE, name, value, data);\n}\n\nexport const metrics = {\n increment,\n distribution,\n set,\n gauge,\n /** @deprecated Use `metrics.metricsAggregratorIntegration()` instead. */\n // eslint-disable-next-line deprecation/deprecation\n MetricsAggregator,\n metricsAggregatorIntegration,\n};\n", "export type { ClientClass } from './sdk';\nexport type { AsyncContextStrategy, Carrier, Layer, RunWithAsyncContextOptions } from './hub';\nexport type { OfflineStore, OfflineTransportOptions } from './transports/offline';\nexport type { ServerRuntimeClientOptions } from './server-runtime-client';\nexport type { RequestDataIntegrationOptions } from './integrations/requestdata';\nexport type { IntegrationIndex } from './integration';\n\nexport * from './tracing';\nexport * from './semanticAttributes';\nexport { createEventEnvelope, createSessionEnvelope } from './envelope';\nexport {\n addBreadcrumb,\n captureCheckIn,\n withMonitor,\n captureException,\n captureEvent,\n captureMessage,\n close,\n // eslint-disable-next-line deprecation/deprecation\n configureScope,\n flush,\n lastEventId,\n // eslint-disable-next-line deprecation/deprecation\n startTransaction,\n setContext,\n setExtra,\n setExtras,\n setTag,\n setTags,\n setUser,\n withScope,\n withIsolationScope,\n getClient,\n isInitialized,\n getCurrentScope,\n startSession,\n endSession,\n captureSession,\n withActiveSpan,\n} from './exports';\nexport {\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub,\n getIsolationScope,\n getHubFromCarrier,\n // eslint-disable-next-line deprecation/deprecation\n Hub,\n // eslint-disable-next-line deprecation/deprecation\n makeMain,\n getMainCarrier,\n runWithAsyncContext,\n setHubOnCarrier,\n ensureHubOnCarrier,\n setAsyncContextStrategy,\n} from './hub';\nexport { makeSession, closeSession, updateSession } from './session';\nexport { SessionFlusher } from './sessionflusher';\nexport { Scope, getGlobalScope, setGlobalScope } from './scope';\nexport {\n notifyEventProcessors,\n // eslint-disable-next-line deprecation/deprecation\n addGlobalEventProcessor,\n} from './eventProcessors';\nexport { getEnvelopeEndpointWithUrlEncodedAuth, getReportDialogEndpoint } from './api';\nexport { BaseClient, addEventProcessor } from './baseclient';\nexport { ServerRuntimeClient } from './server-runtime-client';\nexport { initAndBind, setCurrentClient } from './sdk';\nexport { createTransport } from './transports/base';\nexport { makeOfflineTransport } from './transports/offline';\nexport { makeMultiplexedTransport } from './transports/multiplexed';\nexport { SDK_VERSION } from './version';\nexport {\n getIntegrationsToSetup,\n addIntegration,\n defineIntegration,\n // eslint-disable-next-line deprecation/deprecation\n convertIntegrationFnToClass,\n} from './integration';\nexport { applyScopeDataToEvent, mergeScopeData } from './utils/applyScopeDataToEvent';\nexport { prepareEvent } from './utils/prepareEvent';\nexport { createCheckInEnvelope } from './checkin';\nexport { createSpanEnvelope } from './span';\nexport { hasTracingEnabled } from './utils/hasTracingEnabled';\nexport { isSentryRequestUrl } from './utils/isSentryRequestUrl';\nexport { handleCallbackErrors } from './utils/handleCallbackErrors';\nexport { parameterize } from './utils/parameterize';\nexport { spanToTraceHeader, spanToJSON, spanIsSampled, spanToTraceContext } from './utils/spanUtils';\nexport { getRootSpan } from './utils/getRootSpan';\nexport { applySdkMetadata } from './utils/sdkMetadata';\nexport { DEFAULT_ENVIRONMENT } from './constants';\n/* eslint-disable deprecation/deprecation */\nexport { ModuleMetadata } from './integrations/metadata';\nexport { RequestData } from './integrations/requestdata';\nexport { InboundFilters } from './integrations/inboundfilters';\nexport { FunctionToString } from './integrations/functiontostring';\nexport { LinkedErrors } from './integrations/linkederrors';\n/* eslint-enable deprecation/deprecation */\nimport * as INTEGRATIONS from './integrations';\nexport { functionToStringIntegration } from './integrations/functiontostring';\nexport { inboundFiltersIntegration } from './integrations/inboundfilters';\nexport { linkedErrorsIntegration } from './integrations/linkederrors';\nexport { moduleMetadataIntegration } from './integrations/metadata';\nexport { requestDataIntegration } from './integrations/requestdata';\nexport { metrics } from './metrics/exports';\n\n/** @deprecated Import the integration function directly, e.g. `inboundFiltersIntegration()` instead of `new Integrations.InboundFilter(). */\nconst Integrations = INTEGRATIONS;\n\n// eslint-disable-next-line deprecation/deprecation\nexport { Integrations };\n", "declare const __DEBUG_BUILD__: boolean;\n\n/**\n * This serves as a build time flag that will be true by default, but false in non-debug builds or if users replace `__SENTRY_DEBUG__` in their generated code.\n *\n * ATTENTION: This constant must never cross package boundaries (i.e. be exported) to guarantee that it can be used for tree shaking.\n */\nexport const DEBUG_BUILD = __DEBUG_BUILD__;\n", "import type { Hub } from '@sentry/types';\n\n/**\n * Check if Sentry auto-instrumentation should be disabled.\n *\n * @param getCurrentHub A method to fetch the current hub\n * @returns boolean\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function shouldDisableAutoInstrumentation(getCurrentHub: () => Hub): boolean {\n // eslint-disable-next-line deprecation/deprecation\n const clientOptions = getCurrentHub().getClient()?.getOptions();\n const instrumenter = clientOptions?.instrumenter || 'sentry';\n\n return instrumenter !== 'sentry';\n}\n", "/* eslint-disable max-lines */\nimport { SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, spanToJSON } from '@sentry/core';\nimport type { Hub, Integration, PolymorphicRequest, Transaction } from '@sentry/types';\nimport {\n GLOBAL_OBJ,\n extractPathForTransaction,\n getNumberOfUrlSegments,\n isRegExp,\n logger,\n stripUrlQueryAndFragment,\n} from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../../common/debug-build';\nimport { shouldDisableAutoInstrumentation } from './utils/node-utils';\n\ntype Method =\n | 'all'\n | 'get'\n | 'post'\n | 'put'\n | 'delete'\n | 'patch'\n | 'options'\n | 'head'\n | 'checkout'\n | 'copy'\n | 'lock'\n | 'merge'\n | 'mkactivity'\n | 'mkcol'\n | 'move'\n | 'm-search'\n | 'notify'\n | 'purge'\n | 'report'\n | 'search'\n | 'subscribe'\n | 'trace'\n | 'unlock'\n | 'unsubscribe'\n | 'use';\n\ntype Router = {\n [method in Method]: (...args: any) => any; // eslint-disable-line @typescript-eslint/no-explicit-any\n};\n\n/* Extend the PolymorphicRequest type with a patched parameter to build a reconstructed route */\ntype PatchedRequest = PolymorphicRequest & { _reconstructedRoute?: string; _hasParameters?: boolean };\n\n/* Types used for patching the express router prototype */\ntype ExpressRouter = Router & {\n _router?: ExpressRouter;\n stack?: Layer[];\n lazyrouter?: () => void;\n settings?: unknown;\n process_params: (\n layer: Layer,\n called: unknown,\n req: PatchedRequest,\n res: ExpressResponse,\n done: () => void,\n ) => unknown;\n};\n\ntype Layer = {\n match: (path: string) => boolean;\n handle_request: (req: PatchedRequest, res: ExpressResponse, next: () => void) => void;\n route?: { path: RouteType | RouteType[] };\n path?: string;\n regexp?: RegExp;\n keys?: { name: string | number; offset: number; optional: boolean }[];\n};\n\ntype RouteType = string | RegExp;\n\ninterface ExpressResponse {\n once(name: string, callback: () => void): void;\n}\n\n/**\n * Internal helper for `__sentry_transaction`\n * @hidden\n */\ninterface SentryTracingResponse {\n __sentry_transaction?: Transaction;\n}\n\n/**\n * Express integration\n *\n * Provides an request and error handler for Express framework as well as tracing capabilities\n */\nexport class Express implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'Express';\n\n /**\n * @inheritDoc\n */\n public name: string;\n\n /**\n * Express App instance\n */\n private readonly _router?: Router;\n private readonly _methods?: Method[];\n\n /**\n * @inheritDoc\n */\n public constructor(options: { app?: Router; router?: Router; methods?: Method[] } = {}) {\n this.name = Express.id;\n this._router = options.router || options.app;\n this._methods = (Array.isArray(options.methods) ? options.methods : []).concat('use');\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line deprecation/deprecation\n public setupOnce(_: unknown, getCurrentHub: () => Hub): void {\n if (!this._router) {\n DEBUG_BUILD && logger.error('ExpressIntegration is missing an Express instance');\n return;\n }\n\n if (shouldDisableAutoInstrumentation(getCurrentHub)) {\n DEBUG_BUILD && logger.log('Express Integration is skipped because of instrumenter configuration.');\n return;\n }\n\n instrumentMiddlewares(this._router, this._methods);\n instrumentRouter(this._router as ExpressRouter);\n }\n}\n\n/**\n * Wraps original middleware function in a tracing call, which stores the info about the call as a span,\n * and finishes it once the middleware is done invoking.\n *\n * Express middlewares have 3 various forms, thus we have to take care of all of them:\n * // sync\n * app.use(function (req, res) { ... })\n * // async\n * app.use(function (req, res, next) { ... })\n * // error handler\n * app.use(function (err, req, res, next) { ... })\n *\n * They all internally delegate to the `router[method]` of the given application instance.\n */\n// eslint-disable-next-line @typescript-eslint/ban-types, @typescript-eslint/no-explicit-any\nfunction wrap(fn: Function, method: Method): (...args: any[]) => void {\n const arity = fn.length;\n\n switch (arity) {\n case 2: {\n return function (this: NodeJS.Global, req: unknown, res: ExpressResponse & SentryTracingResponse): void {\n const transaction = res.__sentry_transaction;\n if (transaction) {\n // eslint-disable-next-line deprecation/deprecation\n const span = transaction.startChild({\n description: fn.name,\n op: `middleware.express.${method}`,\n origin: 'auto.middleware.express',\n });\n res.once('finish', () => {\n span.end();\n });\n }\n return fn.call(this, req, res);\n };\n }\n case 3: {\n return function (\n this: NodeJS.Global,\n req: unknown,\n res: ExpressResponse & SentryTracingResponse,\n next: () => void,\n ): void {\n const transaction = res.__sentry_transaction;\n // eslint-disable-next-line deprecation/deprecation\n const span = transaction?.startChild({\n description: fn.name,\n op: `middleware.express.${method}`,\n origin: 'auto.middleware.express',\n });\n fn.call(this, req, res, function (this: NodeJS.Global, ...args: unknown[]): void {\n span?.end();\n next.call(this, ...args);\n });\n };\n }\n case 4: {\n return function (\n this: NodeJS.Global,\n err: Error,\n req: Request,\n res: Response & SentryTracingResponse,\n next: () => void,\n ): void {\n const transaction = res.__sentry_transaction;\n // eslint-disable-next-line deprecation/deprecation\n const span = transaction?.startChild({\n description: fn.name,\n op: `middleware.express.${method}`,\n origin: 'auto.middleware.express',\n });\n fn.call(this, err, req, res, function (this: NodeJS.Global, ...args: unknown[]): void {\n span?.end();\n next.call(this, ...args);\n });\n };\n }\n default: {\n throw new Error(`Express middleware takes 2-4 arguments. Got: ${arity}`);\n }\n }\n}\n\n/**\n * Takes all the function arguments passed to the original `app` or `router` method, eg. `app.use` or `router.use`\n * and wraps every function, as well as array of functions with a call to our `wrap` method.\n * We have to take care of the arrays as well as iterate over all of the arguments,\n * as `app.use` can accept middlewares in few various forms.\n *\n * app.use([], )\n * app.use([], , ...)\n * app.use([], ...[])\n */\nfunction wrapMiddlewareArgs(args: unknown[], method: Method): unknown[] {\n return args.map((arg: unknown) => {\n if (typeof arg === 'function') {\n return wrap(arg, method);\n }\n\n if (Array.isArray(arg)) {\n return arg.map((a: unknown) => {\n if (typeof a === 'function') {\n return wrap(a, method);\n }\n return a;\n });\n }\n\n return arg;\n });\n}\n\n/**\n * Patches original router to utilize our tracing functionality\n */\nfunction patchMiddleware(router: Router, method: Method): Router {\n const originalCallback = router[method];\n\n router[method] = function (...args: unknown[]): void {\n return originalCallback.call(this, ...wrapMiddlewareArgs(args, method));\n };\n\n return router;\n}\n\n/**\n * Patches original router methods\n */\nfunction instrumentMiddlewares(router: Router, methods: Method[] = []): void {\n methods.forEach((method: Method) => patchMiddleware(router, method));\n}\n\n/**\n * Patches the prototype of Express.Router to accumulate the resolved route\n * if a layer instance's `match` function was called and it returned a successful match.\n *\n * @see https://github.com/expressjs/express/blob/master/lib/router/index.js\n *\n * @param appOrRouter the router instance which can either be an app (i.e. top-level) or a (nested) router.\n */\nfunction instrumentRouter(appOrRouter: ExpressRouter): void {\n // This is how we can distinguish between app and routers\n const isApp = 'settings' in appOrRouter;\n\n // In case the app's top-level router hasn't been initialized yet, we have to do it now\n if (isApp && appOrRouter._router === undefined && appOrRouter.lazyrouter) {\n appOrRouter.lazyrouter();\n }\n\n const router = isApp ? appOrRouter._router : appOrRouter;\n\n if (!router) {\n /*\n If we end up here, this means likely that this integration is used with Express 3 or Express 5.\n For now, we don't support these versions (3 is very old and 5 is still in beta). To support Express 5,\n we'd need to make more changes to the routing instrumentation because the router is no longer part of\n the Express core package but maintained in its own package. The new router has different function\n signatures and works slightly differently, demanding more changes than just taking the router from\n `app.router` instead of `app._router`.\n @see https://github.com/pillarjs/router\n\n TODO: Proper Express 5 support\n */\n DEBUG_BUILD && logger.debug('Cannot instrument router for URL Parameterization (did not find a valid router).');\n DEBUG_BUILD && logger.debug('Routing instrumentation is currently only supported in Express 4.');\n return;\n }\n\n const routerProto = Object.getPrototypeOf(router) as ExpressRouter;\n\n const originalProcessParams = routerProto.process_params;\n routerProto.process_params = function process_params(\n layer: Layer,\n called: unknown,\n req: PatchedRequest,\n res: ExpressResponse & SentryTracingResponse,\n done: () => unknown,\n ) {\n // Base case: We're in the first part of the URL (thus we start with the root '/')\n if (!req._reconstructedRoute) {\n req._reconstructedRoute = '';\n }\n\n // If the layer's partial route has params, is a regex or an array, the route is stored in layer.route.\n const { layerRoutePath, isRegex, isArray, numExtraSegments }: LayerRoutePathInfo = getLayerRoutePathInfo(layer);\n\n if (layerRoutePath || isRegex || isArray) {\n req._hasParameters = true;\n }\n\n // Otherwise, the hardcoded path (i.e. a partial route without params) is stored in layer.path\n let partialRoute;\n\n if (layerRoutePath) {\n partialRoute = layerRoutePath;\n } else {\n /**\n * prevent duplicate segment in _reconstructedRoute param if router match multiple routes before final path\n * example:\n * original url: /api/v1/1234\n * prevent: /api/api/v1/:userId\n * router structure\n * /api -> middleware\n * /api/v1 -> middleware\n * /1234 -> endpoint with param :userId\n * final _reconstructedRoute is /api/v1/:userId\n */\n partialRoute = preventDuplicateSegments(req.originalUrl, req._reconstructedRoute, layer.path) || '';\n }\n\n // Normalize the partial route so that it doesn't contain leading or trailing slashes\n // and exclude empty or '*' wildcard routes.\n // The exclusion of '*' routes is our best effort to not \"pollute\" the transaction name\n // with interim handlers (e.g. ones that check authentication or do other middleware stuff).\n // We want to end up with the parameterized URL of the incoming request without any extraneous path segments.\n const finalPartialRoute = partialRoute\n .split('/')\n .filter(segment => segment.length > 0 && (isRegex || isArray || !segment.includes('*')))\n .join('/');\n\n // If we found a valid partial URL, we append it to the reconstructed route\n if (finalPartialRoute && finalPartialRoute.length > 0) {\n // If the partial route is from a regex route, we append a '/' to close the regex\n req._reconstructedRoute += `/${finalPartialRoute}${isRegex ? '/' : ''}`;\n }\n\n // Now we check if we are in the \"last\" part of the route. We determine this by comparing the\n // number of URL segments from the original URL to that of our reconstructed parameterized URL.\n // If we've reached our final destination, we update the transaction name.\n const urlLength = getNumberOfUrlSegments(stripUrlQueryAndFragment(req.originalUrl || '')) + numExtraSegments;\n const routeLength = getNumberOfUrlSegments(req._reconstructedRoute);\n\n if (urlLength === routeLength) {\n if (!req._hasParameters) {\n if (req._reconstructedRoute !== req.originalUrl) {\n req._reconstructedRoute = req.originalUrl ? stripUrlQueryAndFragment(req.originalUrl) : req.originalUrl;\n }\n }\n\n const transaction = res.__sentry_transaction;\n const attributes = (transaction && spanToJSON(transaction).data) || {};\n if (transaction && attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE] !== 'custom') {\n // If the request URL is '/' or empty, the reconstructed route will be empty.\n // Therefore, we fall back to setting the final route to '/' in this case.\n const finalRoute = req._reconstructedRoute || '/';\n\n const [name, source] = extractPathForTransaction(req, { path: true, method: true, customRoute: finalRoute });\n transaction.updateName(name);\n transaction.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, source);\n }\n }\n\n return originalProcessParams.call(this, layer, called, req, res, done);\n };\n}\n\ntype LayerRoutePathInfo = {\n layerRoutePath?: string;\n isRegex: boolean;\n isArray: boolean;\n numExtraSegments: number;\n};\n\n/**\n * Recreate layer.route.path from layer.regexp and layer.keys.\n * Works until express.js used package path-to-regexp@0.1.7\n * or until layer.keys contain offset attribute\n *\n * @param layer the layer to extract the stringified route from\n *\n * @returns string in layer.route.path structure 'router/:pathParam' or undefined\n */\nexport const extractOriginalRoute = (\n path?: Layer['path'],\n regexp?: Layer['regexp'],\n keys?: Layer['keys'],\n): string | undefined => {\n if (!path || !regexp || !keys || Object.keys(keys).length === 0 || !keys[0]?.offset) {\n return undefined;\n }\n\n const orderedKeys = keys.sort((a, b) => a.offset - b.offset);\n\n // add d flag for getting indices from regexp result\n // eslint-disable-next-line @sentry-internal/sdk/no-regexp-constructor -- regexp comes from express.js\n const pathRegex = new RegExp(regexp, `${regexp.flags}d`);\n /**\n * use custom type cause of TS error with missing indices in RegExpExecArray\n */\n const execResult = pathRegex.exec(path) as (RegExpExecArray & { indices: [number, number][] }) | null;\n\n if (!execResult || !execResult.indices) {\n return undefined;\n }\n /**\n * remove first match from regex cause contain whole layer.path\n */\n const [, ...paramIndices] = execResult.indices;\n\n if (paramIndices.length !== orderedKeys.length) {\n return undefined;\n }\n let resultPath = path;\n let indexShift = 0;\n\n /**\n * iterate param matches from regexp.exec\n */\n paramIndices.forEach((item: [number, number] | undefined, index: number) => {\n /** check if offsets is define because in some cases regex d flag returns undefined */\n if (item) {\n const [startOffset, endOffset] = item;\n /**\n * isolate part before param\n */\n const substr1 = resultPath.substring(0, startOffset - indexShift);\n /**\n * define paramName as replacement in format :pathParam\n */\n const replacement = `:${orderedKeys[index].name}`;\n\n /**\n * isolate part after param\n */\n const substr2 = resultPath.substring(endOffset - indexShift);\n\n /**\n * recreate original path but with param replacement\n */\n resultPath = substr1 + replacement + substr2;\n\n /**\n * calculate new index shift after resultPath was modified\n */\n indexShift = indexShift + (endOffset - startOffset - replacement.length);\n }\n });\n\n return resultPath;\n};\n\n/**\n * Extracts and stringifies the layer's route which can either be a string with parameters (`users/:id`),\n * a RegEx (`/test/`) or an array of strings and regexes (`['/path1', /\\/path[2-5]/, /path/:id]`). Additionally\n * returns extra information about the route, such as if the route is defined as regex or as an array.\n *\n * @param layer the layer to extract the stringified route from\n *\n * @returns an object containing the stringified route, a flag determining if the route was a regex\n * and the number of extra segments to the matched path that are additionally in the route,\n * if the route was an array (defaults to 0).\n */\nfunction getLayerRoutePathInfo(layer: Layer): LayerRoutePathInfo {\n let lrp = layer.route?.path;\n\n const isRegex = isRegExp(lrp);\n const isArray = Array.isArray(lrp);\n\n if (!lrp) {\n // parse node.js major version\n // Next.js will complain if we directly use `proces.versions` here because of edge runtime.\n const [major] = (GLOBAL_OBJ as unknown as NodeJS.Global).process.versions.node.split('.').map(Number);\n\n // allow call extractOriginalRoute only if node version support Regex d flag, node 16+\n if (major >= 16) {\n /**\n * If lrp does not exist try to recreate original layer path from route regexp\n */\n lrp = extractOriginalRoute(layer.path, layer.regexp, layer.keys);\n }\n }\n\n if (!lrp) {\n return { isRegex, isArray, numExtraSegments: 0 };\n }\n\n const numExtraSegments = isArray\n ? Math.max(getNumberOfArrayUrlSegments(lrp as RouteType[]) - getNumberOfUrlSegments(layer.path || ''), 0)\n : 0;\n\n const layerRoutePath = getLayerRoutePathString(isArray, lrp);\n\n return { layerRoutePath, isRegex, isArray, numExtraSegments };\n}\n\n/**\n * Returns the number of URL segments in an array of routes\n *\n * Example: ['/api/test', /\\/api\\/post[0-9]/, '/users/:id/details`] -> 7\n */\nfunction getNumberOfArrayUrlSegments(routesArray: RouteType[]): number {\n return routesArray.reduce((accNumSegments: number, currentRoute: RouteType) => {\n // array members can be a RegEx -> convert them toString\n return accNumSegments + getNumberOfUrlSegments(currentRoute.toString());\n }, 0);\n}\n\n/**\n * Extracts and returns the stringified version of the layers route path\n * Handles route arrays (by joining the paths together) as well as RegExp and normal\n * string values (in the latter case the toString conversion is technically unnecessary but\n * it doesn't hurt us either).\n */\nfunction getLayerRoutePathString(isArray: boolean, lrp?: RouteType | RouteType[]): string | undefined {\n if (isArray) {\n return (lrp as RouteType[]).map(r => r.toString()).join(',');\n }\n return lrp && lrp.toString();\n}\n\n/**\n * remove duplicate segment contain in layerPath against reconstructedRoute,\n * and return only unique segment that can be added into reconstructedRoute\n */\nexport function preventDuplicateSegments(\n originalUrl?: string,\n reconstructedRoute?: string,\n layerPath?: string,\n): string | undefined {\n // filter query params\n const normalizeURL = stripUrlQueryAndFragment(originalUrl || '');\n const originalUrlSplit = normalizeURL?.split('/').filter(v => !!v);\n let tempCounter = 0;\n const currentOffset = reconstructedRoute?.split('/').filter(v => !!v).length || 0;\n const result = layerPath\n ?.split('/')\n .filter(segment => {\n if (originalUrlSplit?.[currentOffset + tempCounter] === segment) {\n tempCounter += 1;\n return true;\n }\n return false;\n })\n .join('/');\n return result;\n}\n", "import type { Hub } from '@sentry/core';\nimport type { EventProcessor } from '@sentry/types';\nimport { fill, isThenable, loadModule, logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../../common/debug-build';\nimport type { LazyLoadedIntegration } from './lazy';\nimport { shouldDisableAutoInstrumentation } from './utils/node-utils';\n\ntype PgClientQuery = (\n config: unknown,\n values?: unknown,\n callback?: (err: unknown, result: unknown) => void,\n) => void | Promise;\n\ninterface PgClient {\n prototype: {\n query: PgClientQuery;\n };\n}\n\ninterface PgClientThis {\n database?: string;\n host?: string;\n port?: number;\n user?: string;\n}\n\ninterface PgOptions {\n usePgNative?: boolean;\n /**\n * Supply your postgres module directly, instead of having Sentry attempt automatic resolution.\n * Use this if you (a) use a module that's not `pg`, or (b) use a bundler that breaks resolution (e.g. esbuild).\n *\n * Usage:\n * ```\n * import pg from 'pg';\n *\n * Sentry.init({\n * integrations: [new Sentry.Integrations.Postgres({ module: pg })],\n * });\n * ```\n */\n module?: PGModule;\n}\n\ntype PGModule = { Client: PgClient; native: { Client: PgClient } | null };\n\n/** Tracing integration for node-postgres package */\nexport class Postgres implements LazyLoadedIntegration {\n /**\n * @inheritDoc\n */\n public static id: string = 'Postgres';\n\n /**\n * @inheritDoc\n */\n public name: string;\n\n private _usePgNative: boolean;\n\n private _module?: PGModule;\n\n public constructor(options: PgOptions = {}) {\n this.name = Postgres.id;\n this._usePgNative = !!options.usePgNative;\n this._module = options.module;\n }\n\n /** @inheritdoc */\n public loadDependency(): PGModule | undefined {\n return (this._module = this._module || loadModule('pg'));\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line deprecation/deprecation\n public setupOnce(_: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void {\n if (shouldDisableAutoInstrumentation(getCurrentHub)) {\n DEBUG_BUILD && logger.log('Postgres Integration is skipped because of instrumenter configuration.');\n return;\n }\n\n const pkg = this.loadDependency();\n\n if (!pkg) {\n DEBUG_BUILD && logger.error('Postgres Integration was unable to require `pg` package.');\n return;\n }\n\n const Client = this._usePgNative ? pkg.native?.Client : pkg.Client;\n\n if (!Client) {\n DEBUG_BUILD && logger.error(\"Postgres Integration was unable to access 'pg-native' bindings.\");\n return;\n }\n\n /**\n * function (query, callback) => void\n * function (query, params, callback) => void\n * function (query) => Promise\n * function (query, params) => Promise\n * function (pg.Cursor) => pg.Cursor\n */\n fill(Client.prototype, 'query', function (orig: PgClientQuery) {\n return function (this: PgClientThis, config: unknown, values: unknown, callback: unknown) {\n // eslint-disable-next-line deprecation/deprecation\n const scope = getCurrentHub().getScope();\n // eslint-disable-next-line deprecation/deprecation\n const parentSpan = scope.getSpan();\n\n const data: Record = {\n 'db.system': 'postgresql',\n };\n\n try {\n if (this.database) {\n data['db.name'] = this.database;\n }\n if (this.host) {\n data['server.address'] = this.host;\n }\n if (this.port) {\n data['server.port'] = this.port;\n }\n if (this.user) {\n data['db.user'] = this.user;\n }\n } catch (e) {\n // ignore\n }\n\n // eslint-disable-next-line deprecation/deprecation\n const span = parentSpan?.startChild({\n description: typeof config === 'string' ? config : (config as { text: string }).text,\n op: 'db',\n origin: 'auto.db.postgres',\n data,\n });\n\n if (typeof callback === 'function') {\n return orig.call(this, config, values, function (err: Error, result: unknown) {\n span?.end();\n callback(err, result);\n });\n }\n\n if (typeof values === 'function') {\n return orig.call(this, config, function (err: Error, result: unknown) {\n span?.end();\n values(err, result);\n });\n }\n\n const rv = typeof values !== 'undefined' ? orig.call(this, config, values) : orig.call(this, config);\n\n if (isThenable(rv)) {\n return rv.then((res: unknown) => {\n span?.end();\n return res;\n });\n }\n\n span?.end();\n return rv;\n };\n });\n }\n}\n", "import type { Hub } from '@sentry/core';\nimport type { EventProcessor, Span } from '@sentry/types';\nimport { fill, loadModule, logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../../common/debug-build';\nimport type { LazyLoadedIntegration } from './lazy';\nimport { shouldDisableAutoInstrumentation } from './utils/node-utils';\n\ninterface MysqlConnection {\n prototype: {\n connect: () => void;\n };\n createQuery: () => void;\n}\n\ninterface MysqlConnectionConfig {\n host: string;\n port: number;\n user: string;\n}\n\n/** Tracing integration for node-mysql package */\nexport class Mysql implements LazyLoadedIntegration {\n /**\n * @inheritDoc\n */\n public static id: string = 'Mysql';\n\n /**\n * @inheritDoc\n */\n public name: string;\n\n private _module?: MysqlConnection;\n\n public constructor() {\n this.name = Mysql.id;\n }\n\n /** @inheritdoc */\n public loadDependency(): MysqlConnection | undefined {\n return (this._module = this._module || loadModule('mysql/lib/Connection.js'));\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line deprecation/deprecation\n public setupOnce(_: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void {\n if (shouldDisableAutoInstrumentation(getCurrentHub)) {\n DEBUG_BUILD && logger.log('Mysql Integration is skipped because of instrumenter configuration.');\n return;\n }\n\n const pkg = this.loadDependency();\n\n if (!pkg) {\n DEBUG_BUILD && logger.error('Mysql Integration was unable to require `mysql` package.');\n return;\n }\n\n let mySqlConfig: MysqlConnectionConfig | undefined = undefined;\n\n try {\n pkg.prototype.connect = new Proxy(pkg.prototype.connect, {\n apply(wrappingTarget, thisArg: { config: MysqlConnectionConfig }, args) {\n if (!mySqlConfig) {\n mySqlConfig = thisArg.config;\n }\n return wrappingTarget.apply(thisArg, args);\n },\n });\n } catch (e) {\n DEBUG_BUILD && logger.error('Mysql Integration was unable to instrument `mysql` config.');\n }\n\n function spanDataFromConfig(): Record {\n if (!mySqlConfig) {\n return {};\n }\n return {\n 'server.address': mySqlConfig.host,\n 'server.port': mySqlConfig.port,\n 'db.user': mySqlConfig.user,\n };\n }\n\n function finishSpan(span: Span | undefined): void {\n if (!span) {\n return;\n }\n\n const data = spanDataFromConfig();\n Object.keys(data).forEach(key => {\n span.setAttribute(key, data[key]);\n });\n\n span.end();\n }\n\n // The original function will have one of these signatures:\n // function (callback) => void\n // function (options, callback) => void\n // function (options, values, callback) => void\n fill(pkg, 'createQuery', function (orig: () => void) {\n return function (this: unknown, options: unknown, values: unknown, callback: unknown) {\n // eslint-disable-next-line deprecation/deprecation\n const scope = getCurrentHub().getScope();\n // eslint-disable-next-line deprecation/deprecation\n const parentSpan = scope.getSpan();\n\n // eslint-disable-next-line deprecation/deprecation\n const span = parentSpan?.startChild({\n description: typeof options === 'string' ? options : (options as { sql: string }).sql,\n op: 'db',\n origin: 'auto.db.mysql',\n data: {\n 'db.system': 'mysql',\n },\n });\n\n if (typeof callback === 'function') {\n return orig.call(this, options, values, function (err: Error, result: unknown, fields: unknown) {\n finishSpan(span);\n callback(err, result, fields);\n });\n }\n\n if (typeof values === 'function') {\n return orig.call(this, options, function (err: Error, result: unknown, fields: unknown) {\n finishSpan(span);\n values(err, result, fields);\n });\n }\n\n // streaming, no callback!\n const query = orig.call(this, options, values) as { on: (event: string, callback: () => void) => void };\n\n query.on('end', () => {\n finishSpan(span);\n });\n\n return query;\n };\n });\n }\n}\n", "import type { Hub } from '@sentry/core';\nimport type { EventProcessor, SpanContext } from '@sentry/types';\nimport { fill, isThenable, loadModule, logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../../common/debug-build';\nimport type { LazyLoadedIntegration } from './lazy';\nimport { shouldDisableAutoInstrumentation } from './utils/node-utils';\n\n// This allows us to use the same array for both defaults options and the type itself.\n// (note `as const` at the end to make it a union of string literal types (i.e. \"a\" | \"b\" | ... )\n// and not just a string[])\ntype Operation = (typeof OPERATIONS)[number];\nconst OPERATIONS = [\n 'aggregate', // aggregate(pipeline, options, callback)\n 'bulkWrite', // bulkWrite(operations, options, callback)\n 'countDocuments', // countDocuments(query, options, callback)\n 'createIndex', // createIndex(fieldOrSpec, options, callback)\n 'createIndexes', // createIndexes(indexSpecs, options, callback)\n 'deleteMany', // deleteMany(filter, options, callback)\n 'deleteOne', // deleteOne(filter, options, callback)\n 'distinct', // distinct(key, query, options, callback)\n 'drop', // drop(options, callback)\n 'dropIndex', // dropIndex(indexName, options, callback)\n 'dropIndexes', // dropIndexes(options, callback)\n 'estimatedDocumentCount', // estimatedDocumentCount(options, callback)\n 'find', // find(query, options, callback)\n 'findOne', // findOne(query, options, callback)\n 'findOneAndDelete', // findOneAndDelete(filter, options, callback)\n 'findOneAndReplace', // findOneAndReplace(filter, replacement, options, callback)\n 'findOneAndUpdate', // findOneAndUpdate(filter, update, options, callback)\n 'indexes', // indexes(options, callback)\n 'indexExists', // indexExists(indexes, options, callback)\n 'indexInformation', // indexInformation(options, callback)\n 'initializeOrderedBulkOp', // initializeOrderedBulkOp(options, callback)\n 'insertMany', // insertMany(docs, options, callback)\n 'insertOne', // insertOne(doc, options, callback)\n 'isCapped', // isCapped(options, callback)\n 'mapReduce', // mapReduce(map, reduce, options, callback)\n 'options', // options(options, callback)\n 'parallelCollectionScan', // parallelCollectionScan(options, callback)\n 'rename', // rename(newName, options, callback)\n 'replaceOne', // replaceOne(filter, doc, options, callback)\n 'stats', // stats(options, callback)\n 'updateMany', // updateMany(filter, update, options, callback)\n 'updateOne', // updateOne(filter, update, options, callback)\n] as const;\n\n// All of the operations above take `options` and `callback` as their final parameters, but some of them\n// take additional parameters as well. For those operations, this is a map of\n// { : [] }, as a way to know what to call the operation's\n// positional arguments when we add them to the span's `data` object later\nconst OPERATION_SIGNATURES: {\n [op in Operation]?: string[];\n} = {\n // aggregate intentionally not included because `pipeline` arguments are too complex to serialize well\n // see https://github.com/getsentry/sentry-javascript/pull/3102\n bulkWrite: ['operations'],\n countDocuments: ['query'],\n createIndex: ['fieldOrSpec'],\n createIndexes: ['indexSpecs'],\n deleteMany: ['filter'],\n deleteOne: ['filter'],\n distinct: ['key', 'query'],\n dropIndex: ['indexName'],\n find: ['query'],\n findOne: ['query'],\n findOneAndDelete: ['filter'],\n findOneAndReplace: ['filter', 'replacement'],\n findOneAndUpdate: ['filter', 'update'],\n indexExists: ['indexes'],\n insertMany: ['docs'],\n insertOne: ['doc'],\n mapReduce: ['map', 'reduce'],\n rename: ['newName'],\n replaceOne: ['filter', 'doc'],\n updateMany: ['filter', 'update'],\n updateOne: ['filter', 'update'],\n};\n\ninterface MongoCollection {\n collectionName: string;\n dbName: string;\n namespace: string;\n prototype: {\n [operation in Operation]: (...args: unknown[]) => unknown;\n };\n}\n\ninterface MongoOptions {\n operations?: Operation[];\n describeOperations?: boolean | Operation[];\n useMongoose?: boolean;\n}\n\ninterface MongoCursor {\n once(event: 'close', listener: () => void): void;\n}\n\nfunction isCursor(maybeCursor: MongoCursor): maybeCursor is MongoCursor {\n return maybeCursor && typeof maybeCursor === 'object' && maybeCursor.once && typeof maybeCursor.once === 'function';\n}\n\ntype MongoModule = { Collection: MongoCollection };\n\n/** Tracing integration for mongo package */\nexport class Mongo implements LazyLoadedIntegration {\n /**\n * @inheritDoc\n */\n public static id: string = 'Mongo';\n\n /**\n * @inheritDoc\n */\n public name: string;\n\n private _operations: Operation[];\n private _describeOperations?: boolean | Operation[];\n private _useMongoose: boolean;\n\n private _module?: MongoModule;\n\n /**\n * @inheritDoc\n */\n public constructor(options: MongoOptions = {}) {\n this.name = Mongo.id;\n this._operations = Array.isArray(options.operations) ? options.operations : (OPERATIONS as unknown as Operation[]);\n this._describeOperations = 'describeOperations' in options ? options.describeOperations : true;\n this._useMongoose = !!options.useMongoose;\n }\n\n /** @inheritdoc */\n public loadDependency(): MongoModule | undefined {\n const moduleName = this._useMongoose ? 'mongoose' : 'mongodb';\n return (this._module = this._module || loadModule(moduleName));\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line deprecation/deprecation\n public setupOnce(_: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void {\n if (shouldDisableAutoInstrumentation(getCurrentHub)) {\n DEBUG_BUILD && logger.log('Mongo Integration is skipped because of instrumenter configuration.');\n return;\n }\n\n const pkg = this.loadDependency();\n\n if (!pkg) {\n const moduleName = this._useMongoose ? 'mongoose' : 'mongodb';\n DEBUG_BUILD && logger.error(`Mongo Integration was unable to require \\`${moduleName}\\` package.`);\n return;\n }\n\n this._instrumentOperations(pkg.Collection, this._operations, getCurrentHub);\n }\n\n /**\n * Patches original collection methods\n */\n // eslint-disable-next-line deprecation/deprecation\n private _instrumentOperations(collection: MongoCollection, operations: Operation[], getCurrentHub: () => Hub): void {\n operations.forEach((operation: Operation) => this._patchOperation(collection, operation, getCurrentHub));\n }\n\n /**\n * Patches original collection to utilize our tracing functionality\n */\n // eslint-disable-next-line deprecation/deprecation\n private _patchOperation(collection: MongoCollection, operation: Operation, getCurrentHub: () => Hub): void {\n if (!(operation in collection.prototype)) return;\n\n const getSpanContext = this._getSpanContextFromOperationArguments.bind(this);\n\n fill(collection.prototype, operation, function (orig: () => void | Promise) {\n return function (this: unknown, ...args: unknown[]) {\n const lastArg = args[args.length - 1];\n // eslint-disable-next-line deprecation/deprecation\n const hub = getCurrentHub();\n // eslint-disable-next-line deprecation/deprecation\n const scope = hub.getScope();\n // eslint-disable-next-line deprecation/deprecation\n const client = hub.getClient();\n // eslint-disable-next-line deprecation/deprecation\n const parentSpan = scope.getSpan();\n\n const sendDefaultPii = client?.getOptions().sendDefaultPii;\n\n // Check if the operation was passed a callback. (mapReduce requires a different check, as\n // its (non-callback) arguments can also be functions.)\n if (typeof lastArg !== 'function' || (operation === 'mapReduce' && args.length === 2)) {\n // eslint-disable-next-line deprecation/deprecation\n const span = parentSpan?.startChild(getSpanContext(this, operation, args, sendDefaultPii));\n const maybePromiseOrCursor = orig.call(this, ...args);\n\n if (isThenable(maybePromiseOrCursor)) {\n return maybePromiseOrCursor.then((res: unknown) => {\n span?.end();\n return res;\n });\n }\n // If the operation returns a Cursor\n // we need to attach a listener to it to finish the span when the cursor is closed.\n else if (isCursor(maybePromiseOrCursor)) {\n const cursor = maybePromiseOrCursor as MongoCursor;\n\n try {\n cursor.once('close', () => {\n span?.end();\n });\n } catch (e) {\n // If the cursor is already closed, `once` will throw an error. In that case, we can\n // finish the span immediately.\n span?.end();\n }\n\n return cursor;\n } else {\n span?.end();\n return maybePromiseOrCursor;\n }\n }\n\n // eslint-disable-next-line deprecation/deprecation\n const span = parentSpan?.startChild(getSpanContext(this, operation, args.slice(0, -1)));\n\n return orig.call(this, ...args.slice(0, -1), function (err: Error, result: unknown) {\n span?.end();\n lastArg(err, result);\n });\n };\n });\n }\n\n /**\n * Form a SpanContext based on the user input to a given operation.\n */\n private _getSpanContextFromOperationArguments(\n collection: MongoCollection,\n operation: Operation,\n args: unknown[],\n sendDefaultPii: boolean | undefined = false,\n ): SpanContext {\n const data: { [key: string]: string } = {\n 'db.system': 'mongodb',\n 'db.name': collection.dbName,\n 'db.operation': operation,\n 'db.mongodb.collection': collection.collectionName,\n };\n const spanContext: SpanContext = {\n op: 'db',\n // TODO v8: Use `${collection.collectionName}.${operation}`\n origin: 'auto.db.mongo',\n description: operation,\n data,\n };\n\n // If the operation takes no arguments besides `options` and `callback`, or if argument\n // collection is disabled for this operation, just return early.\n const signature = OPERATION_SIGNATURES[operation];\n const shouldDescribe = Array.isArray(this._describeOperations)\n ? this._describeOperations.includes(operation)\n : this._describeOperations;\n\n if (!signature || !shouldDescribe || !sendDefaultPii) {\n return spanContext;\n }\n\n try {\n // Special case for `mapReduce`, as the only one accepting functions as arguments.\n if (operation === 'mapReduce') {\n const [map, reduce] = args as { name?: string }[];\n data[signature[0]] = typeof map === 'string' ? map : map.name || '';\n data[signature[1]] = typeof reduce === 'string' ? reduce : reduce.name || '';\n } else {\n for (let i = 0; i < signature.length; i++) {\n data[`db.mongodb.${signature[i]}`] = JSON.stringify(args[i]);\n }\n }\n } catch (_oO) {\n // no-empty\n }\n\n return spanContext;\n }\n}\n", "import { SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, getCurrentHub, startSpan } from '@sentry/core';\nimport type { Integration } from '@sentry/types';\nimport { addNonEnumerableProperty, logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../../common/debug-build';\nimport { shouldDisableAutoInstrumentation } from './utils/node-utils';\n\ntype PrismaAction =\n | 'findUnique'\n | 'findMany'\n | 'findFirst'\n | 'create'\n | 'createMany'\n | 'update'\n | 'updateMany'\n | 'upsert'\n | 'delete'\n | 'deleteMany'\n | 'executeRaw'\n | 'queryRaw'\n | 'aggregate'\n | 'count'\n | 'runCommandRaw';\n\ninterface PrismaMiddlewareParams {\n model?: unknown;\n action: PrismaAction;\n args: unknown;\n dataPath: string[];\n runInTransaction: boolean;\n}\n\ntype PrismaMiddleware = (\n params: PrismaMiddlewareParams,\n next: (params: PrismaMiddlewareParams) => Promise,\n) => Promise;\n\ninterface PrismaClient {\n _sentryInstrumented?: boolean;\n _engineConfig?: {\n activeProvider?: string;\n clientVersion?: string;\n };\n $use: (cb: PrismaMiddleware) => void;\n}\n\nfunction isValidPrismaClient(possibleClient: unknown): possibleClient is PrismaClient {\n return !!possibleClient && !!(possibleClient as PrismaClient)['$use'];\n}\n\n/** Tracing integration for @prisma/client package */\nexport class Prisma implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'Prisma';\n\n /**\n * @inheritDoc\n */\n public name: string;\n\n /**\n * @inheritDoc\n */\n public constructor(options: { client?: unknown } = {}) {\n this.name = Prisma.id;\n\n // We instrument the PrismaClient inside the constructor and not inside `setupOnce` because in some cases of server-side\n // bundling (Next.js) multiple Prisma clients can be instantiated, even though users don't intend to. When instrumenting\n // in setupOnce we can only ever instrument one client.\n // https://github.com/getsentry/sentry-javascript/issues/7216#issuecomment-1602375012\n // In the future we might explore providing a dedicated PrismaClient middleware instead of this hack.\n if (isValidPrismaClient(options.client) && !options.client._sentryInstrumented) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n addNonEnumerableProperty(options.client as any, '_sentryInstrumented', true);\n\n const clientData: Record = {};\n try {\n const engineConfig = (options.client as PrismaClient)._engineConfig;\n if (engineConfig) {\n const { activeProvider, clientVersion } = engineConfig;\n if (activeProvider) {\n clientData['db.system'] = activeProvider;\n }\n if (clientVersion) {\n clientData['db.prisma.version'] = clientVersion;\n }\n }\n } catch (e) {\n // ignore\n }\n\n options.client.$use((params, next: (params: PrismaMiddlewareParams) => Promise) => {\n // eslint-disable-next-line deprecation/deprecation\n if (shouldDisableAutoInstrumentation(getCurrentHub)) {\n return next(params);\n }\n\n const action = params.action;\n const model = params.model;\n\n return startSpan(\n {\n name: model ? `${model} ${action}` : action,\n onlyIfParent: true,\n op: 'db.prisma',\n attributes: {\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.db.prisma',\n },\n data: { ...clientData, 'db.operation': action },\n },\n () => next(params),\n );\n });\n } else {\n DEBUG_BUILD &&\n logger.warn('Unsupported Prisma client provided to PrismaIntegration. Provided client:', options.client);\n }\n }\n\n /**\n * @inheritDoc\n */\n public setupOnce(): void {\n // Noop - here for backwards compatibility\n }\n}\n", "import type { Hub } from '@sentry/core';\nimport type { EventProcessor } from '@sentry/types';\nimport { fill, isThenable, loadModule, logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../../common/debug-build';\nimport type { LazyLoadedIntegration } from './lazy';\nimport { shouldDisableAutoInstrumentation } from './utils/node-utils';\n\ntype GraphQLModule = {\n [method: string]: (...args: unknown[]) => unknown;\n};\n\n/** Tracing integration for graphql package */\nexport class GraphQL implements LazyLoadedIntegration {\n /**\n * @inheritDoc\n */\n public static id: string = 'GraphQL';\n\n /**\n * @inheritDoc\n */\n public name: string;\n\n private _module?: GraphQLModule;\n\n public constructor() {\n this.name = GraphQL.id;\n }\n\n /** @inheritdoc */\n public loadDependency(): GraphQLModule | undefined {\n return (this._module = this._module || loadModule('graphql/execution/execute.js'));\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line deprecation/deprecation\n public setupOnce(_: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void {\n if (shouldDisableAutoInstrumentation(getCurrentHub)) {\n DEBUG_BUILD && logger.log('GraphQL Integration is skipped because of instrumenter configuration.');\n return;\n }\n\n const pkg = this.loadDependency();\n\n if (!pkg) {\n DEBUG_BUILD && logger.error('GraphQL Integration was unable to require graphql/execution package.');\n return;\n }\n\n fill(pkg, 'execute', function (orig: () => void | Promise) {\n return function (this: unknown, ...args: unknown[]) {\n // eslint-disable-next-line deprecation/deprecation\n const scope = getCurrentHub().getScope();\n // eslint-disable-next-line deprecation/deprecation\n const parentSpan = scope.getSpan();\n\n // eslint-disable-next-line deprecation/deprecation\n const span = parentSpan?.startChild({\n description: 'execute',\n op: 'graphql.execute',\n origin: 'auto.graphql.graphql',\n });\n\n // eslint-disable-next-line deprecation/deprecation\n scope?.setSpan(span);\n\n const rv = orig.call(this, ...args);\n\n if (isThenable(rv)) {\n return rv.then((res: unknown) => {\n span?.end();\n // eslint-disable-next-line deprecation/deprecation\n scope?.setSpan(parentSpan);\n\n return res;\n });\n }\n\n span?.end();\n // eslint-disable-next-line deprecation/deprecation\n scope?.setSpan(parentSpan);\n return rv;\n };\n });\n }\n}\n", "import type { Hub } from '@sentry/core';\nimport type { EventProcessor } from '@sentry/types';\nimport { arrayify, fill, isThenable, loadModule, logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../../common/debug-build';\nimport type { LazyLoadedIntegration } from './lazy';\nimport { shouldDisableAutoInstrumentation } from './utils/node-utils';\n\ninterface ApolloOptions {\n useNestjs?: boolean;\n}\n\ntype ApolloResolverGroup = {\n [key: string]: () => unknown;\n};\n\ntype ApolloModelResolvers = {\n [key: string]: ApolloResolverGroup;\n};\n\ntype GraphQLModule = {\n GraphQLFactory: {\n prototype: {\n create: (resolvers: ApolloModelResolvers[]) => unknown;\n };\n };\n};\n\ntype ApolloModule = {\n ApolloServerBase: {\n prototype: {\n constructSchema: (config: unknown) => unknown;\n };\n };\n};\n\n/** Tracing integration for Apollo */\nexport class Apollo implements LazyLoadedIntegration {\n /**\n * @inheritDoc\n */\n public static id: string = 'Apollo';\n\n /**\n * @inheritDoc\n */\n public name: string;\n\n private readonly _useNest: boolean;\n\n private _module?: GraphQLModule & ApolloModule;\n\n /**\n * @inheritDoc\n */\n public constructor(\n options: ApolloOptions = {\n useNestjs: false,\n },\n ) {\n this.name = Apollo.id;\n this._useNest = !!options.useNestjs;\n }\n\n /** @inheritdoc */\n public loadDependency(): (GraphQLModule & ApolloModule) | undefined {\n if (this._useNest) {\n this._module = this._module || loadModule('@nestjs/graphql');\n } else {\n this._module = this._module || loadModule('apollo-server-core');\n }\n\n return this._module;\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line deprecation/deprecation\n public setupOnce(_: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void {\n if (shouldDisableAutoInstrumentation(getCurrentHub)) {\n DEBUG_BUILD && logger.log('Apollo Integration is skipped because of instrumenter configuration.');\n return;\n }\n\n if (this._useNest) {\n const pkg = this.loadDependency();\n\n if (!pkg) {\n DEBUG_BUILD && logger.error('Apollo-NestJS Integration was unable to require @nestjs/graphql package.');\n return;\n }\n\n /**\n * Iterate over resolvers of NestJS ResolversExplorerService before schemas are constructed.\n */\n fill(\n pkg.GraphQLFactory.prototype,\n 'mergeWithSchema',\n function (orig: (this: unknown, ...args: unknown[]) => unknown) {\n return function (\n this: { resolversExplorerService: { explore: () => ApolloModelResolvers[] } },\n ...args: unknown[]\n ) {\n fill(this.resolversExplorerService, 'explore', function (orig: () => ApolloModelResolvers[]) {\n return function (this: unknown) {\n const resolvers = arrayify(orig.call(this));\n\n const instrumentedResolvers = instrumentResolvers(resolvers, getCurrentHub);\n\n return instrumentedResolvers;\n };\n });\n\n return orig.call(this, ...args);\n };\n },\n );\n } else {\n const pkg = this.loadDependency();\n\n if (!pkg) {\n DEBUG_BUILD && logger.error('Apollo Integration was unable to require apollo-server-core package.');\n return;\n }\n\n /**\n * Iterate over resolvers of the ApolloServer instance before schemas are constructed.\n */\n fill(pkg.ApolloServerBase.prototype, 'constructSchema', function (orig: (config: unknown) => unknown) {\n return function (this: {\n config: { resolvers?: ApolloModelResolvers[]; schema?: unknown; modules?: unknown };\n }) {\n if (!this.config.resolvers) {\n if (DEBUG_BUILD) {\n if (this.config.schema) {\n logger.warn(\n 'Apollo integration is not able to trace `ApolloServer` instances constructed via `schema` property.' +\n 'If you are using NestJS with Apollo, please use `Sentry.Integrations.Apollo({ useNestjs: true })` instead.',\n );\n logger.warn();\n } else if (this.config.modules) {\n logger.warn(\n 'Apollo integration is not able to trace `ApolloServer` instances constructed via `modules` property.',\n );\n }\n\n logger.error('Skipping tracing as no resolvers found on the `ApolloServer` instance.');\n }\n\n return orig.call(this);\n }\n\n const resolvers = arrayify(this.config.resolvers);\n\n this.config.resolvers = instrumentResolvers(resolvers, getCurrentHub);\n\n return orig.call(this);\n };\n });\n }\n }\n}\n\n// eslint-disable-next-line deprecation/deprecation\nfunction instrumentResolvers(resolvers: ApolloModelResolvers[], getCurrentHub: () => Hub): ApolloModelResolvers[] {\n return resolvers.map(model => {\n Object.keys(model).forEach(resolverGroupName => {\n Object.keys(model[resolverGroupName]).forEach(resolverName => {\n if (typeof model[resolverGroupName][resolverName] !== 'function') {\n return;\n }\n\n wrapResolver(model, resolverGroupName, resolverName, getCurrentHub);\n });\n });\n\n return model;\n });\n}\n\n/**\n * Wrap a single resolver which can be a parent of other resolvers and/or db operations.\n */\nfunction wrapResolver(\n model: ApolloModelResolvers,\n resolverGroupName: string,\n resolverName: string,\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub: () => Hub,\n): void {\n fill(model[resolverGroupName], resolverName, function (orig: () => unknown | Promise) {\n return function (this: unknown, ...args: unknown[]) {\n // eslint-disable-next-line deprecation/deprecation\n const scope = getCurrentHub().getScope();\n // eslint-disable-next-line deprecation/deprecation\n const parentSpan = scope.getSpan();\n // eslint-disable-next-line deprecation/deprecation\n const span = parentSpan?.startChild({\n description: `${resolverGroupName}.${resolverName}`,\n op: 'graphql.resolve',\n origin: 'auto.graphql.apollo',\n });\n\n const rv = orig.call(this, ...args);\n\n if (isThenable(rv)) {\n return rv.then((res: unknown) => {\n span?.end();\n return res;\n });\n }\n\n span?.end();\n\n return rv;\n };\n });\n}\n", "import type { Integration, IntegrationClass } from '@sentry/types';\nimport { dynamicRequire } from '@sentry/utils';\n\nexport interface LazyLoadedIntegration extends Integration {\n /**\n * Loads the integration's dependency and caches it so it doesn't have to be loaded again.\n *\n * If this returns undefined, the dependency could not be loaded.\n */\n loadDependency(): T | undefined;\n}\n\nexport const lazyLoadedNodePerformanceMonitoringIntegrations: (() => LazyLoadedIntegration)[] = [\n () => {\n const integration = dynamicRequire(module, './apollo') as {\n Apollo: IntegrationClass;\n };\n return new integration.Apollo();\n },\n () => {\n const integration = dynamicRequire(module, './apollo') as {\n Apollo: IntegrationClass;\n };\n return new integration.Apollo({ useNestjs: true });\n },\n () => {\n const integration = dynamicRequire(module, './graphql') as {\n GraphQL: IntegrationClass;\n };\n return new integration.GraphQL();\n },\n () => {\n const integration = dynamicRequire(module, './mongo') as {\n Mongo: IntegrationClass;\n };\n return new integration.Mongo();\n },\n () => {\n const integration = dynamicRequire(module, './mongo') as {\n Mongo: IntegrationClass;\n };\n return new integration.Mongo({ mongoose: true });\n },\n () => {\n const integration = dynamicRequire(module, './mysql') as {\n Mysql: IntegrationClass;\n };\n return new integration.Mysql();\n },\n () => {\n const integration = dynamicRequire(module, './postgres') as {\n Postgres: IntegrationClass;\n };\n return new integration.Postgres();\n },\n];\n", "import { GLOBAL_OBJ } from '@sentry/utils';\n\nexport const WINDOW = GLOBAL_OBJ as typeof GLOBAL_OBJ &\n // document is not available in all browser environments (webworkers). We make it optional so you have to explicitly check for it\n Omit &\n Partial>;\n", "import type { IdleTransaction, SpanStatusType } from '@sentry/core';\nimport { getActiveTransaction, spanToJSON } from '@sentry/core';\nimport { logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../common/debug-build';\nimport { WINDOW } from './types';\n\n/**\n * Add a listener that cancels and finishes a transaction when the global\n * document is hidden.\n */\nexport function registerBackgroundTabDetection(): void {\n if (WINDOW.document) {\n WINDOW.document.addEventListener('visibilitychange', () => {\n // eslint-disable-next-line deprecation/deprecation\n const activeTransaction = getActiveTransaction() as IdleTransaction;\n if (WINDOW.document!.hidden && activeTransaction) {\n const statusType: SpanStatusType = 'cancelled';\n\n const { op, status } = spanToJSON(activeTransaction);\n\n DEBUG_BUILD &&\n logger.log(`[Tracing] Transaction: ${statusType} -> since tab moved to the background, op: ${op}`);\n // We should not set status if it is already set, this prevent important statuses like\n // error or data loss from being overwritten on transaction.\n if (!status) {\n activeTransaction.setStatus(statusType);\n }\n // TODO: Can we rewrite this to an attribute?\n // eslint-disable-next-line deprecation/deprecation\n activeTransaction.setTag('visibilitychange', 'document.hidden');\n activeTransaction.end();\n }\n });\n } else {\n DEBUG_BUILD && logger.warn('[Tracing] Could not set up background tab detection due to lack of global document');\n }\n}\n", "/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { Metric, ReportCallback } from '../types';\n\nexport const bindReporter = (\n callback: ReportCallback,\n metric: Metric,\n reportAllChanges?: boolean,\n): ((forceReport?: boolean) => void) => {\n let prevValue: number;\n let delta: number;\n return (forceReport?: boolean) => {\n if (metric.value >= 0) {\n if (forceReport || reportAllChanges) {\n delta = metric.value - (prevValue || 0);\n\n // Report the metric if there's a non-zero delta or if no previous\n // value exists (which can happen in the case of the document becoming\n // hidden when the metric value is 0).\n // See: https://github.com/GoogleChrome/web-vitals/issues/14\n if (delta || prevValue === undefined) {\n prevValue = metric.value;\n metric.delta = delta;\n callback(metric);\n }\n }\n }\n };\n};\n", "/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Performantly generate a unique, 30-char string by combining a version\n * number, the current timestamp with a 13-digit number integer.\n * @return {string}\n */\nexport const generateUniqueID = (): string => {\n return `v3-${Date.now()}-${Math.floor(Math.random() * (9e12 - 1)) + 1e12}`;\n};\n", "/*\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { WINDOW } from '../../types';\nimport type { NavigationTimingPolyfillEntry } from '../types';\n\nconst getNavigationEntryFromPerformanceTiming = (): NavigationTimingPolyfillEntry => {\n // eslint-disable-next-line deprecation/deprecation\n const timing = WINDOW.performance.timing;\n // eslint-disable-next-line deprecation/deprecation\n const type = WINDOW.performance.navigation.type;\n\n const navigationEntry: { [key: string]: number | string } = {\n entryType: 'navigation',\n startTime: 0,\n type: type == 2 ? 'back_forward' : type === 1 ? 'reload' : 'navigate',\n };\n\n for (const key in timing) {\n if (key !== 'navigationStart' && key !== 'toJSON') {\n // eslint-disable-next-line deprecation/deprecation\n navigationEntry[key] = Math.max((timing[key as keyof PerformanceTiming] as number) - timing.navigationStart, 0);\n }\n }\n return navigationEntry as unknown as NavigationTimingPolyfillEntry;\n};\n\nexport const getNavigationEntry = (): PerformanceNavigationTiming | NavigationTimingPolyfillEntry | undefined => {\n if (WINDOW.__WEB_VITALS_POLYFILL__) {\n return (\n WINDOW.performance &&\n ((performance.getEntriesByType && performance.getEntriesByType('navigation')[0]) ||\n getNavigationEntryFromPerformanceTiming())\n );\n } else {\n return WINDOW.performance && performance.getEntriesByType && performance.getEntriesByType('navigation')[0];\n }\n};\n", "/*\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getNavigationEntry } from './getNavigationEntry';\n\nexport const getActivationStart = (): number => {\n const navEntry = getNavigationEntry();\n return (navEntry && navEntry.activationStart) || 0;\n};\n", "/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { WINDOW } from '../../types';\nimport type { Metric } from '../types';\nimport { generateUniqueID } from './generateUniqueID';\nimport { getActivationStart } from './getActivationStart';\nimport { getNavigationEntry } from './getNavigationEntry';\n\nexport const initMetric = (name: Metric['name'], value?: number): Metric => {\n const navEntry = getNavigationEntry();\n let navigationType: Metric['navigationType'] = 'navigate';\n\n if (navEntry) {\n if ((WINDOW.document && WINDOW.document.prerendering) || getActivationStart() > 0) {\n navigationType = 'prerender';\n } else {\n navigationType = navEntry.type.replace(/_/g, '-') as Metric['navigationType'];\n }\n }\n\n return {\n name,\n value: typeof value === 'undefined' ? -1 : value,\n rating: 'good', // Will be updated if the value changes.\n delta: 0,\n entries: [],\n id: generateUniqueID(),\n navigationType,\n };\n};\n", "/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { FirstInputPolyfillEntry, NavigationTimingPolyfillEntry, PerformancePaintTiming } from '../types';\n\nexport interface PerformanceEntryHandler {\n (entry: PerformanceEntry): void;\n}\n\ninterface PerformanceEntryMap {\n event: PerformanceEventTiming[];\n paint: PerformancePaintTiming[];\n 'layout-shift': LayoutShift[];\n 'largest-contentful-paint': LargestContentfulPaint[];\n 'first-input': PerformanceEventTiming[] | FirstInputPolyfillEntry[];\n navigation: PerformanceNavigationTiming[] | NavigationTimingPolyfillEntry[];\n resource: PerformanceResourceTiming[];\n longtask: PerformanceEntry[];\n}\n\n/**\n * Takes a performance entry type and a callback function, and creates a\n * `PerformanceObserver` instance that will observe the specified entry type\n * with buffering enabled and call the callback _for each entry_.\n *\n * This function also feature-detects entry support and wraps the logic in a\n * try/catch to avoid errors in unsupporting browsers.\n */\nexport const observe = (\n type: K,\n callback: (entries: PerformanceEntryMap[K]) => void,\n opts?: PerformanceObserverInit,\n): PerformanceObserver | undefined => {\n try {\n if (PerformanceObserver.supportedEntryTypes.includes(type)) {\n const po = new PerformanceObserver(list => {\n callback(list.getEntries() as PerformanceEntryMap[K]);\n });\n po.observe(\n Object.assign(\n {\n type,\n buffered: true,\n },\n opts || {},\n ) as PerformanceObserverInit,\n );\n return po;\n }\n } catch (e) {\n // Do nothing.\n }\n return;\n};\n", "/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { WINDOW } from '../../types';\n\nexport interface OnHiddenCallback {\n (event: Event): void;\n}\n\nexport const onHidden = (cb: OnHiddenCallback, once?: boolean): void => {\n const onHiddenOrPageHide = (event: Event): void => {\n if (event.type === 'pagehide' || WINDOW.document!.visibilityState === 'hidden') {\n cb(event);\n if (once) {\n removeEventListener('visibilitychange', onHiddenOrPageHide, true);\n removeEventListener('pagehide', onHiddenOrPageHide, true);\n }\n }\n };\n\n if (WINDOW.document) {\n addEventListener('visibilitychange', onHiddenOrPageHide, true);\n // Some browsers have buggy implementations of visibilitychange,\n // so we use pagehide in addition, just to be safe.\n addEventListener('pagehide', onHiddenOrPageHide, true);\n }\n};\n", "/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { bindReporter } from './lib/bindReporter';\nimport { initMetric } from './lib/initMetric';\nimport { observe } from './lib/observe';\nimport { onHidden } from './lib/onHidden';\nimport type { CLSMetric, ReportCallback, StopListening } from './types';\n\n/**\n * Calculates the [CLS](https://web.dev/cls/) value for the current page and\n * calls the `callback` function once the value is ready to be reported, along\n * with all `layout-shift` performance entries that were used in the metric\n * value calculation. The reported value is a `double` (corresponding to a\n * [layout shift score](https://web.dev/cls/#layout-shift-score)).\n *\n * If the `reportAllChanges` configuration option is set to `true`, the\n * `callback` function will be called as soon as the value is initially\n * determined as well as any time the value changes throughout the page\n * lifespan.\n *\n * _**Important:** CLS should be continually monitored for changes throughout\n * the entire lifespan of a page—including if the user returns to the page after\n * it's been hidden/backgrounded. However, since browsers often [will not fire\n * additional callbacks once the user has backgrounded a\n * page](https://developer.chrome.com/blog/page-lifecycle-api/#advice-hidden),\n * `callback` is always called when the page's visibility state changes to\n * hidden. As a result, the `callback` function might be called multiple times\n * during the same page load._\n */\nexport const onCLS = (\n onReport: ReportCallback,\n options: { reportAllChanges?: boolean } = {},\n): StopListening | undefined => {\n const metric = initMetric('CLS', 0);\n let report: ReturnType;\n\n let sessionValue = 0;\n let sessionEntries: PerformanceEntry[] = [];\n\n // const handleEntries = (entries: Metric['entries']) => {\n const handleEntries = (entries: LayoutShift[]): void => {\n entries.forEach(entry => {\n // Only count layout shifts without recent user input.\n if (!entry.hadRecentInput) {\n const firstSessionEntry = sessionEntries[0];\n const lastSessionEntry = sessionEntries[sessionEntries.length - 1];\n\n // If the entry occurred less than 1 second after the previous entry and\n // less than 5 seconds after the first entry in the session, include the\n // entry in the current session. Otherwise, start a new session.\n if (\n sessionValue &&\n sessionEntries.length !== 0 &&\n entry.startTime - lastSessionEntry.startTime < 1000 &&\n entry.startTime - firstSessionEntry.startTime < 5000\n ) {\n sessionValue += entry.value;\n sessionEntries.push(entry);\n } else {\n sessionValue = entry.value;\n sessionEntries = [entry];\n }\n\n // If the current session value is larger than the current CLS value,\n // update CLS and the entries contributing to it.\n if (sessionValue > metric.value) {\n metric.value = sessionValue;\n metric.entries = sessionEntries;\n if (report) {\n report();\n }\n }\n }\n });\n };\n\n const po = observe('layout-shift', handleEntries);\n if (po) {\n report = bindReporter(onReport, metric, options.reportAllChanges);\n\n const stopListening = (): void => {\n handleEntries(po.takeRecords() as CLSMetric['entries']);\n report(true);\n };\n\n onHidden(stopListening);\n\n return stopListening;\n }\n\n return;\n};\n", "/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { WINDOW } from '../../types';\nimport { onHidden } from './onHidden';\n\nlet firstHiddenTime = -1;\n\nconst initHiddenTime = (): void => {\n // If the document is hidden and not prerendering, assume it was always\n // hidden and the page was loaded in the background.\n if (WINDOW.document && WINDOW.document.visibilityState) {\n firstHiddenTime = WINDOW.document.visibilityState === 'hidden' && !WINDOW.document.prerendering ? 0 : Infinity;\n }\n};\n\nconst trackChanges = (): void => {\n // Update the time if/when the document becomes hidden.\n onHidden(({ timeStamp }) => {\n firstHiddenTime = timeStamp;\n }, true);\n};\n\nexport const getVisibilityWatcher = (): {\n readonly firstHiddenTime: number;\n} => {\n if (firstHiddenTime < 0) {\n // If the document is hidden when this code runs, assume it was hidden\n // since navigation start. This isn't a perfect heuristic, but it's the\n // best we can do until an API is available to support querying past\n // visibilityState.\n initHiddenTime();\n trackChanges();\n }\n return {\n get firstHiddenTime() {\n return firstHiddenTime;\n },\n };\n};\n", "/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { bindReporter } from './lib/bindReporter';\nimport { getVisibilityWatcher } from './lib/getVisibilityWatcher';\nimport { initMetric } from './lib/initMetric';\nimport { observe } from './lib/observe';\nimport { onHidden } from './lib/onHidden';\nimport type { FIDMetric, PerformanceEventTiming, ReportCallback } from './types';\n\n/**\n * Calculates the [FID](https://web.dev/fid/) value for the current page and\n * calls the `callback` function once the value is ready, along with the\n * relevant `first-input` performance entry used to determine the value. The\n * reported value is a `DOMHighResTimeStamp`.\n *\n * _**Important:** since FID is only reported after the user interacts with the\n * page, it's possible that it will not be reported for some page loads._\n */\nexport const onFID = (onReport: ReportCallback): void => {\n const visibilityWatcher = getVisibilityWatcher();\n const metric = initMetric('FID');\n // eslint-disable-next-line prefer-const\n let report: ReturnType;\n\n const handleEntry = (entry: PerformanceEventTiming): void => {\n // Only report if the page wasn't hidden prior to the first input.\n if (entry.startTime < visibilityWatcher.firstHiddenTime) {\n metric.value = entry.processingStart - entry.startTime;\n metric.entries.push(entry);\n report(true);\n }\n };\n\n const handleEntries = (entries: FIDMetric['entries']): void => {\n (entries as PerformanceEventTiming[]).forEach(handleEntry);\n };\n\n const po = observe('first-input', handleEntries);\n report = bindReporter(onReport, metric);\n\n if (po) {\n onHidden(() => {\n handleEntries(po.takeRecords() as FIDMetric['entries']);\n po.disconnect();\n }, true);\n }\n};\n", "/*\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { Metric } from '../../types';\nimport { observe } from '../observe';\n\ndeclare global {\n interface Performance {\n interactionCount: number;\n }\n}\n\nlet interactionCountEstimate = 0;\nlet minKnownInteractionId = Infinity;\nlet maxKnownInteractionId = 0;\n\nconst updateEstimate = (entries: Metric['entries']): void => {\n (entries as PerformanceEventTiming[]).forEach(e => {\n if (e.interactionId) {\n minKnownInteractionId = Math.min(minKnownInteractionId, e.interactionId);\n maxKnownInteractionId = Math.max(maxKnownInteractionId, e.interactionId);\n\n interactionCountEstimate = maxKnownInteractionId ? (maxKnownInteractionId - minKnownInteractionId) / 7 + 1 : 0;\n }\n });\n};\n\nlet po: PerformanceObserver | undefined;\n\n/**\n * Returns the `interactionCount` value using the native API (if available)\n * or the polyfill estimate in this module.\n */\nexport const getInteractionCount = (): number => {\n return po ? interactionCountEstimate : performance.interactionCount || 0;\n};\n\n/**\n * Feature detects native support or initializes the polyfill if needed.\n */\nexport const initInteractionCountPolyfill = (): void => {\n if ('interactionCount' in performance || po) return;\n\n po = observe('event', updateEstimate, {\n type: 'event',\n buffered: true,\n durationThreshold: 0,\n } as PerformanceObserverInit);\n};\n", "/*\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { bindReporter } from './lib/bindReporter';\nimport { initMetric } from './lib/initMetric';\nimport { observe } from './lib/observe';\nimport { onHidden } from './lib/onHidden';\nimport { getInteractionCount, initInteractionCountPolyfill } from './lib/polyfills/interactionCountPolyfill';\nimport type { ReportCallback, ReportOpts } from './types';\nimport type { INPMetric } from './types/inp';\n\ninterface Interaction {\n id: number;\n latency: number;\n entries: PerformanceEventTiming[];\n}\n\n/**\n * Returns the interaction count since the last bfcache restore (or for the\n * full page lifecycle if there were no bfcache restores).\n */\nconst getInteractionCountForNavigation = (): number => {\n return getInteractionCount();\n};\n\n// To prevent unnecessary memory usage on pages with lots of interactions,\n// store at most 10 of the longest interactions to consider as INP candidates.\nconst MAX_INTERACTIONS_TO_CONSIDER = 10;\n\n// A list of longest interactions on the page (by latency) sorted so the\n// longest one is first. The list is as most MAX_INTERACTIONS_TO_CONSIDER long.\nconst longestInteractionList: Interaction[] = [];\n\n// A mapping of longest interactions by their interaction ID.\n// This is used for faster lookup.\nconst longestInteractionMap: { [interactionId: string]: Interaction } = {};\n\n/**\n * Takes a performance entry and adds it to the list of worst interactions\n * if its duration is long enough to make it among the worst. If the\n * entry is part of an existing interaction, it is merged and the latency\n * and entries list is updated as needed.\n */\nconst processEntry = (entry: PerformanceEventTiming): void => {\n // The least-long of the 10 longest interactions.\n const minLongestInteraction = longestInteractionList[longestInteractionList.length - 1];\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const existingInteraction = longestInteractionMap[entry.interactionId!];\n\n // Only process the entry if it's possibly one of the ten longest,\n // or if it's part of an existing interaction.\n if (\n existingInteraction ||\n longestInteractionList.length < MAX_INTERACTIONS_TO_CONSIDER ||\n entry.duration > minLongestInteraction.latency\n ) {\n // If the interaction already exists, update it. Otherwise create one.\n if (existingInteraction) {\n existingInteraction.entries.push(entry);\n existingInteraction.latency = Math.max(existingInteraction.latency, entry.duration);\n } else {\n const interaction = {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n id: entry.interactionId!,\n latency: entry.duration,\n entries: [entry],\n };\n longestInteractionMap[interaction.id] = interaction;\n longestInteractionList.push(interaction);\n }\n\n // Sort the entries by latency (descending) and keep only the top ten.\n longestInteractionList.sort((a, b) => b.latency - a.latency);\n longestInteractionList.splice(MAX_INTERACTIONS_TO_CONSIDER).forEach(i => {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete longestInteractionMap[i.id];\n });\n }\n};\n\n/**\n * Returns the estimated p98 longest interaction based on the stored\n * interaction candidates and the interaction count for the current page.\n */\nconst estimateP98LongestInteraction = (): Interaction => {\n const candidateInteractionIndex = Math.min(\n longestInteractionList.length - 1,\n Math.floor(getInteractionCountForNavigation() / 50),\n );\n\n return longestInteractionList[candidateInteractionIndex];\n};\n\n/**\n * Calculates the [INP](https://web.dev/responsiveness/) value for the current\n * page and calls the `callback` function once the value is ready, along with\n * the `event` performance entries reported for that interaction. The reported\n * value is a `DOMHighResTimeStamp`.\n *\n * A custom `durationThreshold` configuration option can optionally be passed to\n * control what `event-timing` entries are considered for INP reporting. The\n * default threshold is `40`, which means INP scores of less than 40 are\n * reported as 0. Note that this will not affect your 75th percentile INP value\n * unless that value is also less than 40 (well below the recommended\n * [good](https://web.dev/inp/#what-is-a-good-inp-score) threshold).\n *\n * If the `reportAllChanges` configuration option is set to `true`, the\n * `callback` function will be called as soon as the value is initially\n * determined as well as any time the value changes throughout the page\n * lifespan.\n *\n * _**Important:** INP should be continually monitored for changes throughout\n * the entire lifespan of a page—including if the user returns to the page after\n * it's been hidden/backgrounded. However, since browsers often [will not fire\n * additional callbacks once the user has backgrounded a\n * page](https://developer.chrome.com/blog/page-lifecycle-api/#advice-hidden),\n * `callback` is always called when the page's visibility state changes to\n * hidden. As a result, the `callback` function might be called multiple times\n * during the same page load._\n */\nexport const onINP = (onReport: ReportCallback, opts?: ReportOpts): void => {\n // Set defaults\n // eslint-disable-next-line no-param-reassign\n opts = opts || {};\n\n // https://web.dev/inp/#what's-a-%22good%22-inp-value\n // const thresholds = [200, 500];\n\n // TODO(philipwalton): remove once the polyfill is no longer needed.\n initInteractionCountPolyfill();\n\n const metric = initMetric('INP');\n // eslint-disable-next-line prefer-const\n let report: ReturnType;\n\n const handleEntries = (entries: INPMetric['entries']): void => {\n entries.forEach(entry => {\n if (entry.interactionId) {\n processEntry(entry);\n }\n\n // Entries of type `first-input` don't currently have an `interactionId`,\n // so to consider them in INP we have to first check that an existing\n // entry doesn't match the `duration` and `startTime`.\n // Note that this logic assumes that `event` entries are dispatched\n // before `first-input` entries. This is true in Chrome but it is not\n // true in Firefox; however, Firefox doesn't support interactionId, so\n // it's not an issue at the moment.\n // TODO(philipwalton): remove once crbug.com/1325826 is fixed.\n if (entry.entryType === 'first-input') {\n const noMatchingEntry = !longestInteractionList.some(interaction => {\n return interaction.entries.some(prevEntry => {\n return entry.duration === prevEntry.duration && entry.startTime === prevEntry.startTime;\n });\n });\n if (noMatchingEntry) {\n processEntry(entry);\n }\n }\n });\n\n const inp = estimateP98LongestInteraction();\n\n if (inp && inp.latency !== metric.value) {\n metric.value = inp.latency;\n metric.entries = inp.entries;\n report();\n }\n };\n\n const po = observe('event', handleEntries, {\n // Event Timing entries have their durations rounded to the nearest 8ms,\n // so a duration of 40ms would be any event that spans 2.5 or more frames\n // at 60Hz. This threshold is chosen to strike a balance between usefulness\n // and performance. Running this callback for any interaction that spans\n // just one or two frames is likely not worth the insight that could be\n // gained.\n durationThreshold: opts.durationThreshold || 40,\n } as PerformanceObserverInit);\n\n report = bindReporter(onReport, metric, opts.reportAllChanges);\n\n if (po) {\n // Also observe entries of type `first-input`. This is useful in cases\n // where the first interaction is less than the `durationThreshold`.\n po.observe({ type: 'first-input', buffered: true });\n\n onHidden(() => {\n handleEntries(po.takeRecords() as INPMetric['entries']);\n\n // If the interaction count shows that there were interactions but\n // none were captured by the PerformanceObserver, report a latency of 0.\n if (metric.value < 0 && getInteractionCountForNavigation() > 0) {\n metric.value = 0;\n metric.entries = [];\n }\n\n report(true);\n });\n }\n};\n", "/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { WINDOW } from '../types';\nimport { bindReporter } from './lib/bindReporter';\nimport { getActivationStart } from './lib/getActivationStart';\nimport { getVisibilityWatcher } from './lib/getVisibilityWatcher';\nimport { initMetric } from './lib/initMetric';\nimport { observe } from './lib/observe';\nimport { onHidden } from './lib/onHidden';\nimport type { LCPMetric, ReportCallback, StopListening } from './types';\n\nconst reportedMetricIDs: Record = {};\n\n/**\n * Calculates the [LCP](https://web.dev/lcp/) value for the current page and\n * calls the `callback` function once the value is ready (along with the\n * relevant `largest-contentful-paint` performance entry used to determine the\n * value). The reported value is a `DOMHighResTimeStamp`.\n */\nexport const onLCP = (onReport: ReportCallback): StopListening | undefined => {\n const visibilityWatcher = getVisibilityWatcher();\n const metric = initMetric('LCP');\n let report: ReturnType;\n\n const handleEntries = (entries: LCPMetric['entries']): void => {\n const lastEntry = entries[entries.length - 1] as LargestContentfulPaint;\n if (lastEntry) {\n // The startTime attribute returns the value of the renderTime if it is\n // not 0, and the value of the loadTime otherwise. The activationStart\n // reference is used because LCP should be relative to page activation\n // rather than navigation start if the page was prerendered.\n const value = Math.max(lastEntry.startTime - getActivationStart(), 0);\n\n // Only report if the page wasn't hidden prior to LCP.\n if (value < visibilityWatcher.firstHiddenTime) {\n metric.value = value;\n metric.entries = [lastEntry];\n report();\n }\n }\n };\n\n const po = observe('largest-contentful-paint', handleEntries);\n\n if (po) {\n report = bindReporter(onReport, metric);\n\n const stopListening = (): void => {\n if (!reportedMetricIDs[metric.id]) {\n handleEntries(po.takeRecords() as LCPMetric['entries']);\n po.disconnect();\n reportedMetricIDs[metric.id] = true;\n report(true);\n }\n };\n\n // Stop listening after input. Note: while scrolling is an input that\n // stop LCP observation, it's unreliable since it can be programmatically\n // generated. See: https://github.com/GoogleChrome/web-vitals/issues/75\n ['keydown', 'click'].forEach(type => {\n if (WINDOW.document) {\n addEventListener(type, stopListening, { once: true, capture: true });\n }\n });\n\n onHidden(stopListening, true);\n\n return stopListening;\n }\n\n return;\n};\n", "/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { WINDOW } from '../types';\nimport { bindReporter } from './lib/bindReporter';\nimport { getActivationStart } from './lib/getActivationStart';\nimport { getNavigationEntry } from './lib/getNavigationEntry';\nimport { initMetric } from './lib/initMetric';\nimport type { ReportCallback, ReportOpts } from './types';\nimport type { TTFBMetric } from './types/ttfb';\n\n/**\n * Runs in the next task after the page is done loading and/or prerendering.\n * @param callback\n */\nconst whenReady = (callback: () => void): void => {\n if (!WINDOW.document) {\n return;\n }\n\n if (WINDOW.document.prerendering) {\n addEventListener('prerenderingchange', () => whenReady(callback), true);\n } else if (WINDOW.document.readyState !== 'complete') {\n addEventListener('load', () => whenReady(callback), true);\n } else {\n // Queue a task so the callback runs after `loadEventEnd`.\n setTimeout(callback, 0);\n }\n};\n\n/**\n * Calculates the [TTFB](https://web.dev/time-to-first-byte/) value for the\n * current page and calls the `callback` function once the page has loaded,\n * along with the relevant `navigation` performance entry used to determine the\n * value. The reported value is a `DOMHighResTimeStamp`.\n *\n * Note, this function waits until after the page is loaded to call `callback`\n * in order to ensure all properties of the `navigation` entry are populated.\n * This is useful if you want to report on other metrics exposed by the\n * [Navigation Timing API](https://w3c.github.io/navigation-timing/). For\n * example, the TTFB metric starts from the page's [time\n * origin](https://www.w3.org/TR/hr-time-2/#sec-time-origin), which means it\n * includes time spent on DNS lookup, connection negotiation, network latency,\n * and server processing time.\n */\nexport const onTTFB = (onReport: ReportCallback, opts?: ReportOpts): void => {\n // Set defaults\n // eslint-disable-next-line no-param-reassign\n opts = opts || {};\n\n // https://web.dev/ttfb/#what-is-a-good-ttfb-score\n // const thresholds = [800, 1800];\n\n const metric = initMetric('TTFB');\n const report = bindReporter(onReport, metric, opts.reportAllChanges);\n\n whenReady(() => {\n const navEntry = getNavigationEntry() as TTFBMetric['entries'][number];\n\n if (navEntry) {\n // The activationStart reference is used because TTFB should be\n // relative to page activation rather than navigation start if the\n // page was prerendered. But in cases where `activationStart` occurs\n // after the first byte is received, this time should be clamped at 0.\n metric.value = Math.max(navEntry.responseStart - getActivationStart(), 0);\n\n // In some cases the value reported is negative or is larger\n // than the current page time. Ignore these cases:\n // https://github.com/GoogleChrome/web-vitals/issues/137\n // https://github.com/GoogleChrome/web-vitals/issues/162\n if (metric.value < 0 || metric.value > performance.now()) return;\n\n metric.entries = [navEntry];\n\n report(true);\n }\n });\n};\n", "import { getFunctionName, logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../common/debug-build';\nimport { onCLS } from './web-vitals/getCLS';\nimport { onFID } from './web-vitals/getFID';\nimport { onINP } from './web-vitals/getINP';\nimport { onLCP } from './web-vitals/getLCP';\nimport { observe } from './web-vitals/lib/observe';\nimport { onTTFB } from './web-vitals/onTTFB';\n\ntype InstrumentHandlerTypePerformanceObserver =\n | 'longtask'\n | 'event'\n | 'navigation'\n | 'paint'\n | 'resource'\n | 'first-input';\n\ntype InstrumentHandlerTypeMetric = 'cls' | 'lcp' | 'fid' | 'ttfb' | 'inp';\n\n// We provide this here manually instead of relying on a global, as this is not available in non-browser environements\n// And we do not want to expose such types\ninterface PerformanceEntry {\n readonly duration: number;\n readonly entryType: string;\n readonly name: string;\n readonly startTime: number;\n toJSON(): Record;\n}\ninterface PerformanceEventTiming extends PerformanceEntry {\n processingStart: number;\n processingEnd: number;\n duration: number;\n cancelable?: boolean;\n target?: unknown | null;\n interactionId?: number;\n}\n\ninterface Metric {\n /**\n * The name of the metric (in acronym form).\n */\n name: 'CLS' | 'FCP' | 'FID' | 'INP' | 'LCP' | 'TTFB';\n\n /**\n * The current value of the metric.\n */\n value: number;\n\n /**\n * The rating as to whether the metric value is within the \"good\",\n * \"needs improvement\", or \"poor\" thresholds of the metric.\n */\n rating: 'good' | 'needs-improvement' | 'poor';\n\n /**\n * The delta between the current value and the last-reported value.\n * On the first report, `delta` and `value` will always be the same.\n */\n delta: number;\n\n /**\n * A unique ID representing this particular metric instance. This ID can\n * be used by an analytics tool to dedupe multiple values sent for the same\n * metric instance, or to group multiple deltas together and calculate a\n * total. It can also be used to differentiate multiple different metric\n * instances sent from the same page, which can happen if the page is\n * restored from the back/forward cache (in that case new metrics object\n * get created).\n */\n id: string;\n\n /**\n * Any performance entries relevant to the metric value calculation.\n * The array may also be empty if the metric value was not based on any\n * entries (e.g. a CLS value of 0 given no layout shifts).\n */\n entries: PerformanceEntry[];\n\n /**\n * The type of navigation\n *\n * Navigation Timing API (or `undefined` if the browser doesn't\n * support that API). For pages that are restored from the bfcache, this\n * value will be 'back-forward-cache'.\n */\n navigationType: 'navigate' | 'reload' | 'back-forward' | 'back-forward-cache' | 'prerender';\n}\n\ntype InstrumentHandlerType = InstrumentHandlerTypeMetric | InstrumentHandlerTypePerformanceObserver;\n\ntype StopListening = undefined | void | (() => void);\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype InstrumentHandlerCallback = (data: any) => void;\n\ntype CleanupHandlerCallback = () => void;\n\nconst handlers: { [key in InstrumentHandlerType]?: InstrumentHandlerCallback[] } = {};\nconst instrumented: { [key in InstrumentHandlerType]?: boolean } = {};\n\nlet _previousCls: Metric | undefined;\nlet _previousFid: Metric | undefined;\nlet _previousLcp: Metric | undefined;\nlet _previousTtfb: Metric | undefined;\nlet _previousInp: Metric | undefined;\n\n/**\n * Add a callback that will be triggered when a CLS metric is available.\n * Returns a cleanup callback which can be called to remove the instrumentation handler.\n *\n * Pass `stopOnCallback = true` to stop listening for CLS when the cleanup callback is called.\n * This will lead to the CLS being finalized and frozen.\n */\nexport function addClsInstrumentationHandler(\n callback: (data: { metric: Metric }) => void,\n stopOnCallback = false,\n): CleanupHandlerCallback {\n return addMetricObserver('cls', callback, instrumentCls, _previousCls, stopOnCallback);\n}\n\n/**\n * Add a callback that will be triggered when a LCP metric is available.\n * Returns a cleanup callback which can be called to remove the instrumentation handler.\n *\n * Pass `stopOnCallback = true` to stop listening for LCP when the cleanup callback is called.\n * This will lead to the LCP being finalized and frozen.\n */\nexport function addLcpInstrumentationHandler(\n callback: (data: { metric: Metric }) => void,\n stopOnCallback = false,\n): CleanupHandlerCallback {\n return addMetricObserver('lcp', callback, instrumentLcp, _previousLcp, stopOnCallback);\n}\n\n/**\n * Add a callback that will be triggered when a FID metric is available.\n */\nexport function addTtfbInstrumentationHandler(callback: (data: { metric: Metric }) => void): CleanupHandlerCallback {\n return addMetricObserver('ttfb', callback, instrumentTtfb, _previousTtfb);\n}\n\n/**\n * Add a callback that will be triggered when a FID metric is available.\n * Returns a cleanup callback which can be called to remove the instrumentation handler.\n */\nexport function addFidInstrumentationHandler(callback: (data: { metric: Metric }) => void): CleanupHandlerCallback {\n return addMetricObserver('fid', callback, instrumentFid, _previousFid);\n}\n\n/**\n * Add a callback that will be triggered when a INP metric is available.\n * Returns a cleanup callback which can be called to remove the instrumentation handler.\n */\nexport function addInpInstrumentationHandler(\n callback: (data: { metric: Omit & { entries: PerformanceEventTiming[] } }) => void,\n): CleanupHandlerCallback {\n return addMetricObserver('inp', callback, instrumentInp, _previousInp);\n}\n\nexport function addPerformanceInstrumentationHandler(\n type: 'event' | 'first-input',\n callback: (data: { entries: ((PerformanceEntry & { target?: unknown | null }) | PerformanceEventTiming)[] }) => void,\n): CleanupHandlerCallback;\nexport function addPerformanceInstrumentationHandler(\n type: InstrumentHandlerTypePerformanceObserver,\n callback: (data: { entries: PerformanceEntry[] }) => void,\n): CleanupHandlerCallback;\n\n/**\n * Add a callback that will be triggered when a performance observer is triggered,\n * and receives the entries of the observer.\n * Returns a cleanup callback which can be called to remove the instrumentation handler.\n */\nexport function addPerformanceInstrumentationHandler(\n type: InstrumentHandlerTypePerformanceObserver,\n callback: (data: { entries: PerformanceEntry[] }) => void,\n): CleanupHandlerCallback {\n addHandler(type, callback);\n\n if (!instrumented[type]) {\n instrumentPerformanceObserver(type);\n instrumented[type] = true;\n }\n\n return getCleanupCallback(type, callback);\n}\n\n/** Trigger all handlers of a given type. */\nfunction triggerHandlers(type: InstrumentHandlerType, data: unknown): void {\n const typeHandlers = handlers[type];\n\n if (!typeHandlers || !typeHandlers.length) {\n return;\n }\n\n for (const handler of typeHandlers) {\n try {\n handler(data);\n } catch (e) {\n DEBUG_BUILD &&\n logger.error(\n `Error while triggering instrumentation handler.\\nType: ${type}\\nName: ${getFunctionName(handler)}\\nError:`,\n e,\n );\n }\n }\n}\n\nfunction instrumentCls(): StopListening {\n return onCLS(\n metric => {\n triggerHandlers('cls', {\n metric,\n });\n _previousCls = metric;\n },\n { reportAllChanges: true },\n );\n}\n\nfunction instrumentFid(): void {\n return onFID(metric => {\n triggerHandlers('fid', {\n metric,\n });\n _previousFid = metric;\n });\n}\n\nfunction instrumentLcp(): StopListening {\n return onLCP(metric => {\n triggerHandlers('lcp', {\n metric,\n });\n _previousLcp = metric;\n });\n}\n\nfunction instrumentTtfb(): StopListening {\n return onTTFB(metric => {\n triggerHandlers('ttfb', {\n metric,\n });\n _previousTtfb = metric;\n });\n}\n\nfunction instrumentInp(): void {\n return onINP(metric => {\n triggerHandlers('inp', {\n metric,\n });\n _previousInp = metric;\n });\n}\n\nfunction addMetricObserver(\n type: InstrumentHandlerTypeMetric,\n callback: InstrumentHandlerCallback,\n instrumentFn: () => StopListening,\n previousValue: Metric | undefined,\n stopOnCallback = false,\n): CleanupHandlerCallback {\n addHandler(type, callback);\n\n let stopListening: StopListening | undefined;\n\n if (!instrumented[type]) {\n stopListening = instrumentFn();\n instrumented[type] = true;\n }\n\n if (previousValue) {\n callback({ metric: previousValue });\n }\n\n return getCleanupCallback(type, callback, stopOnCallback ? stopListening : undefined);\n}\n\nfunction instrumentPerformanceObserver(type: InstrumentHandlerTypePerformanceObserver): void {\n const options: PerformanceObserverInit = {};\n\n // Special per-type options we want to use\n if (type === 'event') {\n options.durationThreshold = 0;\n }\n\n observe(\n type,\n entries => {\n triggerHandlers(type, { entries });\n },\n options,\n );\n}\n\nfunction addHandler(type: InstrumentHandlerType, handler: InstrumentHandlerCallback): void {\n handlers[type] = handlers[type] || [];\n (handlers[type] as InstrumentHandlerCallback[]).push(handler);\n}\n\n// Get a callback which can be called to remove the instrumentation handler\nfunction getCleanupCallback(\n type: InstrumentHandlerType,\n callback: InstrumentHandlerCallback,\n stopListening: StopListening,\n): CleanupHandlerCallback {\n return () => {\n if (stopListening) {\n stopListening();\n }\n\n const typeHandlers = handlers[type];\n\n if (!typeHandlers) {\n return;\n }\n\n const index = typeHandlers.indexOf(callback);\n if (index !== -1) {\n typeHandlers.splice(index, 1);\n }\n };\n}\n", "import type { Transaction } from '@sentry/core';\nimport type { Span, SpanContext } from '@sentry/types';\n\n/**\n * Checks if a given value is a valid measurement value.\n */\nexport function isMeasurementValue(value: unknown): value is number {\n return typeof value === 'number' && isFinite(value);\n}\n\n/**\n * Helper function to start child on transactions. This function will make sure that the transaction will\n * use the start timestamp of the created child span if it is earlier than the transactions actual\n * start timestamp.\n *\n * Note: this will not be possible anymore in v8,\n * unless we do some special handling for browser here...\n */\nexport function _startChild(transaction: Transaction, { startTimestamp, ...ctx }: SpanContext): Span {\n // eslint-disable-next-line deprecation/deprecation\n if (startTimestamp && transaction.startTimestamp > startTimestamp) {\n // eslint-disable-next-line deprecation/deprecation\n transaction.startTimestamp = startTimestamp;\n }\n\n // eslint-disable-next-line deprecation/deprecation\n return transaction.startChild({\n startTimestamp,\n ...ctx,\n });\n}\n", "/* eslint-disable max-lines */\nimport type { IdleTransaction, Transaction } from '@sentry/core';\nimport {\n Span,\n getActiveTransaction,\n getClient,\n hasTracingEnabled,\n isValidSampleRate,\n setMeasurement,\n} from '@sentry/core';\nimport type { ClientOptions, Measurements, SpanContext, TransactionContext } from '@sentry/types';\nimport { browserPerformanceTimeOrigin, getComponentName, htmlTreeAsString, logger, parseUrl } from '@sentry/utils';\n\nimport { spanToJSON } from '@sentry/core';\nimport { DEBUG_BUILD } from '../../common/debug-build';\nimport {\n addClsInstrumentationHandler,\n addFidInstrumentationHandler,\n addInpInstrumentationHandler,\n addLcpInstrumentationHandler,\n addPerformanceInstrumentationHandler,\n addTtfbInstrumentationHandler,\n} from '../instrument';\nimport { WINDOW } from '../types';\nimport { getVisibilityWatcher } from '../web-vitals/lib/getVisibilityWatcher';\nimport type {\n InteractionRouteNameMapping,\n NavigatorDeviceMemory,\n NavigatorNetworkInformation,\n} from '../web-vitals/types';\nimport { _startChild, isMeasurementValue } from './utils';\n\nimport { createSpanEnvelope } from '@sentry/core';\nimport { getNavigationEntry } from '../web-vitals/lib/getNavigationEntry';\n\nconst MAX_INT_AS_BYTES = 2147483647;\n\n/**\n * Converts from milliseconds to seconds\n * @param time time in ms\n */\nfunction msToSec(time: number): number {\n return time / 1000;\n}\n\nfunction getBrowserPerformanceAPI(): Performance | undefined {\n // @ts-expect-error we want to make sure all of these are available, even if TS is sure they are\n return WINDOW && WINDOW.addEventListener && WINDOW.performance;\n}\n\nlet _performanceCursor: number = 0;\n\nlet _measurements: Measurements = {};\nlet _lcpEntry: LargestContentfulPaint | undefined;\nlet _clsEntry: LayoutShift | undefined;\n\n/**\n * Start tracking web vitals.\n * The callback returned by this function can be used to stop tracking & ensure all measurements are final & captured.\n *\n * @returns A function that forces web vitals collection\n */\nexport function startTrackingWebVitals(): () => void {\n const performance = getBrowserPerformanceAPI();\n if (performance && browserPerformanceTimeOrigin) {\n // @ts-expect-error we want to make sure all of these are available, even if TS is sure they are\n if (performance.mark) {\n WINDOW.performance.mark('sentry-tracing-init');\n }\n const fidCallback = _trackFID();\n const clsCallback = _trackCLS();\n const lcpCallback = _trackLCP();\n const ttfbCallback = _trackTtfb();\n\n return (): void => {\n fidCallback();\n clsCallback();\n lcpCallback();\n ttfbCallback();\n };\n }\n\n return () => undefined;\n}\n\n/**\n * Start tracking long tasks.\n */\nexport function startTrackingLongTasks(): void {\n addPerformanceInstrumentationHandler('longtask', ({ entries }) => {\n for (const entry of entries) {\n // eslint-disable-next-line deprecation/deprecation\n const transaction = getActiveTransaction() as IdleTransaction | undefined;\n if (!transaction) {\n return;\n }\n const startTime = msToSec((browserPerformanceTimeOrigin as number) + entry.startTime);\n const duration = msToSec(entry.duration);\n\n // eslint-disable-next-line deprecation/deprecation\n transaction.startChild({\n description: 'Main UI thread blocked',\n op: 'ui.long-task',\n origin: 'auto.ui.browser.metrics',\n startTimestamp: startTime,\n endTimestamp: startTime + duration,\n });\n }\n });\n}\n\n/**\n * Start tracking interaction events.\n */\nexport function startTrackingInteractions(): void {\n addPerformanceInstrumentationHandler('event', ({ entries }) => {\n for (const entry of entries) {\n // eslint-disable-next-line deprecation/deprecation\n const transaction = getActiveTransaction() as IdleTransaction | undefined;\n if (!transaction) {\n return;\n }\n\n if (entry.name === 'click') {\n const startTime = msToSec((browserPerformanceTimeOrigin as number) + entry.startTime);\n const duration = msToSec(entry.duration);\n\n const span: SpanContext = {\n description: htmlTreeAsString(entry.target),\n op: `ui.interaction.${entry.name}`,\n origin: 'auto.ui.browser.metrics',\n startTimestamp: startTime,\n endTimestamp: startTime + duration,\n };\n\n const componentName = getComponentName(entry.target);\n if (componentName) {\n span.attributes = { 'ui.component_name': componentName };\n }\n\n // eslint-disable-next-line deprecation/deprecation\n transaction.startChild(span);\n }\n }\n });\n}\n\n/**\n * Start tracking INP webvital events.\n */\nexport function startTrackingINP(\n interactionIdtoRouteNameMapping: InteractionRouteNameMapping,\n interactionsSampleRate: number,\n): () => void {\n const performance = getBrowserPerformanceAPI();\n if (performance && browserPerformanceTimeOrigin) {\n const inpCallback = _trackINP(interactionIdtoRouteNameMapping, interactionsSampleRate);\n\n return (): void => {\n inpCallback();\n };\n }\n\n return () => undefined;\n}\n\n/** Starts tracking the Cumulative Layout Shift on the current page. */\nfunction _trackCLS(): () => void {\n return addClsInstrumentationHandler(({ metric }) => {\n const entry = metric.entries[metric.entries.length - 1];\n if (!entry) {\n return;\n }\n\n DEBUG_BUILD && logger.log('[Measurements] Adding CLS');\n _measurements['cls'] = { value: metric.value, unit: '' };\n _clsEntry = entry as LayoutShift;\n }, true);\n}\n\n/** Starts tracking the Largest Contentful Paint on the current page. */\nfunction _trackLCP(): () => void {\n return addLcpInstrumentationHandler(({ metric }) => {\n const entry = metric.entries[metric.entries.length - 1];\n if (!entry) {\n return;\n }\n\n DEBUG_BUILD && logger.log('[Measurements] Adding LCP');\n _measurements['lcp'] = { value: metric.value, unit: 'millisecond' };\n _lcpEntry = entry as LargestContentfulPaint;\n }, true);\n}\n\n/** Starts tracking the First Input Delay on the current page. */\nfunction _trackFID(): () => void {\n return addFidInstrumentationHandler(({ metric }) => {\n const entry = metric.entries[metric.entries.length - 1];\n if (!entry) {\n return;\n }\n\n const timeOrigin = msToSec(browserPerformanceTimeOrigin as number);\n const startTime = msToSec(entry.startTime);\n DEBUG_BUILD && logger.log('[Measurements] Adding FID');\n _measurements['fid'] = { value: metric.value, unit: 'millisecond' };\n _measurements['mark.fid'] = { value: timeOrigin + startTime, unit: 'second' };\n });\n}\n\nfunction _trackTtfb(): () => void {\n return addTtfbInstrumentationHandler(({ metric }) => {\n const entry = metric.entries[metric.entries.length - 1];\n if (!entry) {\n return;\n }\n\n DEBUG_BUILD && logger.log('[Measurements] Adding TTFB');\n _measurements['ttfb'] = { value: metric.value, unit: 'millisecond' };\n });\n}\n\nconst INP_ENTRY_MAP: Record = {\n click: 'click',\n pointerdown: 'click',\n pointerup: 'click',\n mousedown: 'click',\n mouseup: 'click',\n touchstart: 'click',\n touchend: 'click',\n mouseover: 'hover',\n mouseout: 'hover',\n mouseenter: 'hover',\n mouseleave: 'hover',\n pointerover: 'hover',\n pointerout: 'hover',\n pointerenter: 'hover',\n pointerleave: 'hover',\n dragstart: 'drag',\n dragend: 'drag',\n drag: 'drag',\n dragenter: 'drag',\n dragleave: 'drag',\n dragover: 'drag',\n drop: 'drag',\n keydown: 'press',\n keyup: 'press',\n keypress: 'press',\n input: 'press',\n};\n\n/** Starts tracking the Interaction to Next Paint on the current page. */\nfunction _trackINP(\n interactionIdToRouteNameMapping: InteractionRouteNameMapping,\n interactionsSampleRate: number,\n): () => void {\n return addInpInstrumentationHandler(({ metric }) => {\n if (metric.value === undefined) {\n return;\n }\n const entry = metric.entries.find(\n entry => entry.duration === metric.value && INP_ENTRY_MAP[entry.name] !== undefined,\n );\n const client = getClient();\n if (!entry || !client) {\n return;\n }\n const interactionType = INP_ENTRY_MAP[entry.name];\n const options = client.getOptions();\n /** Build the INP span, create an envelope from the span, and then send the envelope */\n const startTime = msToSec((browserPerformanceTimeOrigin as number) + entry.startTime);\n const duration = msToSec(metric.value);\n const interaction =\n entry.interactionId !== undefined ? interactionIdToRouteNameMapping[entry.interactionId] : undefined;\n if (interaction === undefined) {\n return;\n }\n const { routeName, parentContext, activeTransaction, user, replayId } = interaction;\n const userDisplay = user !== undefined ? user.email || user.id || user.ip_address : undefined;\n // eslint-disable-next-line deprecation/deprecation\n const profileId = activeTransaction !== undefined ? activeTransaction.getProfileId() : undefined;\n const span = new Span({\n startTimestamp: startTime,\n endTimestamp: startTime + duration,\n op: `ui.interaction.${interactionType}`,\n name: htmlTreeAsString(entry.target),\n attributes: {\n release: options.release,\n environment: options.environment,\n transaction: routeName,\n ...(userDisplay !== undefined && userDisplay !== '' ? { user: userDisplay } : {}),\n ...(profileId !== undefined ? { profile_id: profileId } : {}),\n ...(replayId !== undefined ? { replay_id: replayId } : {}),\n },\n exclusiveTime: metric.value,\n measurements: {\n inp: { value: metric.value, unit: 'millisecond' },\n },\n });\n\n /** Check to see if the span should be sampled */\n const sampleRate = getSampleRate(parentContext, options, interactionsSampleRate);\n\n if (!sampleRate) {\n return;\n }\n\n if (Math.random() < (sampleRate as number | boolean)) {\n const envelope = span ? createSpanEnvelope([span], client.getDsn()) : undefined;\n const transport = client && client.getTransport();\n if (transport && envelope) {\n transport.send(envelope).then(null, reason => {\n DEBUG_BUILD && logger.error('Error while sending interaction:', reason);\n });\n }\n return;\n }\n });\n}\n\n/** Add performance related spans to a transaction */\nexport function addPerformanceEntries(transaction: Transaction): void {\n const performance = getBrowserPerformanceAPI();\n if (!performance || !WINDOW.performance.getEntries || !browserPerformanceTimeOrigin) {\n // Gatekeeper if performance API not available\n return;\n }\n\n DEBUG_BUILD && logger.log('[Tracing] Adding & adjusting spans using Performance API');\n const timeOrigin = msToSec(browserPerformanceTimeOrigin);\n\n const performanceEntries = performance.getEntries();\n\n const { op, start_timestamp: transactionStartTime } = spanToJSON(transaction);\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n performanceEntries.slice(_performanceCursor).forEach((entry: Record) => {\n const startTime = msToSec(entry.startTime);\n const duration = msToSec(entry.duration);\n\n // eslint-disable-next-line deprecation/deprecation\n if (transaction.op === 'navigation' && transactionStartTime && timeOrigin + startTime < transactionStartTime) {\n return;\n }\n\n switch (entry.entryType) {\n case 'navigation': {\n _addNavigationSpans(transaction, entry, timeOrigin);\n break;\n }\n case 'mark':\n case 'paint':\n case 'measure': {\n _addMeasureSpans(transaction, entry, startTime, duration, timeOrigin);\n\n // capture web vitals\n const firstHidden = getVisibilityWatcher();\n // Only report if the page wasn't hidden prior to the web vital.\n const shouldRecord = entry.startTime < firstHidden.firstHiddenTime;\n\n if (entry.name === 'first-paint' && shouldRecord) {\n DEBUG_BUILD && logger.log('[Measurements] Adding FP');\n _measurements['fp'] = { value: entry.startTime, unit: 'millisecond' };\n }\n if (entry.name === 'first-contentful-paint' && shouldRecord) {\n DEBUG_BUILD && logger.log('[Measurements] Adding FCP');\n _measurements['fcp'] = { value: entry.startTime, unit: 'millisecond' };\n }\n break;\n }\n case 'resource': {\n _addResourceSpans(transaction, entry, entry.name as string, startTime, duration, timeOrigin);\n break;\n }\n default:\n // Ignore other entry types.\n }\n });\n\n _performanceCursor = Math.max(performanceEntries.length - 1, 0);\n\n _trackNavigator(transaction);\n\n // Measurements are only available for pageload transactions\n if (op === 'pageload') {\n _addTtfbRequestTimeToMeasurements(_measurements);\n\n ['fcp', 'fp', 'lcp'].forEach(name => {\n if (!_measurements[name] || !transactionStartTime || timeOrigin >= transactionStartTime) {\n return;\n }\n // The web vitals, fcp, fp, lcp, and ttfb, all measure relative to timeOrigin.\n // Unfortunately, timeOrigin is not captured within the transaction span data, so these web vitals will need\n // to be adjusted to be relative to transaction.startTimestamp.\n const oldValue = _measurements[name].value;\n const measurementTimestamp = timeOrigin + msToSec(oldValue);\n\n // normalizedValue should be in milliseconds\n const normalizedValue = Math.abs((measurementTimestamp - transactionStartTime) * 1000);\n const delta = normalizedValue - oldValue;\n\n DEBUG_BUILD && logger.log(`[Measurements] Normalized ${name} from ${oldValue} to ${normalizedValue} (${delta})`);\n _measurements[name].value = normalizedValue;\n });\n\n const fidMark = _measurements['mark.fid'];\n if (fidMark && _measurements['fid']) {\n // create span for FID\n _startChild(transaction, {\n description: 'first input delay',\n endTimestamp: fidMark.value + msToSec(_measurements['fid'].value),\n op: 'ui.action',\n origin: 'auto.ui.browser.metrics',\n startTimestamp: fidMark.value,\n });\n\n // Delete mark.fid as we don't want it to be part of final payload\n delete _measurements['mark.fid'];\n }\n\n // If FCP is not recorded we should not record the cls value\n // according to the new definition of CLS.\n if (!('fcp' in _measurements)) {\n delete _measurements.cls;\n }\n\n Object.keys(_measurements).forEach(measurementName => {\n setMeasurement(measurementName, _measurements[measurementName].value, _measurements[measurementName].unit);\n });\n\n _tagMetricInfo(transaction);\n }\n\n _lcpEntry = undefined;\n _clsEntry = undefined;\n _measurements = {};\n}\n\n/** Create measure related spans */\nexport function _addMeasureSpans(\n transaction: Transaction,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n entry: Record,\n startTime: number,\n duration: number,\n timeOrigin: number,\n): number {\n const measureStartTimestamp = timeOrigin + startTime;\n const measureEndTimestamp = measureStartTimestamp + duration;\n\n _startChild(transaction, {\n description: entry.name as string,\n endTimestamp: measureEndTimestamp,\n op: entry.entryType as string,\n origin: 'auto.resource.browser.metrics',\n startTimestamp: measureStartTimestamp,\n });\n\n return measureStartTimestamp;\n}\n\n/** Instrument navigation entries */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _addNavigationSpans(transaction: Transaction, entry: Record, timeOrigin: number): void {\n ['unloadEvent', 'redirect', 'domContentLoadedEvent', 'loadEvent', 'connect'].forEach(event => {\n _addPerformanceNavigationTiming(transaction, entry, event, timeOrigin);\n });\n _addPerformanceNavigationTiming(transaction, entry, 'secureConnection', timeOrigin, 'TLS/SSL', 'connectEnd');\n _addPerformanceNavigationTiming(transaction, entry, 'fetch', timeOrigin, 'cache', 'domainLookupStart');\n _addPerformanceNavigationTiming(transaction, entry, 'domainLookup', timeOrigin, 'DNS');\n _addRequest(transaction, entry, timeOrigin);\n}\n\n/** Create performance navigation related spans */\nfunction _addPerformanceNavigationTiming(\n transaction: Transaction,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n entry: Record,\n event: string,\n timeOrigin: number,\n description?: string,\n eventEnd?: string,\n): void {\n const end = eventEnd ? (entry[eventEnd] as number | undefined) : (entry[`${event}End`] as number | undefined);\n const start = entry[`${event}Start`] as number | undefined;\n if (!start || !end) {\n return;\n }\n _startChild(transaction, {\n op: 'browser',\n origin: 'auto.browser.browser.metrics',\n description: description || event,\n startTimestamp: timeOrigin + msToSec(start),\n endTimestamp: timeOrigin + msToSec(end),\n });\n}\n\n/** Create request and response related spans */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _addRequest(transaction: Transaction, entry: Record, timeOrigin: number): void {\n if (entry.responseEnd) {\n // It is possible that we are collecting these metrics when the page hasn't finished loading yet, for example when the HTML slowly streams in.\n // In this case, ie. when the document request hasn't finished yet, `entry.responseEnd` will be 0.\n // In order not to produce faulty spans, where the end timestamp is before the start timestamp, we will only collect\n // these spans when the responseEnd value is available. The backend (Relay) would drop the entire transaction if it contained faulty spans.\n _startChild(transaction, {\n op: 'browser',\n origin: 'auto.browser.browser.metrics',\n description: 'request',\n startTimestamp: timeOrigin + msToSec(entry.requestStart as number),\n endTimestamp: timeOrigin + msToSec(entry.responseEnd as number),\n });\n\n _startChild(transaction, {\n op: 'browser',\n origin: 'auto.browser.browser.metrics',\n description: 'response',\n startTimestamp: timeOrigin + msToSec(entry.responseStart as number),\n endTimestamp: timeOrigin + msToSec(entry.responseEnd as number),\n });\n }\n}\n\nexport interface ResourceEntry extends Record {\n initiatorType?: string;\n transferSize?: number;\n encodedBodySize?: number;\n decodedBodySize?: number;\n renderBlockingStatus?: string;\n}\n\n/** Create resource-related spans */\nexport function _addResourceSpans(\n transaction: Transaction,\n entry: ResourceEntry,\n resourceUrl: string,\n startTime: number,\n duration: number,\n timeOrigin: number,\n): void {\n // we already instrument based on fetch and xhr, so we don't need to\n // duplicate spans here.\n if (entry.initiatorType === 'xmlhttprequest' || entry.initiatorType === 'fetch') {\n return;\n }\n\n const parsedUrl = parseUrl(resourceUrl);\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const data: Record = {};\n setResourceEntrySizeData(data, entry, 'transferSize', 'http.response_transfer_size');\n setResourceEntrySizeData(data, entry, 'encodedBodySize', 'http.response_content_length');\n setResourceEntrySizeData(data, entry, 'decodedBodySize', 'http.decoded_response_content_length');\n\n if ('renderBlockingStatus' in entry) {\n data['resource.render_blocking_status'] = entry.renderBlockingStatus;\n }\n if (parsedUrl.protocol) {\n data['url.scheme'] = parsedUrl.protocol.split(':').pop(); // the protocol returned by parseUrl includes a :, but OTEL spec does not, so we remove it.\n }\n\n if (parsedUrl.host) {\n data['server.address'] = parsedUrl.host;\n }\n\n data['url.same_origin'] = resourceUrl.includes(WINDOW.location.origin);\n\n const startTimestamp = timeOrigin + startTime;\n const endTimestamp = startTimestamp + duration;\n\n _startChild(transaction, {\n description: resourceUrl.replace(WINDOW.location.origin, ''),\n endTimestamp,\n op: entry.initiatorType ? `resource.${entry.initiatorType}` : 'resource.other',\n origin: 'auto.resource.browser.metrics',\n startTimestamp,\n data,\n });\n}\n\n/**\n * Capture the information of the user agent.\n */\nfunction _trackNavigator(transaction: Transaction): void {\n const navigator = WINDOW.navigator as null | (Navigator & NavigatorNetworkInformation & NavigatorDeviceMemory);\n if (!navigator) {\n return;\n }\n\n // track network connectivity\n const connection = navigator.connection;\n if (connection) {\n if (connection.effectiveType) {\n // TODO: Can we rewrite this to an attribute?\n // eslint-disable-next-line deprecation/deprecation\n transaction.setTag('effectiveConnectionType', connection.effectiveType);\n }\n\n if (connection.type) {\n // TODO: Can we rewrite this to an attribute?\n // eslint-disable-next-line deprecation/deprecation\n transaction.setTag('connectionType', connection.type);\n }\n\n if (isMeasurementValue(connection.rtt)) {\n _measurements['connection.rtt'] = { value: connection.rtt, unit: 'millisecond' };\n }\n }\n\n if (isMeasurementValue(navigator.deviceMemory)) {\n // TODO: Can we rewrite this to an attribute?\n // eslint-disable-next-line deprecation/deprecation\n transaction.setTag('deviceMemory', `${navigator.deviceMemory} GB`);\n }\n\n if (isMeasurementValue(navigator.hardwareConcurrency)) {\n // TODO: Can we rewrite this to an attribute?\n // eslint-disable-next-line deprecation/deprecation\n transaction.setTag('hardwareConcurrency', String(navigator.hardwareConcurrency));\n }\n}\n\n/** Add LCP / CLS data to transaction to allow debugging */\nfunction _tagMetricInfo(transaction: Transaction): void {\n if (_lcpEntry) {\n DEBUG_BUILD && logger.log('[Measurements] Adding LCP Data');\n\n // Capture Properties of the LCP element that contributes to the LCP.\n\n if (_lcpEntry.element) {\n // TODO: Can we rewrite this to an attribute?\n // eslint-disable-next-line deprecation/deprecation\n transaction.setTag('lcp.element', htmlTreeAsString(_lcpEntry.element));\n }\n\n if (_lcpEntry.id) {\n // TODO: Can we rewrite this to an attribute?\n // eslint-disable-next-line deprecation/deprecation\n transaction.setTag('lcp.id', _lcpEntry.id);\n }\n\n if (_lcpEntry.url) {\n // Trim URL to the first 200 characters.\n // TODO: Can we rewrite this to an attribute?\n // eslint-disable-next-line deprecation/deprecation\n transaction.setTag('lcp.url', _lcpEntry.url.trim().slice(0, 200));\n }\n\n // TODO: Can we rewrite this to an attribute?\n // eslint-disable-next-line deprecation/deprecation\n transaction.setTag('lcp.size', _lcpEntry.size);\n }\n\n // See: https://developer.mozilla.org/en-US/docs/Web/API/LayoutShift\n if (_clsEntry && _clsEntry.sources) {\n DEBUG_BUILD && logger.log('[Measurements] Adding CLS Data');\n _clsEntry.sources.forEach((source, index) =>\n // TODO: Can we rewrite this to an attribute?\n // eslint-disable-next-line deprecation/deprecation\n transaction.setTag(`cls.source.${index + 1}`, htmlTreeAsString(source.node)),\n );\n }\n}\n\nfunction setResourceEntrySizeData(\n data: Record,\n entry: ResourceEntry,\n key: keyof Pick,\n dataKey: 'http.response_transfer_size' | 'http.response_content_length' | 'http.decoded_response_content_length',\n): void {\n const entryVal = entry[key];\n if (entryVal != null && entryVal < MAX_INT_AS_BYTES) {\n data[dataKey] = entryVal;\n }\n}\n\n/**\n * Add ttfb request time information to measurements.\n *\n * ttfb information is added via vendored web vitals library.\n */\nfunction _addTtfbRequestTimeToMeasurements(_measurements: Measurements): void {\n const navEntry = getNavigationEntry();\n if (!navEntry) {\n return;\n }\n\n const { responseStart, requestStart } = navEntry;\n\n if (requestStart <= responseStart) {\n DEBUG_BUILD && logger.log('[Measurements] Adding TTFB Request Time');\n _measurements['ttfb.requestTime'] = {\n value: responseStart - requestStart,\n unit: 'millisecond',\n };\n }\n}\n\n/** Taken from @sentry/core sampling.ts */\nfunction getSampleRate(\n transactionContext: TransactionContext | undefined,\n options: ClientOptions,\n interactionsSampleRate: number,\n): number | boolean {\n if (!hasTracingEnabled(options)) {\n return false;\n }\n let sampleRate;\n if (transactionContext !== undefined && typeof options.tracesSampler === 'function') {\n sampleRate = options.tracesSampler({\n transactionContext,\n name: transactionContext.name,\n parentSampled: transactionContext.parentSampled,\n attributes: {\n // eslint-disable-next-line deprecation/deprecation\n ...transactionContext.data,\n ...transactionContext.attributes,\n },\n location: WINDOW.location,\n });\n } else if (transactionContext !== undefined && transactionContext.sampled !== undefined) {\n sampleRate = transactionContext.sampled;\n } else if (typeof options.tracesSampleRate !== 'undefined') {\n sampleRate = options.tracesSampleRate;\n } else {\n sampleRate = 1;\n }\n if (!isValidSampleRate(sampleRate)) {\n DEBUG_BUILD && logger.warn('[Tracing] Discarding interaction span because of invalid sample rate.');\n return false;\n }\n if (sampleRate === true) {\n return interactionsSampleRate;\n } else if (sampleRate === false) {\n return 0;\n }\n return sampleRate * interactionsSampleRate;\n}\n", "import {\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n getClient,\n getCurrentScope,\n getDynamicSamplingContextFromClient,\n getDynamicSamplingContextFromSpan,\n getIsolationScope,\n hasTracingEnabled,\n setHttpStatus,\n spanToTraceHeader,\n startInactiveSpan,\n} from '@sentry/core';\nimport type { Client, HandlerDataFetch, Scope, Span, SpanOrigin } from '@sentry/types';\nimport {\n BAGGAGE_HEADER_NAME,\n dynamicSamplingContextToSentryBaggageHeader,\n generateSentryTraceHeader,\n isInstanceOf,\n parseUrl,\n} from '@sentry/utils';\n\ntype PolymorphicRequestHeaders =\n | Record\n | Array<[string, string]>\n // the below is not preicsely the Header type used in Request, but it'll pass duck-typing\n | {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [key: string]: any;\n append: (key: string, value: string) => void;\n get: (key: string) => string | null | undefined;\n };\n\n/**\n * Create and track fetch request spans for usage in combination with `addInstrumentationHandler`.\n *\n * @returns Span if a span was created, otherwise void.\n */\nexport function instrumentFetchRequest(\n handlerData: HandlerDataFetch,\n shouldCreateSpan: (url: string) => boolean,\n shouldAttachHeaders: (url: string) => boolean,\n spans: Record,\n spanOrigin: SpanOrigin = 'auto.http.browser',\n): Span | undefined {\n if (!hasTracingEnabled() || !handlerData.fetchData) {\n return undefined;\n }\n\n const shouldCreateSpanResult = shouldCreateSpan(handlerData.fetchData.url);\n\n if (handlerData.endTimestamp && shouldCreateSpanResult) {\n const spanId = handlerData.fetchData.__span;\n if (!spanId) return;\n\n const span = spans[spanId];\n if (span) {\n endSpan(span, handlerData);\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete spans[spanId];\n }\n return undefined;\n }\n\n const scope = getCurrentScope();\n const client = getClient();\n\n const { method, url } = handlerData.fetchData;\n\n const fullUrl = getFullURL(url);\n const host = fullUrl ? parseUrl(fullUrl).host : undefined;\n\n const span = shouldCreateSpanResult\n ? startInactiveSpan({\n name: `${method} ${url}`,\n onlyIfParent: true,\n attributes: {\n url,\n type: 'fetch',\n 'http.method': method,\n 'http.url': fullUrl,\n 'server.address': host,\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: spanOrigin,\n },\n op: 'http.client',\n })\n : undefined;\n\n if (span) {\n handlerData.fetchData.__span = span.spanContext().spanId;\n spans[span.spanContext().spanId] = span;\n }\n\n if (shouldAttachHeaders(handlerData.fetchData.url) && client) {\n const request: string | Request = handlerData.args[0];\n\n // In case the user hasn't set the second argument of a fetch call we default it to `{}`.\n handlerData.args[1] = handlerData.args[1] || {};\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const options: { [key: string]: any } = handlerData.args[1];\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access\n options.headers = addTracingHeadersToFetchRequest(request, client, scope, options, span);\n }\n\n return span;\n}\n\n/**\n * Adds sentry-trace and baggage headers to the various forms of fetch headers\n */\nexport function addTracingHeadersToFetchRequest(\n request: string | unknown, // unknown is actually type Request but we can't export DOM types from this package,\n client: Client,\n scope: Scope,\n options: {\n headers?:\n | {\n [key: string]: string[] | string | undefined;\n }\n | PolymorphicRequestHeaders;\n },\n requestSpan?: Span,\n): PolymorphicRequestHeaders | undefined {\n // eslint-disable-next-line deprecation/deprecation\n const span = requestSpan || scope.getSpan();\n\n const isolationScope = getIsolationScope();\n\n const { traceId, spanId, sampled, dsc } = {\n ...isolationScope.getPropagationContext(),\n ...scope.getPropagationContext(),\n };\n\n const sentryTraceHeader = span ? spanToTraceHeader(span) : generateSentryTraceHeader(traceId, spanId, sampled);\n\n const sentryBaggageHeader = dynamicSamplingContextToSentryBaggageHeader(\n dsc ||\n (span ? getDynamicSamplingContextFromSpan(span) : getDynamicSamplingContextFromClient(traceId, client, scope)),\n );\n\n const headers =\n options.headers ||\n (typeof Request !== 'undefined' && isInstanceOf(request, Request) ? (request as Request).headers : undefined);\n\n if (!headers) {\n return { 'sentry-trace': sentryTraceHeader, baggage: sentryBaggageHeader };\n } else if (typeof Headers !== 'undefined' && isInstanceOf(headers, Headers)) {\n const newHeaders = new Headers(headers as Headers);\n\n newHeaders.append('sentry-trace', sentryTraceHeader);\n\n if (sentryBaggageHeader) {\n // If the same header is appended multiple times the browser will merge the values into a single request header.\n // Its therefore safe to simply push a \"baggage\" entry, even though there might already be another baggage header.\n newHeaders.append(BAGGAGE_HEADER_NAME, sentryBaggageHeader);\n }\n\n return newHeaders as PolymorphicRequestHeaders;\n } else if (Array.isArray(headers)) {\n const newHeaders = [...headers, ['sentry-trace', sentryTraceHeader]];\n\n if (sentryBaggageHeader) {\n // If there are multiple entries with the same key, the browser will merge the values into a single request header.\n // Its therefore safe to simply push a \"baggage\" entry, even though there might already be another baggage header.\n newHeaders.push([BAGGAGE_HEADER_NAME, sentryBaggageHeader]);\n }\n\n return newHeaders as PolymorphicRequestHeaders;\n } else {\n const existingBaggageHeader = 'baggage' in headers ? headers.baggage : undefined;\n const newBaggageHeaders: string[] = [];\n\n if (Array.isArray(existingBaggageHeader)) {\n newBaggageHeaders.push(...existingBaggageHeader);\n } else if (existingBaggageHeader) {\n newBaggageHeaders.push(existingBaggageHeader);\n }\n\n if (sentryBaggageHeader) {\n newBaggageHeaders.push(sentryBaggageHeader);\n }\n\n return {\n ...(headers as Exclude),\n 'sentry-trace': sentryTraceHeader,\n baggage: newBaggageHeaders.length > 0 ? newBaggageHeaders.join(',') : undefined,\n };\n }\n}\n\nfunction getFullURL(url: string): string | undefined {\n try {\n const parsed = new URL(url);\n return parsed.href;\n } catch {\n return undefined;\n }\n}\n\nfunction endSpan(span: Span, handlerData: HandlerDataFetch): void {\n if (handlerData.response) {\n setHttpStatus(span, handlerData.response.status);\n\n const contentLength =\n handlerData.response && handlerData.response.headers && handlerData.response.headers.get('content-length');\n\n if (contentLength) {\n const contentLengthNum = parseInt(contentLength);\n if (contentLengthNum > 0) {\n span.setAttribute('http.response_content_length', contentLengthNum);\n }\n }\n } else if (handlerData.error) {\n span.setStatus('internal_error');\n }\n span.end();\n}\n", "/* eslint-disable max-lines */\nimport {\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n getClient,\n getCurrentScope,\n getDynamicSamplingContextFromClient,\n getDynamicSamplingContextFromSpan,\n getIsolationScope,\n hasTracingEnabled,\n setHttpStatus,\n spanToJSON,\n spanToTraceHeader,\n startInactiveSpan,\n} from '@sentry/core';\nimport type { HandlerDataXhr, SentryWrappedXMLHttpRequest, Span } from '@sentry/types';\nimport {\n BAGGAGE_HEADER_NAME,\n SENTRY_XHR_DATA_KEY,\n addFetchInstrumentationHandler,\n addXhrInstrumentationHandler,\n browserPerformanceTimeOrigin,\n dynamicSamplingContextToSentryBaggageHeader,\n generateSentryTraceHeader,\n parseUrl,\n stringMatchesSomePattern,\n} from '@sentry/utils';\n\nimport { instrumentFetchRequest } from '../common/fetch';\nimport { addPerformanceInstrumentationHandler } from './instrument';\nimport { WINDOW } from './types';\n\nexport const DEFAULT_TRACE_PROPAGATION_TARGETS = ['localhost', /^\\/(?!\\/)/];\n\n/** Options for Request Instrumentation */\nexport interface RequestInstrumentationOptions {\n /**\n * @deprecated Will be removed in v8.\n * Use `shouldCreateSpanForRequest` to control span creation and `tracePropagationTargets` to control\n * trace header attachment.\n */\n tracingOrigins: Array;\n\n /**\n * List of strings and/or regexes used to determine which outgoing requests will have `sentry-trace` and `baggage`\n * headers attached.\n *\n * @deprecated Use the top-level `tracePropagationTargets` option in `Sentry.init` instead.\n * This option will be removed in v8.\n *\n * Default: ['localhost', /^\\//] @see {DEFAULT_TRACE_PROPAGATION_TARGETS}\n */\n tracePropagationTargets: Array;\n\n /**\n * Flag to disable patching all together for fetch requests.\n *\n * Default: true\n */\n traceFetch: boolean;\n\n /**\n * Flag to disable patching all together for xhr requests.\n *\n * Default: true\n */\n traceXHR: boolean;\n\n /**\n * If true, Sentry will capture http timings and add them to the corresponding http spans.\n *\n * Default: true\n */\n enableHTTPTimings: boolean;\n\n /**\n * This function will be called before creating a span for a request with the given url.\n * Return false if you don't want a span for the given url.\n *\n * Default: (url: string) => true\n */\n shouldCreateSpanForRequest?(this: void, url: string): boolean;\n}\n\nexport const defaultRequestInstrumentationOptions: RequestInstrumentationOptions = {\n traceFetch: true,\n traceXHR: true,\n enableHTTPTimings: true,\n // TODO (v8): Remove this property\n tracingOrigins: DEFAULT_TRACE_PROPAGATION_TARGETS,\n tracePropagationTargets: DEFAULT_TRACE_PROPAGATION_TARGETS,\n};\n\n/** Registers span creators for xhr and fetch requests */\nexport function instrumentOutgoingRequests(_options?: Partial): void {\n const {\n traceFetch,\n traceXHR,\n // eslint-disable-next-line deprecation/deprecation\n tracePropagationTargets,\n // eslint-disable-next-line deprecation/deprecation\n tracingOrigins,\n shouldCreateSpanForRequest,\n enableHTTPTimings,\n } = {\n traceFetch: defaultRequestInstrumentationOptions.traceFetch,\n traceXHR: defaultRequestInstrumentationOptions.traceXHR,\n ..._options,\n };\n\n const shouldCreateSpan =\n typeof shouldCreateSpanForRequest === 'function' ? shouldCreateSpanForRequest : (_: string) => true;\n\n // TODO(v8) Remove tracingOrigins here\n // The only reason we're passing it in here is because this instrumentOutgoingRequests function is publicly exported\n // and we don't want to break the API. We can remove it in v8.\n const shouldAttachHeadersWithTargets = (url: string): boolean =>\n shouldAttachHeaders(url, tracePropagationTargets || tracingOrigins);\n\n const spans: Record = {};\n\n if (traceFetch) {\n addFetchInstrumentationHandler(handlerData => {\n const createdSpan = instrumentFetchRequest(handlerData, shouldCreateSpan, shouldAttachHeadersWithTargets, spans);\n // We cannot use `window.location` in the generic fetch instrumentation,\n // but we need it for reliable `server.address` attribute.\n // so we extend this in here\n if (createdSpan) {\n const fullUrl = getFullURL(handlerData.fetchData.url);\n const host = fullUrl ? parseUrl(fullUrl).host : undefined;\n createdSpan.setAttributes({\n 'http.url': fullUrl,\n 'server.address': host,\n });\n }\n\n if (enableHTTPTimings && createdSpan) {\n addHTTPTimings(createdSpan);\n }\n });\n }\n\n if (traceXHR) {\n addXhrInstrumentationHandler(handlerData => {\n const createdSpan = xhrCallback(handlerData, shouldCreateSpan, shouldAttachHeadersWithTargets, spans);\n if (enableHTTPTimings && createdSpan) {\n addHTTPTimings(createdSpan);\n }\n });\n }\n}\n\nfunction isPerformanceResourceTiming(entry: PerformanceEntry): entry is PerformanceResourceTiming {\n return (\n entry.entryType === 'resource' &&\n 'initiatorType' in entry &&\n typeof (entry as PerformanceResourceTiming).nextHopProtocol === 'string' &&\n (entry.initiatorType === 'fetch' || entry.initiatorType === 'xmlhttprequest')\n );\n}\n\n/**\n * Creates a temporary observer to listen to the next fetch/xhr resourcing timings,\n * so that when timings hit their per-browser limit they don't need to be removed.\n *\n * @param span A span that has yet to be finished, must contain `url` on data.\n */\nfunction addHTTPTimings(span: Span): void {\n const { url } = spanToJSON(span).data || {};\n\n if (!url || typeof url !== 'string') {\n return;\n }\n\n const cleanup = addPerformanceInstrumentationHandler('resource', ({ entries }) => {\n entries.forEach(entry => {\n if (isPerformanceResourceTiming(entry) && entry.name.endsWith(url)) {\n const spanData = resourceTimingEntryToSpanData(entry);\n spanData.forEach(data => span.setAttribute(...data));\n // In the next tick, clean this handler up\n // We have to wait here because otherwise this cleans itself up before it is fully done\n setTimeout(cleanup);\n }\n });\n });\n}\n\n/**\n * Converts ALPN protocol ids to name and version.\n *\n * (https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml#alpn-protocol-ids)\n * @param nextHopProtocol PerformanceResourceTiming.nextHopProtocol\n */\nexport function extractNetworkProtocol(nextHopProtocol: string): { name: string; version: string } {\n let name = 'unknown';\n let version = 'unknown';\n let _name = '';\n for (const char of nextHopProtocol) {\n // http/1.1 etc.\n if (char === '/') {\n [name, version] = nextHopProtocol.split('/');\n break;\n }\n // h2, h3 etc.\n if (!isNaN(Number(char))) {\n name = _name === 'h' ? 'http' : _name;\n version = nextHopProtocol.split(_name)[1];\n break;\n }\n _name += char;\n }\n if (_name === nextHopProtocol) {\n // webrtc, ftp, etc.\n name = _name;\n }\n return { name, version };\n}\n\nfunction getAbsoluteTime(time: number = 0): number {\n return ((browserPerformanceTimeOrigin || performance.timeOrigin) + time) / 1000;\n}\n\nfunction resourceTimingEntryToSpanData(resourceTiming: PerformanceResourceTiming): [string, string | number][] {\n const { name, version } = extractNetworkProtocol(resourceTiming.nextHopProtocol);\n\n const timingSpanData: [string, string | number][] = [];\n\n timingSpanData.push(['network.protocol.version', version], ['network.protocol.name', name]);\n\n if (!browserPerformanceTimeOrigin) {\n return timingSpanData;\n }\n return [\n ...timingSpanData,\n ['http.request.redirect_start', getAbsoluteTime(resourceTiming.redirectStart)],\n ['http.request.fetch_start', getAbsoluteTime(resourceTiming.fetchStart)],\n ['http.request.domain_lookup_start', getAbsoluteTime(resourceTiming.domainLookupStart)],\n ['http.request.domain_lookup_end', getAbsoluteTime(resourceTiming.domainLookupEnd)],\n ['http.request.connect_start', getAbsoluteTime(resourceTiming.connectStart)],\n ['http.request.secure_connection_start', getAbsoluteTime(resourceTiming.secureConnectionStart)],\n ['http.request.connection_end', getAbsoluteTime(resourceTiming.connectEnd)],\n ['http.request.request_start', getAbsoluteTime(resourceTiming.requestStart)],\n ['http.request.response_start', getAbsoluteTime(resourceTiming.responseStart)],\n ['http.request.response_end', getAbsoluteTime(resourceTiming.responseEnd)],\n ];\n}\n\n/**\n * A function that determines whether to attach tracing headers to a request.\n * This was extracted from `instrumentOutgoingRequests` to make it easier to test shouldAttachHeaders.\n * We only export this fuction for testing purposes.\n */\nexport function shouldAttachHeaders(url: string, tracePropagationTargets: (string | RegExp)[] | undefined): boolean {\n return stringMatchesSomePattern(url, tracePropagationTargets || DEFAULT_TRACE_PROPAGATION_TARGETS);\n}\n\n/**\n * Create and track xhr request spans\n *\n * @returns Span if a span was created, otherwise void.\n */\n// eslint-disable-next-line complexity\nexport function xhrCallback(\n handlerData: HandlerDataXhr,\n shouldCreateSpan: (url: string) => boolean,\n shouldAttachHeaders: (url: string) => boolean,\n spans: Record,\n): Span | undefined {\n const xhr = handlerData.xhr;\n const sentryXhrData = xhr && xhr[SENTRY_XHR_DATA_KEY];\n\n if (!hasTracingEnabled() || !xhr || xhr.__sentry_own_request__ || !sentryXhrData) {\n return undefined;\n }\n\n const shouldCreateSpanResult = shouldCreateSpan(sentryXhrData.url);\n\n // check first if the request has finished and is tracked by an existing span which should now end\n if (handlerData.endTimestamp && shouldCreateSpanResult) {\n const spanId = xhr.__sentry_xhr_span_id__;\n if (!spanId) return;\n\n const span = spans[spanId];\n if (span && sentryXhrData.status_code !== undefined) {\n setHttpStatus(span, sentryXhrData.status_code);\n span.end();\n\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete spans[spanId];\n }\n return undefined;\n }\n\n const scope = getCurrentScope();\n const isolationScope = getIsolationScope();\n\n const fullUrl = getFullURL(sentryXhrData.url);\n const host = fullUrl ? parseUrl(fullUrl).host : undefined;\n\n const span = shouldCreateSpanResult\n ? startInactiveSpan({\n name: `${sentryXhrData.method} ${sentryXhrData.url}`,\n onlyIfParent: true,\n attributes: {\n type: 'xhr',\n 'http.method': sentryXhrData.method,\n 'http.url': fullUrl,\n url: sentryXhrData.url,\n 'server.address': host,\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.http.browser',\n },\n op: 'http.client',\n })\n : undefined;\n\n if (span) {\n xhr.__sentry_xhr_span_id__ = span.spanContext().spanId;\n spans[xhr.__sentry_xhr_span_id__] = span;\n }\n\n const client = getClient();\n\n if (xhr.setRequestHeader && shouldAttachHeaders(sentryXhrData.url) && client) {\n const { traceId, spanId, sampled, dsc } = {\n ...isolationScope.getPropagationContext(),\n ...scope.getPropagationContext(),\n };\n\n const sentryTraceHeader = span ? spanToTraceHeader(span) : generateSentryTraceHeader(traceId, spanId, sampled);\n\n const sentryBaggageHeader = dynamicSamplingContextToSentryBaggageHeader(\n dsc ||\n (span ? getDynamicSamplingContextFromSpan(span) : getDynamicSamplingContextFromClient(traceId, client, scope)),\n );\n\n setHeaderOnXhr(xhr, sentryTraceHeader, sentryBaggageHeader);\n }\n\n return span;\n}\n\nfunction setHeaderOnXhr(\n xhr: SentryWrappedXMLHttpRequest,\n sentryTraceHeader: string,\n sentryBaggageHeader: string | undefined,\n): void {\n try {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n xhr.setRequestHeader!('sentry-trace', sentryTraceHeader);\n if (sentryBaggageHeader) {\n // From MDN: \"If this method is called several times with the same header, the values are merged into one single request header.\"\n // We can therefore simply set a baggage header without checking what was there before\n // https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/setRequestHeader\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n xhr.setRequestHeader!(BAGGAGE_HEADER_NAME, sentryBaggageHeader);\n }\n } catch (_) {\n // Error: InvalidStateError: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': The object's state must be OPENED.\n }\n}\n\nfunction getFullURL(url: string): string | undefined {\n try {\n // By adding a base URL to new URL(), this will also work for relative urls\n // If `url` is a full URL, the base URL is ignored anyhow\n const parsed = new URL(url, WINDOW.location.origin);\n return parsed.href;\n } catch {\n return undefined;\n }\n}\n", "import type { Transaction, TransactionContext } from '@sentry/types';\nimport { addHistoryInstrumentationHandler, browserPerformanceTimeOrigin, logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../common/debug-build';\nimport { WINDOW } from './types';\n\n/**\n * Default function implementing pageload and navigation transactions\n */\nexport function instrumentRoutingWithDefaults(\n customStartTransaction: (context: TransactionContext) => T | undefined,\n startTransactionOnPageLoad: boolean = true,\n startTransactionOnLocationChange: boolean = true,\n): void {\n if (!WINDOW || !WINDOW.location) {\n DEBUG_BUILD && logger.warn('Could not initialize routing instrumentation due to invalid location');\n return;\n }\n\n let startingUrl: string | undefined = WINDOW.location.href;\n\n let activeTransaction: T | undefined;\n if (startTransactionOnPageLoad) {\n activeTransaction = customStartTransaction({\n name: WINDOW.location.pathname,\n // pageload should always start at timeOrigin (and needs to be in s, not ms)\n startTimestamp: browserPerformanceTimeOrigin ? browserPerformanceTimeOrigin / 1000 : undefined,\n op: 'pageload',\n origin: 'auto.pageload.browser',\n metadata: { source: 'url' },\n });\n }\n\n if (startTransactionOnLocationChange) {\n addHistoryInstrumentationHandler(({ to, from }) => {\n /**\n * This early return is there to account for some cases where a navigation transaction starts right after\n * long-running pageload. We make sure that if `from` is undefined and a valid `startingURL` exists, we don't\n * create an uneccessary navigation transaction.\n *\n * This was hard to duplicate, but this behavior stopped as soon as this fix was applied. This issue might also\n * only be caused in certain development environments where the usage of a hot module reloader is causing\n * errors.\n */\n if (from === undefined && startingUrl && startingUrl.indexOf(to) !== -1) {\n startingUrl = undefined;\n return;\n }\n\n if (from !== to) {\n startingUrl = undefined;\n if (activeTransaction) {\n DEBUG_BUILD && logger.log(`[Tracing] Finishing current transaction with op: ${activeTransaction.op}`);\n // If there's an open transaction on the scope, we need to finish it before creating an new one.\n activeTransaction.end();\n }\n activeTransaction = customStartTransaction({\n name: WINDOW.location.pathname,\n op: 'navigation',\n origin: 'auto.navigation.browser',\n metadata: { source: 'url' },\n });\n }\n });\n }\n}\n", "/* eslint-disable max-lines */\nimport type { Hub, IdleTransaction } from '@sentry/core';\nimport { getClient, getCurrentScope } from '@sentry/core';\nimport {\n SEMANTIC_ATTRIBUTE_SENTRY_SOURCE,\n TRACING_DEFAULTS,\n addTracingExtensions,\n getActiveTransaction,\n startIdleTransaction,\n} from '@sentry/core';\nimport type { EventProcessor, Integration, Transaction, TransactionContext, TransactionSource } from '@sentry/types';\nimport { getDomElement, logger, propagationContextFromHeaders } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../common/debug-build';\nimport { registerBackgroundTabDetection } from './backgroundtab';\nimport { addPerformanceInstrumentationHandler } from './instrument';\nimport {\n addPerformanceEntries,\n startTrackingINP,\n startTrackingInteractions,\n startTrackingLongTasks,\n startTrackingWebVitals,\n} from './metrics';\nimport type { RequestInstrumentationOptions } from './request';\nimport { defaultRequestInstrumentationOptions, instrumentOutgoingRequests } from './request';\nimport { instrumentRoutingWithDefaults } from './router';\nimport { WINDOW } from './types';\nimport type { InteractionRouteNameMapping } from './web-vitals/types';\n\nexport const BROWSER_TRACING_INTEGRATION_ID = 'BrowserTracing';\n\n/** Options for Browser Tracing integration */\nexport interface BrowserTracingOptions extends RequestInstrumentationOptions {\n /**\n * The time to wait in ms until the transaction will be finished during an idle state. An idle state is defined\n * by a moment where there are no in-progress spans.\n *\n * The transaction will use the end timestamp of the last finished span as the endtime for the transaction.\n * If there are still active spans when this the `idleTimeout` is set, the `idleTimeout` will get reset.\n * Time is in ms.\n *\n * Default: 1000\n */\n idleTimeout: number;\n\n /**\n * The max duration for a transaction. If a transaction duration hits the `finalTimeout` value, it\n * will be finished.\n * Time is in ms.\n *\n * Default: 30000\n */\n finalTimeout: number;\n\n /**\n * The heartbeat interval. If no new spans are started or open spans are finished within 3 heartbeats,\n * the transaction will be finished.\n * Time is in ms.\n *\n * Default: 5000\n */\n heartbeatInterval: number;\n\n /**\n * Flag to enable/disable creation of `navigation` transaction on history changes.\n *\n * Default: true\n */\n startTransactionOnLocationChange: boolean;\n\n /**\n * Flag to enable/disable creation of `pageload` transaction on first pageload.\n *\n * Default: true\n */\n startTransactionOnPageLoad: boolean;\n\n /**\n * Flag Transactions where tabs moved to background with \"cancelled\". Browser background tab timing is\n * not suited towards doing precise measurements of operations. By default, we recommend that this option\n * be enabled as background transactions can mess up your statistics in nondeterministic ways.\n *\n * Default: true\n */\n markBackgroundTransactions: boolean;\n\n /**\n * If true, Sentry will capture long tasks and add them to the corresponding transaction.\n *\n * Default: true\n */\n enableLongTask: boolean;\n\n /**\n * If true, Sentry will capture INP web vitals as standalone spans .\n *\n * Default: false\n */\n enableInp: boolean;\n\n /**\n * Sample rate to determine interaction span sampling.\n * interactionsSampleRate is applied on top of the global tracesSampleRate.\n * ie a tracesSampleRate of 0.1 and interactionsSampleRate of 0.5 will result in a 0.05 sample rate for interactions.\n *\n * Default: 1\n */\n interactionsSampleRate: number;\n\n /**\n * _metricOptions allows the user to send options to change how metrics are collected.\n *\n * _metricOptions is currently experimental.\n *\n * Default: undefined\n */\n _metricOptions?: Partial<{\n /**\n * @deprecated This property no longer has any effect and will be removed in v8.\n */\n _reportAllChanges: boolean;\n }>;\n\n /**\n * _experiments allows the user to send options to define how this integration works.\n * Note that the `enableLongTask` options is deprecated in favor of the option at the top level, and will be removed in v8.\n *\n * TODO (v8): Remove enableLongTask\n *\n * Default: undefined\n */\n _experiments: Partial<{\n enableLongTask: boolean;\n enableInteractions: boolean;\n // eslint-disable-next-line deprecation/deprecation\n onStartRouteTransaction: (t: Transaction | undefined, ctx: TransactionContext, getCurrentHub: () => Hub) => void;\n }>;\n\n /**\n * beforeNavigate is called before a pageload/navigation transaction is created and allows users to modify transaction\n * context data, or drop the transaction entirely (by setting `sampled = false` in the context).\n *\n * Note: For legacy reasons, transactions can also be dropped by returning `undefined`.\n *\n * @param context: The context data which will be passed to `startTransaction` by default\n *\n * @returns A (potentially) modified context object, with `sampled = false` if the transaction should be dropped.\n */\n beforeNavigate?(this: void, context: TransactionContext): TransactionContext | undefined;\n\n /**\n * Instrumentation that creates routing change transactions. By default creates\n * pageload and navigation transactions.\n */\n routingInstrumentation(\n this: void,\n customStartTransaction: (context: TransactionContext) => T | undefined,\n startTransactionOnPageLoad?: boolean,\n startTransactionOnLocationChange?: boolean,\n ): void;\n}\n\nconst DEFAULT_BROWSER_TRACING_OPTIONS: BrowserTracingOptions = {\n ...TRACING_DEFAULTS,\n markBackgroundTransactions: true,\n routingInstrumentation: instrumentRoutingWithDefaults,\n startTransactionOnLocationChange: true,\n startTransactionOnPageLoad: true,\n enableLongTask: true,\n enableInp: false,\n interactionsSampleRate: 1,\n _experiments: {},\n ...defaultRequestInstrumentationOptions,\n};\n\n/** We store up to 10 interaction candidates max to cap memory usage. This is the same cap as getINP from web-vitals */\nconst MAX_INTERACTIONS = 10;\n\n/**\n * The Browser Tracing integration automatically instruments browser pageload/navigation\n * actions as transactions, and captures requests, metrics and errors as spans.\n *\n * The integration can be configured with a variety of options, and can be extended to use\n * any routing library. This integration uses {@see IdleTransaction} to create transactions.\n *\n * @deprecated Use `browserTracingIntegration()` instead.\n */\nexport class BrowserTracing implements Integration {\n // This class currently doesn't have a static `id` field like the other integration classes, because it prevented\n // @sentry/tracing from being treeshaken. Tree shakers do not like static fields, because they behave like side effects.\n // TODO: Come up with a better plan, than using static fields on integration classes, and use that plan on all\n // integrations.\n\n /** Browser Tracing integration options */\n public options: BrowserTracingOptions;\n\n /**\n * @inheritDoc\n */\n public name: string;\n\n // eslint-disable-next-line deprecation/deprecation\n private _getCurrentHub?: () => Hub;\n\n private _collectWebVitals: () => void;\n\n private _hasSetTracePropagationTargets: boolean;\n private _interactionIdToRouteNameMapping: InteractionRouteNameMapping;\n private _latestRoute: {\n name: string | undefined;\n context: TransactionContext | undefined;\n };\n\n public constructor(_options?: Partial) {\n this.name = BROWSER_TRACING_INTEGRATION_ID;\n this._hasSetTracePropagationTargets = false;\n\n addTracingExtensions();\n\n if (DEBUG_BUILD) {\n this._hasSetTracePropagationTargets = !!(\n _options &&\n // eslint-disable-next-line deprecation/deprecation\n (_options.tracePropagationTargets || _options.tracingOrigins)\n );\n }\n\n this.options = {\n ...DEFAULT_BROWSER_TRACING_OPTIONS,\n ..._options,\n };\n\n // Special case: enableLongTask can be set in _experiments\n // TODO (v8): Remove this in v8\n if (this.options._experiments.enableLongTask !== undefined) {\n this.options.enableLongTask = this.options._experiments.enableLongTask;\n }\n\n // TODO (v8): remove this block after tracingOrigins is removed\n // Set tracePropagationTargets to tracingOrigins if specified by the user\n // In case both are specified, tracePropagationTargets takes precedence\n // eslint-disable-next-line deprecation/deprecation\n if (_options && !_options.tracePropagationTargets && _options.tracingOrigins) {\n // eslint-disable-next-line deprecation/deprecation\n this.options.tracePropagationTargets = _options.tracingOrigins;\n }\n\n this._collectWebVitals = startTrackingWebVitals();\n /** Stores a mapping of interactionIds from PerformanceEventTimings to the origin interaction path */\n this._interactionIdToRouteNameMapping = {};\n\n if (this.options.enableInp) {\n startTrackingINP(this._interactionIdToRouteNameMapping, this.options.interactionsSampleRate);\n }\n if (this.options.enableLongTask) {\n startTrackingLongTasks();\n }\n if (this.options._experiments.enableInteractions) {\n startTrackingInteractions();\n }\n\n this._latestRoute = {\n name: undefined,\n context: undefined,\n };\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line deprecation/deprecation\n public setupOnce(_: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void {\n this._getCurrentHub = getCurrentHub;\n const hub = getCurrentHub();\n // eslint-disable-next-line deprecation/deprecation\n const client = hub.getClient();\n const clientOptions = client && client.getOptions();\n\n const {\n routingInstrumentation: instrumentRouting,\n startTransactionOnLocationChange,\n startTransactionOnPageLoad,\n markBackgroundTransactions,\n traceFetch,\n traceXHR,\n shouldCreateSpanForRequest,\n enableHTTPTimings,\n _experiments,\n } = this.options;\n\n const clientOptionsTracePropagationTargets = clientOptions && clientOptions.tracePropagationTargets;\n // There are three ways to configure tracePropagationTargets:\n // 1. via top level client option `tracePropagationTargets`\n // 2. via BrowserTracing option `tracePropagationTargets`\n // 3. via BrowserTracing option `tracingOrigins` (deprecated)\n //\n // To avoid confusion, favour top level client option `tracePropagationTargets`, and fallback to\n // BrowserTracing option `tracePropagationTargets` and then `tracingOrigins` (deprecated).\n // This is done as it minimizes bundle size (we don't have to have undefined checks).\n //\n // If both 1 and either one of 2 or 3 are set (from above), we log out a warning.\n // eslint-disable-next-line deprecation/deprecation\n const tracePropagationTargets = clientOptionsTracePropagationTargets || this.options.tracePropagationTargets;\n if (DEBUG_BUILD && this._hasSetTracePropagationTargets && clientOptionsTracePropagationTargets) {\n logger.warn(\n '[Tracing] The `tracePropagationTargets` option was set in the BrowserTracing integration and top level `Sentry.init`. The top level `Sentry.init` value is being used.',\n );\n }\n\n instrumentRouting(\n (context: TransactionContext) => {\n const transaction = this._createRouteTransaction(context);\n\n this.options._experiments.onStartRouteTransaction &&\n this.options._experiments.onStartRouteTransaction(transaction, context, getCurrentHub);\n\n return transaction;\n },\n startTransactionOnPageLoad,\n startTransactionOnLocationChange,\n );\n\n if (markBackgroundTransactions) {\n registerBackgroundTabDetection();\n }\n\n if (_experiments.enableInteractions) {\n this._registerInteractionListener();\n }\n\n if (this.options.enableInp) {\n this._registerInpInteractionListener();\n }\n\n instrumentOutgoingRequests({\n traceFetch,\n traceXHR,\n tracePropagationTargets,\n shouldCreateSpanForRequest,\n enableHTTPTimings,\n });\n }\n\n /** Create routing idle transaction. */\n private _createRouteTransaction(context: TransactionContext): Transaction | undefined {\n if (!this._getCurrentHub) {\n DEBUG_BUILD &&\n logger.warn(`[Tracing] Did not create ${context.op} transaction because _getCurrentHub is invalid.`);\n return undefined;\n }\n\n const hub = this._getCurrentHub();\n\n const { beforeNavigate, idleTimeout, finalTimeout, heartbeatInterval } = this.options;\n\n const isPageloadTransaction = context.op === 'pageload';\n\n let expandedContext: TransactionContext;\n if (isPageloadTransaction) {\n const sentryTrace = isPageloadTransaction ? getMetaContent('sentry-trace') : '';\n const baggage = isPageloadTransaction ? getMetaContent('baggage') : undefined;\n const { traceId, dsc, parentSpanId, sampled } = propagationContextFromHeaders(sentryTrace, baggage);\n expandedContext = {\n traceId,\n parentSpanId,\n parentSampled: sampled,\n ...context,\n metadata: {\n // eslint-disable-next-line deprecation/deprecation\n ...context.metadata,\n dynamicSamplingContext: dsc,\n },\n trimEnd: true,\n };\n } else {\n expandedContext = {\n trimEnd: true,\n ...context,\n };\n }\n\n const modifiedContext = typeof beforeNavigate === 'function' ? beforeNavigate(expandedContext) : expandedContext;\n\n // For backwards compatibility reasons, beforeNavigate can return undefined to \"drop\" the transaction (prevent it\n // from being sent to Sentry).\n const finalContext = modifiedContext === undefined ? { ...expandedContext, sampled: false } : modifiedContext;\n\n // If `beforeNavigate` set a custom name, record that fact\n // eslint-disable-next-line deprecation/deprecation\n finalContext.metadata =\n finalContext.name !== expandedContext.name\n ? // eslint-disable-next-line deprecation/deprecation\n { ...finalContext.metadata, source: 'custom' }\n : // eslint-disable-next-line deprecation/deprecation\n finalContext.metadata;\n\n this._latestRoute.name = finalContext.name;\n this._latestRoute.context = finalContext;\n\n // eslint-disable-next-line deprecation/deprecation\n if (finalContext.sampled === false) {\n DEBUG_BUILD && logger.log(`[Tracing] Will not send ${finalContext.op} transaction because of beforeNavigate.`);\n }\n\n DEBUG_BUILD && logger.log(`[Tracing] Starting ${finalContext.op} transaction on scope`);\n\n const { location } = WINDOW;\n\n const idleTransaction = startIdleTransaction(\n hub,\n finalContext,\n idleTimeout,\n finalTimeout,\n true,\n { location }, // for use in the tracesSampler\n heartbeatInterval,\n isPageloadTransaction, // should wait for finish signal if it's a pageload transaction\n );\n\n if (isPageloadTransaction) {\n if (WINDOW.document) {\n WINDOW.document.addEventListener('readystatechange', () => {\n if (['interactive', 'complete'].includes(WINDOW.document!.readyState)) {\n idleTransaction.sendAutoFinishSignal();\n }\n });\n\n if (['interactive', 'complete'].includes(WINDOW.document.readyState)) {\n idleTransaction.sendAutoFinishSignal();\n }\n }\n }\n\n idleTransaction.registerBeforeFinishCallback(transaction => {\n this._collectWebVitals();\n addPerformanceEntries(transaction);\n });\n\n return idleTransaction as Transaction;\n }\n\n /** Start listener for interaction transactions */\n private _registerInteractionListener(): void {\n let inflightInteractionTransaction: IdleTransaction | undefined;\n const registerInteractionTransaction = (): void => {\n const { idleTimeout, finalTimeout, heartbeatInterval } = this.options;\n const op = 'ui.action.click';\n\n // eslint-disable-next-line deprecation/deprecation\n const currentTransaction = getActiveTransaction();\n if (currentTransaction && currentTransaction.op && ['navigation', 'pageload'].includes(currentTransaction.op)) {\n DEBUG_BUILD &&\n logger.warn(\n `[Tracing] Did not create ${op} transaction because a pageload or navigation transaction is in progress.`,\n );\n return undefined;\n }\n\n if (inflightInteractionTransaction) {\n inflightInteractionTransaction.setFinishReason('interactionInterrupted');\n inflightInteractionTransaction.end();\n inflightInteractionTransaction = undefined;\n }\n\n if (!this._getCurrentHub) {\n DEBUG_BUILD && logger.warn(`[Tracing] Did not create ${op} transaction because _getCurrentHub is invalid.`);\n return undefined;\n }\n\n if (!this._latestRoute.name) {\n DEBUG_BUILD && logger.warn(`[Tracing] Did not create ${op} transaction because _latestRouteName is missing.`);\n return undefined;\n }\n\n const hub = this._getCurrentHub();\n const { location } = WINDOW;\n\n const context: TransactionContext = {\n name: this._latestRoute.name,\n op,\n trimEnd: true,\n data: {\n [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: this._latestRoute.context\n ? getSource(this._latestRoute.context)\n : undefined || 'url',\n },\n };\n\n inflightInteractionTransaction = startIdleTransaction(\n hub,\n context,\n idleTimeout,\n finalTimeout,\n true,\n { location }, // for use in the tracesSampler\n heartbeatInterval,\n );\n };\n\n ['click'].forEach(type => {\n if (WINDOW.document) {\n addEventListener(type, registerInteractionTransaction, { once: false, capture: true });\n }\n });\n }\n\n /** Creates a listener on interaction entries, and maps interactionIds to the origin path of the interaction */\n private _registerInpInteractionListener(): void {\n const handleEntries = ({ entries }: { entries: PerformanceEntry[] }): void => {\n const client = getClient();\n // We need to get the replay, user, and activeTransaction from the current scope\n // so that we can associate replay id, profile id, and a user display to the span\n const replay =\n client !== undefined && client.getIntegrationByName !== undefined\n ? (client.getIntegrationByName('Replay') as Integration & { getReplayId: () => string })\n : undefined;\n const replayId = replay !== undefined ? replay.getReplayId() : undefined;\n // eslint-disable-next-line deprecation/deprecation\n const activeTransaction = getActiveTransaction();\n const currentScope = getCurrentScope();\n const user = currentScope !== undefined ? currentScope.getUser() : undefined;\n entries.forEach(entry => {\n if (isPerformanceEventTiming(entry)) {\n const interactionId = entry.interactionId;\n if (interactionId === undefined) {\n return;\n }\n const existingInteraction = this._interactionIdToRouteNameMapping[interactionId];\n const duration = entry.duration;\n const startTime = entry.startTime;\n const keys = Object.keys(this._interactionIdToRouteNameMapping);\n const minInteractionId =\n keys.length > 0\n ? keys.reduce((a, b) => {\n return this._interactionIdToRouteNameMapping[a].duration <\n this._interactionIdToRouteNameMapping[b].duration\n ? a\n : b;\n })\n : undefined;\n // For a first input event to be considered, we must check that an interaction event does not already exist with the same duration and start time.\n // This is also checked in the web-vitals library.\n if (entry.entryType === 'first-input') {\n const matchingEntry = keys\n .map(key => this._interactionIdToRouteNameMapping[key])\n .some(interaction => {\n return interaction.duration === duration && interaction.startTime === startTime;\n });\n if (matchingEntry) {\n return;\n }\n }\n // Interactions with an id of 0 and are not first-input are not valid.\n if (!interactionId) {\n return;\n }\n // If the interaction already exists, we want to use the duration of the longest entry, since that is what the INP metric uses.\n if (existingInteraction) {\n existingInteraction.duration = Math.max(existingInteraction.duration, duration);\n } else if (\n keys.length < MAX_INTERACTIONS ||\n minInteractionId === undefined ||\n duration > this._interactionIdToRouteNameMapping[minInteractionId].duration\n ) {\n // If the interaction does not exist, we want to add it to the mapping if there is space, or if the duration is longer than the shortest entry.\n const routeName = this._latestRoute.name;\n const parentContext = this._latestRoute.context;\n if (routeName && parentContext) {\n if (minInteractionId && Object.keys(this._interactionIdToRouteNameMapping).length >= MAX_INTERACTIONS) {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete this._interactionIdToRouteNameMapping[minInteractionId];\n }\n this._interactionIdToRouteNameMapping[interactionId] = {\n routeName,\n duration,\n parentContext,\n user,\n activeTransaction,\n replayId,\n startTime,\n };\n }\n }\n }\n });\n };\n addPerformanceInstrumentationHandler('event', handleEntries);\n addPerformanceInstrumentationHandler('first-input', handleEntries);\n }\n}\n\n/** Returns the value of a meta tag */\nexport function getMetaContent(metaName: string): string | undefined {\n // Can't specify generic to `getDomElement` because tracing can be used\n // in a variety of environments, have to disable `no-unsafe-member-access`\n // as a result.\n const metaTag = getDomElement(`meta[name=${metaName}]`);\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return metaTag ? metaTag.getAttribute('content') : undefined;\n}\n\nfunction getSource(context: TransactionContext): TransactionSource | undefined {\n const sourceFromAttributes = context.attributes && context.attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];\n // eslint-disable-next-line deprecation/deprecation\n const sourceFromData = context.data && context.data[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];\n // eslint-disable-next-line deprecation/deprecation\n const sourceFromMetadata = context.metadata && context.metadata.source;\n\n return sourceFromAttributes || sourceFromData || sourceFromMetadata;\n}\n\nfunction isPerformanceEventTiming(entry: PerformanceEntry): entry is PerformanceEventTiming {\n return 'duration' in entry;\n}\n", "/* eslint-disable max-lines */\nimport type { IdleTransaction } from '@sentry/core';\nimport { getActiveSpan, getClient, getCurrentScope } from '@sentry/core';\nimport { getCurrentHub } from '@sentry/core';\nimport {\n SEMANTIC_ATTRIBUTE_SENTRY_SOURCE,\n TRACING_DEFAULTS,\n addTracingExtensions,\n getActiveTransaction,\n spanToJSON,\n startIdleTransaction,\n} from '@sentry/core';\nimport type {\n Client,\n Integration,\n IntegrationFn,\n StartSpanOptions,\n Transaction,\n TransactionContext,\n TransactionSource,\n} from '@sentry/types';\nimport type { Span } from '@sentry/types';\nimport {\n addHistoryInstrumentationHandler,\n browserPerformanceTimeOrigin,\n getDomElement,\n logger,\n propagationContextFromHeaders,\n} from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../common/debug-build';\nimport { registerBackgroundTabDetection } from './backgroundtab';\nimport { addPerformanceInstrumentationHandler } from './instrument';\nimport {\n addPerformanceEntries,\n startTrackingINP,\n startTrackingInteractions,\n startTrackingLongTasks,\n startTrackingWebVitals,\n} from './metrics';\nimport type { RequestInstrumentationOptions } from './request';\nimport { defaultRequestInstrumentationOptions, instrumentOutgoingRequests } from './request';\nimport { WINDOW } from './types';\nimport type { InteractionRouteNameMapping } from './web-vitals/types';\n\nexport const BROWSER_TRACING_INTEGRATION_ID = 'BrowserTracing';\n\n/** Options for Browser Tracing integration */\nexport interface BrowserTracingOptions extends RequestInstrumentationOptions {\n /**\n * The time to wait in ms until the transaction will be finished during an idle state. An idle state is defined\n * by a moment where there are no in-progress spans.\n *\n * The transaction will use the end timestamp of the last finished span as the endtime for the transaction.\n * If there are still active spans when this the `idleTimeout` is set, the `idleTimeout` will get reset.\n * Time is in ms.\n *\n * Default: 1000\n */\n idleTimeout: number;\n\n /**\n * The max duration for a transaction. If a transaction duration hits the `finalTimeout` value, it\n * will be finished.\n * Time is in ms.\n *\n * Default: 30000\n */\n finalTimeout: number;\n\n /**\n * The heartbeat interval. If no new spans are started or open spans are finished within 3 heartbeats,\n * the transaction will be finished.\n * Time is in ms.\n *\n * Default: 5000\n */\n heartbeatInterval: number;\n\n /**\n * If a span should be created on page load.\n * If this is set to `false`, this integration will not start the default page load span.\n * Default: true\n */\n instrumentPageLoad: boolean;\n\n /**\n * If a span should be created on navigation (history change).\n * If this is set to `false`, this integration will not start the default navigation spans.\n * Default: true\n */\n instrumentNavigation: boolean;\n\n /**\n * Flag spans where tabs moved to background with \"cancelled\". Browser background tab timing is\n * not suited towards doing precise measurements of operations. By default, we recommend that this option\n * be enabled as background transactions can mess up your statistics in nondeterministic ways.\n *\n * Default: true\n */\n markBackgroundSpan: boolean;\n\n /**\n * If true, Sentry will capture long tasks and add them to the corresponding transaction.\n *\n * Default: true\n */\n enableLongTask: boolean;\n\n /**\n * If true, Sentry will capture INP web vitals as standalone spans .\n *\n * Default: false\n */\n enableInp: boolean;\n\n /**\n * Sample rate to determine interaction span sampling.\n * interactionsSampleRate is applied on top of the global tracesSampleRate.\n * ie a tracesSampleRate of 0.1 and interactionsSampleRate of 0.5 will result in a 0.05 sample rate for interactions.\n *\n * Default: 1\n */\n interactionsSampleRate: number;\n\n /**\n * _metricOptions allows the user to send options to change how metrics are collected.\n *\n * _metricOptions is currently experimental.\n *\n * Default: undefined\n */\n _metricOptions?: Partial<{\n /**\n * @deprecated This property no longer has any effect and will be removed in v8.\n */\n _reportAllChanges: boolean;\n }>;\n\n /**\n * _experiments allows the user to send options to define how this integration works.\n * Note that the `enableLongTask` options is deprecated in favor of the option at the top level, and will be removed in v8.\n *\n * TODO (v8): Remove enableLongTask\n *\n * Default: undefined\n */\n _experiments: Partial<{\n enableInteractions: boolean;\n }>;\n\n /**\n * A callback which is called before a span for a pageload or navigation is started.\n * It receives the options passed to `startSpan`, and expects to return an updated options object.\n */\n beforeStartSpan?: (options: StartSpanOptions) => StartSpanOptions;\n}\n\nconst DEFAULT_BROWSER_TRACING_OPTIONS: BrowserTracingOptions = {\n ...TRACING_DEFAULTS,\n instrumentNavigation: true,\n instrumentPageLoad: true,\n markBackgroundSpan: true,\n enableLongTask: true,\n enableInp: false,\n interactionsSampleRate: 1,\n _experiments: {},\n ...defaultRequestInstrumentationOptions,\n};\n\n/**\n * The Browser Tracing integration automatically instruments browser pageload/navigation\n * actions as transactions, and captures requests, metrics and errors as spans.\n *\n * The integration can be configured with a variety of options, and can be extended to use\n * any routing library. This integration uses {@see IdleTransaction} to create transactions.\n *\n * We explicitly export the proper type here, as this has to be extended in some cases.\n */\nexport const browserTracingIntegration = ((_options: Partial = {}) => {\n const _hasSetTracePropagationTargets = DEBUG_BUILD\n ? !!(\n // eslint-disable-next-line deprecation/deprecation\n (_options.tracePropagationTargets || _options.tracingOrigins)\n )\n : false;\n\n addTracingExtensions();\n\n // TODO (v8): remove this block after tracingOrigins is removed\n // Set tracePropagationTargets to tracingOrigins if specified by the user\n // In case both are specified, tracePropagationTargets takes precedence\n // eslint-disable-next-line deprecation/deprecation\n if (!_options.tracePropagationTargets && _options.tracingOrigins) {\n // eslint-disable-next-line deprecation/deprecation\n _options.tracePropagationTargets = _options.tracingOrigins;\n }\n\n const options = {\n ...DEFAULT_BROWSER_TRACING_OPTIONS,\n ..._options,\n };\n\n const _collectWebVitals = startTrackingWebVitals();\n\n /** Stores a mapping of interactionIds from PerformanceEventTimings to the origin interaction path */\n const interactionIdToRouteNameMapping: InteractionRouteNameMapping = {};\n if (options.enableInp) {\n startTrackingINP(interactionIdToRouteNameMapping, options.interactionsSampleRate);\n }\n\n if (options.enableLongTask) {\n startTrackingLongTasks();\n }\n if (options._experiments.enableInteractions) {\n startTrackingInteractions();\n }\n\n const latestRoute: {\n name: string | undefined;\n context: TransactionContext | undefined;\n } = {\n name: undefined,\n context: undefined,\n };\n\n /** Create routing idle transaction. */\n function _createRouteTransaction(context: TransactionContext): Transaction | undefined {\n // eslint-disable-next-line deprecation/deprecation\n const hub = getCurrentHub();\n\n const { beforeStartSpan, idleTimeout, finalTimeout, heartbeatInterval } = options;\n\n const isPageloadTransaction = context.op === 'pageload';\n\n let expandedContext: TransactionContext;\n if (isPageloadTransaction) {\n const sentryTrace = isPageloadTransaction ? getMetaContent('sentry-trace') : '';\n const baggage = isPageloadTransaction ? getMetaContent('baggage') : undefined;\n const { traceId, dsc, parentSpanId, sampled } = propagationContextFromHeaders(sentryTrace, baggage);\n expandedContext = {\n traceId,\n parentSpanId,\n parentSampled: sampled,\n ...context,\n metadata: {\n // eslint-disable-next-line deprecation/deprecation\n ...context.metadata,\n dynamicSamplingContext: dsc,\n },\n trimEnd: true,\n };\n } else {\n expandedContext = {\n trimEnd: true,\n ...context,\n };\n }\n\n const finalContext = beforeStartSpan ? beforeStartSpan(expandedContext) : expandedContext;\n\n // If `beforeStartSpan` set a custom name, record that fact\n // eslint-disable-next-line deprecation/deprecation\n finalContext.metadata =\n finalContext.name !== expandedContext.name\n ? // eslint-disable-next-line deprecation/deprecation\n { ...finalContext.metadata, source: 'custom' }\n : // eslint-disable-next-line deprecation/deprecation\n finalContext.metadata;\n\n latestRoute.name = finalContext.name;\n latestRoute.context = finalContext;\n\n if (finalContext.sampled === false) {\n DEBUG_BUILD && logger.log(`[Tracing] Will not send ${finalContext.op} transaction because of beforeNavigate.`);\n }\n\n DEBUG_BUILD && logger.log(`[Tracing] Starting ${finalContext.op} transaction on scope`);\n\n const { location } = WINDOW;\n\n const idleTransaction = startIdleTransaction(\n hub,\n finalContext,\n idleTimeout,\n finalTimeout,\n true,\n { location }, // for use in the tracesSampler\n heartbeatInterval,\n isPageloadTransaction, // should wait for finish signal if it's a pageload transaction\n );\n\n if (isPageloadTransaction && WINDOW.document) {\n WINDOW.document.addEventListener('readystatechange', () => {\n if (['interactive', 'complete'].includes(WINDOW.document!.readyState)) {\n idleTransaction.sendAutoFinishSignal();\n }\n });\n\n if (['interactive', 'complete'].includes(WINDOW.document.readyState)) {\n idleTransaction.sendAutoFinishSignal();\n }\n }\n\n idleTransaction.registerBeforeFinishCallback(transaction => {\n _collectWebVitals();\n addPerformanceEntries(transaction);\n });\n\n return idleTransaction as Transaction;\n }\n\n return {\n name: BROWSER_TRACING_INTEGRATION_ID,\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n setupOnce: () => {},\n afterAllSetup(client) {\n const clientOptions = client.getOptions();\n\n const { markBackgroundSpan, traceFetch, traceXHR, shouldCreateSpanForRequest, enableHTTPTimings, _experiments } =\n options;\n\n const clientOptionsTracePropagationTargets = clientOptions && clientOptions.tracePropagationTargets;\n // There are three ways to configure tracePropagationTargets:\n // 1. via top level client option `tracePropagationTargets`\n // 2. via BrowserTracing option `tracePropagationTargets`\n // 3. via BrowserTracing option `tracingOrigins` (deprecated)\n //\n // To avoid confusion, favour top level client option `tracePropagationTargets`, and fallback to\n // BrowserTracing option `tracePropagationTargets` and then `tracingOrigins` (deprecated).\n // This is done as it minimizes bundle size (we don't have to have undefined checks).\n //\n // If both 1 and either one of 2 or 3 are set (from above), we log out a warning.\n // eslint-disable-next-line deprecation/deprecation\n const tracePropagationTargets = clientOptionsTracePropagationTargets || options.tracePropagationTargets;\n if (DEBUG_BUILD && _hasSetTracePropagationTargets && clientOptionsTracePropagationTargets) {\n logger.warn(\n '[Tracing] The `tracePropagationTargets` option was set in the BrowserTracing integration and top level `Sentry.init`. The top level `Sentry.init` value is being used.',\n );\n }\n\n let activeSpan: Span | undefined;\n let startingUrl: string | undefined = WINDOW.location && WINDOW.location.href;\n\n if (client.on) {\n client.on('startNavigationSpan', (context: StartSpanOptions) => {\n if (activeSpan) {\n DEBUG_BUILD && logger.log(`[Tracing] Finishing current transaction with op: ${spanToJSON(activeSpan).op}`);\n // If there's an open transaction on the scope, we need to finish it before creating an new one.\n activeSpan.end();\n }\n activeSpan = _createRouteTransaction({\n op: 'navigation',\n ...context,\n });\n });\n\n client.on('startPageLoadSpan', (context: StartSpanOptions) => {\n if (activeSpan) {\n DEBUG_BUILD && logger.log(`[Tracing] Finishing current transaction with op: ${spanToJSON(activeSpan).op}`);\n // If there's an open transaction on the scope, we need to finish it before creating an new one.\n activeSpan.end();\n }\n activeSpan = _createRouteTransaction({\n op: 'pageload',\n ...context,\n });\n });\n }\n\n if (options.instrumentPageLoad && client.emit && WINDOW.location) {\n const context: StartSpanOptions = {\n name: WINDOW.location.pathname,\n // pageload should always start at timeOrigin (and needs to be in s, not ms)\n startTimestamp: browserPerformanceTimeOrigin ? browserPerformanceTimeOrigin / 1000 : undefined,\n origin: 'auto.pageload.browser',\n attributes: {\n [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'url',\n },\n };\n startBrowserTracingPageLoadSpan(client, context);\n }\n\n if (options.instrumentNavigation && client.emit && WINDOW.location) {\n addHistoryInstrumentationHandler(({ to, from }) => {\n /**\n * This early return is there to account for some cases where a navigation transaction starts right after\n * long-running pageload. We make sure that if `from` is undefined and a valid `startingURL` exists, we don't\n * create an uneccessary navigation transaction.\n *\n * This was hard to duplicate, but this behavior stopped as soon as this fix was applied. This issue might also\n * only be caused in certain development environments where the usage of a hot module reloader is causing\n * errors.\n */\n if (from === undefined && startingUrl && startingUrl.indexOf(to) !== -1) {\n startingUrl = undefined;\n return;\n }\n\n if (from !== to) {\n startingUrl = undefined;\n const context: StartSpanOptions = {\n name: WINDOW.location.pathname,\n origin: 'auto.navigation.browser',\n attributes: {\n [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'url',\n },\n };\n\n startBrowserTracingNavigationSpan(client, context);\n }\n });\n }\n\n if (markBackgroundSpan) {\n registerBackgroundTabDetection();\n }\n\n if (_experiments.enableInteractions) {\n registerInteractionListener(options, latestRoute);\n }\n\n if (options.enableInp) {\n registerInpInteractionListener(interactionIdToRouteNameMapping, latestRoute);\n }\n\n instrumentOutgoingRequests({\n traceFetch,\n traceXHR,\n tracePropagationTargets,\n shouldCreateSpanForRequest,\n enableHTTPTimings,\n });\n },\n // TODO v8: Remove this again\n // This is private API that we use to fix converted BrowserTracing integrations in Next.js & SvelteKit\n options,\n };\n}) satisfies IntegrationFn;\n\n/**\n * Manually start a page load span.\n * This will only do something if the BrowserTracing integration has been setup.\n */\nexport function startBrowserTracingPageLoadSpan(client: Client, spanOptions: StartSpanOptions): Span | undefined {\n if (!client.emit) {\n return;\n }\n\n client.emit('startPageLoadSpan', spanOptions);\n\n const span = getActiveSpan();\n const op = span && spanToJSON(span).op;\n return op === 'pageload' ? span : undefined;\n}\n\n/**\n * Manually start a navigation span.\n * This will only do something if the BrowserTracing integration has been setup.\n */\nexport function startBrowserTracingNavigationSpan(client: Client, spanOptions: StartSpanOptions): Span | undefined {\n if (!client.emit) {\n return;\n }\n\n client.emit('startNavigationSpan', spanOptions);\n\n const span = getActiveSpan();\n const op = span && spanToJSON(span).op;\n return op === 'navigation' ? span : undefined;\n}\n\n/** Returns the value of a meta tag */\nexport function getMetaContent(metaName: string): string | undefined {\n // Can't specify generic to `getDomElement` because tracing can be used\n // in a variety of environments, have to disable `no-unsafe-member-access`\n // as a result.\n const metaTag = getDomElement(`meta[name=${metaName}]`);\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return metaTag ? metaTag.getAttribute('content') : undefined;\n}\n\n/** Start listener for interaction transactions */\nfunction registerInteractionListener(\n options: BrowserTracingOptions,\n latestRoute: {\n name: string | undefined;\n context: TransactionContext | undefined;\n },\n): void {\n let inflightInteractionTransaction: IdleTransaction | undefined;\n const registerInteractionTransaction = (): void => {\n const { idleTimeout, finalTimeout, heartbeatInterval } = options;\n const op = 'ui.action.click';\n\n // eslint-disable-next-line deprecation/deprecation\n const currentTransaction = getActiveTransaction();\n if (currentTransaction && currentTransaction.op && ['navigation', 'pageload'].includes(currentTransaction.op)) {\n DEBUG_BUILD &&\n logger.warn(\n `[Tracing] Did not create ${op} transaction because a pageload or navigation transaction is in progress.`,\n );\n return undefined;\n }\n\n if (inflightInteractionTransaction) {\n inflightInteractionTransaction.setFinishReason('interactionInterrupted');\n inflightInteractionTransaction.end();\n inflightInteractionTransaction = undefined;\n }\n\n if (!latestRoute.name) {\n DEBUG_BUILD && logger.warn(`[Tracing] Did not create ${op} transaction because _latestRouteName is missing.`);\n return undefined;\n }\n\n const { location } = WINDOW;\n\n const context: TransactionContext = {\n name: latestRoute.name,\n op,\n trimEnd: true,\n data: {\n [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: latestRoute.context ? getSource(latestRoute.context) : undefined || 'url',\n },\n };\n\n inflightInteractionTransaction = startIdleTransaction(\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub(),\n context,\n idleTimeout,\n finalTimeout,\n true,\n { location }, // for use in the tracesSampler\n heartbeatInterval,\n );\n };\n\n ['click'].forEach(type => {\n if (WINDOW.document) {\n addEventListener(type, registerInteractionTransaction, { once: false, capture: true });\n }\n });\n}\n\nfunction isPerformanceEventTiming(entry: PerformanceEntry): entry is PerformanceEventTiming {\n return 'duration' in entry;\n}\n\n/** We store up to 10 interaction candidates max to cap memory usage. This is the same cap as getINP from web-vitals */\nconst MAX_INTERACTIONS = 10;\n\n/** Creates a listener on interaction entries, and maps interactionIds to the origin path of the interaction */\nfunction registerInpInteractionListener(\n interactionIdToRouteNameMapping: InteractionRouteNameMapping,\n latestRoute: {\n name: string | undefined;\n context: TransactionContext | undefined;\n },\n): void {\n const handleEntries = ({ entries }: { entries: PerformanceEntry[] }): void => {\n const client = getClient();\n // We need to get the replay, user, and activeTransaction from the current scope\n // so that we can associate replay id, profile id, and a user display to the span\n const replay =\n client !== undefined && client.getIntegrationByName !== undefined\n ? (client.getIntegrationByName('Replay') as Integration & { getReplayId: () => string })\n : undefined;\n const replayId = replay !== undefined ? replay.getReplayId() : undefined;\n // eslint-disable-next-line deprecation/deprecation\n const activeTransaction = getActiveTransaction();\n const currentScope = getCurrentScope();\n const user = currentScope !== undefined ? currentScope.getUser() : undefined;\n entries.forEach(entry => {\n if (isPerformanceEventTiming(entry)) {\n const interactionId = entry.interactionId;\n if (interactionId === undefined) {\n return;\n }\n const existingInteraction = interactionIdToRouteNameMapping[interactionId];\n const duration = entry.duration;\n const startTime = entry.startTime;\n const keys = Object.keys(interactionIdToRouteNameMapping);\n const minInteractionId =\n keys.length > 0\n ? keys.reduce((a, b) => {\n return interactionIdToRouteNameMapping[a].duration < interactionIdToRouteNameMapping[b].duration\n ? a\n : b;\n })\n : undefined;\n // For a first input event to be considered, we must check that an interaction event does not already exist with the same duration and start time.\n // This is also checked in the web-vitals library.\n if (entry.entryType === 'first-input') {\n const matchingEntry = keys\n .map(key => interactionIdToRouteNameMapping[key])\n .some(interaction => {\n return interaction.duration === duration && interaction.startTime === startTime;\n });\n if (matchingEntry) {\n return;\n }\n }\n // Interactions with an id of 0 and are not first-input are not valid.\n if (!interactionId) {\n return;\n }\n // If the interaction already exists, we want to use the duration of the longest entry, since that is what the INP metric uses.\n if (existingInteraction) {\n existingInteraction.duration = Math.max(existingInteraction.duration, duration);\n } else if (\n keys.length < MAX_INTERACTIONS ||\n minInteractionId === undefined ||\n duration > interactionIdToRouteNameMapping[minInteractionId].duration\n ) {\n // If the interaction does not exist, we want to add it to the mapping if there is space, or if the duration is longer than the shortest entry.\n const routeName = latestRoute.name;\n const parentContext = latestRoute.context;\n if (routeName && parentContext) {\n if (minInteractionId && Object.keys(interactionIdToRouteNameMapping).length >= MAX_INTERACTIONS) {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete interactionIdToRouteNameMapping[minInteractionId];\n }\n interactionIdToRouteNameMapping[interactionId] = {\n routeName,\n duration,\n parentContext,\n user,\n activeTransaction,\n replayId,\n startTime,\n };\n }\n }\n }\n });\n };\n addPerformanceInstrumentationHandler('event', handleEntries);\n addPerformanceInstrumentationHandler('first-input', handleEntries);\n}\n\nfunction getSource(context: TransactionContext): TransactionSource | undefined {\n const sourceFromAttributes = context.attributes && context.attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];\n // eslint-disable-next-line deprecation/deprecation\n const sourceFromData = context.data && context.data[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];\n // eslint-disable-next-line deprecation/deprecation\n const sourceFromMetadata = context.metadata && context.metadata.source;\n\n return sourceFromAttributes || sourceFromData || sourceFromMetadata;\n}\n", "import { addTracingExtensions, getMainCarrier } from '@sentry/core';\nimport type { Integration, IntegrationClass } from '@sentry/types';\nimport { dynamicRequire, isNodeEnv, loadModule } from '@sentry/utils';\n\n/**\n * @private\n */\nfunction _autoloadDatabaseIntegrations(): void {\n const carrier = getMainCarrier();\n if (!carrier.__SENTRY__) {\n return;\n }\n\n const packageToIntegrationMapping: Record Integration> = {\n mongodb() {\n const integration = dynamicRequire(module, './node/integrations/mongo') as {\n Mongo: IntegrationClass;\n };\n return new integration.Mongo();\n },\n mongoose() {\n const integration = dynamicRequire(module, './node/integrations/mongo') as {\n Mongo: IntegrationClass;\n };\n return new integration.Mongo();\n },\n mysql() {\n const integration = dynamicRequire(module, './node/integrations/mysql') as {\n Mysql: IntegrationClass;\n };\n return new integration.Mysql();\n },\n pg() {\n const integration = dynamicRequire(module, './node/integrations/postgres') as {\n Postgres: IntegrationClass;\n };\n return new integration.Postgres();\n },\n };\n\n const mappedPackages = Object.keys(packageToIntegrationMapping)\n .filter(moduleName => !!loadModule(moduleName))\n .map(pkg => {\n try {\n return packageToIntegrationMapping[pkg]();\n } catch (e) {\n return undefined;\n }\n })\n .filter(p => p) as Integration[];\n\n if (mappedPackages.length > 0) {\n carrier.__SENTRY__.integrations = [...(carrier.__SENTRY__.integrations || []), ...mappedPackages];\n }\n}\n\n/**\n * This patches the global object and injects the Tracing extensions methods\n */\nexport function addExtensionMethods(): void {\n addTracingExtensions();\n\n // Detect and automatically load specified integrations.\n if (isNodeEnv()) {\n _autoloadDatabaseIntegrations();\n }\n}\n", "Object.defineProperty(exports, '__esModule', { value: true });\n\nconst core = require('@sentry/core');\nconst utils = require('@sentry/utils');\nconst express = require('./node/integrations/express.js');\nconst postgres = require('./node/integrations/postgres.js');\nconst mysql = require('./node/integrations/mysql.js');\nconst mongo = require('./node/integrations/mongo.js');\nconst prisma = require('./node/integrations/prisma.js');\nconst graphql = require('./node/integrations/graphql.js');\nconst apollo = require('./node/integrations/apollo.js');\nconst lazy = require('./node/integrations/lazy.js');\nconst browsertracing = require('./browser/browsertracing.js');\nconst browserTracingIntegration = require('./browser/browserTracingIntegration.js');\nconst request = require('./browser/request.js');\nconst instrument = require('./browser/instrument.js');\nconst fetch = require('./common/fetch.js');\nconst extensions = require('./extensions.js');\n\n\n\nexports.IdleTransaction = core.IdleTransaction;\nexports.Span = core.Span;\nexports.SpanStatus = core.SpanStatus;\nexports.Transaction = core.Transaction;\nexports.extractTraceparentData = core.extractTraceparentData;\nexports.getActiveTransaction = core.getActiveTransaction;\nexports.hasTracingEnabled = core.hasTracingEnabled;\nexports.spanStatusfromHttpCode = core.spanStatusfromHttpCode;\nexports.startIdleTransaction = core.startIdleTransaction;\nexports.TRACEPARENT_REGEXP = utils.TRACEPARENT_REGEXP;\nexports.stripUrlQueryAndFragment = utils.stripUrlQueryAndFragment;\nexports.Express = express.Express;\nexports.Postgres = postgres.Postgres;\nexports.Mysql = mysql.Mysql;\nexports.Mongo = mongo.Mongo;\nexports.Prisma = prisma.Prisma;\nexports.GraphQL = graphql.GraphQL;\nexports.Apollo = apollo.Apollo;\nexports.lazyLoadedNodePerformanceMonitoringIntegrations = lazy.lazyLoadedNodePerformanceMonitoringIntegrations;\nexports.BROWSER_TRACING_INTEGRATION_ID = browsertracing.BROWSER_TRACING_INTEGRATION_ID;\nexports.BrowserTracing = browsertracing.BrowserTracing;\nexports.browserTracingIntegration = browserTracingIntegration.browserTracingIntegration;\nexports.startBrowserTracingNavigationSpan = browserTracingIntegration.startBrowserTracingNavigationSpan;\nexports.startBrowserTracingPageLoadSpan = browserTracingIntegration.startBrowserTracingPageLoadSpan;\nexports.defaultRequestInstrumentationOptions = request.defaultRequestInstrumentationOptions;\nexports.instrumentOutgoingRequests = request.instrumentOutgoingRequests;\nexports.addClsInstrumentationHandler = instrument.addClsInstrumentationHandler;\nexports.addFidInstrumentationHandler = instrument.addFidInstrumentationHandler;\nexports.addLcpInstrumentationHandler = instrument.addLcpInstrumentationHandler;\nexports.addPerformanceInstrumentationHandler = instrument.addPerformanceInstrumentationHandler;\nexports.addTracingHeadersToFetchRequest = fetch.addTracingHeadersToFetchRequest;\nexports.instrumentFetchRequest = fetch.instrumentFetchRequest;\nexports.addExtensionMethods = extensions.addExtensionMethods;\n//# sourceMappingURL=index.js.map\n", "import type { browserTracingIntegration } from '@sentry-internal/tracing';\nimport { BrowserTracing } from '@sentry-internal/tracing';\nimport { captureException, withScope } from '@sentry/core';\nimport type { DsnLike, Integration, Mechanism, WrappedFunction } from '@sentry/types';\nimport {\n GLOBAL_OBJ,\n addExceptionMechanism,\n addExceptionTypeValue,\n addNonEnumerableProperty,\n getOriginalFunction,\n markFunctionWrapped,\n} from '@sentry/utils';\n\nexport const WINDOW = GLOBAL_OBJ as typeof GLOBAL_OBJ & Window;\n\nlet ignoreOnError: number = 0;\n\n/**\n * @hidden\n */\nexport function shouldIgnoreOnError(): boolean {\n return ignoreOnError > 0;\n}\n\n/**\n * @hidden\n */\nexport function ignoreNextOnError(): void {\n // onerror should trigger before setTimeout\n ignoreOnError++;\n setTimeout(() => {\n ignoreOnError--;\n });\n}\n\n/**\n * Instruments the given function and sends an event to Sentry every time the\n * function throws an exception.\n *\n * @param fn A function to wrap. It is generally safe to pass an unbound function, because the returned wrapper always\n * has a correct `this` context.\n * @returns The wrapped function.\n * @hidden\n */\nexport function wrap(\n fn: WrappedFunction,\n options: {\n mechanism?: Mechanism;\n } = {},\n before?: WrappedFunction,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n): any {\n // for future readers what this does is wrap a function and then create\n // a bi-directional wrapping between them.\n //\n // example: wrapped = wrap(original);\n // original.__sentry_wrapped__ -> wrapped\n // wrapped.__sentry_original__ -> original\n\n if (typeof fn !== 'function') {\n return fn;\n }\n\n try {\n // if we're dealing with a function that was previously wrapped, return\n // the original wrapper.\n const wrapper = fn.__sentry_wrapped__;\n if (wrapper) {\n if (typeof wrapper === 'function') {\n return wrapper;\n } else {\n // If we find that the `__sentry_wrapped__` function is not a function at the time of accessing it, it means\n // that something messed with it. In that case we want to return the originally passed function.\n return fn;\n }\n }\n\n // We don't wanna wrap it twice\n if (getOriginalFunction(fn)) {\n return fn;\n }\n } catch (e) {\n // Just accessing custom props in some Selenium environments\n // can cause a \"Permission denied\" exception (see raven-js#495).\n // Bail on wrapping and return the function as-is (defers to window.onerror).\n return fn;\n }\n\n /* eslint-disable prefer-rest-params */\n // It is important that `sentryWrapped` is not an arrow function to preserve the context of `this`\n const sentryWrapped: WrappedFunction = function (this: unknown): void {\n const args = Array.prototype.slice.call(arguments);\n\n try {\n if (before && typeof before === 'function') {\n before.apply(this, arguments);\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access\n const wrappedArguments = args.map((arg: any) => wrap(arg, options));\n\n // Attempt to invoke user-land function\n // NOTE: If you are a Sentry user, and you are seeing this stack frame, it\n // means the sentry.javascript SDK caught an error invoking your application code. This\n // is expected behavior and NOT indicative of a bug with sentry.javascript.\n return fn.apply(this, wrappedArguments);\n } catch (ex) {\n ignoreNextOnError();\n\n withScope(scope => {\n scope.addEventProcessor(event => {\n if (options.mechanism) {\n addExceptionTypeValue(event, undefined, undefined);\n addExceptionMechanism(event, options.mechanism);\n }\n\n event.extra = {\n ...event.extra,\n arguments: args,\n };\n\n return event;\n });\n\n captureException(ex);\n });\n\n throw ex;\n }\n };\n /* eslint-enable prefer-rest-params */\n\n // Accessing some objects may throw\n // ref: https://github.com/getsentry/sentry-javascript/issues/1168\n try {\n for (const property in fn) {\n if (Object.prototype.hasOwnProperty.call(fn, property)) {\n sentryWrapped[property] = fn[property];\n }\n }\n } catch (_oO) {} // eslint-disable-line no-empty\n\n // Signal that this function has been wrapped/filled already\n // for both debugging and to prevent it to being wrapped/filled twice\n markFunctionWrapped(sentryWrapped, fn);\n\n addNonEnumerableProperty(fn, '__sentry_wrapped__', sentryWrapped);\n\n // Restore original function name (not all browsers allow that)\n try {\n const descriptor = Object.getOwnPropertyDescriptor(sentryWrapped, 'name') as PropertyDescriptor;\n if (descriptor.configurable) {\n Object.defineProperty(sentryWrapped, 'name', {\n get(): string {\n return fn.name;\n },\n });\n }\n // eslint-disable-next-line no-empty\n } catch (_oO) {}\n\n return sentryWrapped;\n}\n\n/**\n * All properties the report dialog supports\n *\n * @deprecated This type will be removed in the next major version of the Sentry SDK. `showReportDialog` will still be around, however the `eventId` option will now be required.\n */\nexport interface ReportDialogOptions {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [key: string]: any;\n eventId?: string;\n dsn?: DsnLike;\n user?: {\n email?: string;\n name?: string;\n };\n lang?: string;\n title?: string;\n subtitle?: string;\n subtitle2?: string;\n labelName?: string;\n labelEmail?: string;\n labelComments?: string;\n labelClose?: string;\n labelSubmit?: string;\n errorGeneric?: string;\n errorFormEntry?: string;\n successMessage?: string;\n /** Callback after reportDialog showed up */\n onLoad?(this: void): void;\n /** Callback after reportDialog closed */\n onClose?(this: void): void;\n}\n\n/**\n * This is a slim shim of `browserTracingIntegration` for the CDN bundles.\n * Since the actual functional integration uses a different code from `BrowserTracing`,\n * we want to avoid shipping both of them in the CDN bundles, as that would blow up the size.\n * Instead, we provide a functional integration with the same API, but the old implementation.\n * This means that it's not possible to register custom routing instrumentation, but that's OK for now.\n * We also don't expose the utilities for this anyhow in the CDN bundles.\n * For users that need custom routing in CDN bundles, they have to continue using `new BrowserTracing()` until v8.\n */\nexport function bundleBrowserTracingIntegration(\n options: Parameters[0] = {},\n): Integration {\n // Migrate some options from the old integration to the new one\n // eslint-disable-next-line deprecation/deprecation\n const opts: ConstructorParameters[0] = options;\n\n if (typeof options.markBackgroundSpan === 'boolean') {\n opts.markBackgroundTransactions = options.markBackgroundSpan;\n }\n\n if (typeof options.instrumentPageLoad === 'boolean') {\n opts.startTransactionOnPageLoad = options.instrumentPageLoad;\n }\n\n if (typeof options.instrumentNavigation === 'boolean') {\n opts.startTransactionOnLocationChange = options.instrumentNavigation;\n }\n\n // eslint-disable-next-line deprecation/deprecation\n return new BrowserTracing(opts);\n}\n", "declare const __DEBUG_BUILD__: boolean;\n\n/**\n * This serves as a build time flag that will be true by default, but false in non-debug builds or if users replace `__SENTRY_DEBUG__` in their generated code.\n *\n * ATTENTION: This constant must never cross package boundaries (i.e. be exported) to guarantee that it can be used for tree shaking.\n */\nexport const DEBUG_BUILD = __DEBUG_BUILD__;\n", "import { getClient } from '@sentry/core';\nimport type {\n Event,\n EventHint,\n Exception,\n ParameterizedString,\n Severity,\n SeverityLevel,\n StackFrame,\n StackParser,\n} from '@sentry/types';\nimport {\n addExceptionMechanism,\n addExceptionTypeValue,\n extractExceptionKeysForMessage,\n isDOMError,\n isDOMException,\n isError,\n isErrorEvent,\n isEvent,\n isParameterizedString,\n isPlainObject,\n normalizeToSize,\n resolvedSyncPromise,\n} from '@sentry/utils';\n\ntype Prototype = { constructor: (...args: unknown[]) => unknown };\n\n/**\n * This function creates an exception from a JavaScript Error\n */\nexport function exceptionFromError(stackParser: StackParser, ex: Error): Exception {\n // Get the frames first since Opera can lose the stack if we touch anything else first\n const frames = parseStackFrames(stackParser, ex);\n\n const exception: Exception = {\n type: ex && ex.name,\n value: extractMessage(ex),\n };\n\n if (frames.length) {\n exception.stacktrace = { frames };\n }\n\n if (exception.type === undefined && exception.value === '') {\n exception.value = 'Unrecoverable error caught';\n }\n\n return exception;\n}\n\n/**\n * @hidden\n */\nexport function eventFromPlainObject(\n stackParser: StackParser,\n exception: Record,\n syntheticException?: Error,\n isUnhandledRejection?: boolean,\n): Event {\n const client = getClient();\n const normalizeDepth = client && client.getOptions().normalizeDepth;\n\n const event: Event = {\n exception: {\n values: [\n {\n type: isEvent(exception) ? exception.constructor.name : isUnhandledRejection ? 'UnhandledRejection' : 'Error',\n value: getNonErrorObjectExceptionValue(exception, { isUnhandledRejection }),\n },\n ],\n },\n extra: {\n __serialized__: normalizeToSize(exception, normalizeDepth),\n },\n };\n\n if (syntheticException) {\n const frames = parseStackFrames(stackParser, syntheticException);\n if (frames.length) {\n // event.exception.values[0] has been set above\n (event.exception as { values: Exception[] }).values[0].stacktrace = { frames };\n }\n }\n\n return event;\n}\n\n/**\n * @hidden\n */\nexport function eventFromError(stackParser: StackParser, ex: Error): Event {\n return {\n exception: {\n values: [exceptionFromError(stackParser, ex)],\n },\n };\n}\n\n/** Parses stack frames from an error */\nexport function parseStackFrames(\n stackParser: StackParser,\n ex: Error & { framesToPop?: number; stacktrace?: string },\n): StackFrame[] {\n // Access and store the stacktrace property before doing ANYTHING\n // else to it because Opera is not very good at providing it\n // reliably in other circumstances.\n const stacktrace = ex.stacktrace || ex.stack || '';\n\n const popSize = getPopSize(ex);\n\n try {\n return stackParser(stacktrace, popSize);\n } catch (e) {\n // no-empty\n }\n\n return [];\n}\n\n// Based on our own mapping pattern - https://github.com/getsentry/sentry/blob/9f08305e09866c8bd6d0c24f5b0aabdd7dd6c59c/src/sentry/lang/javascript/errormapping.py#L83-L108\nconst reactMinifiedRegexp = /Minified React error #\\d+;/i;\n\nfunction getPopSize(ex: Error & { framesToPop?: number }): number {\n if (ex) {\n if (typeof ex.framesToPop === 'number') {\n return ex.framesToPop;\n }\n\n if (reactMinifiedRegexp.test(ex.message)) {\n return 1;\n }\n }\n\n return 0;\n}\n\n/**\n * There are cases where stacktrace.message is an Event object\n * https://github.com/getsentry/sentry-javascript/issues/1949\n * In this specific case we try to extract stacktrace.message.error.message\n */\nfunction extractMessage(ex: Error & { message: { error?: Error } }): string {\n const message = ex && ex.message;\n if (!message) {\n return 'No error message';\n }\n if (message.error && typeof message.error.message === 'string') {\n return message.error.message;\n }\n return message;\n}\n\n/**\n * Creates an {@link Event} from all inputs to `captureException` and non-primitive inputs to `captureMessage`.\n * @hidden\n */\nexport function eventFromException(\n stackParser: StackParser,\n exception: unknown,\n hint?: EventHint,\n attachStacktrace?: boolean,\n): PromiseLike {\n const syntheticException = (hint && hint.syntheticException) || undefined;\n const event = eventFromUnknownInput(stackParser, exception, syntheticException, attachStacktrace);\n addExceptionMechanism(event); // defaults to { type: 'generic', handled: true }\n event.level = 'error';\n if (hint && hint.event_id) {\n event.event_id = hint.event_id;\n }\n return resolvedSyncPromise(event);\n}\n\n/**\n * Builds and Event from a Message\n * @hidden\n */\nexport function eventFromMessage(\n stackParser: StackParser,\n message: ParameterizedString,\n // eslint-disable-next-line deprecation/deprecation\n level: Severity | SeverityLevel = 'info',\n hint?: EventHint,\n attachStacktrace?: boolean,\n): PromiseLike {\n const syntheticException = (hint && hint.syntheticException) || undefined;\n const event = eventFromString(stackParser, message, syntheticException, attachStacktrace);\n event.level = level;\n if (hint && hint.event_id) {\n event.event_id = hint.event_id;\n }\n return resolvedSyncPromise(event);\n}\n\n/**\n * @hidden\n */\nexport function eventFromUnknownInput(\n stackParser: StackParser,\n exception: unknown,\n syntheticException?: Error,\n attachStacktrace?: boolean,\n isUnhandledRejection?: boolean,\n): Event {\n let event: Event;\n\n if (isErrorEvent(exception as ErrorEvent) && (exception as ErrorEvent).error) {\n // If it is an ErrorEvent with `error` property, extract it to get actual Error\n const errorEvent = exception as ErrorEvent;\n return eventFromError(stackParser, errorEvent.error as Error);\n }\n\n // If it is a `DOMError` (which is a legacy API, but still supported in some browsers) then we just extract the name\n // and message, as it doesn't provide anything else. According to the spec, all `DOMExceptions` should also be\n // `Error`s, but that's not the case in IE11, so in that case we treat it the same as we do a `DOMError`.\n //\n // https://developer.mozilla.org/en-US/docs/Web/API/DOMError\n // https://developer.mozilla.org/en-US/docs/Web/API/DOMException\n // https://webidl.spec.whatwg.org/#es-DOMException-specialness\n if (isDOMError(exception) || isDOMException(exception as DOMException)) {\n const domException = exception as DOMException;\n\n if ('stack' in (exception as Error)) {\n event = eventFromError(stackParser, exception as Error);\n } else {\n const name = domException.name || (isDOMError(domException) ? 'DOMError' : 'DOMException');\n const message = domException.message ? `${name}: ${domException.message}` : name;\n event = eventFromString(stackParser, message, syntheticException, attachStacktrace);\n addExceptionTypeValue(event, message);\n }\n if ('code' in domException) {\n // eslint-disable-next-line deprecation/deprecation\n event.tags = { ...event.tags, 'DOMException.code': `${domException.code}` };\n }\n\n return event;\n }\n if (isError(exception)) {\n // we have a real Error object, do nothing\n return eventFromError(stackParser, exception);\n }\n if (isPlainObject(exception) || isEvent(exception)) {\n // If it's a plain object or an instance of `Event` (the built-in JS kind, not this SDK's `Event` type), serialize\n // it manually. This will allow us to group events based on top-level keys which is much better than creating a new\n // group on any key/value change.\n const objectException = exception as Record;\n event = eventFromPlainObject(stackParser, objectException, syntheticException, isUnhandledRejection);\n addExceptionMechanism(event, {\n synthetic: true,\n });\n return event;\n }\n\n // If none of previous checks were valid, then it means that it's not:\n // - an instance of DOMError\n // - an instance of DOMException\n // - an instance of Event\n // - an instance of Error\n // - a valid ErrorEvent (one with an error property)\n // - a plain Object\n //\n // So bail out and capture it as a simple message:\n event = eventFromString(stackParser, exception as string, syntheticException, attachStacktrace);\n addExceptionTypeValue(event, `${exception}`, undefined);\n addExceptionMechanism(event, {\n synthetic: true,\n });\n\n return event;\n}\n\n/**\n * @hidden\n */\nexport function eventFromString(\n stackParser: StackParser,\n message: ParameterizedString,\n syntheticException?: Error,\n attachStacktrace?: boolean,\n): Event {\n const event: Event = {};\n\n if (attachStacktrace && syntheticException) {\n const frames = parseStackFrames(stackParser, syntheticException);\n if (frames.length) {\n event.exception = {\n values: [{ value: message, stacktrace: { frames } }],\n };\n }\n }\n\n if (isParameterizedString(message)) {\n const { __sentry_template_string__, __sentry_template_values__ } = message;\n\n event.logentry = {\n message: __sentry_template_string__,\n params: __sentry_template_values__,\n };\n return event;\n }\n\n event.message = message;\n return event;\n}\n\nfunction getNonErrorObjectExceptionValue(\n exception: Record,\n { isUnhandledRejection }: { isUnhandledRejection?: boolean },\n): string {\n const keys = extractExceptionKeysForMessage(exception);\n const captureType = isUnhandledRejection ? 'promise rejection' : 'exception';\n\n // Some ErrorEvent instances do not have an `error` property, which is why they are not handled before\n // We still want to try to get a decent message for these cases\n if (isErrorEvent(exception)) {\n return `Event \\`ErrorEvent\\` captured as ${captureType} with message \\`${exception.message}\\``;\n }\n\n if (isEvent(exception)) {\n const className = getObjectClassName(exception);\n return `Event \\`${className}\\` (type=${exception.type}) captured as ${captureType}`;\n }\n\n return `Object captured as ${captureType} with keys: ${keys}`;\n}\n\nfunction getObjectClassName(obj: unknown): string | undefined | void {\n try {\n const prototype: Prototype | null = Object.getPrototypeOf(obj);\n return prototype ? prototype.constructor.name : undefined;\n } catch (e) {\n // ignore errors here\n }\n}\n", "import type { DsnComponents, EventEnvelope, SdkMetadata, UserFeedback, UserFeedbackItem } from '@sentry/types';\nimport { createEnvelope, dsnToString } from '@sentry/utils';\n\n/**\n * Creates an envelope from a user feedback.\n */\nexport function createUserFeedbackEnvelope(\n feedback: UserFeedback,\n {\n metadata,\n tunnel,\n dsn,\n }: {\n metadata: SdkMetadata | undefined;\n tunnel: string | undefined;\n dsn: DsnComponents | undefined;\n },\n): EventEnvelope {\n const headers: EventEnvelope[0] = {\n event_id: feedback.event_id,\n sent_at: new Date().toISOString(),\n ...(metadata &&\n metadata.sdk && {\n sdk: {\n name: metadata.sdk.name,\n version: metadata.sdk.version,\n },\n }),\n ...(!!tunnel && !!dsn && { dsn: dsnToString(dsn) }),\n };\n const item = createUserFeedbackEnvelopeItem(feedback);\n\n return createEnvelope(headers, [item]);\n}\n\nfunction createUserFeedbackEnvelopeItem(feedback: UserFeedback): UserFeedbackItem {\n const feedbackHeaders: UserFeedbackItem[0] = {\n type: 'user_report',\n };\n return [feedbackHeaders, feedback];\n}\n", "import type { Scope } from '@sentry/core';\nimport { applySdkMetadata } from '@sentry/core';\nimport { BaseClient } from '@sentry/core';\nimport type {\n BrowserClientProfilingOptions,\n BrowserClientReplayOptions,\n ClientOptions,\n Event,\n EventHint,\n Options,\n ParameterizedString,\n Severity,\n SeverityLevel,\n UserFeedback,\n} from '@sentry/types';\nimport { createClientReportEnvelope, dsnToString, getSDKSource, logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from './debug-build';\nimport { eventFromException, eventFromMessage } from './eventbuilder';\nimport { WINDOW } from './helpers';\nimport type { BrowserTransportOptions } from './transports/types';\nimport { createUserFeedbackEnvelope } from './userfeedback';\n\n/**\n * Configuration options for the Sentry Browser SDK.\n * @see @sentry/types Options for more information.\n */\nexport type BrowserOptions = Options &\n BrowserClientReplayOptions &\n BrowserClientProfilingOptions;\n\n/**\n * Configuration options for the Sentry Browser SDK Client class\n * @see BrowserClient for more information.\n */\nexport type BrowserClientOptions = ClientOptions &\n BrowserClientReplayOptions &\n BrowserClientProfilingOptions;\n\n/**\n * The Sentry Browser SDK Client.\n *\n * @see BrowserOptions for documentation on configuration options.\n * @see SentryClient for usage documentation.\n */\nexport class BrowserClient extends BaseClient {\n /**\n * Creates a new Browser SDK instance.\n *\n * @param options Configuration options for this SDK.\n */\n public constructor(options: BrowserClientOptions) {\n const sdkSource = WINDOW.SENTRY_SDK_SOURCE || getSDKSource();\n applySdkMetadata(options, 'browser', ['browser'], sdkSource);\n\n super(options);\n\n if (options.sendClientReports && WINDOW.document) {\n WINDOW.document.addEventListener('visibilitychange', () => {\n if (WINDOW.document.visibilityState === 'hidden') {\n this._flushOutcomes();\n }\n });\n }\n }\n\n /**\n * @inheritDoc\n */\n public eventFromException(exception: unknown, hint?: EventHint): PromiseLike {\n return eventFromException(this._options.stackParser, exception, hint, this._options.attachStacktrace);\n }\n\n /**\n * @inheritDoc\n */\n public eventFromMessage(\n message: ParameterizedString,\n // eslint-disable-next-line deprecation/deprecation\n level: Severity | SeverityLevel = 'info',\n hint?: EventHint,\n ): PromiseLike {\n return eventFromMessage(this._options.stackParser, message, level, hint, this._options.attachStacktrace);\n }\n\n /**\n * Sends user feedback to Sentry.\n */\n public captureUserFeedback(feedback: UserFeedback): void {\n if (!this._isEnabled()) {\n DEBUG_BUILD && logger.warn('SDK not enabled, will not capture user feedback.');\n return;\n }\n\n const envelope = createUserFeedbackEnvelope(feedback, {\n metadata: this.getSdkMetadata(),\n dsn: this.getDsn(),\n tunnel: this.getOptions().tunnel,\n });\n\n // _sendEnvelope should not throw\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this._sendEnvelope(envelope);\n }\n\n /**\n * @inheritDoc\n */\n protected _prepareEvent(event: Event, hint: EventHint, scope?: Scope): PromiseLike {\n event.platform = event.platform || 'javascript';\n return super._prepareEvent(event, hint, scope);\n }\n\n /**\n * Sends client reports as an envelope.\n */\n private _flushOutcomes(): void {\n const outcomes = this._clearOutcomes();\n\n if (outcomes.length === 0) {\n DEBUG_BUILD && logger.log('No outcomes to send');\n return;\n }\n\n // This is really the only place where we want to check for a DSN and only send outcomes then\n if (!this._dsn) {\n DEBUG_BUILD && logger.log('No dsn provided, will not send outcomes');\n return;\n }\n\n DEBUG_BUILD && logger.log('Sending outcomes:', outcomes);\n\n const envelope = createClientReportEnvelope(outcomes, this._options.tunnel && dsnToString(this._dsn));\n\n // _sendEnvelope should not throw\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this._sendEnvelope(envelope);\n }\n}\n", "import { isNativeFetch, logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\nimport { WINDOW } from '../helpers';\n\nlet cachedFetchImpl: FetchImpl | undefined = undefined;\n\nexport type FetchImpl = typeof fetch;\n\n/**\n * A special usecase for incorrectly wrapped Fetch APIs in conjunction with ad-blockers.\n * Whenever someone wraps the Fetch API and returns the wrong promise chain,\n * this chain becomes orphaned and there is no possible way to capture it's rejections\n * other than allowing it bubble up to this very handler. eg.\n *\n * const f = window.fetch;\n * window.fetch = function () {\n * const p = f.apply(this, arguments);\n *\n * p.then(function() {\n * console.log('hi.');\n * });\n *\n * return p;\n * }\n *\n * `p.then(function () { ... })` is producing a completely separate promise chain,\n * however, what's returned is `p` - the result of original `fetch` call.\n *\n * This mean, that whenever we use the Fetch API to send our own requests, _and_\n * some ad-blocker blocks it, this orphaned chain will _always_ reject,\n * effectively causing another event to be captured.\n * This makes a whole process become an infinite loop, which we need to somehow\n * deal with, and break it in one way or another.\n *\n * To deal with this issue, we are making sure that we _always_ use the real\n * browser Fetch API, instead of relying on what `window.fetch` exposes.\n * The only downside to this would be missing our own requests as breadcrumbs,\n * but because we are already not doing this, it should be just fine.\n *\n * Possible failed fetch error messages per-browser:\n *\n * Chrome: Failed to fetch\n * Edge: Failed to Fetch\n * Firefox: NetworkError when attempting to fetch resource\n * Safari: resource blocked by content blocker\n */\nexport function getNativeFetchImplementation(): FetchImpl {\n if (cachedFetchImpl) {\n return cachedFetchImpl;\n }\n\n /* eslint-disable @typescript-eslint/unbound-method */\n\n // Fast path to avoid DOM I/O\n if (isNativeFetch(WINDOW.fetch)) {\n return (cachedFetchImpl = WINDOW.fetch.bind(WINDOW));\n }\n\n const document = WINDOW.document;\n let fetchImpl = WINDOW.fetch;\n // eslint-disable-next-line deprecation/deprecation\n if (document && typeof document.createElement === 'function') {\n try {\n const sandbox = document.createElement('iframe');\n sandbox.hidden = true;\n document.head.appendChild(sandbox);\n const contentWindow = sandbox.contentWindow;\n if (contentWindow && contentWindow.fetch) {\n fetchImpl = contentWindow.fetch;\n }\n document.head.removeChild(sandbox);\n } catch (e) {\n DEBUG_BUILD && logger.warn('Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ', e);\n }\n }\n\n return (cachedFetchImpl = fetchImpl.bind(WINDOW));\n /* eslint-enable @typescript-eslint/unbound-method */\n}\n\n/** Clears cached fetch impl */\nexport function clearCachedFetchImplementation(): void {\n cachedFetchImpl = undefined;\n}\n", "import { createTransport } from '@sentry/core';\nimport type { Transport, TransportMakeRequestResponse, TransportRequest } from '@sentry/types';\nimport { rejectedSyncPromise } from '@sentry/utils';\n\nimport type { BrowserTransportOptions } from './types';\nimport type { FetchImpl } from './utils';\nimport { clearCachedFetchImplementation, getNativeFetchImplementation } from './utils';\n\n/**\n * Creates a Transport that uses the Fetch API to send events to Sentry.\n */\nexport function makeFetchTransport(\n options: BrowserTransportOptions,\n nativeFetch: FetchImpl = getNativeFetchImplementation(),\n): Transport {\n let pendingBodySize = 0;\n let pendingCount = 0;\n\n function makeRequest(request: TransportRequest): PromiseLike {\n const requestSize = request.body.length;\n pendingBodySize += requestSize;\n pendingCount++;\n\n const requestOptions: RequestInit = {\n body: request.body,\n method: 'POST',\n referrerPolicy: 'origin',\n headers: options.headers,\n // Outgoing requests are usually cancelled when navigating to a different page, causing a \"TypeError: Failed to\n // fetch\" error and sending a \"network_error\" client-outcome - in Chrome, the request status shows \"(cancelled)\".\n // The `keepalive` flag keeps outgoing requests alive, even when switching pages. We want this since we're\n // frequently sending events right before the user is switching pages (eg. whenfinishing navigation transactions).\n // Gotchas:\n // - `keepalive` isn't supported by Firefox\n // - As per spec (https://fetch.spec.whatwg.org/#http-network-or-cache-fetch):\n // If the sum of contentLength and inflightKeepaliveBytes is greater than 64 kibibytes, then return a network error.\n // We will therefore only activate the flag when we're below that limit.\n // There is also a limit of requests that can be open at the same time, so we also limit this to 15\n // See https://github.com/getsentry/sentry-javascript/pull/7553 for details\n keepalive: pendingBodySize <= 60_000 && pendingCount < 15,\n ...options.fetchOptions,\n };\n\n try {\n return nativeFetch(options.url, requestOptions).then(response => {\n pendingBodySize -= requestSize;\n pendingCount--;\n return {\n statusCode: response.status,\n headers: {\n 'x-sentry-rate-limits': response.headers.get('X-Sentry-Rate-Limits'),\n 'retry-after': response.headers.get('Retry-After'),\n },\n };\n });\n } catch (e) {\n clearCachedFetchImplementation();\n pendingBodySize -= requestSize;\n pendingCount--;\n return rejectedSyncPromise(e);\n }\n }\n\n return createTransport(options, makeRequest);\n}\n", "import { createTransport } from '@sentry/core';\nimport type { Transport, TransportMakeRequestResponse, TransportRequest } from '@sentry/types';\nimport { SyncPromise } from '@sentry/utils';\n\nimport type { BrowserTransportOptions } from './types';\n\n/**\n * The DONE ready state for XmlHttpRequest\n *\n * Defining it here as a constant b/c XMLHttpRequest.DONE is not always defined\n * (e.g. during testing, it is `undefined`)\n *\n * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/readyState}\n */\nconst XHR_READYSTATE_DONE = 4;\n\n/**\n * Creates a Transport that uses the XMLHttpRequest API to send events to Sentry.\n */\nexport function makeXHRTransport(options: BrowserTransportOptions): Transport {\n function makeRequest(request: TransportRequest): PromiseLike {\n return new SyncPromise((resolve, reject) => {\n const xhr = new XMLHttpRequest();\n\n xhr.onerror = reject;\n\n xhr.onreadystatechange = (): void => {\n if (xhr.readyState === XHR_READYSTATE_DONE) {\n resolve({\n statusCode: xhr.status,\n headers: {\n 'x-sentry-rate-limits': xhr.getResponseHeader('X-Sentry-Rate-Limits'),\n 'retry-after': xhr.getResponseHeader('Retry-After'),\n },\n });\n }\n };\n\n xhr.open('POST', options.url);\n\n for (const header in options.headers) {\n if (Object.prototype.hasOwnProperty.call(options.headers, header)) {\n xhr.setRequestHeader(header, options.headers[header]);\n }\n }\n\n xhr.send(request.body);\n });\n }\n\n return createTransport(options, makeRequest);\n}\n", "// This was originally forked from https://github.com/csnover/TraceKit, and was largely\n// re - written as part of raven - js.\n//\n// This code was later copied to the JavaScript mono - repo and further modified and\n// refactored over the years.\n\n// Copyright (c) 2013 Onur Can Cakmak onur.cakmak@gmail.com and all TraceKit contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy of this\n// software and associated documentation files(the 'Software'), to deal in the Software\n// without restriction, including without limitation the rights to use, copy, modify,\n// merge, publish, distribute, sublicense, and / or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to the following\n// conditions:\n//\n// The above copyright notice and this permission notice shall be included in all copies\n// or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF\n// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE\n// OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nimport type { StackFrame, StackLineParser, StackLineParserFn } from '@sentry/types';\nimport { createStackParser } from '@sentry/utils';\n\n// global reference to slice\nconst UNKNOWN_FUNCTION = '?';\n\nconst OPERA10_PRIORITY = 10;\nconst OPERA11_PRIORITY = 20;\nconst CHROME_PRIORITY = 30;\nconst WINJS_PRIORITY = 40;\nconst GECKO_PRIORITY = 50;\n\nfunction createFrame(filename: string, func: string, lineno?: number, colno?: number): StackFrame {\n const frame: StackFrame = {\n filename,\n function: func,\n in_app: true, // All browser frames are considered in_app\n };\n\n if (lineno !== undefined) {\n frame.lineno = lineno;\n }\n\n if (colno !== undefined) {\n frame.colno = colno;\n }\n\n return frame;\n}\n\n// Chromium based browsers: Chrome, Brave, new Opera, new Edge\nconst chromeRegex =\n /^\\s*at (?:(.+?\\)(?: \\[.+\\])?|.*?) ?\\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\\/)?.*?)(?::(\\d+))?(?::(\\d+))?\\)?\\s*$/i;\nconst chromeEvalRegex = /\\((\\S*)(?::(\\d+))(?::(\\d+))\\)/;\n\n// We cannot call this variable `chrome` because it can conflict with global `chrome` variable in certain environments\n// See: https://github.com/getsentry/sentry-javascript/issues/6880\nconst chromeStackParserFn: StackLineParserFn = line => {\n const parts = chromeRegex.exec(line);\n\n if (parts) {\n const isEval = parts[2] && parts[2].indexOf('eval') === 0; // start of line\n\n if (isEval) {\n const subMatch = chromeEvalRegex.exec(parts[2]);\n\n if (subMatch) {\n // throw out eval line/column and use top-most line/column number\n parts[2] = subMatch[1]; // url\n parts[3] = subMatch[2]; // line\n parts[4] = subMatch[3]; // column\n }\n }\n\n // Kamil: One more hack won't hurt us right? Understanding and adding more rules on top of these regexps right now\n // would be way too time consuming. (TODO: Rewrite whole RegExp to be more readable)\n const [func, filename] = extractSafariExtensionDetails(parts[1] || UNKNOWN_FUNCTION, parts[2]);\n\n return createFrame(filename, func, parts[3] ? +parts[3] : undefined, parts[4] ? +parts[4] : undefined);\n }\n\n return;\n};\n\nexport const chromeStackLineParser: StackLineParser = [CHROME_PRIORITY, chromeStackParserFn];\n\n// gecko regex: `(?:bundle|\\d+\\.js)`: `bundle` is for react native, `\\d+\\.js` also but specifically for ram bundles because it\n// generates filenames without a prefix like `file://` the filenames in the stacktrace are just 42.js\n// We need this specific case for now because we want no other regex to match.\nconst geckoREgex =\n /^\\s*(.*?)(?:\\((.*?)\\))?(?:^|@)?((?:[-a-z]+)?:\\/.*?|\\[native code\\]|[^@]*(?:bundle|\\d+\\.js)|\\/[\\w\\-. /=]+)(?::(\\d+))?(?::(\\d+))?\\s*$/i;\nconst geckoEvalRegex = /(\\S+) line (\\d+)(?: > eval line \\d+)* > eval/i;\n\nconst gecko: StackLineParserFn = line => {\n const parts = geckoREgex.exec(line);\n\n if (parts) {\n const isEval = parts[3] && parts[3].indexOf(' > eval') > -1;\n if (isEval) {\n const subMatch = geckoEvalRegex.exec(parts[3]);\n\n if (subMatch) {\n // throw out eval line/column and use top-most line number\n parts[1] = parts[1] || 'eval';\n parts[3] = subMatch[1];\n parts[4] = subMatch[2];\n parts[5] = ''; // no column when eval\n }\n }\n\n let filename = parts[3];\n let func = parts[1] || UNKNOWN_FUNCTION;\n [func, filename] = extractSafariExtensionDetails(func, filename);\n\n return createFrame(filename, func, parts[4] ? +parts[4] : undefined, parts[5] ? +parts[5] : undefined);\n }\n\n return;\n};\n\nexport const geckoStackLineParser: StackLineParser = [GECKO_PRIORITY, gecko];\n\nconst winjsRegex = /^\\s*at (?:((?:\\[object object\\])?.+) )?\\(?((?:[-a-z]+):.*?):(\\d+)(?::(\\d+))?\\)?\\s*$/i;\n\nconst winjs: StackLineParserFn = line => {\n const parts = winjsRegex.exec(line);\n\n return parts\n ? createFrame(parts[2], parts[1] || UNKNOWN_FUNCTION, +parts[3], parts[4] ? +parts[4] : undefined)\n : undefined;\n};\n\nexport const winjsStackLineParser: StackLineParser = [WINJS_PRIORITY, winjs];\n\nconst opera10Regex = / line (\\d+).*script (?:in )?(\\S+)(?:: in function (\\S+))?$/i;\n\nconst opera10: StackLineParserFn = line => {\n const parts = opera10Regex.exec(line);\n return parts ? createFrame(parts[2], parts[3] || UNKNOWN_FUNCTION, +parts[1]) : undefined;\n};\n\nexport const opera10StackLineParser: StackLineParser = [OPERA10_PRIORITY, opera10];\n\nconst opera11Regex =\n / line (\\d+), column (\\d+)\\s*(?:in (?:]+)>|([^)]+))\\(.*\\))? in (.*):\\s*$/i;\n\nconst opera11: StackLineParserFn = line => {\n const parts = opera11Regex.exec(line);\n return parts ? createFrame(parts[5], parts[3] || parts[4] || UNKNOWN_FUNCTION, +parts[1], +parts[2]) : undefined;\n};\n\nexport const opera11StackLineParser: StackLineParser = [OPERA11_PRIORITY, opera11];\n\nexport const defaultStackLineParsers = [chromeStackLineParser, geckoStackLineParser, winjsStackLineParser];\n\nexport const defaultStackParser = createStackParser(...defaultStackLineParsers);\n\n/**\n * Safari web extensions, starting version unknown, can produce \"frames-only\" stacktraces.\n * What it means, is that instead of format like:\n *\n * Error: wat\n * at function@url:row:col\n * at function@url:row:col\n * at function@url:row:col\n *\n * it produces something like:\n *\n * function@url:row:col\n * function@url:row:col\n * function@url:row:col\n *\n * Because of that, it won't be captured by `chrome` RegExp and will fall into `Gecko` branch.\n * This function is extracted so that we can use it in both places without duplicating the logic.\n * Unfortunately \"just\" changing RegExp is too complicated now and making it pass all tests\n * and fix this case seems like an impossible, or at least way too time-consuming task.\n */\nconst extractSafariExtensionDetails = (func: string, filename: string): [string, string] => {\n const isSafariExtension = func.indexOf('safari-extension') !== -1;\n const isSafariWebExtension = func.indexOf('safari-web-extension') !== -1;\n\n return isSafariExtension || isSafariWebExtension\n ? [\n func.indexOf('@') !== -1 ? func.split('@')[0] : UNKNOWN_FUNCTION,\n isSafariExtension ? `safari-extension:${filename}` : `safari-web-extension:${filename}`,\n ]\n : [func, filename];\n};\n", "/* eslint-disable max-lines */\nimport { addBreadcrumb, convertIntegrationFnToClass, defineIntegration, getClient } from '@sentry/core';\nimport type {\n Client,\n Event as SentryEvent,\n HandlerDataConsole,\n HandlerDataDom,\n HandlerDataFetch,\n HandlerDataHistory,\n HandlerDataXhr,\n Integration,\n IntegrationClass,\n IntegrationFn,\n} from '@sentry/types';\nimport type {\n Breadcrumb,\n FetchBreadcrumbData,\n FetchBreadcrumbHint,\n XhrBreadcrumbData,\n XhrBreadcrumbHint,\n} from '@sentry/types/build/types/breadcrumb';\nimport {\n SENTRY_XHR_DATA_KEY,\n addClickKeypressInstrumentationHandler,\n addConsoleInstrumentationHandler,\n addFetchInstrumentationHandler,\n addHistoryInstrumentationHandler,\n addXhrInstrumentationHandler,\n getComponentName,\n getEventDescription,\n htmlTreeAsString,\n logger,\n parseUrl,\n safeJoin,\n severityLevelFromString,\n} from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\nimport { WINDOW } from '../helpers';\n\ninterface BreadcrumbsOptions {\n console: boolean;\n dom:\n | boolean\n | {\n serializeAttribute?: string | string[];\n maxStringLength?: number;\n };\n fetch: boolean;\n history: boolean;\n sentry: boolean;\n xhr: boolean;\n}\n\n/** maxStringLength gets capped to prevent 100 breadcrumbs exceeding 1MB event payload size */\nconst MAX_ALLOWED_STRING_LENGTH = 1024;\n\nconst INTEGRATION_NAME = 'Breadcrumbs';\n\nconst _breadcrumbsIntegration = ((options: Partial = {}) => {\n const _options = {\n console: true,\n dom: true,\n fetch: true,\n history: true,\n sentry: true,\n xhr: true,\n ...options,\n };\n\n return {\n name: INTEGRATION_NAME,\n // TODO v8: Remove this\n setupOnce() {}, // eslint-disable-line @typescript-eslint/no-empty-function\n setup(client) {\n if (_options.console) {\n addConsoleInstrumentationHandler(_getConsoleBreadcrumbHandler(client));\n }\n if (_options.dom) {\n addClickKeypressInstrumentationHandler(_getDomBreadcrumbHandler(client, _options.dom));\n }\n if (_options.xhr) {\n addXhrInstrumentationHandler(_getXhrBreadcrumbHandler(client));\n }\n if (_options.fetch) {\n addFetchInstrumentationHandler(_getFetchBreadcrumbHandler(client));\n }\n if (_options.history) {\n addHistoryInstrumentationHandler(_getHistoryBreadcrumbHandler(client));\n }\n if (_options.sentry && client.on) {\n client.on('beforeSendEvent', _getSentryBreadcrumbHandler(client));\n }\n },\n };\n}) satisfies IntegrationFn;\n\nexport const breadcrumbsIntegration = defineIntegration(_breadcrumbsIntegration);\n\n/**\n * Default Breadcrumbs instrumentations\n *\n * @deprecated Use `breadcrumbsIntegration()` instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport const Breadcrumbs = convertIntegrationFnToClass(INTEGRATION_NAME, breadcrumbsIntegration) as IntegrationClass<\n Integration & { setup: (client: Client) => void }\n> & {\n new (\n options?: Partial<{\n console: boolean;\n dom:\n | boolean\n | {\n serializeAttribute?: string | string[];\n maxStringLength?: number;\n };\n fetch: boolean;\n history: boolean;\n sentry: boolean;\n xhr: boolean;\n }>,\n ): Integration;\n};\n\n/**\n * Adds a breadcrumb for Sentry events or transactions if this option is enabled.\n */\nfunction _getSentryBreadcrumbHandler(client: Client): (event: SentryEvent) => void {\n return function addSentryBreadcrumb(event: SentryEvent): void {\n if (getClient() !== client) {\n return;\n }\n\n addBreadcrumb(\n {\n category: `sentry.${event.type === 'transaction' ? 'transaction' : 'event'}`,\n event_id: event.event_id,\n level: event.level,\n message: getEventDescription(event),\n },\n {\n event,\n },\n );\n };\n}\n\n/**\n * A HOC that creaes a function that creates breadcrumbs from DOM API calls.\n * This is a HOC so that we get access to dom options in the closure.\n */\nfunction _getDomBreadcrumbHandler(\n client: Client,\n dom: BreadcrumbsOptions['dom'],\n): (handlerData: HandlerDataDom) => void {\n return function _innerDomBreadcrumb(handlerData: HandlerDataDom): void {\n if (getClient() !== client) {\n return;\n }\n\n let target;\n let componentName;\n let keyAttrs = typeof dom === 'object' ? dom.serializeAttribute : undefined;\n\n let maxStringLength =\n typeof dom === 'object' && typeof dom.maxStringLength === 'number' ? dom.maxStringLength : undefined;\n if (maxStringLength && maxStringLength > MAX_ALLOWED_STRING_LENGTH) {\n DEBUG_BUILD &&\n logger.warn(\n `\\`dom.maxStringLength\\` cannot exceed ${MAX_ALLOWED_STRING_LENGTH}, but a value of ${maxStringLength} was configured. Sentry will use ${MAX_ALLOWED_STRING_LENGTH} instead.`,\n );\n maxStringLength = MAX_ALLOWED_STRING_LENGTH;\n }\n\n if (typeof keyAttrs === 'string') {\n keyAttrs = [keyAttrs];\n }\n\n // Accessing event.target can throw (see getsentry/raven-js#838, #768)\n try {\n const event = handlerData.event as Event | Node;\n const element = _isEvent(event) ? event.target : event;\n\n target = htmlTreeAsString(element, { keyAttrs, maxStringLength });\n componentName = getComponentName(element);\n } catch (e) {\n target = '';\n }\n\n if (target.length === 0) {\n return;\n }\n\n const breadcrumb: Breadcrumb = {\n category: `ui.${handlerData.name}`,\n message: target,\n };\n\n if (componentName) {\n breadcrumb.data = { 'ui.component_name': componentName };\n }\n\n addBreadcrumb(breadcrumb, {\n event: handlerData.event,\n name: handlerData.name,\n global: handlerData.global,\n });\n };\n}\n\n/**\n * Creates breadcrumbs from console API calls\n */\nfunction _getConsoleBreadcrumbHandler(client: Client): (handlerData: HandlerDataConsole) => void {\n return function _consoleBreadcrumb(handlerData: HandlerDataConsole): void {\n if (getClient() !== client) {\n return;\n }\n\n const breadcrumb = {\n category: 'console',\n data: {\n arguments: handlerData.args,\n logger: 'console',\n },\n level: severityLevelFromString(handlerData.level),\n message: safeJoin(handlerData.args, ' '),\n };\n\n if (handlerData.level === 'assert') {\n if (handlerData.args[0] === false) {\n breadcrumb.message = `Assertion failed: ${safeJoin(handlerData.args.slice(1), ' ') || 'console.assert'}`;\n breadcrumb.data.arguments = handlerData.args.slice(1);\n } else {\n // Don't capture a breadcrumb for passed assertions\n return;\n }\n }\n\n addBreadcrumb(breadcrumb, {\n input: handlerData.args,\n level: handlerData.level,\n });\n };\n}\n\n/**\n * Creates breadcrumbs from XHR API calls\n */\nfunction _getXhrBreadcrumbHandler(client: Client): (handlerData: HandlerDataXhr) => void {\n return function _xhrBreadcrumb(handlerData: HandlerDataXhr): void {\n if (getClient() !== client) {\n return;\n }\n\n const { startTimestamp, endTimestamp } = handlerData;\n\n const sentryXhrData = handlerData.xhr[SENTRY_XHR_DATA_KEY];\n\n // We only capture complete, non-sentry requests\n if (!startTimestamp || !endTimestamp || !sentryXhrData) {\n return;\n }\n\n const { method, url, status_code, body } = sentryXhrData;\n\n const data: XhrBreadcrumbData = {\n method,\n url,\n status_code,\n };\n\n const hint: XhrBreadcrumbHint = {\n xhr: handlerData.xhr,\n input: body,\n startTimestamp,\n endTimestamp,\n };\n\n addBreadcrumb(\n {\n category: 'xhr',\n data,\n type: 'http',\n },\n hint,\n );\n };\n}\n\n/**\n * Creates breadcrumbs from fetch API calls\n */\nfunction _getFetchBreadcrumbHandler(client: Client): (handlerData: HandlerDataFetch) => void {\n return function _fetchBreadcrumb(handlerData: HandlerDataFetch): void {\n if (getClient() !== client) {\n return;\n }\n\n const { startTimestamp, endTimestamp } = handlerData;\n\n // We only capture complete fetch requests\n if (!endTimestamp) {\n return;\n }\n\n if (handlerData.fetchData.url.match(/sentry_key/) && handlerData.fetchData.method === 'POST') {\n // We will not create breadcrumbs for fetch requests that contain `sentry_key` (internal sentry requests)\n return;\n }\n\n if (handlerData.error) {\n const data: FetchBreadcrumbData = handlerData.fetchData;\n const hint: FetchBreadcrumbHint = {\n data: handlerData.error,\n input: handlerData.args,\n startTimestamp,\n endTimestamp,\n };\n\n addBreadcrumb(\n {\n category: 'fetch',\n data,\n level: 'error',\n type: 'http',\n },\n hint,\n );\n } else {\n const response = handlerData.response as Response | undefined;\n const data: FetchBreadcrumbData = {\n ...handlerData.fetchData,\n status_code: response && response.status,\n };\n const hint: FetchBreadcrumbHint = {\n input: handlerData.args,\n response,\n startTimestamp,\n endTimestamp,\n };\n addBreadcrumb(\n {\n category: 'fetch',\n data,\n type: 'http',\n },\n hint,\n );\n }\n };\n}\n\n/**\n * Creates breadcrumbs from history API calls\n */\nfunction _getHistoryBreadcrumbHandler(client: Client): (handlerData: HandlerDataHistory) => void {\n return function _historyBreadcrumb(handlerData: HandlerDataHistory): void {\n if (getClient() !== client) {\n return;\n }\n\n let from: string | undefined = handlerData.from;\n let to: string | undefined = handlerData.to;\n const parsedLoc = parseUrl(WINDOW.location.href);\n let parsedFrom = from ? parseUrl(from) : undefined;\n const parsedTo = parseUrl(to);\n\n // Initial pushState doesn't provide `from` information\n if (!parsedFrom || !parsedFrom.path) {\n parsedFrom = parsedLoc;\n }\n\n // Use only the path component of the URL if the URL matches the current\n // document (almost all the time when using pushState)\n if (parsedLoc.protocol === parsedTo.protocol && parsedLoc.host === parsedTo.host) {\n to = parsedTo.relative;\n }\n if (parsedLoc.protocol === parsedFrom.protocol && parsedLoc.host === parsedFrom.host) {\n from = parsedFrom.relative;\n }\n\n addBreadcrumb({\n category: 'navigation',\n data: {\n from,\n to,\n },\n });\n };\n}\n\nfunction _isEvent(event: unknown): event is Event {\n return !!event && !!(event as Record).target;\n}\n", "import { convertIntegrationFnToClass, defineIntegration } from '@sentry/core';\nimport type { Event, Exception, Integration, IntegrationClass, IntegrationFn, StackFrame } from '@sentry/types';\nimport { logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\n\nconst INTEGRATION_NAME = 'Dedupe';\n\nconst _dedupeIntegration = (() => {\n let previousEvent: Event | undefined;\n\n return {\n name: INTEGRATION_NAME,\n // TODO v8: Remove this\n setupOnce() {}, // eslint-disable-line @typescript-eslint/no-empty-function\n processEvent(currentEvent) {\n // We want to ignore any non-error type events, e.g. transactions or replays\n // These should never be deduped, and also not be compared against as _previousEvent.\n if (currentEvent.type) {\n return currentEvent;\n }\n\n // Juuust in case something goes wrong\n try {\n if (_shouldDropEvent(currentEvent, previousEvent)) {\n DEBUG_BUILD && logger.warn('Event dropped due to being a duplicate of previously captured event.');\n return null;\n }\n } catch (_oO) {} // eslint-disable-line no-empty\n\n return (previousEvent = currentEvent);\n },\n };\n}) satisfies IntegrationFn;\n\nexport const dedupeIntegration = defineIntegration(_dedupeIntegration);\n\n/**\n * Deduplication filter.\n * @deprecated Use `dedupeIntegration()` instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport const Dedupe = convertIntegrationFnToClass(INTEGRATION_NAME, dedupeIntegration) as IntegrationClass<\n Integration & { processEvent: (event: Event) => Event }\n>;\n\nfunction _shouldDropEvent(currentEvent: Event, previousEvent?: Event): boolean {\n if (!previousEvent) {\n return false;\n }\n\n if (_isSameMessageEvent(currentEvent, previousEvent)) {\n return true;\n }\n\n if (_isSameExceptionEvent(currentEvent, previousEvent)) {\n return true;\n }\n\n return false;\n}\n\nfunction _isSameMessageEvent(currentEvent: Event, previousEvent: Event): boolean {\n const currentMessage = currentEvent.message;\n const previousMessage = previousEvent.message;\n\n // If neither event has a message property, they were both exceptions, so bail out\n if (!currentMessage && !previousMessage) {\n return false;\n }\n\n // If only one event has a stacktrace, but not the other one, they are not the same\n if ((currentMessage && !previousMessage) || (!currentMessage && previousMessage)) {\n return false;\n }\n\n if (currentMessage !== previousMessage) {\n return false;\n }\n\n if (!_isSameFingerprint(currentEvent, previousEvent)) {\n return false;\n }\n\n if (!_isSameStacktrace(currentEvent, previousEvent)) {\n return false;\n }\n\n return true;\n}\n\nfunction _isSameExceptionEvent(currentEvent: Event, previousEvent: Event): boolean {\n const previousException = _getExceptionFromEvent(previousEvent);\n const currentException = _getExceptionFromEvent(currentEvent);\n\n if (!previousException || !currentException) {\n return false;\n }\n\n if (previousException.type !== currentException.type || previousException.value !== currentException.value) {\n return false;\n }\n\n if (!_isSameFingerprint(currentEvent, previousEvent)) {\n return false;\n }\n\n if (!_isSameStacktrace(currentEvent, previousEvent)) {\n return false;\n }\n\n return true;\n}\n\nfunction _isSameStacktrace(currentEvent: Event, previousEvent: Event): boolean {\n let currentFrames = _getFramesFromEvent(currentEvent);\n let previousFrames = _getFramesFromEvent(previousEvent);\n\n // If neither event has a stacktrace, they are assumed to be the same\n if (!currentFrames && !previousFrames) {\n return true;\n }\n\n // If only one event has a stacktrace, but not the other one, they are not the same\n if ((currentFrames && !previousFrames) || (!currentFrames && previousFrames)) {\n return false;\n }\n\n currentFrames = currentFrames as StackFrame[];\n previousFrames = previousFrames as StackFrame[];\n\n // If number of frames differ, they are not the same\n if (previousFrames.length !== currentFrames.length) {\n return false;\n }\n\n // Otherwise, compare the two\n for (let i = 0; i < previousFrames.length; i++) {\n const frameA = previousFrames[i];\n const frameB = currentFrames[i];\n\n if (\n frameA.filename !== frameB.filename ||\n frameA.lineno !== frameB.lineno ||\n frameA.colno !== frameB.colno ||\n frameA.function !== frameB.function\n ) {\n return false;\n }\n }\n\n return true;\n}\n\nfunction _isSameFingerprint(currentEvent: Event, previousEvent: Event): boolean {\n let currentFingerprint = currentEvent.fingerprint;\n let previousFingerprint = previousEvent.fingerprint;\n\n // If neither event has a fingerprint, they are assumed to be the same\n if (!currentFingerprint && !previousFingerprint) {\n return true;\n }\n\n // If only one event has a fingerprint, but not the other one, they are not the same\n if ((currentFingerprint && !previousFingerprint) || (!currentFingerprint && previousFingerprint)) {\n return false;\n }\n\n currentFingerprint = currentFingerprint as string[];\n previousFingerprint = previousFingerprint as string[];\n\n // Otherwise, compare the two\n try {\n return !!(currentFingerprint.join('') === previousFingerprint.join(''));\n } catch (_oO) {\n return false;\n }\n}\n\nfunction _getExceptionFromEvent(event: Event): Exception | undefined {\n return event.exception && event.exception.values && event.exception.values[0];\n}\n\nfunction _getFramesFromEvent(event: Event): StackFrame[] | undefined {\n const exception = event.exception;\n\n if (exception) {\n try {\n // @ts-expect-error Object could be undefined\n return exception.values[0].stacktrace.frames;\n } catch (_oO) {\n return undefined;\n }\n }\n return undefined;\n}\n", "/* eslint-disable @typescript-eslint/no-unsafe-member-access */\nimport { captureEvent, convertIntegrationFnToClass, defineIntegration, getClient } from '@sentry/core';\nimport type {\n Client,\n Event,\n Integration,\n IntegrationClass,\n IntegrationFn,\n Primitive,\n StackParser,\n} from '@sentry/types';\nimport {\n addGlobalErrorInstrumentationHandler,\n addGlobalUnhandledRejectionInstrumentationHandler,\n getLocationHref,\n isErrorEvent,\n isPrimitive,\n isString,\n logger,\n} from '@sentry/utils';\n\nimport type { BrowserClient } from '../client';\nimport { DEBUG_BUILD } from '../debug-build';\nimport { eventFromUnknownInput } from '../eventbuilder';\nimport { shouldIgnoreOnError } from '../helpers';\n\ntype GlobalHandlersIntegrationsOptionKeys = 'onerror' | 'onunhandledrejection';\n\ntype GlobalHandlersIntegrations = Record;\n\nconst INTEGRATION_NAME = 'GlobalHandlers';\n\nconst _globalHandlersIntegration = ((options: Partial = {}) => {\n const _options = {\n onerror: true,\n onunhandledrejection: true,\n ...options,\n };\n\n return {\n name: INTEGRATION_NAME,\n setupOnce() {\n Error.stackTraceLimit = 50;\n },\n setup(client) {\n if (_options.onerror) {\n _installGlobalOnErrorHandler(client);\n globalHandlerLog('onerror');\n }\n if (_options.onunhandledrejection) {\n _installGlobalOnUnhandledRejectionHandler(client);\n globalHandlerLog('onunhandledrejection');\n }\n },\n };\n}) satisfies IntegrationFn;\n\nexport const globalHandlersIntegration = defineIntegration(_globalHandlersIntegration);\n\n/**\n * Global handlers.\n * @deprecated Use `globalHandlersIntegration()` instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport const GlobalHandlers = convertIntegrationFnToClass(\n INTEGRATION_NAME,\n globalHandlersIntegration,\n) as IntegrationClass void }> & {\n new (options?: Partial): Integration;\n};\n\nfunction _installGlobalOnErrorHandler(client: Client): void {\n addGlobalErrorInstrumentationHandler(data => {\n const { stackParser, attachStacktrace } = getOptions();\n\n if (getClient() !== client || shouldIgnoreOnError()) {\n return;\n }\n\n const { msg, url, line, column, error } = data;\n\n const event =\n error === undefined && isString(msg)\n ? _eventFromIncompleteOnError(msg, url, line, column)\n : _enhanceEventWithInitialFrame(\n eventFromUnknownInput(stackParser, error || msg, undefined, attachStacktrace, false),\n url,\n line,\n column,\n );\n\n event.level = 'error';\n\n captureEvent(event, {\n originalException: error,\n mechanism: {\n handled: false,\n type: 'onerror',\n },\n });\n });\n}\n\nfunction _installGlobalOnUnhandledRejectionHandler(client: Client): void {\n addGlobalUnhandledRejectionInstrumentationHandler(e => {\n const { stackParser, attachStacktrace } = getOptions();\n\n if (getClient() !== client || shouldIgnoreOnError()) {\n return;\n }\n\n const error = _getUnhandledRejectionError(e as unknown);\n\n const event = isPrimitive(error)\n ? _eventFromRejectionWithPrimitive(error)\n : eventFromUnknownInput(stackParser, error, undefined, attachStacktrace, true);\n\n event.level = 'error';\n\n captureEvent(event, {\n originalException: error,\n mechanism: {\n handled: false,\n type: 'onunhandledrejection',\n },\n });\n });\n}\n\nfunction _getUnhandledRejectionError(error: unknown): unknown {\n if (isPrimitive(error)) {\n return error;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const e = error as any;\n\n // dig the object of the rejection out of known event types\n try {\n // PromiseRejectionEvents store the object of the rejection under 'reason'\n // see https://developer.mozilla.org/en-US/docs/Web/API/PromiseRejectionEvent\n if ('reason' in e) {\n return e.reason;\n }\n\n // something, somewhere, (likely a browser extension) effectively casts PromiseRejectionEvents\n // to CustomEvents, moving the `promise` and `reason` attributes of the PRE into\n // the CustomEvent's `detail` attribute, since they're not part of CustomEvent's spec\n // see https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent and\n // https://github.com/getsentry/sentry-javascript/issues/2380\n else if ('detail' in e && 'reason' in e.detail) {\n return e.detail.reason;\n }\n } catch {} // eslint-disable-line no-empty\n\n return error;\n}\n\n/**\n * Create an event from a promise rejection where the `reason` is a primitive.\n *\n * @param reason: The `reason` property of the promise rejection\n * @returns An Event object with an appropriate `exception` value\n */\nfunction _eventFromRejectionWithPrimitive(reason: Primitive): Event {\n return {\n exception: {\n values: [\n {\n type: 'UnhandledRejection',\n // String() is needed because the Primitive type includes symbols (which can't be automatically stringified)\n value: `Non-Error promise rejection captured with value: ${String(reason)}`,\n },\n ],\n },\n };\n}\n\n/**\n * This function creates a stack from an old, error-less onerror handler.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _eventFromIncompleteOnError(msg: any, url: any, line: any, column: any): Event {\n const ERROR_TYPES_RE =\n /^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;\n\n // If 'message' is ErrorEvent, get real message from inside\n let message = isErrorEvent(msg) ? msg.message : msg;\n let name = 'Error';\n\n const groups = message.match(ERROR_TYPES_RE);\n if (groups) {\n name = groups[1];\n message = groups[2];\n }\n\n const event = {\n exception: {\n values: [\n {\n type: name,\n value: message,\n },\n ],\n },\n };\n\n return _enhanceEventWithInitialFrame(event, url, line, column);\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _enhanceEventWithInitialFrame(event: Event, url: any, line: any, column: any): Event {\n // event.exception\n const e = (event.exception = event.exception || {});\n // event.exception.values\n const ev = (e.values = e.values || []);\n // event.exception.values[0]\n const ev0 = (ev[0] = ev[0] || {});\n // event.exception.values[0].stacktrace\n const ev0s = (ev0.stacktrace = ev0.stacktrace || {});\n // event.exception.values[0].stacktrace.frames\n const ev0sf = (ev0s.frames = ev0s.frames || []);\n\n const colno = isNaN(parseInt(column, 10)) ? undefined : column;\n const lineno = isNaN(parseInt(line, 10)) ? undefined : line;\n const filename = isString(url) && url.length > 0 ? url : getLocationHref();\n\n // event.exception.values[0].stacktrace.frames\n if (ev0sf.length === 0) {\n ev0sf.push({\n colno,\n filename,\n function: '?',\n in_app: true,\n lineno,\n });\n }\n\n return event;\n}\n\nfunction globalHandlerLog(type: string): void {\n DEBUG_BUILD && logger.log(`Global Handler attached: ${type}`);\n}\n\nfunction getOptions(): { stackParser: StackParser; attachStacktrace?: boolean } {\n const client = getClient();\n const options = (client && client.getOptions()) || {\n stackParser: () => [],\n attachStacktrace: false,\n };\n return options;\n}\n", "import { convertIntegrationFnToClass, defineIntegration } from '@sentry/core';\nimport type { Event, Integration, IntegrationClass, IntegrationFn } from '@sentry/types';\n\nimport { WINDOW } from '../helpers';\n\nconst INTEGRATION_NAME = 'HttpContext';\n\nconst _httpContextIntegration = (() => {\n return {\n name: INTEGRATION_NAME,\n // TODO v8: Remove this\n setupOnce() {}, // eslint-disable-line @typescript-eslint/no-empty-function\n preprocessEvent(event) {\n // if none of the information we want exists, don't bother\n if (!WINDOW.navigator && !WINDOW.location && !WINDOW.document) {\n return;\n }\n\n // grab as much info as exists and add it to the event\n const url = (event.request && event.request.url) || (WINDOW.location && WINDOW.location.href);\n const { referrer } = WINDOW.document || {};\n const { userAgent } = WINDOW.navigator || {};\n\n const headers = {\n ...(event.request && event.request.headers),\n ...(referrer && { Referer: referrer }),\n ...(userAgent && { 'User-Agent': userAgent }),\n };\n const request = { ...event.request, ...(url && { url }), headers };\n\n event.request = request;\n },\n };\n}) satisfies IntegrationFn;\n\nexport const httpContextIntegration = defineIntegration(_httpContextIntegration);\n\n/**\n * HttpContext integration collects information about HTTP request headers.\n * @deprecated Use `httpContextIntegration()` instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport const HttpContext = convertIntegrationFnToClass(INTEGRATION_NAME, httpContextIntegration) as IntegrationClass<\n Integration & { preprocessEvent: (event: Event) => void }\n>;\n", "import { convertIntegrationFnToClass, defineIntegration } from '@sentry/core';\nimport type { Client, Event, EventHint, Integration, IntegrationClass, IntegrationFn } from '@sentry/types';\nimport { applyAggregateErrorsToEvent } from '@sentry/utils';\nimport { exceptionFromError } from '../eventbuilder';\n\ninterface LinkedErrorsOptions {\n key?: string;\n limit?: number;\n}\n\nconst DEFAULT_KEY = 'cause';\nconst DEFAULT_LIMIT = 5;\n\nconst INTEGRATION_NAME = 'LinkedErrors';\n\nconst _linkedErrorsIntegration = ((options: LinkedErrorsOptions = {}) => {\n const limit = options.limit || DEFAULT_LIMIT;\n const key = options.key || DEFAULT_KEY;\n\n return {\n name: INTEGRATION_NAME,\n // TODO v8: Remove this\n setupOnce() {}, // eslint-disable-line @typescript-eslint/no-empty-function\n preprocessEvent(event, hint, client) {\n const options = client.getOptions();\n\n applyAggregateErrorsToEvent(\n // This differs from the LinkedErrors integration in core by using a different exceptionFromError function\n exceptionFromError,\n options.stackParser,\n options.maxValueLength,\n key,\n limit,\n event,\n hint,\n );\n },\n };\n}) satisfies IntegrationFn;\n\nexport const linkedErrorsIntegration = defineIntegration(_linkedErrorsIntegration);\n\n/**\n * Aggregrate linked errors in an event.\n * @deprecated Use `linkedErrorsIntegration()` instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport const LinkedErrors = convertIntegrationFnToClass(INTEGRATION_NAME, linkedErrorsIntegration) as IntegrationClass<\n Integration & { preprocessEvent: (event: Event, hint: EventHint, client: Client) => void }\n> & { new (options?: { key?: string; limit?: number }): Integration };\n", "import { convertIntegrationFnToClass, defineIntegration } from '@sentry/core';\nimport type { Integration, IntegrationClass, IntegrationFn, WrappedFunction } from '@sentry/types';\nimport { fill, getFunctionName, getOriginalFunction } from '@sentry/utils';\n\nimport { WINDOW, wrap } from '../helpers';\n\nconst DEFAULT_EVENT_TARGET = [\n 'EventTarget',\n 'Window',\n 'Node',\n 'ApplicationCache',\n 'AudioTrackList',\n 'BroadcastChannel',\n 'ChannelMergerNode',\n 'CryptoOperation',\n 'EventSource',\n 'FileReader',\n 'HTMLUnknownElement',\n 'IDBDatabase',\n 'IDBRequest',\n 'IDBTransaction',\n 'KeyOperation',\n 'MediaController',\n 'MessagePort',\n 'ModalWindow',\n 'Notification',\n 'SVGElementInstance',\n 'Screen',\n 'SharedWorker',\n 'TextTrack',\n 'TextTrackCue',\n 'TextTrackList',\n 'WebSocket',\n 'WebSocketWorker',\n 'Worker',\n 'XMLHttpRequest',\n 'XMLHttpRequestEventTarget',\n 'XMLHttpRequestUpload',\n];\n\nconst INTEGRATION_NAME = 'TryCatch';\n\ntype XMLHttpRequestProp = 'onload' | 'onerror' | 'onprogress' | 'onreadystatechange';\n\ninterface TryCatchOptions {\n setTimeout: boolean;\n setInterval: boolean;\n requestAnimationFrame: boolean;\n XMLHttpRequest: boolean;\n eventTarget: boolean | string[];\n}\n\nconst _browserApiErrorsIntegration = ((options: Partial = {}) => {\n const _options = {\n XMLHttpRequest: true,\n eventTarget: true,\n requestAnimationFrame: true,\n setInterval: true,\n setTimeout: true,\n ...options,\n };\n\n return {\n name: INTEGRATION_NAME,\n // TODO: This currently only works for the first client this is setup\n // We may want to adjust this to check for client etc.\n setupOnce() {\n if (_options.setTimeout) {\n fill(WINDOW, 'setTimeout', _wrapTimeFunction);\n }\n\n if (_options.setInterval) {\n fill(WINDOW, 'setInterval', _wrapTimeFunction);\n }\n\n if (_options.requestAnimationFrame) {\n fill(WINDOW, 'requestAnimationFrame', _wrapRAF);\n }\n\n if (_options.XMLHttpRequest && 'XMLHttpRequest' in WINDOW) {\n fill(XMLHttpRequest.prototype, 'send', _wrapXHR);\n }\n\n const eventTargetOption = _options.eventTarget;\n if (eventTargetOption) {\n const eventTarget = Array.isArray(eventTargetOption) ? eventTargetOption : DEFAULT_EVENT_TARGET;\n eventTarget.forEach(_wrapEventTarget);\n }\n },\n };\n}) satisfies IntegrationFn;\n\nexport const browserApiErrorsIntegration = defineIntegration(_browserApiErrorsIntegration);\n\n/**\n * Wrap timer functions and event targets to catch errors and provide better meta data.\n * @deprecated Use `browserApiErrorsIntegration()` instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport const TryCatch = convertIntegrationFnToClass(\n INTEGRATION_NAME,\n browserApiErrorsIntegration,\n) as IntegrationClass & {\n new (options?: {\n setTimeout: boolean;\n setInterval: boolean;\n requestAnimationFrame: boolean;\n XMLHttpRequest: boolean;\n eventTarget: boolean | string[];\n }): Integration;\n};\n\nfunction _wrapTimeFunction(original: () => void): () => number {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return function (this: any, ...args: any[]): number {\n const originalCallback = args[0];\n args[0] = wrap(originalCallback, {\n mechanism: {\n data: { function: getFunctionName(original) },\n handled: false,\n type: 'instrument',\n },\n });\n return original.apply(this, args);\n };\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _wrapRAF(original: any): (callback: () => void) => any {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return function (this: any, callback: () => void): () => void {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return original.apply(this, [\n wrap(callback, {\n mechanism: {\n data: {\n function: 'requestAnimationFrame',\n handler: getFunctionName(original),\n },\n handled: false,\n type: 'instrument',\n },\n }),\n ]);\n };\n}\n\nfunction _wrapXHR(originalSend: () => void): () => void {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return function (this: XMLHttpRequest, ...args: any[]): void {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const xhr = this;\n const xmlHttpRequestProps: XMLHttpRequestProp[] = ['onload', 'onerror', 'onprogress', 'onreadystatechange'];\n\n xmlHttpRequestProps.forEach(prop => {\n if (prop in xhr && typeof xhr[prop] === 'function') {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n fill(xhr, prop, function (original: WrappedFunction): () => any {\n const wrapOptions = {\n mechanism: {\n data: {\n function: prop,\n handler: getFunctionName(original),\n },\n handled: false,\n type: 'instrument',\n },\n };\n\n // If Instrument integration has been called before TryCatch, get the name of original function\n const originalFunction = getOriginalFunction(original);\n if (originalFunction) {\n wrapOptions.mechanism.data.handler = getFunctionName(originalFunction);\n }\n\n // Otherwise wrap directly\n return wrap(original, wrapOptions);\n });\n }\n });\n\n return originalSend.apply(this, args);\n };\n}\n\nfunction _wrapEventTarget(target: string): void {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const globalObject = WINDOW as { [key: string]: any };\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n const proto = globalObject[target] && globalObject[target].prototype;\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, no-prototype-builtins\n if (!proto || !proto.hasOwnProperty || !proto.hasOwnProperty('addEventListener')) {\n return;\n }\n\n fill(proto, 'addEventListener', function (original: VoidFunction,): (\n eventName: string,\n fn: EventListenerObject,\n options?: boolean | AddEventListenerOptions,\n ) => void {\n return function (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this: any,\n eventName: string,\n fn: EventListenerObject,\n options?: boolean | AddEventListenerOptions,\n ): (eventName: string, fn: EventListenerObject, capture?: boolean, secure?: boolean) => void {\n try {\n if (typeof fn.handleEvent === 'function') {\n // ESlint disable explanation:\n // First, it is generally safe to call `wrap` with an unbound function. Furthermore, using `.bind()` would\n // introduce a bug here, because bind returns a new function that doesn't have our\n // flags(like __sentry_original__) attached. `wrap` checks for those flags to avoid unnecessary wrapping.\n // Without those flags, every call to addEventListener wraps the function again, causing a memory leak.\n // eslint-disable-next-line @typescript-eslint/unbound-method\n fn.handleEvent = wrap(fn.handleEvent, {\n mechanism: {\n data: {\n function: 'handleEvent',\n handler: getFunctionName(fn),\n target,\n },\n handled: false,\n type: 'instrument',\n },\n });\n }\n } catch (err) {\n // can sometimes get 'Permission denied to access property \"handle Event'\n }\n\n return original.apply(this, [\n eventName,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n wrap(fn as any as WrappedFunction, {\n mechanism: {\n data: {\n function: 'addEventListener',\n handler: getFunctionName(fn),\n target,\n },\n handled: false,\n type: 'instrument',\n },\n }),\n options,\n ]);\n };\n });\n\n fill(\n proto,\n 'removeEventListener',\n function (\n originalRemoveEventListener: () => void,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ): (this: any, eventName: string, fn: EventListenerObject, options?: boolean | EventListenerOptions) => () => void {\n return function (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this: any,\n eventName: string,\n fn: EventListenerObject,\n options?: boolean | EventListenerOptions,\n ): () => void {\n /**\n * There are 2 possible scenarios here:\n *\n * 1. Someone passes a callback, which was attached prior to Sentry initialization, or by using unmodified\n * method, eg. `document.addEventListener.call(el, name, handler). In this case, we treat this function\n * as a pass-through, and call original `removeEventListener` with it.\n *\n * 2. Someone passes a callback, which was attached after Sentry was initialized, which means that it was using\n * our wrapped version of `addEventListener`, which internally calls `wrap` helper.\n * This helper \"wraps\" whole callback inside a try/catch statement, and attached appropriate metadata to it,\n * in order for us to make a distinction between wrapped/non-wrapped functions possible.\n * If a function was wrapped, it has additional property of `__sentry_wrapped__`, holding the handler.\n *\n * When someone adds a handler prior to initialization, and then do it again, but after,\n * then we have to detach both of them. Otherwise, if we'd detach only wrapped one, it'd be impossible\n * to get rid of the initial handler and it'd stick there forever.\n */\n const wrappedEventHandler = fn as unknown as WrappedFunction;\n try {\n const originalEventHandler = wrappedEventHandler && wrappedEventHandler.__sentry_wrapped__;\n if (originalEventHandler) {\n originalRemoveEventListener.call(this, eventName, originalEventHandler, options);\n }\n } catch (e) {\n // ignore, accessing __sentry_wrapped__ will throw in some Selenium environments\n }\n return originalRemoveEventListener.call(this, eventName, wrappedEventHandler, options);\n };\n },\n );\n}\n", "import type { Hub } from '@sentry/core';\nimport { functionToStringIntegration, inboundFiltersIntegration } from '@sentry/core';\nimport {\n captureSession,\n getClient,\n getCurrentHub,\n getIntegrationsToSetup,\n getReportDialogEndpoint,\n initAndBind,\n startSession,\n} from '@sentry/core';\nimport type { Integration, Options, UserFeedback } from '@sentry/types';\nimport {\n addHistoryInstrumentationHandler,\n logger,\n stackParserFromStackParserOptions,\n supportsFetch,\n} from '@sentry/utils';\n\nimport type { BrowserClientOptions, BrowserOptions } from './client';\nimport { BrowserClient } from './client';\nimport { DEBUG_BUILD } from './debug-build';\nimport type { ReportDialogOptions } from './helpers';\nimport { WINDOW, wrap as internalWrap } from './helpers';\nimport { breadcrumbsIntegration } from './integrations/breadcrumbs';\nimport { dedupeIntegration } from './integrations/dedupe';\nimport { globalHandlersIntegration } from './integrations/globalhandlers';\nimport { httpContextIntegration } from './integrations/httpcontext';\nimport { linkedErrorsIntegration } from './integrations/linkederrors';\nimport { browserApiErrorsIntegration } from './integrations/trycatch';\nimport { defaultStackParser } from './stack-parsers';\nimport { makeFetchTransport, makeXHRTransport } from './transports';\n\n/** @deprecated Use `getDefaultIntegrations(options)` instead. */\nexport const defaultIntegrations = [\n inboundFiltersIntegration(),\n functionToStringIntegration(),\n browserApiErrorsIntegration(),\n breadcrumbsIntegration(),\n globalHandlersIntegration(),\n linkedErrorsIntegration(),\n dedupeIntegration(),\n httpContextIntegration(),\n];\n\n/** Get the default integrations for the browser SDK. */\nexport function getDefaultIntegrations(_options: Options): Integration[] {\n // We return a copy of the defaultIntegrations here to avoid mutating this\n return [\n // eslint-disable-next-line deprecation/deprecation\n ...defaultIntegrations,\n ];\n}\n\n/**\n * A magic string that build tooling can leverage in order to inject a release value into the SDK.\n */\ndeclare const __SENTRY_RELEASE__: string | undefined;\n\n/**\n * The Sentry Browser SDK Client.\n *\n * To use this SDK, call the {@link init} function as early as possible when\n * loading the web page. To set context information or send manual events, use\n * the provided methods.\n *\n * @example\n *\n * ```\n *\n * import { init } from '@sentry/browser';\n *\n * init({\n * dsn: '__DSN__',\n * // ...\n * });\n * ```\n *\n * @example\n * ```\n *\n * import { configureScope } from '@sentry/browser';\n * configureScope((scope: Scope) => {\n * scope.setExtra({ battery: 0.7 });\n * scope.setTag({ user_mode: 'admin' });\n * scope.setUser({ id: '4711' });\n * });\n * ```\n *\n * @example\n * ```\n *\n * import { addBreadcrumb } from '@sentry/browser';\n * addBreadcrumb({\n * message: 'My Breadcrumb',\n * // ...\n * });\n * ```\n *\n * @example\n *\n * ```\n *\n * import * as Sentry from '@sentry/browser';\n * Sentry.captureMessage('Hello, world!');\n * Sentry.captureException(new Error('Good bye'));\n * Sentry.captureEvent({\n * message: 'Manual',\n * stacktrace: [\n * // ...\n * ],\n * });\n * ```\n *\n * @see {@link BrowserOptions} for documentation on configuration options.\n */\nexport function init(options: BrowserOptions = {}): void {\n if (options.defaultIntegrations === undefined) {\n options.defaultIntegrations = getDefaultIntegrations(options);\n }\n if (options.release === undefined) {\n // This allows build tooling to find-and-replace __SENTRY_RELEASE__ to inject a release value\n if (typeof __SENTRY_RELEASE__ === 'string') {\n options.release = __SENTRY_RELEASE__;\n }\n\n // This supports the variable that sentry-webpack-plugin injects\n if (WINDOW.SENTRY_RELEASE && WINDOW.SENTRY_RELEASE.id) {\n options.release = WINDOW.SENTRY_RELEASE.id;\n }\n }\n if (options.autoSessionTracking === undefined) {\n options.autoSessionTracking = true;\n }\n if (options.sendClientReports === undefined) {\n options.sendClientReports = true;\n }\n\n const clientOptions: BrowserClientOptions = {\n ...options,\n stackParser: stackParserFromStackParserOptions(options.stackParser || defaultStackParser),\n integrations: getIntegrationsToSetup(options),\n transport: options.transport || (supportsFetch() ? makeFetchTransport : makeXHRTransport),\n };\n\n initAndBind(BrowserClient, clientOptions);\n\n if (options.autoSessionTracking) {\n startSessionTracking();\n }\n}\n\ntype NewReportDialogOptions = ReportDialogOptions & { eventId: string }; // eslint-disable-line\n\ninterface ShowReportDialogFunction {\n /**\n * Present the user with a report dialog.\n *\n * @param options Everything is optional, we try to fetch all info need from the global scope.\n */\n (options: NewReportDialogOptions): void;\n\n /**\n * Present the user with a report dialog.\n *\n * @param options Everything is optional, we try to fetch all info need from the global scope.\n *\n * @deprecated Please always pass an `options` argument with `eventId`. The `hub` argument will not be used in the next version of the SDK.\n */\n // eslint-disable-next-line deprecation/deprecation\n (options?: ReportDialogOptions, hub?: Hub): void;\n}\n\nexport const showReportDialog: ShowReportDialogFunction = (\n // eslint-disable-next-line deprecation/deprecation\n options: ReportDialogOptions = {},\n // eslint-disable-next-line deprecation/deprecation\n hub: Hub = getCurrentHub(),\n) => {\n // doesn't work without a document (React Native)\n if (!WINDOW.document) {\n DEBUG_BUILD && logger.error('Global document not defined in showReportDialog call');\n return;\n }\n\n // eslint-disable-next-line deprecation/deprecation\n const { client, scope } = hub.getStackTop();\n const dsn = options.dsn || (client && client.getDsn());\n if (!dsn) {\n DEBUG_BUILD && logger.error('DSN not configured for showReportDialog call');\n return;\n }\n\n if (scope) {\n options.user = {\n ...scope.getUser(),\n ...options.user,\n };\n }\n\n if (!options.eventId) {\n // eslint-disable-next-line deprecation/deprecation\n options.eventId = hub.lastEventId();\n }\n\n const script = WINDOW.document.createElement('script');\n script.async = true;\n script.crossOrigin = 'anonymous';\n script.src = getReportDialogEndpoint(dsn, options);\n\n if (options.onLoad) {\n script.onload = options.onLoad;\n }\n\n const { onClose } = options;\n if (onClose) {\n const reportDialogClosedMessageHandler = (event: MessageEvent): void => {\n if (event.data === '__sentry_reportdialog_closed__') {\n try {\n onClose();\n } finally {\n WINDOW.removeEventListener('message', reportDialogClosedMessageHandler);\n }\n }\n };\n WINDOW.addEventListener('message', reportDialogClosedMessageHandler);\n }\n\n const injectionPoint = WINDOW.document.head || WINDOW.document.body;\n if (injectionPoint) {\n injectionPoint.appendChild(script);\n } else {\n DEBUG_BUILD && logger.error('Not injecting report dialog. No injection point found in HTML');\n }\n};\n\n/**\n * This function is here to be API compatible with the loader.\n * @hidden\n */\nexport function forceLoad(): void {\n // Noop\n}\n\n/**\n * This function is here to be API compatible with the loader.\n * @hidden\n */\nexport function onLoad(callback: () => void): void {\n callback();\n}\n\n/**\n * Wrap code within a try/catch block so the SDK is able to capture errors.\n *\n * @deprecated This function will be removed in v8.\n * It is not part of Sentry's official API and it's easily replaceable by using a try/catch block\n * and calling Sentry.captureException.\n *\n * @param fn A function to wrap.\n *\n * @returns The result of wrapped function call.\n */\n// TODO(v8): Remove this function\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function wrap(fn: (...args: any) => any): any {\n return internalWrap(fn)();\n}\n\n/**\n * Enable automatic Session Tracking for the initial page load.\n */\nfunction startSessionTracking(): void {\n if (typeof WINDOW.document === 'undefined') {\n DEBUG_BUILD && logger.warn('Session tracking in non-browser environment with @sentry/browser is not supported.');\n return;\n }\n\n // The session duration for browser sessions does not track a meaningful\n // concept that can be used as a metric.\n // Automatically captured sessions are akin to page views, and thus we\n // discard their duration.\n startSession({ ignoreDuration: true });\n captureSession();\n\n // We want to create a session for every navigation as well\n addHistoryInstrumentationHandler(({ from, to }) => {\n // Don't create an additional session for the initial route or if the location did not change\n if (from !== undefined && from !== to) {\n startSession({ ignoreDuration: true });\n captureSession();\n }\n });\n}\n\n/**\n * Captures user feedback and sends it to Sentry.\n */\nexport function captureUserFeedback(feedback: UserFeedback): void {\n const client = getClient();\n if (client) {\n client.captureUserFeedback(feedback);\n }\n}\n", "import { GLOBAL_OBJ } from '@sentry/utils';\n\n// exporting a separate copy of `WINDOW` rather than exporting the one from `@sentry/browser`\n// prevents the browser package from being bundled in the CDN bundle, and avoids a\n// circular dependency between the browser and replay packages should `@sentry/browser` import\n// from `@sentry/replay` in the future\nexport const WINDOW = GLOBAL_OBJ as typeof GLOBAL_OBJ & Window;\n\nexport const REPLAY_SESSION_KEY = 'sentryReplaySession';\nexport const REPLAY_EVENT_NAME = 'replay_event';\nexport const RECORDING_EVENT_NAME = 'replay_recording';\nexport const UNABLE_TO_SEND_REPLAY = 'Unable to send Replay';\n\n// The idle limit for a session after which recording is paused.\nexport const SESSION_IDLE_PAUSE_DURATION = 300_000; // 5 minutes in ms\n\n// The idle limit for a session after which the session expires.\nexport const SESSION_IDLE_EXPIRE_DURATION = 900_000; // 15 minutes in ms\n\n/** Default flush delays */\nexport const DEFAULT_FLUSH_MIN_DELAY = 5_000;\n// XXX: Temp fix for our debounce logic where `maxWait` would never occur if it\n// was the same as `wait`\nexport const DEFAULT_FLUSH_MAX_DELAY = 5_500;\n\n/* How long to wait for error checkouts */\nexport const BUFFER_CHECKOUT_TIME = 60_000;\n\nexport const RETRY_BASE_INTERVAL = 5000;\nexport const RETRY_MAX_COUNT = 3;\n\n/* The max (uncompressed) size in bytes of a network body. Any body larger than this will be truncated. */\nexport const NETWORK_BODY_MAX_SIZE = 150_000;\n\n/* The max size of a single console arg that is captured. Any arg larger than this will be truncated. */\nexport const CONSOLE_ARG_MAX_SIZE = 5_000;\n\n/* Min. time to wait before we consider something a slow click. */\nexport const SLOW_CLICK_THRESHOLD = 3_000;\n/* For scroll actions after a click, we only look for a very short time period to detect programmatic scrolling. */\nexport const SLOW_CLICK_SCROLL_TIMEOUT = 300;\n\n/** When encountering a total segment size exceeding this size, stop the replay (as we cannot properly ingest it). */\nexport const REPLAY_MAX_EVENT_BUFFER_SIZE = 20_000_000; // ~20MB\n\n/** Replays must be min. 5s long before we send them. */\nexport const MIN_REPLAY_DURATION = 4_999;\n/* The max. allowed value that the minReplayDuration can be set to. */\nexport const MIN_REPLAY_DURATION_LIMIT = 15_000;\n\n/** The max. length of a replay. */\nexport const MAX_REPLAY_DURATION = 3_600_000; // 60 minutes in ms;\n\n/** Default attributes to be ignored when `maskAllText` is enabled */\nexport const DEFAULT_IGNORED_ATTRIBUTES = ['title', 'placeholder'];\n", "var NodeType;\r\n(function (NodeType) {\r\n NodeType[NodeType[\"Document\"] = 0] = \"Document\";\r\n NodeType[NodeType[\"DocumentType\"] = 1] = \"DocumentType\";\r\n NodeType[NodeType[\"Element\"] = 2] = \"Element\";\r\n NodeType[NodeType[\"Text\"] = 3] = \"Text\";\r\n NodeType[NodeType[\"CDATA\"] = 4] = \"CDATA\";\r\n NodeType[NodeType[\"Comment\"] = 5] = \"Comment\";\r\n})(NodeType || (NodeType = {}));\n\nfunction isElement(n) {\r\n return n.nodeType === n.ELEMENT_NODE;\r\n}\r\nfunction isShadowRoot(n) {\r\n const host = n?.host;\r\n return Boolean(host?.shadowRoot === n);\r\n}\r\nfunction isNativeShadowDom(shadowRoot) {\r\n return Object.prototype.toString.call(shadowRoot) === '[object ShadowRoot]';\r\n}\r\nfunction fixBrowserCompatibilityIssuesInCSS(cssText) {\r\n if (cssText.includes(' background-clip: text;') &&\r\n !cssText.includes(' -webkit-background-clip: text;')) {\r\n cssText = cssText.replace(' background-clip: text;', ' -webkit-background-clip: text; background-clip: text;');\r\n }\r\n return cssText;\r\n}\r\nfunction escapeImportStatement(rule) {\r\n const { cssText } = rule;\r\n if (cssText.split('\"').length < 3)\r\n return cssText;\r\n const statement = ['@import', `url(${JSON.stringify(rule.href)})`];\r\n if (rule.layerName === '') {\r\n statement.push(`layer`);\r\n }\r\n else if (rule.layerName) {\r\n statement.push(`layer(${rule.layerName})`);\r\n }\r\n if (rule.supportsText) {\r\n statement.push(`supports(${rule.supportsText})`);\r\n }\r\n if (rule.media.length) {\r\n statement.push(rule.media.mediaText);\r\n }\r\n return statement.join(' ') + ';';\r\n}\r\nfunction stringifyStylesheet(s) {\r\n try {\r\n const rules = s.rules || s.cssRules;\r\n return rules\r\n ? fixBrowserCompatibilityIssuesInCSS(Array.from(rules, stringifyRule).join(''))\r\n : null;\r\n }\r\n catch (error) {\r\n return null;\r\n }\r\n}\r\nfunction stringifyRule(rule) {\r\n let importStringified;\r\n if (isCSSImportRule(rule)) {\r\n try {\r\n importStringified =\r\n stringifyStylesheet(rule.styleSheet) ||\r\n escapeImportStatement(rule);\r\n }\r\n catch (error) {\r\n }\r\n }\r\n else if (isCSSStyleRule(rule) && rule.selectorText.includes(':')) {\r\n return fixSafariColons(rule.cssText);\r\n }\r\n return importStringified || rule.cssText;\r\n}\r\nfunction fixSafariColons(cssStringified) {\r\n const regex = /(\\[(?:[\\w-]+)[^\\\\])(:(?:[\\w-]+)\\])/gm;\r\n return cssStringified.replace(regex, '$1\\\\$2');\r\n}\r\nfunction isCSSImportRule(rule) {\r\n return 'styleSheet' in rule;\r\n}\r\nfunction isCSSStyleRule(rule) {\r\n return 'selectorText' in rule;\r\n}\r\nclass Mirror {\r\n constructor() {\r\n this.idNodeMap = new Map();\r\n this.nodeMetaMap = new WeakMap();\r\n }\r\n getId(n) {\r\n if (!n)\r\n return -1;\r\n const id = this.getMeta(n)?.id;\r\n return id ?? -1;\r\n }\r\n getNode(id) {\r\n return this.idNodeMap.get(id) || null;\r\n }\r\n getIds() {\r\n return Array.from(this.idNodeMap.keys());\r\n }\r\n getMeta(n) {\r\n return this.nodeMetaMap.get(n) || null;\r\n }\r\n removeNodeFromMap(n) {\r\n const id = this.getId(n);\r\n this.idNodeMap.delete(id);\r\n if (n.childNodes) {\r\n n.childNodes.forEach((childNode) => this.removeNodeFromMap(childNode));\r\n }\r\n }\r\n has(id) {\r\n return this.idNodeMap.has(id);\r\n }\r\n hasNode(node) {\r\n return this.nodeMetaMap.has(node);\r\n }\r\n add(n, meta) {\r\n const id = meta.id;\r\n this.idNodeMap.set(id, n);\r\n this.nodeMetaMap.set(n, meta);\r\n }\r\n replace(id, n) {\r\n const oldNode = this.getNode(id);\r\n if (oldNode) {\r\n const meta = this.nodeMetaMap.get(oldNode);\r\n if (meta)\r\n this.nodeMetaMap.set(n, meta);\r\n }\r\n this.idNodeMap.set(id, n);\r\n }\r\n reset() {\r\n this.idNodeMap = new Map();\r\n this.nodeMetaMap = new WeakMap();\r\n }\r\n}\r\nfunction createMirror() {\r\n return new Mirror();\r\n}\r\nfunction shouldMaskInput({ maskInputOptions, tagName, type, }) {\r\n if (tagName === 'OPTION') {\r\n tagName = 'SELECT';\r\n }\r\n return Boolean(maskInputOptions[tagName.toLowerCase()] ||\r\n (type && maskInputOptions[type]) ||\r\n type === 'password' ||\r\n (tagName === 'INPUT' && !type && maskInputOptions['text']));\r\n}\r\nfunction maskInputValue({ isMasked, element, value, maskInputFn, }) {\r\n let text = value || '';\r\n if (!isMasked) {\r\n return text;\r\n }\r\n if (maskInputFn) {\r\n text = maskInputFn(text, element);\r\n }\r\n return '*'.repeat(text.length);\r\n}\r\nfunction toLowerCase(str) {\r\n return str.toLowerCase();\r\n}\r\nfunction toUpperCase(str) {\r\n return str.toUpperCase();\r\n}\r\nconst ORIGINAL_ATTRIBUTE_NAME = '__rrweb_original__';\r\nfunction is2DCanvasBlank(canvas) {\r\n const ctx = canvas.getContext('2d');\r\n if (!ctx)\r\n return true;\r\n const chunkSize = 50;\r\n for (let x = 0; x < canvas.width; x += chunkSize) {\r\n for (let y = 0; y < canvas.height; y += chunkSize) {\r\n const getImageData = ctx.getImageData;\r\n const originalGetImageData = ORIGINAL_ATTRIBUTE_NAME in getImageData\r\n ? getImageData[ORIGINAL_ATTRIBUTE_NAME]\r\n : getImageData;\r\n const pixelBuffer = new Uint32Array(originalGetImageData.call(ctx, x, y, Math.min(chunkSize, canvas.width - x), Math.min(chunkSize, canvas.height - y)).data.buffer);\r\n if (pixelBuffer.some((pixel) => pixel !== 0))\r\n return false;\r\n }\r\n }\r\n return true;\r\n}\r\nfunction isNodeMetaEqual(a, b) {\r\n if (!a || !b || a.type !== b.type)\r\n return false;\r\n if (a.type === NodeType.Document)\r\n return a.compatMode === b.compatMode;\r\n else if (a.type === NodeType.DocumentType)\r\n return (a.name === b.name &&\r\n a.publicId === b.publicId &&\r\n a.systemId === b.systemId);\r\n else if (a.type === NodeType.Comment ||\r\n a.type === NodeType.Text ||\r\n a.type === NodeType.CDATA)\r\n return a.textContent === b.textContent;\r\n else if (a.type === NodeType.Element)\r\n return (a.tagName === b.tagName &&\r\n JSON.stringify(a.attributes) ===\r\n JSON.stringify(b.attributes) &&\r\n a.isSVG === b.isSVG &&\r\n a.needBlock === b.needBlock);\r\n return false;\r\n}\r\nfunction getInputType(element) {\r\n const type = element.type;\r\n return element.hasAttribute('data-rr-is-password')\r\n ? 'password'\r\n : type\r\n ?\r\n toLowerCase(type)\r\n : null;\r\n}\r\nfunction getInputValue(el, tagName, type) {\r\n if (tagName === 'INPUT' && (type === 'radio' || type === 'checkbox')) {\r\n return el.getAttribute('value') || '';\r\n }\r\n return el.value;\r\n}\n\nlet _id = 1;\r\nconst tagNameRegex = new RegExp('[^a-z0-9-_:]');\r\nconst IGNORED_NODE = -2;\r\nfunction genId() {\r\n return _id++;\r\n}\r\nfunction getValidTagName(element) {\r\n if (element instanceof HTMLFormElement) {\r\n return 'form';\r\n }\r\n const processedTagName = toLowerCase(element.tagName);\r\n if (tagNameRegex.test(processedTagName)) {\r\n return 'div';\r\n }\r\n return processedTagName;\r\n}\r\nfunction extractOrigin(url) {\r\n let origin = '';\r\n if (url.indexOf('//') > -1) {\r\n origin = url.split('/').slice(0, 3).join('/');\r\n }\r\n else {\r\n origin = url.split('/')[0];\r\n }\r\n origin = origin.split('?')[0];\r\n return origin;\r\n}\r\nlet canvasService;\r\nlet canvasCtx;\r\nconst URL_IN_CSS_REF = /url\\((?:(')([^']*)'|(\")(.*?)\"|([^)]*))\\)/gm;\r\nconst URL_PROTOCOL_MATCH = /^(?:[a-z+]+:)?\\/\\//i;\r\nconst URL_WWW_MATCH = /^www\\..*/i;\r\nconst DATA_URI = /^(data:)([^,]*),(.*)/i;\r\nfunction absoluteToStylesheet(cssText, href) {\r\n return (cssText || '').replace(URL_IN_CSS_REF, (origin, quote1, path1, quote2, path2, path3) => {\r\n const filePath = path1 || path2 || path3;\r\n const maybeQuote = quote1 || quote2 || '';\r\n if (!filePath) {\r\n return origin;\r\n }\r\n if (URL_PROTOCOL_MATCH.test(filePath) || URL_WWW_MATCH.test(filePath)) {\r\n return `url(${maybeQuote}${filePath}${maybeQuote})`;\r\n }\r\n if (DATA_URI.test(filePath)) {\r\n return `url(${maybeQuote}${filePath}${maybeQuote})`;\r\n }\r\n if (filePath[0] === '/') {\r\n return `url(${maybeQuote}${extractOrigin(href) + filePath}${maybeQuote})`;\r\n }\r\n const stack = href.split('/');\r\n const parts = filePath.split('/');\r\n stack.pop();\r\n for (const part of parts) {\r\n if (part === '.') {\r\n continue;\r\n }\r\n else if (part === '..') {\r\n stack.pop();\r\n }\r\n else {\r\n stack.push(part);\r\n }\r\n }\r\n return `url(${maybeQuote}${stack.join('/')}${maybeQuote})`;\r\n });\r\n}\r\nconst SRCSET_NOT_SPACES = /^[^ \\t\\n\\r\\u000c]+/;\r\nconst SRCSET_COMMAS_OR_SPACES = /^[, \\t\\n\\r\\u000c]+/;\r\nfunction getAbsoluteSrcsetString(doc, attributeValue) {\r\n if (attributeValue.trim() === '') {\r\n return attributeValue;\r\n }\r\n let pos = 0;\r\n function collectCharacters(regEx) {\r\n let chars;\r\n const match = regEx.exec(attributeValue.substring(pos));\r\n if (match) {\r\n chars = match[0];\r\n pos += chars.length;\r\n return chars;\r\n }\r\n return '';\r\n }\r\n const output = [];\r\n while (true) {\r\n collectCharacters(SRCSET_COMMAS_OR_SPACES);\r\n if (pos >= attributeValue.length) {\r\n break;\r\n }\r\n let url = collectCharacters(SRCSET_NOT_SPACES);\r\n if (url.slice(-1) === ',') {\r\n url = absoluteToDoc(doc, url.substring(0, url.length - 1));\r\n output.push(url);\r\n }\r\n else {\r\n let descriptorsStr = '';\r\n url = absoluteToDoc(doc, url);\r\n let inParens = false;\r\n while (true) {\r\n const c = attributeValue.charAt(pos);\r\n if (c === '') {\r\n output.push((url + descriptorsStr).trim());\r\n break;\r\n }\r\n else if (!inParens) {\r\n if (c === ',') {\r\n pos += 1;\r\n output.push((url + descriptorsStr).trim());\r\n break;\r\n }\r\n else if (c === '(') {\r\n inParens = true;\r\n }\r\n }\r\n else {\r\n if (c === ')') {\r\n inParens = false;\r\n }\r\n }\r\n descriptorsStr += c;\r\n pos += 1;\r\n }\r\n }\r\n }\r\n return output.join(', ');\r\n}\r\nfunction absoluteToDoc(doc, attributeValue) {\r\n if (!attributeValue || attributeValue.trim() === '') {\r\n return attributeValue;\r\n }\r\n const a = doc.createElement('a');\r\n a.href = attributeValue;\r\n return a.href;\r\n}\r\nfunction isSVGElement(el) {\r\n return Boolean(el.tagName === 'svg' || el.ownerSVGElement);\r\n}\r\nfunction getHref() {\r\n const a = document.createElement('a');\r\n a.href = '';\r\n return a.href;\r\n}\r\nfunction transformAttribute(doc, tagName, name, value, element, maskAttributeFn) {\r\n if (!value) {\r\n return value;\r\n }\r\n if (name === 'src' ||\r\n (name === 'href' && !(tagName === 'use' && value[0] === '#'))) {\r\n return absoluteToDoc(doc, value);\r\n }\r\n else if (name === 'xlink:href' && value[0] !== '#') {\r\n return absoluteToDoc(doc, value);\r\n }\r\n else if (name === 'background' &&\r\n (tagName === 'table' || tagName === 'td' || tagName === 'th')) {\r\n return absoluteToDoc(doc, value);\r\n }\r\n else if (name === 'srcset') {\r\n return getAbsoluteSrcsetString(doc, value);\r\n }\r\n else if (name === 'style') {\r\n return absoluteToStylesheet(value, getHref());\r\n }\r\n else if (tagName === 'object' && name === 'data') {\r\n return absoluteToDoc(doc, value);\r\n }\r\n if (typeof maskAttributeFn === 'function') {\r\n return maskAttributeFn(name, value, element);\r\n }\r\n return value;\r\n}\r\nfunction ignoreAttribute(tagName, name, _value) {\r\n return (tagName === 'video' || tagName === 'audio') && name === 'autoplay';\r\n}\r\nfunction _isBlockedElement(element, blockClass, blockSelector, unblockSelector) {\r\n try {\r\n if (unblockSelector && element.matches(unblockSelector)) {\r\n return false;\r\n }\r\n if (typeof blockClass === 'string') {\r\n if (element.classList.contains(blockClass)) {\r\n return true;\r\n }\r\n }\r\n else {\r\n for (let eIndex = element.classList.length; eIndex--;) {\r\n const className = element.classList[eIndex];\r\n if (blockClass.test(className)) {\r\n return true;\r\n }\r\n }\r\n }\r\n if (blockSelector) {\r\n return element.matches(blockSelector);\r\n }\r\n }\r\n catch (e) {\r\n }\r\n return false;\r\n}\r\nfunction elementClassMatchesRegex(el, regex) {\r\n for (let eIndex = el.classList.length; eIndex--;) {\r\n const className = el.classList[eIndex];\r\n if (regex.test(className)) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n}\r\nfunction distanceToMatch(node, matchPredicate, limit = Infinity, distance = 0) {\r\n if (!node)\r\n return -1;\r\n if (node.nodeType !== node.ELEMENT_NODE)\r\n return -1;\r\n if (distance > limit)\r\n return -1;\r\n if (matchPredicate(node))\r\n return distance;\r\n return distanceToMatch(node.parentNode, matchPredicate, limit, distance + 1);\r\n}\r\nfunction createMatchPredicate(className, selector) {\r\n return (node) => {\r\n const el = node;\r\n if (el === null)\r\n return false;\r\n try {\r\n if (className) {\r\n if (typeof className === 'string') {\r\n if (el.matches(`.${className}`))\r\n return true;\r\n }\r\n else if (elementClassMatchesRegex(el, className)) {\r\n return true;\r\n }\r\n }\r\n if (selector && el.matches(selector))\r\n return true;\r\n return false;\r\n }\r\n catch {\r\n return false;\r\n }\r\n };\r\n}\r\nfunction needMaskingText(node, maskTextClass, maskTextSelector, unmaskTextClass, unmaskTextSelector, maskAllText) {\r\n try {\r\n const el = node.nodeType === node.ELEMENT_NODE\r\n ? node\r\n : node.parentElement;\r\n if (el === null)\r\n return false;\r\n if (el.tagName === 'INPUT') {\r\n const autocomplete = el.getAttribute('autocomplete');\r\n const disallowedAutocompleteValues = [\r\n 'current-password',\r\n 'new-password',\r\n 'cc-number',\r\n 'cc-exp',\r\n 'cc-exp-month',\r\n 'cc-exp-year',\r\n 'cc-csc',\r\n ];\r\n if (disallowedAutocompleteValues.includes(autocomplete)) {\r\n return true;\r\n }\r\n }\r\n let maskDistance = -1;\r\n let unmaskDistance = -1;\r\n if (maskAllText) {\r\n unmaskDistance = distanceToMatch(el, createMatchPredicate(unmaskTextClass, unmaskTextSelector));\r\n if (unmaskDistance < 0) {\r\n return true;\r\n }\r\n maskDistance = distanceToMatch(el, createMatchPredicate(maskTextClass, maskTextSelector), unmaskDistance >= 0 ? unmaskDistance : Infinity);\r\n }\r\n else {\r\n maskDistance = distanceToMatch(el, createMatchPredicate(maskTextClass, maskTextSelector));\r\n if (maskDistance < 0) {\r\n return false;\r\n }\r\n unmaskDistance = distanceToMatch(el, createMatchPredicate(unmaskTextClass, unmaskTextSelector), maskDistance >= 0 ? maskDistance : Infinity);\r\n }\r\n return maskDistance >= 0\r\n ? unmaskDistance >= 0\r\n ? maskDistance <= unmaskDistance\r\n : true\r\n : unmaskDistance >= 0\r\n ? false\r\n : !!maskAllText;\r\n }\r\n catch (e) {\r\n }\r\n return !!maskAllText;\r\n}\r\nfunction onceIframeLoaded(iframeEl, listener, iframeLoadTimeout) {\r\n const win = iframeEl.contentWindow;\r\n if (!win) {\r\n return;\r\n }\r\n let fired = false;\r\n let readyState;\r\n try {\r\n readyState = win.document.readyState;\r\n }\r\n catch (error) {\r\n return;\r\n }\r\n if (readyState !== 'complete') {\r\n const timer = setTimeout(() => {\r\n if (!fired) {\r\n listener();\r\n fired = true;\r\n }\r\n }, iframeLoadTimeout);\r\n iframeEl.addEventListener('load', () => {\r\n clearTimeout(timer);\r\n fired = true;\r\n listener();\r\n });\r\n return;\r\n }\r\n const blankUrl = 'about:blank';\r\n if (win.location.href !== blankUrl ||\r\n iframeEl.src === blankUrl ||\r\n iframeEl.src === '') {\r\n setTimeout(listener, 0);\r\n return iframeEl.addEventListener('load', listener);\r\n }\r\n iframeEl.addEventListener('load', listener);\r\n}\r\nfunction onceStylesheetLoaded(link, listener, styleSheetLoadTimeout) {\r\n let fired = false;\r\n let styleSheetLoaded;\r\n try {\r\n styleSheetLoaded = link.sheet;\r\n }\r\n catch (error) {\r\n return;\r\n }\r\n if (styleSheetLoaded)\r\n return;\r\n const timer = setTimeout(() => {\r\n if (!fired) {\r\n listener();\r\n fired = true;\r\n }\r\n }, styleSheetLoadTimeout);\r\n link.addEventListener('load', () => {\r\n clearTimeout(timer);\r\n fired = true;\r\n listener();\r\n });\r\n}\r\nfunction serializeNode(n, options) {\r\n const { doc, mirror, blockClass, blockSelector, unblockSelector, maskAllText, maskAttributeFn, maskTextClass, unmaskTextClass, maskTextSelector, unmaskTextSelector, inlineStylesheet, maskInputOptions = {}, maskTextFn, maskInputFn, dataURLOptions = {}, inlineImages, recordCanvas, keepIframeSrcFn, newlyAddedElement = false, } = options;\r\n const rootId = getRootId(doc, mirror);\r\n switch (n.nodeType) {\r\n case n.DOCUMENT_NODE:\r\n if (n.compatMode !== 'CSS1Compat') {\r\n return {\r\n type: NodeType.Document,\r\n childNodes: [],\r\n compatMode: n.compatMode,\r\n };\r\n }\r\n else {\r\n return {\r\n type: NodeType.Document,\r\n childNodes: [],\r\n };\r\n }\r\n case n.DOCUMENT_TYPE_NODE:\r\n return {\r\n type: NodeType.DocumentType,\r\n name: n.name,\r\n publicId: n.publicId,\r\n systemId: n.systemId,\r\n rootId,\r\n };\r\n case n.ELEMENT_NODE:\r\n return serializeElementNode(n, {\r\n doc,\r\n blockClass,\r\n blockSelector,\r\n unblockSelector,\r\n inlineStylesheet,\r\n maskAttributeFn,\r\n maskInputOptions,\r\n maskInputFn,\r\n dataURLOptions,\r\n inlineImages,\r\n recordCanvas,\r\n keepIframeSrcFn,\r\n newlyAddedElement,\r\n rootId,\r\n maskAllText,\r\n maskTextClass,\r\n unmaskTextClass,\r\n maskTextSelector,\r\n unmaskTextSelector,\r\n });\r\n case n.TEXT_NODE:\r\n return serializeTextNode(n, {\r\n maskAllText,\r\n maskTextClass,\r\n unmaskTextClass,\r\n maskTextSelector,\r\n unmaskTextSelector,\r\n maskTextFn,\r\n maskInputOptions,\r\n maskInputFn,\r\n rootId,\r\n });\r\n case n.CDATA_SECTION_NODE:\r\n return {\r\n type: NodeType.CDATA,\r\n textContent: '',\r\n rootId,\r\n };\r\n case n.COMMENT_NODE:\r\n return {\r\n type: NodeType.Comment,\r\n textContent: n.textContent || '',\r\n rootId,\r\n };\r\n default:\r\n return false;\r\n }\r\n}\r\nfunction getRootId(doc, mirror) {\r\n if (!mirror.hasNode(doc))\r\n return undefined;\r\n const docId = mirror.getId(doc);\r\n return docId === 1 ? undefined : docId;\r\n}\r\nfunction serializeTextNode(n, options) {\r\n const { maskAllText, maskTextClass, unmaskTextClass, maskTextSelector, unmaskTextSelector, maskTextFn, maskInputOptions, maskInputFn, rootId, } = options;\r\n const parentTagName = n.parentNode && n.parentNode.tagName;\r\n let textContent = n.textContent;\r\n const isStyle = parentTagName === 'STYLE' ? true : undefined;\r\n const isScript = parentTagName === 'SCRIPT' ? true : undefined;\r\n const isTextarea = parentTagName === 'TEXTAREA' ? true : undefined;\r\n if (isStyle && textContent) {\r\n try {\r\n if (n.nextSibling || n.previousSibling) {\r\n }\r\n else if (n.parentNode.sheet?.cssRules) {\r\n textContent = stringifyStylesheet(n.parentNode.sheet);\r\n }\r\n }\r\n catch (err) {\r\n console.warn(`Cannot get CSS styles from text's parentNode. Error: ${err}`, n);\r\n }\r\n textContent = absoluteToStylesheet(textContent, getHref());\r\n }\r\n if (isScript) {\r\n textContent = 'SCRIPT_PLACEHOLDER';\r\n }\r\n const forceMask = needMaskingText(n, maskTextClass, maskTextSelector, unmaskTextClass, unmaskTextSelector, maskAllText);\r\n if (!isStyle && !isScript && !isTextarea && textContent && forceMask) {\r\n textContent = maskTextFn\r\n ? maskTextFn(textContent, n.parentElement)\r\n : textContent.replace(/[\\S]/g, '*');\r\n }\r\n if (isTextarea && textContent && (maskInputOptions.textarea || forceMask)) {\r\n textContent = maskInputFn\r\n ? maskInputFn(textContent, n.parentNode)\r\n : textContent.replace(/[\\S]/g, '*');\r\n }\r\n if (parentTagName === 'OPTION' && textContent) {\r\n const isInputMasked = shouldMaskInput({\r\n type: null,\r\n tagName: parentTagName,\r\n maskInputOptions,\r\n });\r\n textContent = maskInputValue({\r\n isMasked: needMaskingText(n, maskTextClass, maskTextSelector, unmaskTextClass, unmaskTextSelector, isInputMasked),\r\n element: n,\r\n value: textContent,\r\n maskInputFn,\r\n });\r\n }\r\n return {\r\n type: NodeType.Text,\r\n textContent: textContent || '',\r\n isStyle,\r\n rootId,\r\n };\r\n}\r\nfunction serializeElementNode(n, options) {\r\n const { doc, blockClass, blockSelector, unblockSelector, inlineStylesheet, maskInputOptions = {}, maskAttributeFn, maskInputFn, dataURLOptions = {}, inlineImages, recordCanvas, keepIframeSrcFn, newlyAddedElement = false, rootId, maskAllText, maskTextClass, unmaskTextClass, maskTextSelector, unmaskTextSelector, } = options;\r\n const needBlock = _isBlockedElement(n, blockClass, blockSelector, unblockSelector);\r\n const tagName = getValidTagName(n);\r\n let attributes = {};\r\n const len = n.attributes.length;\r\n for (let i = 0; i < len; i++) {\r\n const attr = n.attributes[i];\r\n if (attr.name && !ignoreAttribute(tagName, attr.name, attr.value)) {\r\n attributes[attr.name] = transformAttribute(doc, tagName, toLowerCase(attr.name), attr.value, n, maskAttributeFn);\r\n }\r\n }\r\n if (tagName === 'link' && inlineStylesheet) {\r\n const stylesheet = Array.from(doc.styleSheets).find((s) => {\r\n return s.href === n.href;\r\n });\r\n let cssText = null;\r\n if (stylesheet) {\r\n cssText = stringifyStylesheet(stylesheet);\r\n }\r\n if (cssText) {\r\n delete attributes.rel;\r\n delete attributes.href;\r\n attributes._cssText = absoluteToStylesheet(cssText, stylesheet.href);\r\n }\r\n }\r\n if (tagName === 'style' &&\r\n n.sheet &&\r\n !(n.innerText || n.textContent || '').trim().length) {\r\n const cssText = stringifyStylesheet(n.sheet);\r\n if (cssText) {\r\n attributes._cssText = absoluteToStylesheet(cssText, getHref());\r\n }\r\n }\r\n if (tagName === 'input' ||\r\n tagName === 'textarea' ||\r\n tagName === 'select' ||\r\n tagName === 'option') {\r\n const el = n;\r\n const type = getInputType(el);\r\n const value = getInputValue(el, toUpperCase(tagName), type);\r\n const checked = el.checked;\r\n if (type !== 'submit' && type !== 'button' && value) {\r\n const forceMask = needMaskingText(el, maskTextClass, maskTextSelector, unmaskTextClass, unmaskTextSelector, shouldMaskInput({\r\n type,\r\n tagName: toUpperCase(tagName),\r\n maskInputOptions,\r\n }));\r\n attributes.value = maskInputValue({\r\n isMasked: forceMask,\r\n element: el,\r\n value,\r\n maskInputFn,\r\n });\r\n }\r\n if (checked) {\r\n attributes.checked = checked;\r\n }\r\n }\r\n if (tagName === 'option') {\r\n if (n.selected && !maskInputOptions['select']) {\r\n attributes.selected = true;\r\n }\r\n else {\r\n delete attributes.selected;\r\n }\r\n }\r\n if (tagName === 'canvas' && recordCanvas) {\r\n if (n.__context === '2d') {\r\n if (!is2DCanvasBlank(n)) {\r\n attributes.rr_dataURL = n.toDataURL(dataURLOptions.type, dataURLOptions.quality);\r\n }\r\n }\r\n else if (!('__context' in n)) {\r\n const canvasDataURL = n.toDataURL(dataURLOptions.type, dataURLOptions.quality);\r\n const blankCanvas = document.createElement('canvas');\r\n blankCanvas.width = n.width;\r\n blankCanvas.height = n.height;\r\n const blankCanvasDataURL = blankCanvas.toDataURL(dataURLOptions.type, dataURLOptions.quality);\r\n if (canvasDataURL !== blankCanvasDataURL) {\r\n attributes.rr_dataURL = canvasDataURL;\r\n }\r\n }\r\n }\r\n if (tagName === 'img' && inlineImages) {\r\n if (!canvasService) {\r\n canvasService = doc.createElement('canvas');\r\n canvasCtx = canvasService.getContext('2d');\r\n }\r\n const image = n;\r\n const oldValue = image.crossOrigin;\r\n image.crossOrigin = 'anonymous';\r\n const recordInlineImage = () => {\r\n image.removeEventListener('load', recordInlineImage);\r\n try {\r\n canvasService.width = image.naturalWidth;\r\n canvasService.height = image.naturalHeight;\r\n canvasCtx.drawImage(image, 0, 0);\r\n attributes.rr_dataURL = canvasService.toDataURL(dataURLOptions.type, dataURLOptions.quality);\r\n }\r\n catch (err) {\r\n console.warn(`Cannot inline img src=${image.currentSrc}! Error: ${err}`);\r\n }\r\n oldValue\r\n ? (attributes.crossOrigin = oldValue)\r\n : image.removeAttribute('crossorigin');\r\n };\r\n if (image.complete && image.naturalWidth !== 0)\r\n recordInlineImage();\r\n else\r\n image.addEventListener('load', recordInlineImage);\r\n }\r\n if (tagName === 'audio' || tagName === 'video') {\r\n attributes.rr_mediaState = n.paused\r\n ? 'paused'\r\n : 'played';\r\n attributes.rr_mediaCurrentTime = n.currentTime;\r\n }\r\n if (!newlyAddedElement) {\r\n if (n.scrollLeft) {\r\n attributes.rr_scrollLeft = n.scrollLeft;\r\n }\r\n if (n.scrollTop) {\r\n attributes.rr_scrollTop = n.scrollTop;\r\n }\r\n }\r\n if (needBlock) {\r\n const { width, height } = n.getBoundingClientRect();\r\n attributes = {\r\n class: attributes.class,\r\n rr_width: `${width}px`,\r\n rr_height: `${height}px`,\r\n };\r\n }\r\n if (tagName === 'iframe' && !keepIframeSrcFn(attributes.src)) {\r\n if (!n.contentDocument) {\r\n attributes.rr_src = attributes.src;\r\n }\r\n delete attributes.src;\r\n }\r\n let isCustomElement;\r\n try {\r\n if (customElements.get(tagName))\r\n isCustomElement = true;\r\n }\r\n catch (e) {\r\n }\r\n return {\r\n type: NodeType.Element,\r\n tagName,\r\n attributes,\r\n childNodes: [],\r\n isSVG: isSVGElement(n) || undefined,\r\n needBlock,\r\n rootId,\r\n isCustom: isCustomElement,\r\n };\r\n}\r\nfunction lowerIfExists(maybeAttr) {\r\n if (maybeAttr === undefined || maybeAttr === null) {\r\n return '';\r\n }\r\n else {\r\n return maybeAttr.toLowerCase();\r\n }\r\n}\r\nfunction slimDOMExcluded(sn, slimDOMOptions) {\r\n if (slimDOMOptions.comment && sn.type === NodeType.Comment) {\r\n return true;\r\n }\r\n else if (sn.type === NodeType.Element) {\r\n if (slimDOMOptions.script &&\r\n (sn.tagName === 'script' ||\r\n (sn.tagName === 'link' &&\r\n (sn.attributes.rel === 'preload' ||\r\n sn.attributes.rel === 'modulepreload') &&\r\n sn.attributes.as === 'script') ||\r\n (sn.tagName === 'link' &&\r\n sn.attributes.rel === 'prefetch' &&\r\n typeof sn.attributes.href === 'string' &&\r\n sn.attributes.href.endsWith('.js')))) {\r\n return true;\r\n }\r\n else if (slimDOMOptions.headFavicon &&\r\n ((sn.tagName === 'link' && sn.attributes.rel === 'shortcut icon') ||\r\n (sn.tagName === 'meta' &&\r\n (lowerIfExists(sn.attributes.name).match(/^msapplication-tile(image|color)$/) ||\r\n lowerIfExists(sn.attributes.name) === 'application-name' ||\r\n lowerIfExists(sn.attributes.rel) === 'icon' ||\r\n lowerIfExists(sn.attributes.rel) === 'apple-touch-icon' ||\r\n lowerIfExists(sn.attributes.rel) === 'shortcut icon')))) {\r\n return true;\r\n }\r\n else if (sn.tagName === 'meta') {\r\n if (slimDOMOptions.headMetaDescKeywords &&\r\n lowerIfExists(sn.attributes.name).match(/^description|keywords$/)) {\r\n return true;\r\n }\r\n else if (slimDOMOptions.headMetaSocial &&\r\n (lowerIfExists(sn.attributes.property).match(/^(og|twitter|fb):/) ||\r\n lowerIfExists(sn.attributes.name).match(/^(og|twitter):/) ||\r\n lowerIfExists(sn.attributes.name) === 'pinterest')) {\r\n return true;\r\n }\r\n else if (slimDOMOptions.headMetaRobots &&\r\n (lowerIfExists(sn.attributes.name) === 'robots' ||\r\n lowerIfExists(sn.attributes.name) === 'googlebot' ||\r\n lowerIfExists(sn.attributes.name) === 'bingbot')) {\r\n return true;\r\n }\r\n else if (slimDOMOptions.headMetaHttpEquiv &&\r\n sn.attributes['http-equiv'] !== undefined) {\r\n return true;\r\n }\r\n else if (slimDOMOptions.headMetaAuthorship &&\r\n (lowerIfExists(sn.attributes.name) === 'author' ||\r\n lowerIfExists(sn.attributes.name) === 'generator' ||\r\n lowerIfExists(sn.attributes.name) === 'framework' ||\r\n lowerIfExists(sn.attributes.name) === 'publisher' ||\r\n lowerIfExists(sn.attributes.name) === 'progid' ||\r\n lowerIfExists(sn.attributes.property).match(/^article:/) ||\r\n lowerIfExists(sn.attributes.property).match(/^product:/))) {\r\n return true;\r\n }\r\n else if (slimDOMOptions.headMetaVerification &&\r\n (lowerIfExists(sn.attributes.name) === 'google-site-verification' ||\r\n lowerIfExists(sn.attributes.name) === 'yandex-verification' ||\r\n lowerIfExists(sn.attributes.name) === 'csrf-token' ||\r\n lowerIfExists(sn.attributes.name) === 'p:domain_verify' ||\r\n lowerIfExists(sn.attributes.name) === 'verify-v1' ||\r\n lowerIfExists(sn.attributes.name) === 'verification' ||\r\n lowerIfExists(sn.attributes.name) === 'shopify-checkout-api-token')) {\r\n return true;\r\n }\r\n }\r\n }\r\n return false;\r\n}\r\nfunction serializeNodeWithId(n, options) {\r\n const { doc, mirror, blockClass, blockSelector, unblockSelector, maskAllText, maskTextClass, unmaskTextClass, maskTextSelector, unmaskTextSelector, skipChild = false, inlineStylesheet = true, maskInputOptions = {}, maskAttributeFn, maskTextFn, maskInputFn, slimDOMOptions, dataURLOptions = {}, inlineImages = false, recordCanvas = false, onSerialize, onIframeLoad, iframeLoadTimeout = 5000, onStylesheetLoad, stylesheetLoadTimeout = 5000, keepIframeSrcFn = () => false, newlyAddedElement = false, } = options;\r\n let { preserveWhiteSpace = true } = options;\r\n const _serializedNode = serializeNode(n, {\r\n doc,\r\n mirror,\r\n blockClass,\r\n blockSelector,\r\n maskAllText,\r\n unblockSelector,\r\n maskTextClass,\r\n unmaskTextClass,\r\n maskTextSelector,\r\n unmaskTextSelector,\r\n inlineStylesheet,\r\n maskInputOptions,\r\n maskAttributeFn,\r\n maskTextFn,\r\n maskInputFn,\r\n dataURLOptions,\r\n inlineImages,\r\n recordCanvas,\r\n keepIframeSrcFn,\r\n newlyAddedElement,\r\n });\r\n if (!_serializedNode) {\r\n console.warn(n, 'not serialized');\r\n return null;\r\n }\r\n let id;\r\n if (mirror.hasNode(n)) {\r\n id = mirror.getId(n);\r\n }\r\n else if (slimDOMExcluded(_serializedNode, slimDOMOptions) ||\r\n (!preserveWhiteSpace &&\r\n _serializedNode.type === NodeType.Text &&\r\n !_serializedNode.isStyle &&\r\n !_serializedNode.textContent.replace(/^\\s+|\\s+$/gm, '').length)) {\r\n id = IGNORED_NODE;\r\n }\r\n else {\r\n id = genId();\r\n }\r\n const serializedNode = Object.assign(_serializedNode, { id });\r\n mirror.add(n, serializedNode);\r\n if (id === IGNORED_NODE) {\r\n return null;\r\n }\r\n if (onSerialize) {\r\n onSerialize(n);\r\n }\r\n let recordChild = !skipChild;\r\n if (serializedNode.type === NodeType.Element) {\r\n recordChild = recordChild && !serializedNode.needBlock;\r\n delete serializedNode.needBlock;\r\n const shadowRoot = n.shadowRoot;\r\n if (shadowRoot && isNativeShadowDom(shadowRoot))\r\n serializedNode.isShadowHost = true;\r\n }\r\n if ((serializedNode.type === NodeType.Document ||\r\n serializedNode.type === NodeType.Element) &&\r\n recordChild) {\r\n if (slimDOMOptions.headWhitespace &&\r\n serializedNode.type === NodeType.Element &&\r\n serializedNode.tagName === 'head') {\r\n preserveWhiteSpace = false;\r\n }\r\n const bypassOptions = {\r\n doc,\r\n mirror,\r\n blockClass,\r\n blockSelector,\r\n maskAllText,\r\n unblockSelector,\r\n maskTextClass,\r\n unmaskTextClass,\r\n maskTextSelector,\r\n unmaskTextSelector,\r\n skipChild,\r\n inlineStylesheet,\r\n maskInputOptions,\r\n maskAttributeFn,\r\n maskTextFn,\r\n maskInputFn,\r\n slimDOMOptions,\r\n dataURLOptions,\r\n inlineImages,\r\n recordCanvas,\r\n preserveWhiteSpace,\r\n onSerialize,\r\n onIframeLoad,\r\n iframeLoadTimeout,\r\n onStylesheetLoad,\r\n stylesheetLoadTimeout,\r\n keepIframeSrcFn,\r\n };\r\n for (const childN of Array.from(n.childNodes)) {\r\n const serializedChildNode = serializeNodeWithId(childN, bypassOptions);\r\n if (serializedChildNode) {\r\n serializedNode.childNodes.push(serializedChildNode);\r\n }\r\n }\r\n if (isElement(n) && n.shadowRoot) {\r\n for (const childN of Array.from(n.shadowRoot.childNodes)) {\r\n const serializedChildNode = serializeNodeWithId(childN, bypassOptions);\r\n if (serializedChildNode) {\r\n isNativeShadowDom(n.shadowRoot) &&\r\n (serializedChildNode.isShadow = true);\r\n serializedNode.childNodes.push(serializedChildNode);\r\n }\r\n }\r\n }\r\n }\r\n if (n.parentNode &&\r\n isShadowRoot(n.parentNode) &&\r\n isNativeShadowDom(n.parentNode)) {\r\n serializedNode.isShadow = true;\r\n }\r\n if (serializedNode.type === NodeType.Element &&\r\n serializedNode.tagName === 'iframe') {\r\n onceIframeLoaded(n, () => {\r\n const iframeDoc = n.contentDocument;\r\n if (iframeDoc && onIframeLoad) {\r\n const serializedIframeNode = serializeNodeWithId(iframeDoc, {\r\n doc: iframeDoc,\r\n mirror,\r\n blockClass,\r\n blockSelector,\r\n unblockSelector,\r\n maskAllText,\r\n maskTextClass,\r\n unmaskTextClass,\r\n maskTextSelector,\r\n unmaskTextSelector,\r\n skipChild: false,\r\n inlineStylesheet,\r\n maskInputOptions,\r\n maskAttributeFn,\r\n maskTextFn,\r\n maskInputFn,\r\n slimDOMOptions,\r\n dataURLOptions,\r\n inlineImages,\r\n recordCanvas,\r\n preserveWhiteSpace,\r\n onSerialize,\r\n onIframeLoad,\r\n iframeLoadTimeout,\r\n onStylesheetLoad,\r\n stylesheetLoadTimeout,\r\n keepIframeSrcFn,\r\n });\r\n if (serializedIframeNode) {\r\n onIframeLoad(n, serializedIframeNode);\r\n }\r\n }\r\n }, iframeLoadTimeout);\r\n }\r\n if (serializedNode.type === NodeType.Element &&\r\n serializedNode.tagName === 'link' &&\r\n serializedNode.attributes.rel === 'stylesheet') {\r\n onceStylesheetLoaded(n, () => {\r\n if (onStylesheetLoad) {\r\n const serializedLinkNode = serializeNodeWithId(n, {\r\n doc,\r\n mirror,\r\n blockClass,\r\n blockSelector,\r\n unblockSelector,\r\n maskAllText,\r\n maskTextClass,\r\n unmaskTextClass,\r\n maskTextSelector,\r\n unmaskTextSelector,\r\n skipChild: false,\r\n inlineStylesheet,\r\n maskInputOptions,\r\n maskAttributeFn,\r\n maskTextFn,\r\n maskInputFn,\r\n slimDOMOptions,\r\n dataURLOptions,\r\n inlineImages,\r\n recordCanvas,\r\n preserveWhiteSpace,\r\n onSerialize,\r\n onIframeLoad,\r\n iframeLoadTimeout,\r\n onStylesheetLoad,\r\n stylesheetLoadTimeout,\r\n keepIframeSrcFn,\r\n });\r\n if (serializedLinkNode) {\r\n onStylesheetLoad(n, serializedLinkNode);\r\n }\r\n }\r\n }, stylesheetLoadTimeout);\r\n }\r\n return serializedNode;\r\n}\r\nfunction snapshot(n, options) {\r\n const { mirror = new Mirror(), blockClass = 'rr-block', blockSelector = null, unblockSelector = null, maskAllText = false, maskTextClass = 'rr-mask', unmaskTextClass = null, maskTextSelector = null, unmaskTextSelector = null, inlineStylesheet = true, inlineImages = false, recordCanvas = false, maskAllInputs = false, maskAttributeFn, maskTextFn, maskInputFn, slimDOM = false, dataURLOptions, preserveWhiteSpace, onSerialize, onIframeLoad, iframeLoadTimeout, onStylesheetLoad, stylesheetLoadTimeout, keepIframeSrcFn = () => false, } = options || {};\r\n const maskInputOptions = maskAllInputs === true\r\n ? {\r\n color: true,\r\n date: true,\r\n 'datetime-local': true,\r\n email: true,\r\n month: true,\r\n number: true,\r\n range: true,\r\n search: true,\r\n tel: true,\r\n text: true,\r\n time: true,\r\n url: true,\r\n week: true,\r\n textarea: true,\r\n select: true,\r\n }\r\n : maskAllInputs === false\r\n ? {}\r\n : maskAllInputs;\r\n const slimDOMOptions = slimDOM === true || slimDOM === 'all'\r\n ?\r\n {\r\n script: true,\r\n comment: true,\r\n headFavicon: true,\r\n headWhitespace: true,\r\n headMetaDescKeywords: slimDOM === 'all',\r\n headMetaSocial: true,\r\n headMetaRobots: true,\r\n headMetaHttpEquiv: true,\r\n headMetaAuthorship: true,\r\n headMetaVerification: true,\r\n }\r\n : slimDOM === false\r\n ? {}\r\n : slimDOM;\r\n return serializeNodeWithId(n, {\r\n doc: n,\r\n mirror,\r\n blockClass,\r\n blockSelector,\r\n unblockSelector,\r\n maskAllText,\r\n maskTextClass,\r\n unmaskTextClass,\r\n maskTextSelector,\r\n unmaskTextSelector,\r\n skipChild: false,\r\n inlineStylesheet,\r\n maskInputOptions,\r\n maskAttributeFn,\r\n maskTextFn,\r\n maskInputFn,\r\n slimDOMOptions,\r\n dataURLOptions,\r\n inlineImages,\r\n recordCanvas,\r\n preserveWhiteSpace,\r\n onSerialize,\r\n onIframeLoad,\r\n iframeLoadTimeout,\r\n onStylesheetLoad,\r\n stylesheetLoadTimeout,\r\n keepIframeSrcFn,\r\n newlyAddedElement: false,\r\n });\r\n}\r\n\nconst commentre = /\\/\\*[^*]*\\*+([^/*][^*]*\\*+)*\\//g;\r\nfunction parse(css, options = {}) {\r\n let lineno = 1;\r\n let column = 1;\r\n function updatePosition(str) {\r\n const lines = str.match(/\\n/g);\r\n if (lines) {\r\n lineno += lines.length;\r\n }\r\n const i = str.lastIndexOf('\\n');\r\n column = i === -1 ? column + str.length : str.length - i;\r\n }\r\n function position() {\r\n const start = { line: lineno, column };\r\n return (node) => {\r\n node.position = new Position(start);\r\n whitespace();\r\n return node;\r\n };\r\n }\r\n class Position {\r\n constructor(start) {\r\n this.start = start;\r\n this.end = { line: lineno, column };\r\n this.source = options.source;\r\n }\r\n }\r\n Position.prototype.content = css;\r\n const errorsList = [];\r\n function error(msg) {\r\n const err = new Error(`${options.source || ''}:${lineno}:${column}: ${msg}`);\r\n err.reason = msg;\r\n err.filename = options.source;\r\n err.line = lineno;\r\n err.column = column;\r\n err.source = css;\r\n if (options.silent) {\r\n errorsList.push(err);\r\n }\r\n else {\r\n throw err;\r\n }\r\n }\r\n function stylesheet() {\r\n const rulesList = rules();\r\n return {\r\n type: 'stylesheet',\r\n stylesheet: {\r\n source: options.source,\r\n rules: rulesList,\r\n parsingErrors: errorsList,\r\n },\r\n };\r\n }\r\n function open() {\r\n return match(/^{\\s*/);\r\n }\r\n function close() {\r\n return match(/^}/);\r\n }\r\n function rules() {\r\n let node;\r\n const rules = [];\r\n whitespace();\r\n comments(rules);\r\n while (css.length && css.charAt(0) !== '}' && (node = atrule() || rule())) {\r\n if (node) {\r\n rules.push(node);\r\n comments(rules);\r\n }\r\n }\r\n return rules;\r\n }\r\n function match(re) {\r\n const m = re.exec(css);\r\n if (!m) {\r\n return;\r\n }\r\n const str = m[0];\r\n updatePosition(str);\r\n css = css.slice(str.length);\r\n return m;\r\n }\r\n function whitespace() {\r\n match(/^\\s*/);\r\n }\r\n function comments(rules = []) {\r\n let c;\r\n while ((c = comment())) {\r\n if (c) {\r\n rules.push(c);\r\n }\r\n c = comment();\r\n }\r\n return rules;\r\n }\r\n function comment() {\r\n const pos = position();\r\n if ('/' !== css.charAt(0) || '*' !== css.charAt(1)) {\r\n return;\r\n }\r\n let i = 2;\r\n while ('' !== css.charAt(i) &&\r\n ('*' !== css.charAt(i) || '/' !== css.charAt(i + 1))) {\r\n ++i;\r\n }\r\n i += 2;\r\n if ('' === css.charAt(i - 1)) {\r\n return error('End of comment missing');\r\n }\r\n const str = css.slice(2, i - 2);\r\n column += 2;\r\n updatePosition(str);\r\n css = css.slice(i);\r\n column += 2;\r\n return pos({\r\n type: 'comment',\r\n comment: str,\r\n });\r\n }\r\n function selector() {\r\n whitespace();\r\n while (css[0] == '}') {\r\n error('extra closing bracket');\r\n css = css.slice(1);\r\n whitespace();\r\n }\r\n const m = match(/^((\"(?:\\\\\"|[^\"])*\"|'(?:\\\\'|[^'])*'|[^{])+)/);\r\n if (!m) {\r\n return;\r\n }\r\n const cleanedInput = m[0]\r\n .trim()\r\n .replace(/\\/\\*([^*]|[\\r\\n]|(\\*+([^*/]|[\\r\\n])))*\\*\\/+/g, '')\r\n .replace(/\"(?:\\\\\"|[^\"])*\"|'(?:\\\\'|[^'])*'/g, (m) => {\r\n return m.replace(/,/g, '\\u200C');\r\n });\r\n return customSplit(cleanedInput).map((s) => s.replace(/\\u200C/g, ',').trim());\r\n }\r\n function customSplit(input) {\r\n const result = [];\r\n let currentSegment = '';\r\n let depthParentheses = 0;\r\n let depthBrackets = 0;\r\n let currentStringChar = null;\r\n for (const char of input) {\r\n const hasStringEscape = currentSegment.endsWith('\\\\');\r\n if (currentStringChar) {\r\n if (currentStringChar === char && !hasStringEscape) {\r\n currentStringChar = null;\r\n }\r\n }\r\n else if (char === '(') {\r\n depthParentheses++;\r\n }\r\n else if (char === ')') {\r\n depthParentheses--;\r\n }\r\n else if (char === '[') {\r\n depthBrackets++;\r\n }\r\n else if (char === ']') {\r\n depthBrackets--;\r\n }\r\n else if ('\\'\"'.includes(char)) {\r\n currentStringChar = char;\r\n }\r\n if (char === ',' && depthParentheses === 0 && depthBrackets === 0) {\r\n result.push(currentSegment);\r\n currentSegment = '';\r\n }\r\n else {\r\n currentSegment += char;\r\n }\r\n }\r\n if (currentSegment) {\r\n result.push(currentSegment);\r\n }\r\n return result;\r\n }\r\n function declaration() {\r\n const pos = position();\r\n const propMatch = match(/^(\\*?[-#\\/\\*\\\\\\w]+(\\[[0-9a-z_-]+\\])?)\\s*/);\r\n if (!propMatch) {\r\n return;\r\n }\r\n const prop = trim(propMatch[0]);\r\n if (!match(/^:\\s*/)) {\r\n return error(`property missing ':'`);\r\n }\r\n const val = match(/^((?:'(?:\\\\'|.)*?'|\"(?:\\\\\"|.)*?\"|\\([^\\)]*?\\)|[^};])+)/);\r\n const ret = pos({\r\n type: 'declaration',\r\n property: prop.replace(commentre, ''),\r\n value: val ? trim(val[0]).replace(commentre, '') : '',\r\n });\r\n match(/^[;\\s]*/);\r\n return ret;\r\n }\r\n function declarations() {\r\n const decls = [];\r\n if (!open()) {\r\n return error(`missing '{'`);\r\n }\r\n comments(decls);\r\n let decl;\r\n while ((decl = declaration())) {\r\n if (decl !== false) {\r\n decls.push(decl);\r\n comments(decls);\r\n }\r\n decl = declaration();\r\n }\r\n if (!close()) {\r\n return error(`missing '}'`);\r\n }\r\n return decls;\r\n }\r\n function keyframe() {\r\n let m;\r\n const vals = [];\r\n const pos = position();\r\n while ((m = match(/^((\\d+\\.\\d+|\\.\\d+|\\d+)%?|[a-z]+)\\s*/))) {\r\n vals.push(m[1]);\r\n match(/^,\\s*/);\r\n }\r\n if (!vals.length) {\r\n return;\r\n }\r\n return pos({\r\n type: 'keyframe',\r\n values: vals,\r\n declarations: declarations(),\r\n });\r\n }\r\n function atkeyframes() {\r\n const pos = position();\r\n let m = match(/^@([-\\w]+)?keyframes\\s*/);\r\n if (!m) {\r\n return;\r\n }\r\n const vendor = m[1];\r\n m = match(/^([-\\w]+)\\s*/);\r\n if (!m) {\r\n return error('@keyframes missing name');\r\n }\r\n const name = m[1];\r\n if (!open()) {\r\n return error(`@keyframes missing '{'`);\r\n }\r\n let frame;\r\n let frames = comments();\r\n while ((frame = keyframe())) {\r\n frames.push(frame);\r\n frames = frames.concat(comments());\r\n }\r\n if (!close()) {\r\n return error(`@keyframes missing '}'`);\r\n }\r\n return pos({\r\n type: 'keyframes',\r\n name,\r\n vendor,\r\n keyframes: frames,\r\n });\r\n }\r\n function atsupports() {\r\n const pos = position();\r\n const m = match(/^@supports *([^{]+)/);\r\n if (!m) {\r\n return;\r\n }\r\n const supports = trim(m[1]);\r\n if (!open()) {\r\n return error(`@supports missing '{'`);\r\n }\r\n const style = comments().concat(rules());\r\n if (!close()) {\r\n return error(`@supports missing '}'`);\r\n }\r\n return pos({\r\n type: 'supports',\r\n supports,\r\n rules: style,\r\n });\r\n }\r\n function athost() {\r\n const pos = position();\r\n const m = match(/^@host\\s*/);\r\n if (!m) {\r\n return;\r\n }\r\n if (!open()) {\r\n return error(`@host missing '{'`);\r\n }\r\n const style = comments().concat(rules());\r\n if (!close()) {\r\n return error(`@host missing '}'`);\r\n }\r\n return pos({\r\n type: 'host',\r\n rules: style,\r\n });\r\n }\r\n function atmedia() {\r\n const pos = position();\r\n const m = match(/^@media *([^{]+)/);\r\n if (!m) {\r\n return;\r\n }\r\n const media = trim(m[1]);\r\n if (!open()) {\r\n return error(`@media missing '{'`);\r\n }\r\n const style = comments().concat(rules());\r\n if (!close()) {\r\n return error(`@media missing '}'`);\r\n }\r\n return pos({\r\n type: 'media',\r\n media,\r\n rules: style,\r\n });\r\n }\r\n function atcustommedia() {\r\n const pos = position();\r\n const m = match(/^@custom-media\\s+(--[^\\s]+)\\s*([^{;]+);/);\r\n if (!m) {\r\n return;\r\n }\r\n return pos({\r\n type: 'custom-media',\r\n name: trim(m[1]),\r\n media: trim(m[2]),\r\n });\r\n }\r\n function atpage() {\r\n const pos = position();\r\n const m = match(/^@page */);\r\n if (!m) {\r\n return;\r\n }\r\n const sel = selector() || [];\r\n if (!open()) {\r\n return error(`@page missing '{'`);\r\n }\r\n let decls = comments();\r\n let decl;\r\n while ((decl = declaration())) {\r\n decls.push(decl);\r\n decls = decls.concat(comments());\r\n }\r\n if (!close()) {\r\n return error(`@page missing '}'`);\r\n }\r\n return pos({\r\n type: 'page',\r\n selectors: sel,\r\n declarations: decls,\r\n });\r\n }\r\n function atdocument() {\r\n const pos = position();\r\n const m = match(/^@([-\\w]+)?document *([^{]+)/);\r\n if (!m) {\r\n return;\r\n }\r\n const vendor = trim(m[1]);\r\n const doc = trim(m[2]);\r\n if (!open()) {\r\n return error(`@document missing '{'`);\r\n }\r\n const style = comments().concat(rules());\r\n if (!close()) {\r\n return error(`@document missing '}'`);\r\n }\r\n return pos({\r\n type: 'document',\r\n document: doc,\r\n vendor,\r\n rules: style,\r\n });\r\n }\r\n function atfontface() {\r\n const pos = position();\r\n const m = match(/^@font-face\\s*/);\r\n if (!m) {\r\n return;\r\n }\r\n if (!open()) {\r\n return error(`@font-face missing '{'`);\r\n }\r\n let decls = comments();\r\n let decl;\r\n while ((decl = declaration())) {\r\n decls.push(decl);\r\n decls = decls.concat(comments());\r\n }\r\n if (!close()) {\r\n return error(`@font-face missing '}'`);\r\n }\r\n return pos({\r\n type: 'font-face',\r\n declarations: decls,\r\n });\r\n }\r\n const atimport = _compileAtrule('import');\r\n const atcharset = _compileAtrule('charset');\r\n const atnamespace = _compileAtrule('namespace');\r\n function _compileAtrule(name) {\r\n const re = new RegExp('^@' + name + '\\\\s*([^;]+);');\r\n return () => {\r\n const pos = position();\r\n const m = match(re);\r\n if (!m) {\r\n return;\r\n }\r\n const ret = { type: name };\r\n ret[name] = m[1].trim();\r\n return pos(ret);\r\n };\r\n }\r\n function atrule() {\r\n if (css[0] !== '@') {\r\n return;\r\n }\r\n return (atkeyframes() ||\r\n atmedia() ||\r\n atcustommedia() ||\r\n atsupports() ||\r\n atimport() ||\r\n atcharset() ||\r\n atnamespace() ||\r\n atdocument() ||\r\n atpage() ||\r\n athost() ||\r\n atfontface());\r\n }\r\n function rule() {\r\n const pos = position();\r\n const sel = selector();\r\n if (!sel) {\r\n return error('selector missing');\r\n }\r\n comments();\r\n return pos({\r\n type: 'rule',\r\n selectors: sel,\r\n declarations: declarations(),\r\n });\r\n }\r\n return addParent(stylesheet());\r\n}\r\nfunction trim(str) {\r\n return str ? str.replace(/^\\s+|\\s+$/g, '') : '';\r\n}\r\nfunction addParent(obj, parent) {\r\n const isNode = obj && typeof obj.type === 'string';\r\n const childParent = isNode ? obj : parent;\r\n for (const k of Object.keys(obj)) {\r\n const value = obj[k];\r\n if (Array.isArray(value)) {\r\n value.forEach((v) => {\r\n addParent(v, childParent);\r\n });\r\n }\r\n else if (value && typeof value === 'object') {\r\n addParent(value, childParent);\r\n }\r\n }\r\n if (isNode) {\r\n Object.defineProperty(obj, 'parent', {\r\n configurable: true,\r\n writable: true,\r\n enumerable: false,\r\n value: parent || null,\r\n });\r\n }\r\n return obj;\r\n}\n\nconst tagMap = {\r\n script: 'noscript',\r\n altglyph: 'altGlyph',\r\n altglyphdef: 'altGlyphDef',\r\n altglyphitem: 'altGlyphItem',\r\n animatecolor: 'animateColor',\r\n animatemotion: 'animateMotion',\r\n animatetransform: 'animateTransform',\r\n clippath: 'clipPath',\r\n feblend: 'feBlend',\r\n fecolormatrix: 'feColorMatrix',\r\n fecomponenttransfer: 'feComponentTransfer',\r\n fecomposite: 'feComposite',\r\n feconvolvematrix: 'feConvolveMatrix',\r\n fediffuselighting: 'feDiffuseLighting',\r\n fedisplacementmap: 'feDisplacementMap',\r\n fedistantlight: 'feDistantLight',\r\n fedropshadow: 'feDropShadow',\r\n feflood: 'feFlood',\r\n fefunca: 'feFuncA',\r\n fefuncb: 'feFuncB',\r\n fefuncg: 'feFuncG',\r\n fefuncr: 'feFuncR',\r\n fegaussianblur: 'feGaussianBlur',\r\n feimage: 'feImage',\r\n femerge: 'feMerge',\r\n femergenode: 'feMergeNode',\r\n femorphology: 'feMorphology',\r\n feoffset: 'feOffset',\r\n fepointlight: 'fePointLight',\r\n fespecularlighting: 'feSpecularLighting',\r\n fespotlight: 'feSpotLight',\r\n fetile: 'feTile',\r\n feturbulence: 'feTurbulence',\r\n foreignobject: 'foreignObject',\r\n glyphref: 'glyphRef',\r\n lineargradient: 'linearGradient',\r\n radialgradient: 'radialGradient',\r\n};\r\nfunction getTagName(n) {\r\n let tagName = tagMap[n.tagName] ? tagMap[n.tagName] : n.tagName;\r\n if (tagName === 'link' && n.attributes._cssText) {\r\n tagName = 'style';\r\n }\r\n return tagName;\r\n}\r\nfunction escapeRegExp(str) {\r\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\r\n}\r\nconst HOVER_SELECTOR = /([^\\\\]):hover/;\r\nconst HOVER_SELECTOR_GLOBAL = new RegExp(HOVER_SELECTOR.source, 'g');\r\nfunction addHoverClass(cssText, cache) {\r\n const cachedStyle = cache?.stylesWithHoverClass.get(cssText);\r\n if (cachedStyle)\r\n return cachedStyle;\r\n if (cssText.length >= 1000000) {\r\n return cssText;\r\n }\r\n const ast = parse(cssText, {\r\n silent: true,\r\n });\r\n if (!ast.stylesheet) {\r\n return cssText;\r\n }\r\n const selectors = [];\r\n ast.stylesheet.rules.forEach((rule) => {\r\n if ('selectors' in rule) {\r\n (rule.selectors || []).forEach((selector) => {\r\n if (HOVER_SELECTOR.test(selector)) {\r\n selectors.push(selector);\r\n }\r\n });\r\n }\r\n });\r\n if (selectors.length === 0) {\r\n return cssText;\r\n }\r\n const selectorMatcher = new RegExp(selectors\r\n .filter((selector, index) => selectors.indexOf(selector) === index)\r\n .sort((a, b) => b.length - a.length)\r\n .map((selector) => {\r\n return escapeRegExp(selector);\r\n })\r\n .join('|'), 'g');\r\n const result = cssText.replace(selectorMatcher, (selector) => {\r\n const newSelector = selector.replace(HOVER_SELECTOR_GLOBAL, '$1.\\\\:hover');\r\n return `${selector}, ${newSelector}`;\r\n });\r\n cache?.stylesWithHoverClass.set(cssText, result);\r\n return result;\r\n}\r\nfunction createCache() {\r\n const stylesWithHoverClass = new Map();\r\n return {\r\n stylesWithHoverClass,\r\n };\r\n}\r\nfunction buildNode(n, options) {\r\n const { doc, hackCss, cache } = options;\r\n switch (n.type) {\r\n case NodeType.Document:\r\n return doc.implementation.createDocument(null, '', null);\r\n case NodeType.DocumentType:\r\n return doc.implementation.createDocumentType(n.name || 'html', n.publicId, n.systemId);\r\n case NodeType.Element: {\r\n const tagName = getTagName(n);\r\n let node;\r\n if (n.isSVG) {\r\n node = doc.createElementNS('http://www.w3.org/2000/svg', tagName);\r\n }\r\n else {\r\n if (n.isCustom &&\r\n doc.defaultView?.customElements &&\r\n !doc.defaultView.customElements.get(n.tagName))\r\n doc.defaultView.customElements.define(n.tagName, class extends doc.defaultView.HTMLElement {\r\n });\r\n node = doc.createElement(tagName);\r\n }\r\n const specialAttributes = {};\r\n for (const name in n.attributes) {\r\n if (!Object.prototype.hasOwnProperty.call(n.attributes, name)) {\r\n continue;\r\n }\r\n let value = n.attributes[name];\r\n if (tagName === 'option' &&\r\n name === 'selected' &&\r\n value === false) {\r\n continue;\r\n }\r\n if (value === null) {\r\n continue;\r\n }\r\n if (value === true)\r\n value = '';\r\n if (name.startsWith('rr_')) {\r\n specialAttributes[name] = value;\r\n continue;\r\n }\r\n const isTextarea = tagName === 'textarea' && name === 'value';\r\n const isRemoteOrDynamicCss = tagName === 'style' && name === '_cssText';\r\n if (isRemoteOrDynamicCss && hackCss && typeof value === 'string') {\r\n value = addHoverClass(value, cache);\r\n }\r\n if ((isTextarea || isRemoteOrDynamicCss) && typeof value === 'string') {\r\n const child = doc.createTextNode(value);\r\n for (const c of Array.from(node.childNodes)) {\r\n if (c.nodeType === node.TEXT_NODE) {\r\n node.removeChild(c);\r\n }\r\n }\r\n node.appendChild(child);\r\n continue;\r\n }\r\n try {\r\n if (n.isSVG && name === 'xlink:href') {\r\n node.setAttributeNS('http://www.w3.org/1999/xlink', name, value.toString());\r\n }\r\n else if (name === 'onload' ||\r\n name === 'onclick' ||\r\n name.substring(0, 7) === 'onmouse') {\r\n node.setAttribute('_' + name, value.toString());\r\n }\r\n else if (tagName === 'meta' &&\r\n n.attributes['http-equiv'] === 'Content-Security-Policy' &&\r\n name === 'content') {\r\n node.setAttribute('csp-content', value.toString());\r\n continue;\r\n }\r\n else if (tagName === 'link' &&\r\n (n.attributes.rel === 'preload' ||\r\n n.attributes.rel === 'modulepreload') &&\r\n n.attributes.as === 'script') {\r\n }\r\n else if (tagName === 'link' &&\r\n n.attributes.rel === 'prefetch' &&\r\n typeof n.attributes.href === 'string' &&\r\n n.attributes.href.endsWith('.js')) {\r\n }\r\n else if (tagName === 'img' &&\r\n n.attributes.srcset &&\r\n n.attributes.rr_dataURL) {\r\n node.setAttribute('rrweb-original-srcset', n.attributes.srcset);\r\n }\r\n else {\r\n node.setAttribute(name, value.toString());\r\n }\r\n }\r\n catch (error) {\r\n }\r\n }\r\n for (const name in specialAttributes) {\r\n const value = specialAttributes[name];\r\n if (tagName === 'canvas' && name === 'rr_dataURL') {\r\n const image = document.createElement('img');\r\n image.onload = () => {\r\n const ctx = node.getContext('2d');\r\n if (ctx) {\r\n ctx.drawImage(image, 0, 0, image.width, image.height);\r\n }\r\n };\r\n image.src = value.toString();\r\n if (node.RRNodeType)\r\n node.rr_dataURL = value.toString();\r\n }\r\n else if (tagName === 'img' && name === 'rr_dataURL') {\r\n const image = node;\r\n if (!image.currentSrc.startsWith('data:')) {\r\n image.setAttribute('rrweb-original-src', n.attributes.src);\r\n image.src = value.toString();\r\n }\r\n }\r\n if (name === 'rr_width') {\r\n node.style.setProperty('width', value.toString());\r\n }\r\n else if (name === 'rr_height') {\r\n node.style.setProperty('height', value.toString());\r\n }\r\n else if (name === 'rr_mediaCurrentTime' &&\r\n typeof value === 'number') {\r\n node.currentTime = value;\r\n }\r\n else if (name === 'rr_mediaState') {\r\n switch (value) {\r\n case 'played':\r\n node\r\n .play()\r\n .catch((e) => console.warn('media playback error', e));\r\n break;\r\n case 'paused':\r\n node.pause();\r\n break;\r\n }\r\n }\r\n }\r\n if (n.isShadowHost) {\r\n if (!node.shadowRoot) {\r\n node.attachShadow({ mode: 'open' });\r\n }\r\n else {\r\n while (node.shadowRoot.firstChild) {\r\n node.shadowRoot.removeChild(node.shadowRoot.firstChild);\r\n }\r\n }\r\n }\r\n return node;\r\n }\r\n case NodeType.Text:\r\n return doc.createTextNode(n.isStyle && hackCss\r\n ? addHoverClass(n.textContent, cache)\r\n : n.textContent);\r\n case NodeType.CDATA:\r\n return doc.createCDATASection(n.textContent);\r\n case NodeType.Comment:\r\n return doc.createComment(n.textContent);\r\n default:\r\n return null;\r\n }\r\n}\r\nfunction buildNodeWithSN(n, options) {\r\n const { doc, mirror, skipChild = false, hackCss = true, afterAppend, cache, } = options;\r\n if (mirror.has(n.id)) {\r\n const nodeInMirror = mirror.getNode(n.id);\r\n const meta = mirror.getMeta(nodeInMirror);\r\n if (isNodeMetaEqual(meta, n))\r\n return mirror.getNode(n.id);\r\n }\r\n let node = buildNode(n, { doc, hackCss, cache });\r\n if (!node) {\r\n return null;\r\n }\r\n if (n.rootId && mirror.getNode(n.rootId) !== doc) {\r\n mirror.replace(n.rootId, doc);\r\n }\r\n if (n.type === NodeType.Document) {\r\n doc.close();\r\n doc.open();\r\n if (n.compatMode === 'BackCompat' &&\r\n n.childNodes &&\r\n n.childNodes[0].type !== NodeType.DocumentType) {\r\n if (n.childNodes[0].type === NodeType.Element &&\r\n 'xmlns' in n.childNodes[0].attributes &&\r\n n.childNodes[0].attributes.xmlns === 'http://www.w3.org/1999/xhtml') {\r\n doc.write('');\r\n }\r\n else {\r\n doc.write('');\r\n }\r\n }\r\n node = doc;\r\n }\r\n mirror.add(node, n);\r\n if ((n.type === NodeType.Document || n.type === NodeType.Element) &&\r\n !skipChild) {\r\n for (const childN of n.childNodes) {\r\n const childNode = buildNodeWithSN(childN, {\r\n doc,\r\n mirror,\r\n skipChild: false,\r\n hackCss,\r\n afterAppend,\r\n cache,\r\n });\r\n if (!childNode) {\r\n console.warn('Failed to rebuild', childN);\r\n continue;\r\n }\r\n if (childN.isShadow && isElement(node) && node.shadowRoot) {\r\n node.shadowRoot.appendChild(childNode);\r\n }\r\n else if (n.type === NodeType.Document &&\r\n childN.type == NodeType.Element) {\r\n const htmlElement = childNode;\r\n let body = null;\r\n htmlElement.childNodes.forEach((child) => {\r\n if (child.nodeName === 'BODY')\r\n body = child;\r\n });\r\n if (body) {\r\n htmlElement.removeChild(body);\r\n node.appendChild(childNode);\r\n htmlElement.appendChild(body);\r\n }\r\n else {\r\n node.appendChild(childNode);\r\n }\r\n }\r\n else {\r\n node.appendChild(childNode);\r\n }\r\n if (afterAppend) {\r\n afterAppend(childNode, childN.id);\r\n }\r\n }\r\n }\r\n return node;\r\n}\r\nfunction visit(mirror, onVisit) {\r\n function walk(node) {\r\n onVisit(node);\r\n }\r\n for (const id of mirror.getIds()) {\r\n if (mirror.has(id)) {\r\n walk(mirror.getNode(id));\r\n }\r\n }\r\n}\r\nfunction handleScroll(node, mirror) {\r\n const n = mirror.getMeta(node);\r\n if (n?.type !== NodeType.Element) {\r\n return;\r\n }\r\n const el = node;\r\n for (const name in n.attributes) {\r\n if (!(Object.prototype.hasOwnProperty.call(n.attributes, name) &&\r\n name.startsWith('rr_'))) {\r\n continue;\r\n }\r\n const value = n.attributes[name];\r\n if (name === 'rr_scrollLeft') {\r\n el.scrollLeft = value;\r\n }\r\n if (name === 'rr_scrollTop') {\r\n el.scrollTop = value;\r\n }\r\n }\r\n}\r\nfunction rebuild(n, options) {\r\n const { doc, onVisit, hackCss = true, afterAppend, cache, mirror = new Mirror(), } = options;\r\n const node = buildNodeWithSN(n, {\r\n doc,\r\n mirror,\r\n skipChild: false,\r\n hackCss,\r\n afterAppend,\r\n cache,\r\n });\r\n visit(mirror, (visitedNode) => {\r\n if (onVisit) {\r\n onVisit(visitedNode);\r\n }\r\n handleScroll(visitedNode, mirror);\r\n });\r\n return node;\r\n}\n\nexport { IGNORED_NODE, Mirror, NodeType, addHoverClass, buildNodeWithSN, createCache, createMatchPredicate, createMirror, distanceToMatch, escapeImportStatement, fixSafariColons, genId, getInputType, getInputValue, ignoreAttribute, is2DCanvasBlank, isCSSImportRule, isCSSStyleRule, isElement, isNativeShadowDom, isNodeMetaEqual, isShadowRoot, maskInputValue, needMaskingText, rebuild, serializeNodeWithId, shouldMaskInput, snapshot, stringifyRule, stringifyStylesheet, toLowerCase, toUpperCase, transformAttribute };\n", "import { distanceToMatch, IGNORED_NODE, isShadowRoot, createMatchPredicate } from '../../rrweb-snapshot/es/rrweb-snapshot.js';\n\nfunction on(type, fn, target = document) {\r\n const options = { capture: true, passive: true };\r\n target.addEventListener(type, fn, options);\r\n return () => target.removeEventListener(type, fn, options);\r\n}\r\nconst DEPARTED_MIRROR_ACCESS_WARNING = 'Please stop import mirror directly. Instead of that,' +\r\n '\\r\\n' +\r\n 'now you can use replayer.getMirror() to access the mirror instance of a replayer,' +\r\n '\\r\\n' +\r\n 'or you can use record.mirror to access the mirror instance during recording.';\r\nlet _mirror = {\r\n map: {},\r\n getId() {\r\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\r\n return -1;\r\n },\r\n getNode() {\r\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\r\n return null;\r\n },\r\n removeNodeFromMap() {\r\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\r\n },\r\n has() {\r\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\r\n return false;\r\n },\r\n reset() {\r\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\r\n },\r\n};\r\nif (typeof window !== 'undefined' && window.Proxy && window.Reflect) {\r\n _mirror = new Proxy(_mirror, {\r\n get(target, prop, receiver) {\r\n if (prop === 'map') {\r\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\r\n }\r\n return Reflect.get(target, prop, receiver);\r\n },\r\n });\r\n}\r\nfunction throttle(func, wait, options = {}) {\r\n let timeout = null;\r\n let previous = 0;\r\n return function (...args) {\r\n const now = Date.now();\r\n if (!previous && options.leading === false) {\r\n previous = now;\r\n }\r\n const remaining = wait - (now - previous);\r\n const context = this;\r\n if (remaining <= 0 || remaining > wait) {\r\n if (timeout) {\r\n clearTimeout(timeout);\r\n timeout = null;\r\n }\r\n previous = now;\r\n func.apply(context, args);\r\n }\r\n else if (!timeout && options.trailing !== false) {\r\n timeout = setTimeout(() => {\r\n previous = options.leading === false ? 0 : Date.now();\r\n timeout = null;\r\n func.apply(context, args);\r\n }, remaining);\r\n }\r\n };\r\n}\r\nfunction hookSetter(target, key, d, isRevoked, win = window) {\r\n const original = win.Object.getOwnPropertyDescriptor(target, key);\r\n win.Object.defineProperty(target, key, isRevoked\r\n ? d\r\n : {\r\n set(value) {\r\n setTimeout(() => {\r\n d.set.call(this, value);\r\n }, 0);\r\n if (original && original.set) {\r\n original.set.call(this, value);\r\n }\r\n },\r\n });\r\n return () => hookSetter(target, key, original || {}, true);\r\n}\r\nfunction patch(source, name, replacement) {\r\n try {\r\n if (!(name in source)) {\r\n return () => {\r\n };\r\n }\r\n const original = source[name];\r\n const wrapped = replacement(original);\r\n if (typeof wrapped === 'function') {\r\n wrapped.prototype = wrapped.prototype || {};\r\n Object.defineProperties(wrapped, {\r\n __rrweb_original__: {\r\n enumerable: false,\r\n value: original,\r\n },\r\n });\r\n }\r\n source[name] = wrapped;\r\n return () => {\r\n source[name] = original;\r\n };\r\n }\r\n catch {\r\n return () => {\r\n };\r\n }\r\n}\r\nlet nowTimestamp = Date.now;\r\nif (!(/[1-9][0-9]{12}/.test(Date.now().toString()))) {\r\n nowTimestamp = () => new Date().getTime();\r\n}\r\nfunction getWindowScroll(win) {\r\n const doc = win.document;\r\n return {\r\n left: doc.scrollingElement\r\n ? doc.scrollingElement.scrollLeft\r\n : win.pageXOffset !== undefined\r\n ? win.pageXOffset\r\n : doc?.documentElement.scrollLeft ||\r\n doc?.body?.parentElement?.scrollLeft ||\r\n doc?.body?.scrollLeft ||\r\n 0,\r\n top: doc.scrollingElement\r\n ? doc.scrollingElement.scrollTop\r\n : win.pageYOffset !== undefined\r\n ? win.pageYOffset\r\n : doc?.documentElement.scrollTop ||\r\n doc?.body?.parentElement?.scrollTop ||\r\n doc?.body?.scrollTop ||\r\n 0,\r\n };\r\n}\r\nfunction getWindowHeight() {\r\n return (window.innerHeight ||\r\n (document.documentElement && document.documentElement.clientHeight) ||\r\n (document.body && document.body.clientHeight));\r\n}\r\nfunction getWindowWidth() {\r\n return (window.innerWidth ||\r\n (document.documentElement && document.documentElement.clientWidth) ||\r\n (document.body && document.body.clientWidth));\r\n}\r\nfunction closestElementOfNode(node) {\r\n if (!node) {\r\n return null;\r\n }\r\n const el = node.nodeType === node.ELEMENT_NODE\r\n ? node\r\n : node.parentElement;\r\n return el;\r\n}\r\nfunction isBlocked(node, blockClass, blockSelector, unblockSelector, checkAncestors) {\r\n if (!node) {\r\n return false;\r\n }\r\n const el = closestElementOfNode(node);\r\n if (!el) {\r\n return false;\r\n }\r\n const blockedPredicate = createMatchPredicate(blockClass, blockSelector);\r\n if (!checkAncestors) {\r\n const isUnblocked = unblockSelector && el.matches(unblockSelector);\r\n return blockedPredicate(el) && !isUnblocked;\r\n }\r\n const blockDistance = distanceToMatch(el, blockedPredicate);\r\n let unblockDistance = -1;\r\n if (blockDistance < 0) {\r\n return false;\r\n }\r\n if (unblockSelector) {\r\n unblockDistance = distanceToMatch(el, createMatchPredicate(null, unblockSelector));\r\n }\r\n if (blockDistance > -1 && unblockDistance < 0) {\r\n return true;\r\n }\r\n return blockDistance < unblockDistance;\r\n}\r\nfunction isSerialized(n, mirror) {\r\n return mirror.getId(n) !== -1;\r\n}\r\nfunction isIgnored(n, mirror) {\r\n return mirror.getId(n) === IGNORED_NODE;\r\n}\r\nfunction isAncestorRemoved(target, mirror) {\r\n if (isShadowRoot(target)) {\r\n return false;\r\n }\r\n const id = mirror.getId(target);\r\n if (!mirror.has(id)) {\r\n return true;\r\n }\r\n if (target.parentNode &&\r\n target.parentNode.nodeType === target.DOCUMENT_NODE) {\r\n return false;\r\n }\r\n if (!target.parentNode) {\r\n return true;\r\n }\r\n return isAncestorRemoved(target.parentNode, mirror);\r\n}\r\nfunction legacy_isTouchEvent(event) {\r\n return Boolean(event.changedTouches);\r\n}\r\nfunction polyfill(win = window) {\r\n if ('NodeList' in win && !win.NodeList.prototype.forEach) {\r\n win.NodeList.prototype.forEach = Array.prototype\r\n .forEach;\r\n }\r\n if ('DOMTokenList' in win && !win.DOMTokenList.prototype.forEach) {\r\n win.DOMTokenList.prototype.forEach = Array.prototype\r\n .forEach;\r\n }\r\n if (!Node.prototype.contains) {\r\n Node.prototype.contains = (...args) => {\r\n let node = args[0];\r\n if (!(0 in args)) {\r\n throw new TypeError('1 argument is required');\r\n }\r\n do {\r\n if (this === node) {\r\n return true;\r\n }\r\n } while ((node = node && node.parentNode));\r\n return false;\r\n };\r\n }\r\n}\r\nfunction queueToResolveTrees(queue) {\r\n const queueNodeMap = {};\r\n const putIntoMap = (m, parent) => {\r\n const nodeInTree = {\r\n value: m,\r\n parent,\r\n children: [],\r\n };\r\n queueNodeMap[m.node.id] = nodeInTree;\r\n return nodeInTree;\r\n };\r\n const queueNodeTrees = [];\r\n for (const mutation of queue) {\r\n const { nextId, parentId } = mutation;\r\n if (nextId && nextId in queueNodeMap) {\r\n const nextInTree = queueNodeMap[nextId];\r\n if (nextInTree.parent) {\r\n const idx = nextInTree.parent.children.indexOf(nextInTree);\r\n nextInTree.parent.children.splice(idx, 0, putIntoMap(mutation, nextInTree.parent));\r\n }\r\n else {\r\n const idx = queueNodeTrees.indexOf(nextInTree);\r\n queueNodeTrees.splice(idx, 0, putIntoMap(mutation, null));\r\n }\r\n continue;\r\n }\r\n if (parentId in queueNodeMap) {\r\n const parentInTree = queueNodeMap[parentId];\r\n parentInTree.children.push(putIntoMap(mutation, parentInTree));\r\n continue;\r\n }\r\n queueNodeTrees.push(putIntoMap(mutation, null));\r\n }\r\n return queueNodeTrees;\r\n}\r\nfunction iterateResolveTree(tree, cb) {\r\n cb(tree.value);\r\n for (let i = tree.children.length - 1; i >= 0; i--) {\r\n iterateResolveTree(tree.children[i], cb);\r\n }\r\n}\r\nfunction isSerializedIframe(n, mirror) {\r\n return Boolean(n.nodeName === 'IFRAME' && mirror.getMeta(n));\r\n}\r\nfunction isSerializedStylesheet(n, mirror) {\r\n return Boolean(n.nodeName === 'LINK' &&\r\n n.nodeType === n.ELEMENT_NODE &&\r\n n.getAttribute &&\r\n n.getAttribute('rel') === 'stylesheet' &&\r\n mirror.getMeta(n));\r\n}\r\nfunction getBaseDimension(node, rootIframe) {\r\n const frameElement = node.ownerDocument?.defaultView?.frameElement;\r\n if (!frameElement || frameElement === rootIframe) {\r\n return {\r\n x: 0,\r\n y: 0,\r\n relativeScale: 1,\r\n absoluteScale: 1,\r\n };\r\n }\r\n const frameDimension = frameElement.getBoundingClientRect();\r\n const frameBaseDimension = getBaseDimension(frameElement, rootIframe);\r\n const relativeScale = frameDimension.height / frameElement.clientHeight;\r\n return {\r\n x: frameDimension.x * frameBaseDimension.relativeScale +\r\n frameBaseDimension.x,\r\n y: frameDimension.y * frameBaseDimension.relativeScale +\r\n frameBaseDimension.y,\r\n relativeScale,\r\n absoluteScale: frameBaseDimension.absoluteScale * relativeScale,\r\n };\r\n}\r\nfunction hasShadowRoot(n) {\r\n return Boolean(n?.shadowRoot);\r\n}\r\nfunction getNestedRule(rules, position) {\r\n const rule = rules[position[0]];\r\n if (position.length === 1) {\r\n return rule;\r\n }\r\n else {\r\n return getNestedRule(rule.cssRules[position[1]].cssRules, position.slice(2));\r\n }\r\n}\r\nfunction getPositionsAndIndex(nestedIndex) {\r\n const positions = [...nestedIndex];\r\n const index = positions.pop();\r\n return { positions, index };\r\n}\r\nfunction uniqueTextMutations(mutations) {\r\n const idSet = new Set();\r\n const uniqueMutations = [];\r\n for (let i = mutations.length; i--;) {\r\n const mutation = mutations[i];\r\n if (!idSet.has(mutation.id)) {\r\n uniqueMutations.push(mutation);\r\n idSet.add(mutation.id);\r\n }\r\n }\r\n return uniqueMutations;\r\n}\r\nclass StyleSheetMirror {\r\n constructor() {\r\n this.id = 1;\r\n this.styleIDMap = new WeakMap();\r\n this.idStyleMap = new Map();\r\n }\r\n getId(stylesheet) {\r\n return this.styleIDMap.get(stylesheet) ?? -1;\r\n }\r\n has(stylesheet) {\r\n return this.styleIDMap.has(stylesheet);\r\n }\r\n add(stylesheet, id) {\r\n if (this.has(stylesheet))\r\n return this.getId(stylesheet);\r\n let newId;\r\n if (id === undefined) {\r\n newId = this.id++;\r\n }\r\n else\r\n newId = id;\r\n this.styleIDMap.set(stylesheet, newId);\r\n this.idStyleMap.set(newId, stylesheet);\r\n return newId;\r\n }\r\n getStyle(id) {\r\n return this.idStyleMap.get(id) || null;\r\n }\r\n reset() {\r\n this.styleIDMap = new WeakMap();\r\n this.idStyleMap = new Map();\r\n this.id = 1;\r\n }\r\n generateId() {\r\n return this.id++;\r\n }\r\n}\r\nfunction getShadowHost(n) {\r\n let shadowHost = null;\r\n if (n.getRootNode?.()?.nodeType === Node.DOCUMENT_FRAGMENT_NODE &&\r\n n.getRootNode().host)\r\n shadowHost = n.getRootNode().host;\r\n return shadowHost;\r\n}\r\nfunction getRootShadowHost(n) {\r\n let rootShadowHost = n;\r\n let shadowHost;\r\n while ((shadowHost = getShadowHost(rootShadowHost)))\r\n rootShadowHost = shadowHost;\r\n return rootShadowHost;\r\n}\r\nfunction shadowHostInDom(n) {\r\n const doc = n.ownerDocument;\r\n if (!doc)\r\n return false;\r\n const shadowHost = getRootShadowHost(n);\r\n return doc.contains(shadowHost);\r\n}\r\nfunction inDom(n) {\r\n const doc = n.ownerDocument;\r\n if (!doc)\r\n return false;\r\n return doc.contains(n) || shadowHostInDom(n);\r\n}\r\nconst cachedImplementations = {};\r\nfunction getImplementation(name) {\r\n const cached = cachedImplementations[name];\r\n if (cached) {\r\n return cached;\r\n }\r\n const document = window.document;\r\n let impl = window[name];\r\n if (document && typeof document.createElement === 'function') {\r\n try {\r\n const sandbox = document.createElement('iframe');\r\n sandbox.hidden = true;\r\n document.head.appendChild(sandbox);\r\n const contentWindow = sandbox.contentWindow;\r\n if (contentWindow && contentWindow[name]) {\r\n impl =\r\n contentWindow[name];\r\n }\r\n document.head.removeChild(sandbox);\r\n }\r\n catch (e) {\r\n }\r\n }\r\n return (cachedImplementations[name] = impl.bind(window));\r\n}\r\nfunction onRequestAnimationFrame(...rest) {\r\n return getImplementation('requestAnimationFrame')(...rest);\r\n}\r\nfunction setTimeout(...rest) {\r\n return getImplementation('setTimeout')(...rest);\r\n}\r\nfunction clearTimeout(...rest) {\r\n return getImplementation('clearTimeout')(...rest);\r\n}\n\nexport { StyleSheetMirror, _mirror, clearTimeout, closestElementOfNode, getBaseDimension, getNestedRule, getPositionsAndIndex, getRootShadowHost, getShadowHost, getWindowHeight, getWindowScroll, getWindowWidth, hasShadowRoot, hookSetter, inDom, isAncestorRemoved, isBlocked, isIgnored, isSerialized, isSerializedIframe, isSerializedStylesheet, iterateResolveTree, legacy_isTouchEvent, nowTimestamp, on, onRequestAnimationFrame, patch, polyfill, queueToResolveTrees, setTimeout, shadowHostInDom, throttle, uniqueTextMutations };\n", "var EventType = /* @__PURE__ */ ((EventType2) => {\n EventType2[EventType2[\"DomContentLoaded\"] = 0] = \"DomContentLoaded\";\n EventType2[EventType2[\"Load\"] = 1] = \"Load\";\n EventType2[EventType2[\"FullSnapshot\"] = 2] = \"FullSnapshot\";\n EventType2[EventType2[\"IncrementalSnapshot\"] = 3] = \"IncrementalSnapshot\";\n EventType2[EventType2[\"Meta\"] = 4] = \"Meta\";\n EventType2[EventType2[\"Custom\"] = 5] = \"Custom\";\n EventType2[EventType2[\"Plugin\"] = 6] = \"Plugin\";\n return EventType2;\n})(EventType || {});\nvar IncrementalSource = /* @__PURE__ */ ((IncrementalSource2) => {\n IncrementalSource2[IncrementalSource2[\"Mutation\"] = 0] = \"Mutation\";\n IncrementalSource2[IncrementalSource2[\"MouseMove\"] = 1] = \"MouseMove\";\n IncrementalSource2[IncrementalSource2[\"MouseInteraction\"] = 2] = \"MouseInteraction\";\n IncrementalSource2[IncrementalSource2[\"Scroll\"] = 3] = \"Scroll\";\n IncrementalSource2[IncrementalSource2[\"ViewportResize\"] = 4] = \"ViewportResize\";\n IncrementalSource2[IncrementalSource2[\"Input\"] = 5] = \"Input\";\n IncrementalSource2[IncrementalSource2[\"TouchMove\"] = 6] = \"TouchMove\";\n IncrementalSource2[IncrementalSource2[\"MediaInteraction\"] = 7] = \"MediaInteraction\";\n IncrementalSource2[IncrementalSource2[\"StyleSheetRule\"] = 8] = \"StyleSheetRule\";\n IncrementalSource2[IncrementalSource2[\"CanvasMutation\"] = 9] = \"CanvasMutation\";\n IncrementalSource2[IncrementalSource2[\"Font\"] = 10] = \"Font\";\n IncrementalSource2[IncrementalSource2[\"Log\"] = 11] = \"Log\";\n IncrementalSource2[IncrementalSource2[\"Drag\"] = 12] = \"Drag\";\n IncrementalSource2[IncrementalSource2[\"StyleDeclaration\"] = 13] = \"StyleDeclaration\";\n IncrementalSource2[IncrementalSource2[\"Selection\"] = 14] = \"Selection\";\n IncrementalSource2[IncrementalSource2[\"AdoptedStyleSheet\"] = 15] = \"AdoptedStyleSheet\";\n IncrementalSource2[IncrementalSource2[\"CustomElement\"] = 16] = \"CustomElement\";\n return IncrementalSource2;\n})(IncrementalSource || {});\nvar MouseInteractions = /* @__PURE__ */ ((MouseInteractions2) => {\n MouseInteractions2[MouseInteractions2[\"MouseUp\"] = 0] = \"MouseUp\";\n MouseInteractions2[MouseInteractions2[\"MouseDown\"] = 1] = \"MouseDown\";\n MouseInteractions2[MouseInteractions2[\"Click\"] = 2] = \"Click\";\n MouseInteractions2[MouseInteractions2[\"ContextMenu\"] = 3] = \"ContextMenu\";\n MouseInteractions2[MouseInteractions2[\"DblClick\"] = 4] = \"DblClick\";\n MouseInteractions2[MouseInteractions2[\"Focus\"] = 5] = \"Focus\";\n MouseInteractions2[MouseInteractions2[\"Blur\"] = 6] = \"Blur\";\n MouseInteractions2[MouseInteractions2[\"TouchStart\"] = 7] = \"TouchStart\";\n MouseInteractions2[MouseInteractions2[\"TouchMove_Departed\"] = 8] = \"TouchMove_Departed\";\n MouseInteractions2[MouseInteractions2[\"TouchEnd\"] = 9] = \"TouchEnd\";\n MouseInteractions2[MouseInteractions2[\"TouchCancel\"] = 10] = \"TouchCancel\";\n return MouseInteractions2;\n})(MouseInteractions || {});\nvar PointerTypes = /* @__PURE__ */ ((PointerTypes2) => {\n PointerTypes2[PointerTypes2[\"Mouse\"] = 0] = \"Mouse\";\n PointerTypes2[PointerTypes2[\"Pen\"] = 1] = \"Pen\";\n PointerTypes2[PointerTypes2[\"Touch\"] = 2] = \"Touch\";\n return PointerTypes2;\n})(PointerTypes || {});\nvar CanvasContext = /* @__PURE__ */ ((CanvasContext2) => {\n CanvasContext2[CanvasContext2[\"2D\"] = 0] = \"2D\";\n CanvasContext2[CanvasContext2[\"WebGL\"] = 1] = \"WebGL\";\n CanvasContext2[CanvasContext2[\"WebGL2\"] = 2] = \"WebGL2\";\n return CanvasContext2;\n})(CanvasContext || {});\nvar ReplayerEvents = /* @__PURE__ */ ((ReplayerEvents2) => {\n ReplayerEvents2[\"Start\"] = \"start\";\n ReplayerEvents2[\"Pause\"] = \"pause\";\n ReplayerEvents2[\"Resume\"] = \"resume\";\n ReplayerEvents2[\"Resize\"] = \"resize\";\n ReplayerEvents2[\"Finish\"] = \"finish\";\n ReplayerEvents2[\"FullsnapshotRebuilded\"] = \"fullsnapshot-rebuilded\";\n ReplayerEvents2[\"LoadStylesheetStart\"] = \"load-stylesheet-start\";\n ReplayerEvents2[\"LoadStylesheetEnd\"] = \"load-stylesheet-end\";\n ReplayerEvents2[\"SkipStart\"] = \"skip-start\";\n ReplayerEvents2[\"SkipEnd\"] = \"skip-end\";\n ReplayerEvents2[\"MouseInteraction\"] = \"mouse-interaction\";\n ReplayerEvents2[\"EventCast\"] = \"event-cast\";\n ReplayerEvents2[\"CustomEvent\"] = \"custom-event\";\n ReplayerEvents2[\"Flush\"] = \"flush\";\n ReplayerEvents2[\"StateChange\"] = \"state-change\";\n ReplayerEvents2[\"PlayBack\"] = \"play-back\";\n ReplayerEvents2[\"Destroy\"] = \"destroy\";\n return ReplayerEvents2;\n})(ReplayerEvents || {});\n\nexport { CanvasContext, EventType, IncrementalSource, MouseInteractions, PointerTypes, ReplayerEvents };\n", "import { isShadowRoot, isNativeShadowDom, getInputType, getInputValue, shouldMaskInput, needMaskingText, maskInputValue, ignoreAttribute, transformAttribute, toLowerCase, IGNORED_NODE, serializeNodeWithId } from '../../../rrweb-snapshot/es/rrweb-snapshot.js';\nimport { isIgnored, isBlocked, isSerialized, isAncestorRemoved, closestElementOfNode, hasShadowRoot, inDom, getShadowHost, isSerializedIframe, isSerializedStylesheet } from '../utils.js';\n\nfunction isNodeInLinkedList(n) {\r\n return '__ln' in n;\r\n}\r\nclass DoubleLinkedList {\r\n constructor() {\r\n this.length = 0;\r\n this.head = null;\r\n this.tail = null;\r\n }\r\n get(position) {\r\n if (position >= this.length) {\r\n throw new Error('Position outside of list range');\r\n }\r\n let current = this.head;\r\n for (let index = 0; index < position; index++) {\r\n current = current?.next || null;\r\n }\r\n return current;\r\n }\r\n addNode(n) {\r\n const node = {\r\n value: n,\r\n previous: null,\r\n next: null,\r\n };\r\n n.__ln = node;\r\n if (n.previousSibling && isNodeInLinkedList(n.previousSibling)) {\r\n const current = n.previousSibling.__ln.next;\r\n node.next = current;\r\n node.previous = n.previousSibling.__ln;\r\n n.previousSibling.__ln.next = node;\r\n if (current) {\r\n current.previous = node;\r\n }\r\n }\r\n else if (n.nextSibling &&\r\n isNodeInLinkedList(n.nextSibling) &&\r\n n.nextSibling.__ln.previous) {\r\n const current = n.nextSibling.__ln.previous;\r\n node.previous = current;\r\n node.next = n.nextSibling.__ln;\r\n n.nextSibling.__ln.previous = node;\r\n if (current) {\r\n current.next = node;\r\n }\r\n }\r\n else {\r\n if (this.head) {\r\n this.head.previous = node;\r\n }\r\n node.next = this.head;\r\n this.head = node;\r\n }\r\n if (node.next === null) {\r\n this.tail = node;\r\n }\r\n this.length++;\r\n }\r\n removeNode(n) {\r\n const current = n.__ln;\r\n if (!this.head) {\r\n return;\r\n }\r\n if (!current.previous) {\r\n this.head = current.next;\r\n if (this.head) {\r\n this.head.previous = null;\r\n }\r\n else {\r\n this.tail = null;\r\n }\r\n }\r\n else {\r\n current.previous.next = current.next;\r\n if (current.next) {\r\n current.next.previous = current.previous;\r\n }\r\n else {\r\n this.tail = current.previous;\r\n }\r\n }\r\n if (n.__ln) {\r\n delete n.__ln;\r\n }\r\n this.length--;\r\n }\r\n}\r\nconst moveKey = (id, parentId) => `${id}@${parentId}`;\r\nclass MutationBuffer {\r\n constructor() {\r\n this.frozen = false;\r\n this.locked = false;\r\n this.texts = [];\r\n this.attributes = [];\r\n this.attributeMap = new WeakMap();\r\n this.removes = [];\r\n this.mapRemoves = [];\r\n this.movedMap = {};\r\n this.addedSet = new Set();\r\n this.movedSet = new Set();\r\n this.droppedSet = new Set();\r\n this.processMutations = (mutations) => {\r\n mutations.forEach(this.processMutation);\r\n this.emit();\r\n };\r\n this.emit = () => {\r\n if (this.frozen || this.locked) {\r\n return;\r\n }\r\n const adds = [];\r\n const addedIds = new Set();\r\n const addList = new DoubleLinkedList();\r\n const getNextId = (n) => {\r\n let ns = n;\r\n let nextId = IGNORED_NODE;\r\n while (nextId === IGNORED_NODE) {\r\n ns = ns && ns.nextSibling;\r\n nextId = ns && this.mirror.getId(ns);\r\n }\r\n return nextId;\r\n };\r\n const pushAdd = (n) => {\r\n if (!n.parentNode || !inDom(n)) {\r\n return;\r\n }\r\n const parentId = isShadowRoot(n.parentNode)\r\n ? this.mirror.getId(getShadowHost(n))\r\n : this.mirror.getId(n.parentNode);\r\n const nextId = getNextId(n);\r\n if (parentId === -1 || nextId === -1) {\r\n return addList.addNode(n);\r\n }\r\n const sn = serializeNodeWithId(n, {\r\n doc: this.doc,\r\n mirror: this.mirror,\r\n blockClass: this.blockClass,\r\n blockSelector: this.blockSelector,\r\n maskAllText: this.maskAllText,\r\n unblockSelector: this.unblockSelector,\r\n maskTextClass: this.maskTextClass,\r\n unmaskTextClass: this.unmaskTextClass,\r\n maskTextSelector: this.maskTextSelector,\r\n unmaskTextSelector: this.unmaskTextSelector,\r\n skipChild: true,\r\n newlyAddedElement: true,\r\n inlineStylesheet: this.inlineStylesheet,\r\n maskInputOptions: this.maskInputOptions,\r\n maskAttributeFn: this.maskAttributeFn,\r\n maskTextFn: this.maskTextFn,\r\n maskInputFn: this.maskInputFn,\r\n slimDOMOptions: this.slimDOMOptions,\r\n dataURLOptions: this.dataURLOptions,\r\n recordCanvas: this.recordCanvas,\r\n inlineImages: this.inlineImages,\r\n onSerialize: (currentN) => {\r\n if (isSerializedIframe(currentN, this.mirror)) {\r\n this.iframeManager.addIframe(currentN);\r\n }\r\n if (isSerializedStylesheet(currentN, this.mirror)) {\r\n this.stylesheetManager.trackLinkElement(currentN);\r\n }\r\n if (hasShadowRoot(n)) {\r\n this.shadowDomManager.addShadowRoot(n.shadowRoot, this.doc);\r\n }\r\n },\r\n onIframeLoad: (iframe, childSn) => {\r\n this.iframeManager.attachIframe(iframe, childSn);\r\n this.shadowDomManager.observeAttachShadow(iframe);\r\n },\r\n onStylesheetLoad: (link, childSn) => {\r\n this.stylesheetManager.attachLinkElement(link, childSn);\r\n },\r\n });\r\n if (sn) {\r\n adds.push({\r\n parentId,\r\n nextId,\r\n node: sn,\r\n });\r\n addedIds.add(sn.id);\r\n }\r\n };\r\n while (this.mapRemoves.length) {\r\n this.mirror.removeNodeFromMap(this.mapRemoves.shift());\r\n }\r\n for (const n of this.movedSet) {\r\n if (isParentRemoved(this.removes, n, this.mirror) &&\r\n !this.movedSet.has(n.parentNode)) {\r\n continue;\r\n }\r\n pushAdd(n);\r\n }\r\n for (const n of this.addedSet) {\r\n if (!isAncestorInSet(this.droppedSet, n) &&\r\n !isParentRemoved(this.removes, n, this.mirror)) {\r\n pushAdd(n);\r\n }\r\n else if (isAncestorInSet(this.movedSet, n)) {\r\n pushAdd(n);\r\n }\r\n else {\r\n this.droppedSet.add(n);\r\n }\r\n }\r\n let candidate = null;\r\n while (addList.length) {\r\n let node = null;\r\n if (candidate) {\r\n const parentId = this.mirror.getId(candidate.value.parentNode);\r\n const nextId = getNextId(candidate.value);\r\n if (parentId !== -1 && nextId !== -1) {\r\n node = candidate;\r\n }\r\n }\r\n if (!node) {\r\n let tailNode = addList.tail;\r\n while (tailNode) {\r\n const _node = tailNode;\r\n tailNode = tailNode.previous;\r\n if (_node) {\r\n const parentId = this.mirror.getId(_node.value.parentNode);\r\n const nextId = getNextId(_node.value);\r\n if (nextId === -1)\r\n continue;\r\n else if (parentId !== -1) {\r\n node = _node;\r\n break;\r\n }\r\n else {\r\n const unhandledNode = _node.value;\r\n if (unhandledNode.parentNode &&\r\n unhandledNode.parentNode.nodeType ===\r\n Node.DOCUMENT_FRAGMENT_NODE) {\r\n const shadowHost = unhandledNode.parentNode\r\n .host;\r\n const parentId = this.mirror.getId(shadowHost);\r\n if (parentId !== -1) {\r\n node = _node;\r\n break;\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n if (!node) {\r\n while (addList.head) {\r\n addList.removeNode(addList.head.value);\r\n }\r\n break;\r\n }\r\n candidate = node.previous;\r\n addList.removeNode(node.value);\r\n pushAdd(node.value);\r\n }\r\n const payload = {\r\n texts: this.texts\r\n .map((text) => ({\r\n id: this.mirror.getId(text.node),\r\n value: text.value,\r\n }))\r\n .filter((text) => !addedIds.has(text.id))\r\n .filter((text) => this.mirror.has(text.id)),\r\n attributes: this.attributes\r\n .map((attribute) => {\r\n const { attributes } = attribute;\r\n if (typeof attributes.style === 'string') {\r\n const diffAsStr = JSON.stringify(attribute.styleDiff);\r\n const unchangedAsStr = JSON.stringify(attribute._unchangedStyles);\r\n if (diffAsStr.length < attributes.style.length) {\r\n if ((diffAsStr + unchangedAsStr).split('var(').length ===\r\n attributes.style.split('var(').length) {\r\n attributes.style = attribute.styleDiff;\r\n }\r\n }\r\n }\r\n return {\r\n id: this.mirror.getId(attribute.node),\r\n attributes: attributes,\r\n };\r\n })\r\n .filter((attribute) => !addedIds.has(attribute.id))\r\n .filter((attribute) => this.mirror.has(attribute.id)),\r\n removes: this.removes,\r\n adds,\r\n };\r\n if (!payload.texts.length &&\r\n !payload.attributes.length &&\r\n !payload.removes.length &&\r\n !payload.adds.length) {\r\n return;\r\n }\r\n this.texts = [];\r\n this.attributes = [];\r\n this.attributeMap = new WeakMap();\r\n this.removes = [];\r\n this.addedSet = new Set();\r\n this.movedSet = new Set();\r\n this.droppedSet = new Set();\r\n this.movedMap = {};\r\n this.mutationCb(payload);\r\n };\r\n this.processMutation = (m) => {\r\n if (isIgnored(m.target, this.mirror)) {\r\n return;\r\n }\r\n switch (m.type) {\r\n case 'characterData': {\r\n const value = m.target.textContent;\r\n if (!isBlocked(m.target, this.blockClass, this.blockSelector, this.unblockSelector, false) &&\r\n value !== m.oldValue) {\r\n this.texts.push({\r\n value: needMaskingText(m.target, this.maskTextClass, this.maskTextSelector, this.unmaskTextClass, this.unmaskTextSelector, this.maskAllText) && value\r\n ? this.maskTextFn\r\n ? this.maskTextFn(value, closestElementOfNode(m.target))\r\n : value.replace(/[\\S]/g, '*')\r\n : value,\r\n node: m.target,\r\n });\r\n }\r\n break;\r\n }\r\n case 'attributes': {\r\n const target = m.target;\r\n let attributeName = m.attributeName;\r\n let value = m.target.getAttribute(attributeName);\r\n if (attributeName === 'value') {\r\n const type = getInputType(target);\r\n const tagName = target.tagName;\r\n value = getInputValue(target, tagName, type);\r\n const isInputMasked = shouldMaskInput({\r\n maskInputOptions: this.maskInputOptions,\r\n tagName,\r\n type,\r\n });\r\n const forceMask = needMaskingText(m.target, this.maskTextClass, this.maskTextSelector, this.unmaskTextClass, this.unmaskTextSelector, isInputMasked);\r\n value = maskInputValue({\r\n isMasked: forceMask,\r\n element: target,\r\n value,\r\n maskInputFn: this.maskInputFn,\r\n });\r\n }\r\n if (isBlocked(m.target, this.blockClass, this.blockSelector, this.unblockSelector, false) ||\r\n value === m.oldValue) {\r\n return;\r\n }\r\n let item = this.attributeMap.get(m.target);\r\n if (target.tagName === 'IFRAME' &&\r\n attributeName === 'src' &&\r\n !this.keepIframeSrcFn(value)) {\r\n if (!target.contentDocument) {\r\n attributeName = 'rr_src';\r\n }\r\n else {\r\n return;\r\n }\r\n }\r\n if (!item) {\r\n item = {\r\n node: m.target,\r\n attributes: {},\r\n styleDiff: {},\r\n _unchangedStyles: {},\r\n };\r\n this.attributes.push(item);\r\n this.attributeMap.set(m.target, item);\r\n }\r\n if (attributeName === 'type' &&\r\n target.tagName === 'INPUT' &&\r\n (m.oldValue || '').toLowerCase() === 'password') {\r\n target.setAttribute('data-rr-is-password', 'true');\r\n }\r\n if (!ignoreAttribute(target.tagName, attributeName)) {\r\n item.attributes[attributeName] = transformAttribute(this.doc, toLowerCase(target.tagName), toLowerCase(attributeName), value, target, this.maskAttributeFn);\r\n if (attributeName === 'style') {\r\n if (!this.unattachedDoc) {\r\n try {\r\n this.unattachedDoc =\r\n document.implementation.createHTMLDocument();\r\n }\r\n catch (e) {\r\n this.unattachedDoc = this.doc;\r\n }\r\n }\r\n const old = this.unattachedDoc.createElement('span');\r\n if (m.oldValue) {\r\n old.setAttribute('style', m.oldValue);\r\n }\r\n for (const pname of Array.from(target.style)) {\r\n const newValue = target.style.getPropertyValue(pname);\r\n const newPriority = target.style.getPropertyPriority(pname);\r\n if (newValue !== old.style.getPropertyValue(pname) ||\r\n newPriority !== old.style.getPropertyPriority(pname)) {\r\n if (newPriority === '') {\r\n item.styleDiff[pname] = newValue;\r\n }\r\n else {\r\n item.styleDiff[pname] = [newValue, newPriority];\r\n }\r\n }\r\n else {\r\n item._unchangedStyles[pname] = [newValue, newPriority];\r\n }\r\n }\r\n for (const pname of Array.from(old.style)) {\r\n if (target.style.getPropertyValue(pname) === '') {\r\n item.styleDiff[pname] = false;\r\n }\r\n }\r\n }\r\n }\r\n break;\r\n }\r\n case 'childList': {\r\n if (isBlocked(m.target, this.blockClass, this.blockSelector, this.unblockSelector, true)) {\r\n return;\r\n }\r\n m.addedNodes.forEach((n) => this.genAdds(n, m.target));\r\n m.removedNodes.forEach((n) => {\r\n const nodeId = this.mirror.getId(n);\r\n const parentId = isShadowRoot(m.target)\r\n ? this.mirror.getId(m.target.host)\r\n : this.mirror.getId(m.target);\r\n if (isBlocked(m.target, this.blockClass, this.blockSelector, this.unblockSelector, false) ||\r\n isIgnored(n, this.mirror) ||\r\n !isSerialized(n, this.mirror)) {\r\n return;\r\n }\r\n if (this.addedSet.has(n)) {\r\n deepDelete(this.addedSet, n);\r\n this.droppedSet.add(n);\r\n }\r\n else if (this.addedSet.has(m.target) && nodeId === -1) ;\r\n else if (isAncestorRemoved(m.target, this.mirror)) ;\r\n else if (this.movedSet.has(n) &&\r\n this.movedMap[moveKey(nodeId, parentId)]) {\r\n deepDelete(this.movedSet, n);\r\n }\r\n else {\r\n this.removes.push({\r\n parentId,\r\n id: nodeId,\r\n isShadow: isShadowRoot(m.target) && isNativeShadowDom(m.target)\r\n ? true\r\n : undefined,\r\n });\r\n }\r\n this.mapRemoves.push(n);\r\n });\r\n break;\r\n }\r\n }\r\n };\r\n this.genAdds = (n, target) => {\r\n if (this.processedNodeManager.inOtherBuffer(n, this))\r\n return;\r\n if (this.addedSet.has(n) || this.movedSet.has(n))\r\n return;\r\n if (this.mirror.hasNode(n)) {\r\n if (isIgnored(n, this.mirror)) {\r\n return;\r\n }\r\n this.movedSet.add(n);\r\n let targetId = null;\r\n if (target && this.mirror.hasNode(target)) {\r\n targetId = this.mirror.getId(target);\r\n }\r\n if (targetId && targetId !== -1) {\r\n this.movedMap[moveKey(this.mirror.getId(n), targetId)] = true;\r\n }\r\n }\r\n else {\r\n this.addedSet.add(n);\r\n this.droppedSet.delete(n);\r\n }\r\n if (!isBlocked(n, this.blockClass, this.blockSelector, this.unblockSelector, false)) {\r\n n.childNodes.forEach((childN) => this.genAdds(childN));\r\n if (hasShadowRoot(n)) {\r\n n.shadowRoot.childNodes.forEach((childN) => {\r\n this.processedNodeManager.add(childN, this);\r\n this.genAdds(childN, n);\r\n });\r\n }\r\n }\r\n };\r\n }\r\n init(options) {\r\n [\r\n 'mutationCb',\r\n 'blockClass',\r\n 'blockSelector',\r\n 'unblockSelector',\r\n 'maskAllText',\r\n 'maskTextClass',\r\n 'unmaskTextClass',\r\n 'maskTextSelector',\r\n 'unmaskTextSelector',\r\n 'inlineStylesheet',\r\n 'maskInputOptions',\r\n 'maskAttributeFn',\r\n 'maskTextFn',\r\n 'maskInputFn',\r\n 'keepIframeSrcFn',\r\n 'recordCanvas',\r\n 'inlineImages',\r\n 'slimDOMOptions',\r\n 'dataURLOptions',\r\n 'doc',\r\n 'mirror',\r\n 'iframeManager',\r\n 'stylesheetManager',\r\n 'shadowDomManager',\r\n 'canvasManager',\r\n 'processedNodeManager',\r\n ].forEach((key) => {\r\n this[key] = options[key];\r\n });\r\n }\r\n freeze() {\r\n this.frozen = true;\r\n this.canvasManager.freeze();\r\n }\r\n unfreeze() {\r\n this.frozen = false;\r\n this.canvasManager.unfreeze();\r\n this.emit();\r\n }\r\n isFrozen() {\r\n return this.frozen;\r\n }\r\n lock() {\r\n this.locked = true;\r\n this.canvasManager.lock();\r\n }\r\n unlock() {\r\n this.locked = false;\r\n this.canvasManager.unlock();\r\n this.emit();\r\n }\r\n reset() {\r\n this.shadowDomManager.reset();\r\n this.canvasManager.reset();\r\n }\r\n}\r\nfunction deepDelete(addsSet, n) {\r\n addsSet.delete(n);\r\n n.childNodes.forEach((childN) => deepDelete(addsSet, childN));\r\n}\r\nfunction isParentRemoved(removes, n, mirror) {\r\n if (removes.length === 0)\r\n return false;\r\n return _isParentRemoved(removes, n, mirror);\r\n}\r\nfunction _isParentRemoved(removes, n, mirror) {\r\n const { parentNode } = n;\r\n if (!parentNode) {\r\n return false;\r\n }\r\n const parentId = mirror.getId(parentNode);\r\n if (removes.some((r) => r.id === parentId)) {\r\n return true;\r\n }\r\n return _isParentRemoved(removes, parentNode, mirror);\r\n}\r\nfunction isAncestorInSet(set, n) {\r\n if (set.size === 0)\r\n return false;\r\n return _isAncestorInSet(set, n);\r\n}\r\nfunction _isAncestorInSet(set, n) {\r\n const { parentNode } = n;\r\n if (!parentNode) {\r\n return false;\r\n }\r\n if (set.has(parentNode)) {\r\n return true;\r\n }\r\n return _isAncestorInSet(set, parentNode);\r\n}\n\nexport { MutationBuffer as default };\n", "let errorHandler;\r\nfunction registerErrorHandler(handler) {\r\n errorHandler = handler;\r\n}\r\nfunction unregisterErrorHandler() {\r\n errorHandler = undefined;\r\n}\r\nconst callbackWrapper = (cb) => {\r\n if (!errorHandler) {\r\n return cb;\r\n }\r\n const rrwebWrapped = ((...rest) => {\r\n try {\r\n return cb(...rest);\r\n }\r\n catch (error) {\r\n if (errorHandler && errorHandler(error) === true) {\r\n return () => {\r\n };\r\n }\r\n throw error;\r\n }\r\n });\r\n return rrwebWrapped;\r\n};\n\nexport { callbackWrapper, registerErrorHandler, unregisterErrorHandler };\n", "import { toLowerCase, toUpperCase, getInputType, getInputValue, shouldMaskInput, needMaskingText, maskInputValue } from '../../../rrweb-snapshot/es/rrweb-snapshot.js';\nimport { on, throttle, isBlocked, getWindowScroll, hookSetter, patch, setTimeout, legacy_isTouchEvent, nowTimestamp, getWindowHeight, getWindowWidth } from '../utils.js';\nimport { MouseInteractions, IncrementalSource, PointerTypes } from '../../../types/dist/rrweb-types.js';\nimport MutationBuffer from './mutation.js';\nimport { callbackWrapper } from './error-handler.js';\n\nconst mutationBuffers = [];\r\nfunction getEventTarget(event) {\r\n try {\r\n if ('composedPath' in event) {\r\n const path = event.composedPath();\r\n if (path.length) {\r\n return path[0];\r\n }\r\n }\r\n else if ('path' in event && event.path.length) {\r\n return event.path[0];\r\n }\r\n }\r\n catch {\r\n }\r\n return event && event.target;\r\n}\r\nfunction initMutationObserver(options, rootEl) {\r\n const mutationBuffer = new MutationBuffer();\r\n mutationBuffers.push(mutationBuffer);\r\n mutationBuffer.init(options);\r\n let mutationObserverCtor = window.MutationObserver ||\r\n window.__rrMutationObserver;\r\n const angularZoneSymbol = window?.Zone?.__symbol__?.('MutationObserver');\r\n if (angularZoneSymbol &&\r\n window[angularZoneSymbol]) {\r\n mutationObserverCtor = window[angularZoneSymbol];\r\n }\r\n const observer = new mutationObserverCtor(callbackWrapper((mutations) => {\r\n if (options.onMutation && options.onMutation(mutations) === false) {\r\n return;\r\n }\r\n mutationBuffer.processMutations.bind(mutationBuffer)(mutations);\r\n }));\r\n observer.observe(rootEl, {\r\n attributes: true,\r\n attributeOldValue: true,\r\n characterData: true,\r\n characterDataOldValue: true,\r\n childList: true,\r\n subtree: true,\r\n });\r\n return observer;\r\n}\r\nfunction initMoveObserver({ mousemoveCb, sampling, doc, mirror, }) {\r\n if (sampling.mousemove === false) {\r\n return () => {\r\n };\r\n }\r\n const threshold = typeof sampling.mousemove === 'number' ? sampling.mousemove : 50;\r\n const callbackThreshold = typeof sampling.mousemoveCallback === 'number'\r\n ? sampling.mousemoveCallback\r\n : 500;\r\n let positions = [];\r\n let timeBaseline;\r\n const wrappedCb = throttle(callbackWrapper((source) => {\r\n const totalOffset = Date.now() - timeBaseline;\r\n mousemoveCb(positions.map((p) => {\r\n p.timeOffset -= totalOffset;\r\n return p;\r\n }), source);\r\n positions = [];\r\n timeBaseline = null;\r\n }), callbackThreshold);\r\n const updatePosition = callbackWrapper(throttle(callbackWrapper((evt) => {\r\n const target = getEventTarget(evt);\r\n const { clientX, clientY } = legacy_isTouchEvent(evt)\r\n ? evt.changedTouches[0]\r\n : evt;\r\n if (!timeBaseline) {\r\n timeBaseline = nowTimestamp();\r\n }\r\n positions.push({\r\n x: clientX,\r\n y: clientY,\r\n id: mirror.getId(target),\r\n timeOffset: nowTimestamp() - timeBaseline,\r\n });\r\n wrappedCb(typeof DragEvent !== 'undefined' && evt instanceof DragEvent\r\n ? IncrementalSource.Drag\r\n : evt instanceof MouseEvent\r\n ? IncrementalSource.MouseMove\r\n : IncrementalSource.TouchMove);\r\n }), threshold, {\r\n trailing: false,\r\n }));\r\n const handlers = [\r\n on('mousemove', updatePosition, doc),\r\n on('touchmove', updatePosition, doc),\r\n on('drag', updatePosition, doc),\r\n ];\r\n return callbackWrapper(() => {\r\n handlers.forEach((h) => h());\r\n });\r\n}\r\nfunction initMouseInteractionObserver({ mouseInteractionCb, doc, mirror, blockClass, blockSelector, unblockSelector, sampling, }) {\r\n if (sampling.mouseInteraction === false) {\r\n return () => {\r\n };\r\n }\r\n const disableMap = sampling.mouseInteraction === true ||\r\n sampling.mouseInteraction === undefined\r\n ? {}\r\n : sampling.mouseInteraction;\r\n const handlers = [];\r\n let currentPointerType = null;\r\n const getHandler = (eventKey) => {\r\n return (event) => {\r\n const target = getEventTarget(event);\r\n if (isBlocked(target, blockClass, blockSelector, unblockSelector, true)) {\r\n return;\r\n }\r\n let pointerType = null;\r\n let thisEventKey = eventKey;\r\n if ('pointerType' in event) {\r\n switch (event.pointerType) {\r\n case 'mouse':\r\n pointerType = PointerTypes.Mouse;\r\n break;\r\n case 'touch':\r\n pointerType = PointerTypes.Touch;\r\n break;\r\n case 'pen':\r\n pointerType = PointerTypes.Pen;\r\n break;\r\n }\r\n if (pointerType === PointerTypes.Touch) {\r\n if (MouseInteractions[eventKey] === MouseInteractions.MouseDown) {\r\n thisEventKey = 'TouchStart';\r\n }\r\n else if (MouseInteractions[eventKey] === MouseInteractions.MouseUp) {\r\n thisEventKey = 'TouchEnd';\r\n }\r\n }\r\n else if (pointerType === PointerTypes.Pen) ;\r\n }\r\n else if (legacy_isTouchEvent(event)) {\r\n pointerType = PointerTypes.Touch;\r\n }\r\n if (pointerType !== null) {\r\n currentPointerType = pointerType;\r\n if ((thisEventKey.startsWith('Touch') &&\r\n pointerType === PointerTypes.Touch) ||\r\n (thisEventKey.startsWith('Mouse') &&\r\n pointerType === PointerTypes.Mouse)) {\r\n pointerType = null;\r\n }\r\n }\r\n else if (MouseInteractions[eventKey] === MouseInteractions.Click) {\r\n pointerType = currentPointerType;\r\n currentPointerType = null;\r\n }\r\n const e = legacy_isTouchEvent(event) ? event.changedTouches[0] : event;\r\n if (!e) {\r\n return;\r\n }\r\n const id = mirror.getId(target);\r\n const { clientX, clientY } = e;\r\n callbackWrapper(mouseInteractionCb)({\r\n type: MouseInteractions[thisEventKey],\r\n id,\r\n x: clientX,\r\n y: clientY,\r\n ...(pointerType !== null && { pointerType }),\r\n });\r\n };\r\n };\r\n Object.keys(MouseInteractions)\r\n .filter((key) => Number.isNaN(Number(key)) &&\r\n !key.endsWith('_Departed') &&\r\n disableMap[key] !== false)\r\n .forEach((eventKey) => {\r\n let eventName = toLowerCase(eventKey);\r\n const handler = getHandler(eventKey);\r\n if (window.PointerEvent) {\r\n switch (MouseInteractions[eventKey]) {\r\n case MouseInteractions.MouseDown:\r\n case MouseInteractions.MouseUp:\r\n eventName = eventName.replace('mouse', 'pointer');\r\n break;\r\n case MouseInteractions.TouchStart:\r\n case MouseInteractions.TouchEnd:\r\n return;\r\n }\r\n }\r\n handlers.push(on(eventName, handler, doc));\r\n });\r\n return callbackWrapper(() => {\r\n handlers.forEach((h) => h());\r\n });\r\n}\r\nfunction initScrollObserver({ scrollCb, doc, mirror, blockClass, blockSelector, unblockSelector, sampling, }) {\r\n const updatePosition = callbackWrapper(throttle(callbackWrapper((evt) => {\r\n const target = getEventTarget(evt);\r\n if (!target ||\r\n isBlocked(target, blockClass, blockSelector, unblockSelector, true)) {\r\n return;\r\n }\r\n const id = mirror.getId(target);\r\n if (target === doc && doc.defaultView) {\r\n const scrollLeftTop = getWindowScroll(doc.defaultView);\r\n scrollCb({\r\n id,\r\n x: scrollLeftTop.left,\r\n y: scrollLeftTop.top,\r\n });\r\n }\r\n else {\r\n scrollCb({\r\n id,\r\n x: target.scrollLeft,\r\n y: target.scrollTop,\r\n });\r\n }\r\n }), sampling.scroll || 100));\r\n return on('scroll', updatePosition, doc);\r\n}\r\nfunction initViewportResizeObserver({ viewportResizeCb }, { win }) {\r\n let lastH = -1;\r\n let lastW = -1;\r\n const updateDimension = callbackWrapper(throttle(callbackWrapper(() => {\r\n const height = getWindowHeight();\r\n const width = getWindowWidth();\r\n if (lastH !== height || lastW !== width) {\r\n viewportResizeCb({\r\n width: Number(width),\r\n height: Number(height),\r\n });\r\n lastH = height;\r\n lastW = width;\r\n }\r\n }), 200));\r\n return on('resize', updateDimension, win);\r\n}\r\nconst INPUT_TAGS = ['INPUT', 'TEXTAREA', 'SELECT'];\r\nconst lastInputValueMap = new WeakMap();\r\nfunction initInputObserver({ inputCb, doc, mirror, blockClass, blockSelector, unblockSelector, ignoreClass, ignoreSelector, maskInputOptions, maskInputFn, sampling, userTriggeredOnInput, maskTextClass, unmaskTextClass, maskTextSelector, unmaskTextSelector, }) {\r\n function eventHandler(event) {\r\n let target = getEventTarget(event);\r\n const userTriggered = event.isTrusted;\r\n const tagName = target && toUpperCase(target.tagName);\r\n if (tagName === 'OPTION')\r\n target = target.parentElement;\r\n if (!target ||\r\n !tagName ||\r\n INPUT_TAGS.indexOf(tagName) < 0 ||\r\n isBlocked(target, blockClass, blockSelector, unblockSelector, true)) {\r\n return;\r\n }\r\n const el = target;\r\n if (el.classList.contains(ignoreClass) ||\r\n (ignoreSelector && el.matches(ignoreSelector))) {\r\n return;\r\n }\r\n const type = getInputType(target);\r\n let text = getInputValue(el, tagName, type);\r\n let isChecked = false;\r\n const isInputMasked = shouldMaskInput({\r\n maskInputOptions,\r\n tagName,\r\n type,\r\n });\r\n const forceMask = needMaskingText(target, maskTextClass, maskTextSelector, unmaskTextClass, unmaskTextSelector, isInputMasked);\r\n if (type === 'radio' || type === 'checkbox') {\r\n isChecked = target.checked;\r\n }\r\n text = maskInputValue({\r\n isMasked: forceMask,\r\n element: target,\r\n value: text,\r\n maskInputFn,\r\n });\r\n cbWithDedup(target, userTriggeredOnInput\r\n ? { text, isChecked, userTriggered }\r\n : { text, isChecked });\r\n const name = target.name;\r\n if (type === 'radio' && name && isChecked) {\r\n doc\r\n .querySelectorAll(`input[type=\"radio\"][name=\"${name}\"]`)\r\n .forEach((el) => {\r\n if (el !== target) {\r\n const text = maskInputValue({\r\n isMasked: forceMask,\r\n element: el,\r\n value: getInputValue(el, tagName, type),\r\n maskInputFn,\r\n });\r\n cbWithDedup(el, userTriggeredOnInput\r\n ? { text, isChecked: !isChecked, userTriggered: false }\r\n : { text, isChecked: !isChecked });\r\n }\r\n });\r\n }\r\n }\r\n function cbWithDedup(target, v) {\r\n const lastInputValue = lastInputValueMap.get(target);\r\n if (!lastInputValue ||\r\n lastInputValue.text !== v.text ||\r\n lastInputValue.isChecked !== v.isChecked) {\r\n lastInputValueMap.set(target, v);\r\n const id = mirror.getId(target);\r\n callbackWrapper(inputCb)({\r\n ...v,\r\n id,\r\n });\r\n }\r\n }\r\n const events = sampling.input === 'last' ? ['change'] : ['input', 'change'];\r\n const handlers = events.map((eventName) => on(eventName, callbackWrapper(eventHandler), doc));\r\n const currentWindow = doc.defaultView;\r\n if (!currentWindow) {\r\n return () => {\r\n handlers.forEach((h) => h());\r\n };\r\n }\r\n const propertyDescriptor = currentWindow.Object.getOwnPropertyDescriptor(currentWindow.HTMLInputElement.prototype, 'value');\r\n const hookProperties = [\r\n [currentWindow.HTMLInputElement.prototype, 'value'],\r\n [currentWindow.HTMLInputElement.prototype, 'checked'],\r\n [currentWindow.HTMLSelectElement.prototype, 'value'],\r\n [currentWindow.HTMLTextAreaElement.prototype, 'value'],\r\n [currentWindow.HTMLSelectElement.prototype, 'selectedIndex'],\r\n [currentWindow.HTMLOptionElement.prototype, 'selected'],\r\n ];\r\n if (propertyDescriptor && propertyDescriptor.set) {\r\n handlers.push(...hookProperties.map((p) => hookSetter(p[0], p[1], {\r\n set() {\r\n callbackWrapper(eventHandler)({\r\n target: this,\r\n isTrusted: false,\r\n });\r\n },\r\n }, false, currentWindow)));\r\n }\r\n return callbackWrapper(() => {\r\n handlers.forEach((h) => h());\r\n });\r\n}\r\nfunction getNestedCSSRulePositions(rule) {\r\n const positions = [];\r\n function recurse(childRule, pos) {\r\n if ((hasNestedCSSRule('CSSGroupingRule') &&\r\n childRule.parentRule instanceof CSSGroupingRule) ||\r\n (hasNestedCSSRule('CSSMediaRule') &&\r\n childRule.parentRule instanceof CSSMediaRule) ||\r\n (hasNestedCSSRule('CSSSupportsRule') &&\r\n childRule.parentRule instanceof CSSSupportsRule) ||\r\n (hasNestedCSSRule('CSSConditionRule') &&\r\n childRule.parentRule instanceof CSSConditionRule)) {\r\n const rules = Array.from(childRule.parentRule.cssRules);\r\n const index = rules.indexOf(childRule);\r\n pos.unshift(index);\r\n }\r\n else if (childRule.parentStyleSheet) {\r\n const rules = Array.from(childRule.parentStyleSheet.cssRules);\r\n const index = rules.indexOf(childRule);\r\n pos.unshift(index);\r\n }\r\n return pos;\r\n }\r\n return recurse(rule, positions);\r\n}\r\nfunction getIdAndStyleId(sheet, mirror, styleMirror) {\r\n let id, styleId;\r\n if (!sheet)\r\n return {};\r\n if (sheet.ownerNode)\r\n id = mirror.getId(sheet.ownerNode);\r\n else\r\n styleId = styleMirror.getId(sheet);\r\n return {\r\n styleId,\r\n id,\r\n };\r\n}\r\nfunction initStyleSheetObserver({ styleSheetRuleCb, mirror, stylesheetManager }, { win }) {\r\n if (!win.CSSStyleSheet || !win.CSSStyleSheet.prototype) {\r\n return () => {\r\n };\r\n }\r\n const insertRule = win.CSSStyleSheet.prototype.insertRule;\r\n win.CSSStyleSheet.prototype.insertRule = new Proxy(insertRule, {\r\n apply: callbackWrapper((target, thisArg, argumentsList) => {\r\n const [rule, index] = argumentsList;\r\n const { id, styleId } = getIdAndStyleId(thisArg, mirror, stylesheetManager.styleMirror);\r\n if ((id && id !== -1) || (styleId && styleId !== -1)) {\r\n styleSheetRuleCb({\r\n id,\r\n styleId,\r\n adds: [{ rule, index }],\r\n });\r\n }\r\n return target.apply(thisArg, argumentsList);\r\n }),\r\n });\r\n const deleteRule = win.CSSStyleSheet.prototype.deleteRule;\r\n win.CSSStyleSheet.prototype.deleteRule = new Proxy(deleteRule, {\r\n apply: callbackWrapper((target, thisArg, argumentsList) => {\r\n const [index] = argumentsList;\r\n const { id, styleId } = getIdAndStyleId(thisArg, mirror, stylesheetManager.styleMirror);\r\n if ((id && id !== -1) || (styleId && styleId !== -1)) {\r\n styleSheetRuleCb({\r\n id,\r\n styleId,\r\n removes: [{ index }],\r\n });\r\n }\r\n return target.apply(thisArg, argumentsList);\r\n }),\r\n });\r\n let replace;\r\n if (win.CSSStyleSheet.prototype.replace) {\r\n replace = win.CSSStyleSheet.prototype.replace;\r\n win.CSSStyleSheet.prototype.replace = new Proxy(replace, {\r\n apply: callbackWrapper((target, thisArg, argumentsList) => {\r\n const [text] = argumentsList;\r\n const { id, styleId } = getIdAndStyleId(thisArg, mirror, stylesheetManager.styleMirror);\r\n if ((id && id !== -1) || (styleId && styleId !== -1)) {\r\n styleSheetRuleCb({\r\n id,\r\n styleId,\r\n replace: text,\r\n });\r\n }\r\n return target.apply(thisArg, argumentsList);\r\n }),\r\n });\r\n }\r\n let replaceSync;\r\n if (win.CSSStyleSheet.prototype.replaceSync) {\r\n replaceSync = win.CSSStyleSheet.prototype.replaceSync;\r\n win.CSSStyleSheet.prototype.replaceSync = new Proxy(replaceSync, {\r\n apply: callbackWrapper((target, thisArg, argumentsList) => {\r\n const [text] = argumentsList;\r\n const { id, styleId } = getIdAndStyleId(thisArg, mirror, stylesheetManager.styleMirror);\r\n if ((id && id !== -1) || (styleId && styleId !== -1)) {\r\n styleSheetRuleCb({\r\n id,\r\n styleId,\r\n replaceSync: text,\r\n });\r\n }\r\n return target.apply(thisArg, argumentsList);\r\n }),\r\n });\r\n }\r\n const supportedNestedCSSRuleTypes = {};\r\n if (canMonkeyPatchNestedCSSRule('CSSGroupingRule')) {\r\n supportedNestedCSSRuleTypes.CSSGroupingRule = win.CSSGroupingRule;\r\n }\r\n else {\r\n if (canMonkeyPatchNestedCSSRule('CSSMediaRule')) {\r\n supportedNestedCSSRuleTypes.CSSMediaRule = win.CSSMediaRule;\r\n }\r\n if (canMonkeyPatchNestedCSSRule('CSSConditionRule')) {\r\n supportedNestedCSSRuleTypes.CSSConditionRule = win.CSSConditionRule;\r\n }\r\n if (canMonkeyPatchNestedCSSRule('CSSSupportsRule')) {\r\n supportedNestedCSSRuleTypes.CSSSupportsRule = win.CSSSupportsRule;\r\n }\r\n }\r\n const unmodifiedFunctions = {};\r\n Object.entries(supportedNestedCSSRuleTypes).forEach(([typeKey, type]) => {\r\n unmodifiedFunctions[typeKey] = {\r\n insertRule: type.prototype.insertRule,\r\n deleteRule: type.prototype.deleteRule,\r\n };\r\n type.prototype.insertRule = new Proxy(unmodifiedFunctions[typeKey].insertRule, {\r\n apply: callbackWrapper((target, thisArg, argumentsList) => {\r\n const [rule, index] = argumentsList;\r\n const { id, styleId } = getIdAndStyleId(thisArg.parentStyleSheet, mirror, stylesheetManager.styleMirror);\r\n if ((id && id !== -1) || (styleId && styleId !== -1)) {\r\n styleSheetRuleCb({\r\n id,\r\n styleId,\r\n adds: [\r\n {\r\n rule,\r\n index: [\r\n ...getNestedCSSRulePositions(thisArg),\r\n index || 0,\r\n ],\r\n },\r\n ],\r\n });\r\n }\r\n return target.apply(thisArg, argumentsList);\r\n }),\r\n });\r\n type.prototype.deleteRule = new Proxy(unmodifiedFunctions[typeKey].deleteRule, {\r\n apply: callbackWrapper((target, thisArg, argumentsList) => {\r\n const [index] = argumentsList;\r\n const { id, styleId } = getIdAndStyleId(thisArg.parentStyleSheet, mirror, stylesheetManager.styleMirror);\r\n if ((id && id !== -1) || (styleId && styleId !== -1)) {\r\n styleSheetRuleCb({\r\n id,\r\n styleId,\r\n removes: [\r\n { index: [...getNestedCSSRulePositions(thisArg), index] },\r\n ],\r\n });\r\n }\r\n return target.apply(thisArg, argumentsList);\r\n }),\r\n });\r\n });\r\n return callbackWrapper(() => {\r\n win.CSSStyleSheet.prototype.insertRule = insertRule;\r\n win.CSSStyleSheet.prototype.deleteRule = deleteRule;\r\n replace && (win.CSSStyleSheet.prototype.replace = replace);\r\n replaceSync && (win.CSSStyleSheet.prototype.replaceSync = replaceSync);\r\n Object.entries(supportedNestedCSSRuleTypes).forEach(([typeKey, type]) => {\r\n type.prototype.insertRule = unmodifiedFunctions[typeKey].insertRule;\r\n type.prototype.deleteRule = unmodifiedFunctions[typeKey].deleteRule;\r\n });\r\n });\r\n}\r\nfunction initAdoptedStyleSheetObserver({ mirror, stylesheetManager, }, host) {\r\n let hostId = null;\r\n if (host.nodeName === '#document')\r\n hostId = mirror.getId(host);\r\n else\r\n hostId = mirror.getId(host.host);\r\n const patchTarget = host.nodeName === '#document'\r\n ? host.defaultView?.Document\r\n : host.ownerDocument?.defaultView?.ShadowRoot;\r\n const originalPropertyDescriptor = patchTarget?.prototype\r\n ? Object.getOwnPropertyDescriptor(patchTarget?.prototype, 'adoptedStyleSheets')\r\n : undefined;\r\n if (hostId === null ||\r\n hostId === -1 ||\r\n !patchTarget ||\r\n !originalPropertyDescriptor)\r\n return () => {\r\n };\r\n Object.defineProperty(host, 'adoptedStyleSheets', {\r\n configurable: originalPropertyDescriptor.configurable,\r\n enumerable: originalPropertyDescriptor.enumerable,\r\n get() {\r\n return originalPropertyDescriptor.get?.call(this);\r\n },\r\n set(sheets) {\r\n const result = originalPropertyDescriptor.set?.call(this, sheets);\r\n if (hostId !== null && hostId !== -1) {\r\n try {\r\n stylesheetManager.adoptStyleSheets(sheets, hostId);\r\n }\r\n catch (e) {\r\n }\r\n }\r\n return result;\r\n },\r\n });\r\n return callbackWrapper(() => {\r\n Object.defineProperty(host, 'adoptedStyleSheets', {\r\n configurable: originalPropertyDescriptor.configurable,\r\n enumerable: originalPropertyDescriptor.enumerable,\r\n get: originalPropertyDescriptor.get,\r\n set: originalPropertyDescriptor.set,\r\n });\r\n });\r\n}\r\nfunction initStyleDeclarationObserver({ styleDeclarationCb, mirror, ignoreCSSAttributes, stylesheetManager, }, { win }) {\r\n const setProperty = win.CSSStyleDeclaration.prototype.setProperty;\r\n win.CSSStyleDeclaration.prototype.setProperty = new Proxy(setProperty, {\r\n apply: callbackWrapper((target, thisArg, argumentsList) => {\r\n const [property, value, priority] = argumentsList;\r\n if (ignoreCSSAttributes.has(property)) {\r\n return setProperty.apply(thisArg, [property, value, priority]);\r\n }\r\n const { id, styleId } = getIdAndStyleId(thisArg.parentRule?.parentStyleSheet, mirror, stylesheetManager.styleMirror);\r\n if ((id && id !== -1) || (styleId && styleId !== -1)) {\r\n styleDeclarationCb({\r\n id,\r\n styleId,\r\n set: {\r\n property,\r\n value,\r\n priority,\r\n },\r\n index: getNestedCSSRulePositions(thisArg.parentRule),\r\n });\r\n }\r\n return target.apply(thisArg, argumentsList);\r\n }),\r\n });\r\n const removeProperty = win.CSSStyleDeclaration.prototype.removeProperty;\r\n win.CSSStyleDeclaration.prototype.removeProperty = new Proxy(removeProperty, {\r\n apply: callbackWrapper((target, thisArg, argumentsList) => {\r\n const [property] = argumentsList;\r\n if (ignoreCSSAttributes.has(property)) {\r\n return removeProperty.apply(thisArg, [property]);\r\n }\r\n const { id, styleId } = getIdAndStyleId(thisArg.parentRule?.parentStyleSheet, mirror, stylesheetManager.styleMirror);\r\n if ((id && id !== -1) || (styleId && styleId !== -1)) {\r\n styleDeclarationCb({\r\n id,\r\n styleId,\r\n remove: {\r\n property,\r\n },\r\n index: getNestedCSSRulePositions(thisArg.parentRule),\r\n });\r\n }\r\n return target.apply(thisArg, argumentsList);\r\n }),\r\n });\r\n return callbackWrapper(() => {\r\n win.CSSStyleDeclaration.prototype.setProperty = setProperty;\r\n win.CSSStyleDeclaration.prototype.removeProperty = removeProperty;\r\n });\r\n}\r\nfunction initMediaInteractionObserver({ mediaInteractionCb, blockClass, blockSelector, unblockSelector, mirror, sampling, doc, }) {\r\n const handler = callbackWrapper((type) => throttle(callbackWrapper((event) => {\r\n const target = getEventTarget(event);\r\n if (!target ||\r\n isBlocked(target, blockClass, blockSelector, unblockSelector, true)) {\r\n return;\r\n }\r\n const { currentTime, volume, muted, playbackRate } = target;\r\n mediaInteractionCb({\r\n type,\r\n id: mirror.getId(target),\r\n currentTime,\r\n volume,\r\n muted,\r\n playbackRate,\r\n });\r\n }), sampling.media || 500));\r\n const handlers = [\r\n on('play', handler(0), doc),\r\n on('pause', handler(1), doc),\r\n on('seeked', handler(2), doc),\r\n on('volumechange', handler(3), doc),\r\n on('ratechange', handler(4), doc),\r\n ];\r\n return callbackWrapper(() => {\r\n handlers.forEach((h) => h());\r\n });\r\n}\r\nfunction initFontObserver({ fontCb, doc }) {\r\n const win = doc.defaultView;\r\n if (!win) {\r\n return () => {\r\n };\r\n }\r\n const handlers = [];\r\n const fontMap = new WeakMap();\r\n const originalFontFace = win.FontFace;\r\n win.FontFace = function FontFace(family, source, descriptors) {\r\n const fontFace = new originalFontFace(family, source, descriptors);\r\n fontMap.set(fontFace, {\r\n family,\r\n buffer: typeof source !== 'string',\r\n descriptors,\r\n fontSource: typeof source === 'string'\r\n ? source\r\n : JSON.stringify(Array.from(new Uint8Array(source))),\r\n });\r\n return fontFace;\r\n };\r\n const restoreHandler = patch(doc.fonts, 'add', function (original) {\r\n return function (fontFace) {\r\n setTimeout(callbackWrapper(() => {\r\n const p = fontMap.get(fontFace);\r\n if (p) {\r\n fontCb(p);\r\n fontMap.delete(fontFace);\r\n }\r\n }), 0);\r\n return original.apply(this, [fontFace]);\r\n };\r\n });\r\n handlers.push(() => {\r\n win.FontFace = originalFontFace;\r\n });\r\n handlers.push(restoreHandler);\r\n return callbackWrapper(() => {\r\n handlers.forEach((h) => h());\r\n });\r\n}\r\nfunction initSelectionObserver(param) {\r\n const { doc, mirror, blockClass, blockSelector, unblockSelector, selectionCb, } = param;\r\n let collapsed = true;\r\n const updateSelection = callbackWrapper(() => {\r\n const selection = doc.getSelection();\r\n if (!selection || (collapsed && selection?.isCollapsed))\r\n return;\r\n collapsed = selection.isCollapsed || false;\r\n const ranges = [];\r\n const count = selection.rangeCount || 0;\r\n for (let i = 0; i < count; i++) {\r\n const range = selection.getRangeAt(i);\r\n const { startContainer, startOffset, endContainer, endOffset } = range;\r\n const blocked = isBlocked(startContainer, blockClass, blockSelector, unblockSelector, true) ||\r\n isBlocked(endContainer, blockClass, blockSelector, unblockSelector, true);\r\n if (blocked)\r\n continue;\r\n ranges.push({\r\n start: mirror.getId(startContainer),\r\n startOffset,\r\n end: mirror.getId(endContainer),\r\n endOffset,\r\n });\r\n }\r\n selectionCb({ ranges });\r\n });\r\n updateSelection();\r\n return on('selectionchange', updateSelection);\r\n}\r\nfunction initCustomElementObserver({ doc, customElementCb, }) {\r\n const win = doc.defaultView;\r\n if (!win || !win.customElements)\r\n return () => { };\r\n const restoreHandler = patch(win.customElements, 'define', function (original) {\r\n return function (name, constructor, options) {\r\n try {\r\n customElementCb({\r\n define: {\r\n name,\r\n },\r\n });\r\n }\r\n catch (e) {\r\n }\r\n return original.apply(this, [name, constructor, options]);\r\n };\r\n });\r\n return restoreHandler;\r\n}\r\nfunction initObservers(o, _hooks = {}) {\r\n const currentWindow = o.doc.defaultView;\r\n if (!currentWindow) {\r\n return () => {\r\n };\r\n }\r\n const mutationObserver = initMutationObserver(o, o.doc);\r\n const mousemoveHandler = initMoveObserver(o);\r\n const mouseInteractionHandler = initMouseInteractionObserver(o);\r\n const scrollHandler = initScrollObserver(o);\r\n const viewportResizeHandler = initViewportResizeObserver(o, {\r\n win: currentWindow,\r\n });\r\n const inputHandler = initInputObserver(o);\r\n const mediaInteractionHandler = initMediaInteractionObserver(o);\r\n const styleSheetObserver = initStyleSheetObserver(o, { win: currentWindow });\r\n const adoptedStyleSheetObserver = initAdoptedStyleSheetObserver(o, o.doc);\r\n const styleDeclarationObserver = initStyleDeclarationObserver(o, {\r\n win: currentWindow,\r\n });\r\n const fontObserver = o.collectFonts\r\n ? initFontObserver(o)\r\n : () => {\r\n };\r\n const selectionObserver = initSelectionObserver(o);\r\n const customElementObserver = initCustomElementObserver(o);\r\n const pluginHandlers = [];\r\n for (const plugin of o.plugins) {\r\n pluginHandlers.push(plugin.observer(plugin.callback, currentWindow, plugin.options));\r\n }\r\n return callbackWrapper(() => {\r\n mutationBuffers.forEach((b) => b.reset());\r\n mutationObserver.disconnect();\r\n mousemoveHandler();\r\n mouseInteractionHandler();\r\n scrollHandler();\r\n viewportResizeHandler();\r\n inputHandler();\r\n mediaInteractionHandler();\r\n styleSheetObserver();\r\n adoptedStyleSheetObserver();\r\n styleDeclarationObserver();\r\n fontObserver();\r\n selectionObserver();\r\n customElementObserver();\r\n pluginHandlers.forEach((h) => h());\r\n });\r\n}\r\nfunction hasNestedCSSRule(prop) {\r\n return typeof window[prop] !== 'undefined';\r\n}\r\nfunction canMonkeyPatchNestedCSSRule(prop) {\r\n return Boolean(typeof window[prop] !== 'undefined' &&\r\n window[prop].prototype &&\r\n 'insertRule' in window[prop].prototype &&\r\n 'deleteRule' in window[prop].prototype);\r\n}\n\nexport { INPUT_TAGS, initAdoptedStyleSheetObserver, initMutationObserver, initObservers, initScrollObserver, mutationBuffers };\n", "class CrossOriginIframeMirror {\r\n constructor(generateIdFn) {\r\n this.generateIdFn = generateIdFn;\r\n this.iframeIdToRemoteIdMap = new WeakMap();\r\n this.iframeRemoteIdToIdMap = new WeakMap();\r\n }\r\n getId(iframe, remoteId, idToRemoteMap, remoteToIdMap) {\r\n const idToRemoteIdMap = idToRemoteMap || this.getIdToRemoteIdMap(iframe);\r\n const remoteIdToIdMap = remoteToIdMap || this.getRemoteIdToIdMap(iframe);\r\n let id = idToRemoteIdMap.get(remoteId);\r\n if (!id) {\r\n id = this.generateIdFn();\r\n idToRemoteIdMap.set(remoteId, id);\r\n remoteIdToIdMap.set(id, remoteId);\r\n }\r\n return id;\r\n }\r\n getIds(iframe, remoteId) {\r\n const idToRemoteIdMap = this.getIdToRemoteIdMap(iframe);\r\n const remoteIdToIdMap = this.getRemoteIdToIdMap(iframe);\r\n return remoteId.map((id) => this.getId(iframe, id, idToRemoteIdMap, remoteIdToIdMap));\r\n }\r\n getRemoteId(iframe, id, map) {\r\n const remoteIdToIdMap = map || this.getRemoteIdToIdMap(iframe);\r\n if (typeof id !== 'number')\r\n return id;\r\n const remoteId = remoteIdToIdMap.get(id);\r\n if (!remoteId)\r\n return -1;\r\n return remoteId;\r\n }\r\n getRemoteIds(iframe, ids) {\r\n const remoteIdToIdMap = this.getRemoteIdToIdMap(iframe);\r\n return ids.map((id) => this.getRemoteId(iframe, id, remoteIdToIdMap));\r\n }\r\n reset(iframe) {\r\n if (!iframe) {\r\n this.iframeIdToRemoteIdMap = new WeakMap();\r\n this.iframeRemoteIdToIdMap = new WeakMap();\r\n return;\r\n }\r\n this.iframeIdToRemoteIdMap.delete(iframe);\r\n this.iframeRemoteIdToIdMap.delete(iframe);\r\n }\r\n getIdToRemoteIdMap(iframe) {\r\n let idToRemoteIdMap = this.iframeIdToRemoteIdMap.get(iframe);\r\n if (!idToRemoteIdMap) {\r\n idToRemoteIdMap = new Map();\r\n this.iframeIdToRemoteIdMap.set(iframe, idToRemoteIdMap);\r\n }\r\n return idToRemoteIdMap;\r\n }\r\n getRemoteIdToIdMap(iframe) {\r\n let remoteIdToIdMap = this.iframeRemoteIdToIdMap.get(iframe);\r\n if (!remoteIdToIdMap) {\r\n remoteIdToIdMap = new Map();\r\n this.iframeRemoteIdToIdMap.set(iframe, remoteIdToIdMap);\r\n }\r\n return remoteIdToIdMap;\r\n }\r\n}\n\nexport { CrossOriginIframeMirror as default };\n", "import { genId, NodeType } from '../../../rrweb-snapshot/es/rrweb-snapshot.js';\nimport CrossOriginIframeMirror from './cross-origin-iframe-mirror.js';\nimport { EventType, IncrementalSource } from '../../../types/dist/rrweb-types.js';\n\nclass IframeManagerNoop {\r\n constructor() {\r\n this.crossOriginIframeMirror = new CrossOriginIframeMirror(genId);\r\n this.crossOriginIframeRootIdMap = new WeakMap();\r\n }\r\n addIframe() {\r\n }\r\n addLoadListener() {\r\n }\r\n attachIframe() {\r\n }\r\n}\r\nclass IframeManager {\r\n constructor(options) {\r\n this.iframes = new WeakMap();\r\n this.crossOriginIframeMap = new WeakMap();\r\n this.crossOriginIframeMirror = new CrossOriginIframeMirror(genId);\r\n this.crossOriginIframeRootIdMap = new WeakMap();\r\n this.mutationCb = options.mutationCb;\r\n this.wrappedEmit = options.wrappedEmit;\r\n this.stylesheetManager = options.stylesheetManager;\r\n this.recordCrossOriginIframes = options.recordCrossOriginIframes;\r\n this.crossOriginIframeStyleMirror = new CrossOriginIframeMirror(this.stylesheetManager.styleMirror.generateId.bind(this.stylesheetManager.styleMirror));\r\n this.mirror = options.mirror;\r\n if (this.recordCrossOriginIframes) {\r\n window.addEventListener('message', this.handleMessage.bind(this));\r\n }\r\n }\r\n addIframe(iframeEl) {\r\n this.iframes.set(iframeEl, true);\r\n if (iframeEl.contentWindow)\r\n this.crossOriginIframeMap.set(iframeEl.contentWindow, iframeEl);\r\n }\r\n addLoadListener(cb) {\r\n this.loadListener = cb;\r\n }\r\n attachIframe(iframeEl, childSn) {\r\n this.mutationCb({\r\n adds: [\r\n {\r\n parentId: this.mirror.getId(iframeEl),\r\n nextId: null,\r\n node: childSn,\r\n },\r\n ],\r\n removes: [],\r\n texts: [],\r\n attributes: [],\r\n isAttachIframe: true,\r\n });\r\n this.loadListener?.(iframeEl);\r\n if (iframeEl.contentDocument &&\r\n iframeEl.contentDocument.adoptedStyleSheets &&\r\n iframeEl.contentDocument.adoptedStyleSheets.length > 0)\r\n this.stylesheetManager.adoptStyleSheets(iframeEl.contentDocument.adoptedStyleSheets, this.mirror.getId(iframeEl.contentDocument));\r\n }\r\n handleMessage(message) {\r\n const crossOriginMessageEvent = message;\r\n if (crossOriginMessageEvent.data.type !== 'rrweb' ||\r\n crossOriginMessageEvent.origin !== crossOriginMessageEvent.data.origin)\r\n return;\r\n const iframeSourceWindow = message.source;\r\n if (!iframeSourceWindow)\r\n return;\r\n const iframeEl = this.crossOriginIframeMap.get(message.source);\r\n if (!iframeEl)\r\n return;\r\n const transformedEvent = this.transformCrossOriginEvent(iframeEl, crossOriginMessageEvent.data.event);\r\n if (transformedEvent)\r\n this.wrappedEmit(transformedEvent, crossOriginMessageEvent.data.isCheckout);\r\n }\r\n transformCrossOriginEvent(iframeEl, e) {\r\n switch (e.type) {\r\n case EventType.FullSnapshot: {\r\n this.crossOriginIframeMirror.reset(iframeEl);\r\n this.crossOriginIframeStyleMirror.reset(iframeEl);\r\n this.replaceIdOnNode(e.data.node, iframeEl);\r\n const rootId = e.data.node.id;\r\n this.crossOriginIframeRootIdMap.set(iframeEl, rootId);\r\n this.patchRootIdOnNode(e.data.node, rootId);\r\n return {\r\n timestamp: e.timestamp,\r\n type: EventType.IncrementalSnapshot,\r\n data: {\r\n source: IncrementalSource.Mutation,\r\n adds: [\r\n {\r\n parentId: this.mirror.getId(iframeEl),\r\n nextId: null,\r\n node: e.data.node,\r\n },\r\n ],\r\n removes: [],\r\n texts: [],\r\n attributes: [],\r\n isAttachIframe: true,\r\n },\r\n };\r\n }\r\n case EventType.Meta:\r\n case EventType.Load:\r\n case EventType.DomContentLoaded: {\r\n return false;\r\n }\r\n case EventType.Plugin: {\r\n return e;\r\n }\r\n case EventType.Custom: {\r\n this.replaceIds(e.data.payload, iframeEl, ['id', 'parentId', 'previousId', 'nextId']);\r\n return e;\r\n }\r\n case EventType.IncrementalSnapshot: {\r\n switch (e.data.source) {\r\n case IncrementalSource.Mutation: {\r\n e.data.adds.forEach((n) => {\r\n this.replaceIds(n, iframeEl, [\r\n 'parentId',\r\n 'nextId',\r\n 'previousId',\r\n ]);\r\n this.replaceIdOnNode(n.node, iframeEl);\r\n const rootId = this.crossOriginIframeRootIdMap.get(iframeEl);\r\n rootId && this.patchRootIdOnNode(n.node, rootId);\r\n });\r\n e.data.removes.forEach((n) => {\r\n this.replaceIds(n, iframeEl, ['parentId', 'id']);\r\n });\r\n e.data.attributes.forEach((n) => {\r\n this.replaceIds(n, iframeEl, ['id']);\r\n });\r\n e.data.texts.forEach((n) => {\r\n this.replaceIds(n, iframeEl, ['id']);\r\n });\r\n return e;\r\n }\r\n case IncrementalSource.Drag:\r\n case IncrementalSource.TouchMove:\r\n case IncrementalSource.MouseMove: {\r\n e.data.positions.forEach((p) => {\r\n this.replaceIds(p, iframeEl, ['id']);\r\n });\r\n return e;\r\n }\r\n case IncrementalSource.ViewportResize: {\r\n return false;\r\n }\r\n case IncrementalSource.MediaInteraction:\r\n case IncrementalSource.MouseInteraction:\r\n case IncrementalSource.Scroll:\r\n case IncrementalSource.CanvasMutation:\r\n case IncrementalSource.Input: {\r\n this.replaceIds(e.data, iframeEl, ['id']);\r\n return e;\r\n }\r\n case IncrementalSource.StyleSheetRule:\r\n case IncrementalSource.StyleDeclaration: {\r\n this.replaceIds(e.data, iframeEl, ['id']);\r\n this.replaceStyleIds(e.data, iframeEl, ['styleId']);\r\n return e;\r\n }\r\n case IncrementalSource.Font: {\r\n return e;\r\n }\r\n case IncrementalSource.Selection: {\r\n e.data.ranges.forEach((range) => {\r\n this.replaceIds(range, iframeEl, ['start', 'end']);\r\n });\r\n return e;\r\n }\r\n case IncrementalSource.AdoptedStyleSheet: {\r\n this.replaceIds(e.data, iframeEl, ['id']);\r\n this.replaceStyleIds(e.data, iframeEl, ['styleIds']);\r\n e.data.styles?.forEach((style) => {\r\n this.replaceStyleIds(style, iframeEl, ['styleId']);\r\n });\r\n return e;\r\n }\r\n }\r\n }\r\n }\r\n return false;\r\n }\r\n replace(iframeMirror, obj, iframeEl, keys) {\r\n for (const key of keys) {\r\n if (!Array.isArray(obj[key]) && typeof obj[key] !== 'number')\r\n continue;\r\n if (Array.isArray(obj[key])) {\r\n obj[key] = iframeMirror.getIds(iframeEl, obj[key]);\r\n }\r\n else {\r\n obj[key] = iframeMirror.getId(iframeEl, obj[key]);\r\n }\r\n }\r\n return obj;\r\n }\r\n replaceIds(obj, iframeEl, keys) {\r\n return this.replace(this.crossOriginIframeMirror, obj, iframeEl, keys);\r\n }\r\n replaceStyleIds(obj, iframeEl, keys) {\r\n return this.replace(this.crossOriginIframeStyleMirror, obj, iframeEl, keys);\r\n }\r\n replaceIdOnNode(node, iframeEl) {\r\n this.replaceIds(node, iframeEl, ['id', 'rootId']);\r\n if ('childNodes' in node) {\r\n node.childNodes.forEach((child) => {\r\n this.replaceIdOnNode(child, iframeEl);\r\n });\r\n }\r\n }\r\n patchRootIdOnNode(node, rootId) {\r\n if (node.type !== NodeType.Document && !node.rootId)\r\n node.rootId = rootId;\r\n if ('childNodes' in node) {\r\n node.childNodes.forEach((child) => {\r\n this.patchRootIdOnNode(child, rootId);\r\n });\r\n }\r\n }\r\n}\n\nexport { IframeManager, IframeManagerNoop };\n", "import { initMutationObserver, initScrollObserver, initAdoptedStyleSheetObserver } from './observer.js';\nimport { setTimeout, patch, inDom } from '../utils.js';\nimport { isNativeShadowDom } from '../../../rrweb-snapshot/es/rrweb-snapshot.js';\n\nclass ShadowDomManagerNoop {\r\n init() {\r\n }\r\n addShadowRoot() {\r\n }\r\n observeAttachShadow() {\r\n }\r\n reset() {\r\n }\r\n}\r\nclass ShadowDomManager {\r\n constructor(options) {\r\n this.shadowDoms = new WeakSet();\r\n this.restoreHandlers = [];\r\n this.mutationCb = options.mutationCb;\r\n this.scrollCb = options.scrollCb;\r\n this.bypassOptions = options.bypassOptions;\r\n this.mirror = options.mirror;\r\n this.init();\r\n }\r\n init() {\r\n this.reset();\r\n this.patchAttachShadow(Element, document);\r\n }\r\n addShadowRoot(shadowRoot, doc) {\r\n if (!isNativeShadowDom(shadowRoot))\r\n return;\r\n if (this.shadowDoms.has(shadowRoot))\r\n return;\r\n this.shadowDoms.add(shadowRoot);\r\n const observer = initMutationObserver({\r\n ...this.bypassOptions,\r\n doc,\r\n mutationCb: this.mutationCb,\r\n mirror: this.mirror,\r\n shadowDomManager: this,\r\n }, shadowRoot);\r\n this.restoreHandlers.push(() => observer.disconnect());\r\n this.restoreHandlers.push(initScrollObserver({\r\n ...this.bypassOptions,\r\n scrollCb: this.scrollCb,\r\n doc: shadowRoot,\r\n mirror: this.mirror,\r\n }));\r\n setTimeout(() => {\r\n if (shadowRoot.adoptedStyleSheets &&\r\n shadowRoot.adoptedStyleSheets.length > 0)\r\n this.bypassOptions.stylesheetManager.adoptStyleSheets(shadowRoot.adoptedStyleSheets, this.mirror.getId(shadowRoot.host));\r\n this.restoreHandlers.push(initAdoptedStyleSheetObserver({\r\n mirror: this.mirror,\r\n stylesheetManager: this.bypassOptions.stylesheetManager,\r\n }, shadowRoot));\r\n }, 0);\r\n }\r\n observeAttachShadow(iframeElement) {\r\n if (!iframeElement.contentWindow || !iframeElement.contentDocument)\r\n return;\r\n this.patchAttachShadow(iframeElement.contentWindow.Element, iframeElement.contentDocument);\r\n }\r\n patchAttachShadow(element, doc) {\r\n const manager = this;\r\n this.restoreHandlers.push(patch(element.prototype, 'attachShadow', function (original) {\r\n return function (option) {\r\n const shadowRoot = original.call(this, option);\r\n if (this.shadowRoot && inDom(this))\r\n manager.addShadowRoot(this.shadowRoot, doc);\r\n return shadowRoot;\r\n };\r\n }));\r\n }\r\n reset() {\r\n this.restoreHandlers.forEach((handler) => {\r\n try {\r\n handler();\r\n }\r\n catch (e) {\r\n }\r\n });\r\n this.restoreHandlers = [];\r\n this.shadowDoms = new WeakSet();\r\n }\r\n}\n\nexport { ShadowDomManager, ShadowDomManagerNoop };\n", "import { onRequestAnimationFrame, isBlocked } from '../../../utils.js';\nimport { CanvasContext } from '../../../../../types/dist/rrweb-types.js';\nimport initCanvas2DMutationObserver from './2d.js';\nimport initCanvasContextObserver from './canvas.js';\nimport initCanvasWebGLMutationObserver from './webgl.js';\nimport { getImageBitmapDataUrlWorkerURL as t } from '../../../../../rrweb-worker/es/rrweb-worker/index.js';\nimport { callbackWrapper, registerErrorHandler } from '../../error-handler.js';\n\nclass CanvasManagerNoop {\r\n reset() {\r\n }\r\n freeze() {\r\n }\r\n unfreeze() {\r\n }\r\n lock() {\r\n }\r\n unlock() {\r\n }\r\n snapshot() {\r\n }\r\n}\r\nclass CanvasManager {\r\n reset() {\r\n this.pendingCanvasMutations.clear();\r\n this.resetObservers && this.resetObservers();\r\n }\r\n freeze() {\r\n this.frozen = true;\r\n }\r\n unfreeze() {\r\n this.frozen = false;\r\n }\r\n lock() {\r\n this.locked = true;\r\n }\r\n unlock() {\r\n this.locked = false;\r\n }\r\n constructor(options) {\r\n this.pendingCanvasMutations = new Map();\r\n this.rafStamps = { latestId: 0, invokeId: null };\r\n this.frozen = false;\r\n this.locked = false;\r\n this.processMutation = (target, mutation) => {\r\n const newFrame = this.rafStamps.invokeId &&\r\n this.rafStamps.latestId !== this.rafStamps.invokeId;\r\n if (newFrame || !this.rafStamps.invokeId)\r\n this.rafStamps.invokeId = this.rafStamps.latestId;\r\n if (!this.pendingCanvasMutations.has(target)) {\r\n this.pendingCanvasMutations.set(target, []);\r\n }\r\n this.pendingCanvasMutations.get(target).push(mutation);\r\n };\r\n const { sampling = 'all', win, blockClass, blockSelector, unblockSelector, maxCanvasSize, recordCanvas, dataURLOptions, errorHandler, } = options;\r\n this.mutationCb = options.mutationCb;\r\n this.mirror = options.mirror;\r\n this.options = options;\r\n if (errorHandler) {\r\n registerErrorHandler(errorHandler);\r\n }\r\n if (options.enableManualSnapshot) {\r\n return;\r\n }\r\n callbackWrapper(() => {\r\n if (recordCanvas && sampling === 'all')\r\n this.initCanvasMutationObserver(win, blockClass, blockSelector, unblockSelector);\r\n if (recordCanvas && typeof sampling === 'number')\r\n this.initCanvasFPSObserver(sampling, win, blockClass, blockSelector, unblockSelector, maxCanvasSize, {\r\n dataURLOptions,\r\n });\r\n })();\r\n }\r\n initCanvasFPSObserver(fps, win, blockClass, blockSelector, unblockSelector, maxCanvasSize, options) {\r\n const canvasContextReset = initCanvasContextObserver(win, blockClass, blockSelector, unblockSelector, true);\r\n const rafId = this.takeSnapshot(false, fps, win, blockClass, blockSelector, unblockSelector, maxCanvasSize, options.dataURLOptions);\r\n this.resetObservers = () => {\r\n canvasContextReset();\r\n cancelAnimationFrame(rafId);\r\n };\r\n }\r\n initCanvasMutationObserver(win, blockClass, blockSelector, unblockSelector) {\r\n this.startRAFTimestamping();\r\n this.startPendingCanvasMutationFlusher();\r\n const canvasContextReset = initCanvasContextObserver(win, blockClass, blockSelector, unblockSelector, false);\r\n const canvas2DReset = initCanvas2DMutationObserver(this.processMutation.bind(this), win, blockClass, blockSelector, unblockSelector);\r\n const canvasWebGL1and2Reset = initCanvasWebGLMutationObserver(this.processMutation.bind(this), win, blockClass, blockSelector, unblockSelector, this.mirror);\r\n this.resetObservers = () => {\r\n canvasContextReset();\r\n canvas2DReset();\r\n canvasWebGL1and2Reset();\r\n };\r\n }\r\n snapshot(canvasElement) {\r\n const { options } = this;\r\n const rafId = this.takeSnapshot(true, options.sampling === 'all' ? 2 : options.sampling || 2, options.win, options.blockClass, options.blockSelector, options.unblockSelector, options.maxCanvasSize, options.dataURLOptions, canvasElement);\r\n this.resetObservers = () => {\r\n cancelAnimationFrame(rafId);\r\n };\r\n }\r\n takeSnapshot(isManualSnapshot, fps, win, blockClass, blockSelector, unblockSelector, maxCanvasSize, dataURLOptions, canvasElement) {\r\n const snapshotInProgressMap = new Map();\r\n const worker = new Worker(t());\r\n worker.onmessage = (e) => {\r\n const data = e.data;\r\n const { id } = data;\r\n snapshotInProgressMap.set(id, false);\r\n if (!('base64' in data))\r\n return;\r\n const { base64, type, width, height } = data;\r\n this.mutationCb({\r\n id,\r\n type: CanvasContext['2D'],\r\n commands: [\r\n {\r\n property: 'clearRect',\r\n args: [0, 0, width, height],\r\n },\r\n {\r\n property: 'drawImage',\r\n args: [\r\n {\r\n rr_type: 'ImageBitmap',\r\n args: [\r\n {\r\n rr_type: 'Blob',\r\n data: [{ rr_type: 'ArrayBuffer', base64 }],\r\n type,\r\n },\r\n ],\r\n },\r\n 0,\r\n 0,\r\n width,\r\n height,\r\n ],\r\n },\r\n ],\r\n });\r\n };\r\n const timeBetweenSnapshots = 1000 / fps;\r\n let lastSnapshotTime = 0;\r\n let rafId;\r\n const getCanvas = (canvasElement) => {\r\n if (canvasElement) {\r\n return [canvasElement];\r\n }\r\n const matchedCanvas = [];\r\n win.document.querySelectorAll('canvas').forEach((canvas) => {\r\n if (!isBlocked(canvas, blockClass, blockSelector, unblockSelector, true)) {\r\n matchedCanvas.push(canvas);\r\n }\r\n });\r\n return matchedCanvas;\r\n };\r\n const takeCanvasSnapshots = (timestamp) => {\r\n if (lastSnapshotTime &&\r\n timestamp - lastSnapshotTime < timeBetweenSnapshots) {\r\n rafId = onRequestAnimationFrame(takeCanvasSnapshots);\r\n return;\r\n }\r\n lastSnapshotTime = timestamp;\r\n getCanvas(canvasElement).forEach((canvas) => {\r\n const id = this.mirror.getId(canvas);\r\n if (snapshotInProgressMap.get(id))\r\n return;\r\n if (!canvas.width || !canvas.height)\r\n return;\r\n snapshotInProgressMap.set(id, true);\r\n if (!isManualSnapshot &&\r\n ['webgl', 'webgl2'].includes(canvas.__context)) {\r\n const context = canvas.getContext(canvas.__context);\r\n if (context?.getContextAttributes()?.preserveDrawingBuffer === false) {\r\n context.clear(context.COLOR_BUFFER_BIT);\r\n }\r\n }\r\n createImageBitmap(canvas)\r\n .then((bitmap) => {\r\n worker.postMessage({\r\n id,\r\n bitmap,\r\n width: canvas.width,\r\n height: canvas.height,\r\n dataURLOptions,\r\n maxCanvasSize,\r\n }, [bitmap]);\r\n })\r\n .catch((error) => {\r\n callbackWrapper(() => {\r\n throw error;\r\n })();\r\n });\r\n });\r\n rafId = onRequestAnimationFrame(takeCanvasSnapshots);\r\n };\r\n rafId = onRequestAnimationFrame(takeCanvasSnapshots);\r\n return rafId;\r\n }\r\n startPendingCanvasMutationFlusher() {\r\n onRequestAnimationFrame(() => this.flushPendingCanvasMutations());\r\n }\r\n startRAFTimestamping() {\r\n const setLatestRAFTimestamp = (timestamp) => {\r\n this.rafStamps.latestId = timestamp;\r\n onRequestAnimationFrame(setLatestRAFTimestamp);\r\n };\r\n onRequestAnimationFrame(setLatestRAFTimestamp);\r\n }\r\n flushPendingCanvasMutations() {\r\n this.pendingCanvasMutations.forEach((values, canvas) => {\r\n const id = this.mirror.getId(canvas);\r\n this.flushPendingCanvasMutationFor(canvas, id);\r\n });\r\n onRequestAnimationFrame(() => this.flushPendingCanvasMutations());\r\n }\r\n flushPendingCanvasMutationFor(canvas, id) {\r\n if (this.frozen || this.locked) {\r\n return;\r\n }\r\n const valuesWithType = this.pendingCanvasMutations.get(canvas);\r\n if (!valuesWithType || id === -1)\r\n return;\r\n const values = valuesWithType.map((value) => {\r\n const { type, ...rest } = value;\r\n return rest;\r\n });\r\n const { type } = valuesWithType[0];\r\n this.mutationCb({ id, type, commands: values });\r\n this.pendingCanvasMutations.delete(canvas);\r\n }\r\n}\n\nexport { CanvasManager, CanvasManagerNoop };\n", "import { stringifyRule } from '../../../rrweb-snapshot/es/rrweb-snapshot.js';\nimport { StyleSheetMirror } from '../utils.js';\n\nclass StylesheetManager {\r\n constructor(options) {\r\n this.trackedLinkElements = new WeakSet();\r\n this.styleMirror = new StyleSheetMirror();\r\n this.mutationCb = options.mutationCb;\r\n this.adoptedStyleSheetCb = options.adoptedStyleSheetCb;\r\n }\r\n attachLinkElement(linkEl, childSn) {\r\n if ('_cssText' in childSn.attributes)\r\n this.mutationCb({\r\n adds: [],\r\n removes: [],\r\n texts: [],\r\n attributes: [\r\n {\r\n id: childSn.id,\r\n attributes: childSn\r\n .attributes,\r\n },\r\n ],\r\n });\r\n this.trackLinkElement(linkEl);\r\n }\r\n trackLinkElement(linkEl) {\r\n if (this.trackedLinkElements.has(linkEl))\r\n return;\r\n this.trackedLinkElements.add(linkEl);\r\n this.trackStylesheetInLinkElement(linkEl);\r\n }\r\n adoptStyleSheets(sheets, hostId) {\r\n if (sheets.length === 0)\r\n return;\r\n const adoptedStyleSheetData = {\r\n id: hostId,\r\n styleIds: [],\r\n };\r\n const styles = [];\r\n for (const sheet of sheets) {\r\n let styleId;\r\n if (!this.styleMirror.has(sheet)) {\r\n styleId = this.styleMirror.add(sheet);\r\n styles.push({\r\n styleId,\r\n rules: Array.from(sheet.rules || CSSRule, (r, index) => ({\r\n rule: stringifyRule(r),\r\n index,\r\n })),\r\n });\r\n }\r\n else\r\n styleId = this.styleMirror.getId(sheet);\r\n adoptedStyleSheetData.styleIds.push(styleId);\r\n }\r\n if (styles.length > 0)\r\n adoptedStyleSheetData.styles = styles;\r\n this.adoptedStyleSheetCb(adoptedStyleSheetData);\r\n }\r\n reset() {\r\n this.styleMirror.reset();\r\n this.trackedLinkElements = new WeakSet();\r\n }\r\n trackStylesheetInLinkElement(linkEl) {\r\n }\r\n}\n\nexport { StylesheetManager };\n", "import { onRequestAnimationFrame } from '../utils.js';\n\nclass ProcessedNodeManager {\r\n constructor() {\r\n this.nodeMap = new WeakMap();\r\n this.loop = true;\r\n this.periodicallyClear();\r\n }\r\n periodicallyClear() {\r\n onRequestAnimationFrame(() => {\r\n this.clear();\r\n if (this.loop)\r\n this.periodicallyClear();\r\n });\r\n }\r\n inOtherBuffer(node, thisBuffer) {\r\n const buffers = this.nodeMap.get(node);\r\n return (buffers && Array.from(buffers).some((buffer) => buffer !== thisBuffer));\r\n }\r\n add(node, buffer) {\r\n this.nodeMap.set(node, (this.nodeMap.get(node) || new Set()).add(buffer));\r\n }\r\n clear() {\r\n this.nodeMap = new WeakMap();\r\n }\r\n destroy() {\r\n this.loop = false;\r\n }\r\n}\n\nexport { ProcessedNodeManager as default };\n", "import { createMirror, snapshot } from '../../../rrweb-snapshot/es/rrweb-snapshot.js';\nimport { initObservers, mutationBuffers } from './observer.js';\nimport { polyfill, on, nowTimestamp, getWindowWidth, getWindowHeight, getWindowScroll, isSerializedIframe, isSerializedStylesheet, hasShadowRoot } from '../utils.js';\nimport { EventType, IncrementalSource } from '../../../types/dist/rrweb-types.js';\nimport { IframeManagerNoop, IframeManager } from './iframe-manager.js';\nimport { ShadowDomManagerNoop, ShadowDomManager } from './shadow-dom-manager.js';\nimport { CanvasManagerNoop } from './observers/canvas/canvas-manager.js';\nexport { CanvasManager } from './observers/canvas/canvas-manager.js';\nimport { StylesheetManager } from './stylesheet-manager.js';\nimport ProcessedNodeManager from './processed-node-manager.js';\nimport { callbackWrapper, unregisterErrorHandler, registerErrorHandler } from './error-handler.js';\n\nlet wrappedEmit;\r\nlet _wrappedEmit;\r\nlet _takeFullSnapshot;\r\nconst mirror = createMirror();\r\nfunction record(options = {}) {\r\n const { emit, checkoutEveryNms, checkoutEveryNth, blockClass = 'rr-block', blockSelector = null, unblockSelector = null, ignoreClass = 'rr-ignore', ignoreSelector = null, maskAllText = false, maskTextClass = 'rr-mask', unmaskTextClass = null, maskTextSelector = null, unmaskTextSelector = null, inlineStylesheet = true, maskAllInputs, maskInputOptions: _maskInputOptions, slimDOMOptions: _slimDOMOptions, maskAttributeFn, maskInputFn, maskTextFn, maxCanvasSize = null, packFn, sampling = {}, dataURLOptions = {}, mousemoveWait, recordCanvas = false, recordCrossOriginIframes = false, recordAfter = options.recordAfter === 'DOMContentLoaded'\r\n ? options.recordAfter\r\n : 'load', userTriggeredOnInput = false, collectFonts = false, inlineImages = false, plugins, keepIframeSrcFn = () => false, ignoreCSSAttributes = new Set([]), errorHandler, onMutation, getCanvasManager, } = options;\r\n registerErrorHandler(errorHandler);\r\n const inEmittingFrame = recordCrossOriginIframes\r\n ? window.parent === window\r\n : true;\r\n let passEmitsToParent = false;\r\n if (!inEmittingFrame) {\r\n try {\r\n if (window.parent.document) {\r\n passEmitsToParent = false;\r\n }\r\n }\r\n catch (e) {\r\n passEmitsToParent = true;\r\n }\r\n }\r\n if (inEmittingFrame && !emit) {\r\n throw new Error('emit function is required');\r\n }\r\n if (mousemoveWait !== undefined && sampling.mousemove === undefined) {\r\n sampling.mousemove = mousemoveWait;\r\n }\r\n mirror.reset();\r\n const maskInputOptions = maskAllInputs === true\r\n ? {\r\n color: true,\r\n date: true,\r\n 'datetime-local': true,\r\n email: true,\r\n month: true,\r\n number: true,\r\n range: true,\r\n search: true,\r\n tel: true,\r\n text: true,\r\n time: true,\r\n url: true,\r\n week: true,\r\n textarea: true,\r\n select: true,\r\n radio: true,\r\n checkbox: true,\r\n }\r\n : _maskInputOptions !== undefined\r\n ? _maskInputOptions\r\n : {};\r\n const slimDOMOptions = _slimDOMOptions === true || _slimDOMOptions === 'all'\r\n ? {\r\n script: true,\r\n comment: true,\r\n headFavicon: true,\r\n headWhitespace: true,\r\n headMetaSocial: true,\r\n headMetaRobots: true,\r\n headMetaHttpEquiv: true,\r\n headMetaVerification: true,\r\n headMetaAuthorship: _slimDOMOptions === 'all',\r\n headMetaDescKeywords: _slimDOMOptions === 'all',\r\n }\r\n : _slimDOMOptions\r\n ? _slimDOMOptions\r\n : {};\r\n polyfill();\r\n let lastFullSnapshotEvent;\r\n let incrementalSnapshotCount = 0;\r\n const eventProcessor = (e) => {\r\n for (const plugin of plugins || []) {\r\n if (plugin.eventProcessor) {\r\n e = plugin.eventProcessor(e);\r\n }\r\n }\r\n if (packFn &&\r\n !passEmitsToParent) {\r\n e = packFn(e);\r\n }\r\n return e;\r\n };\r\n wrappedEmit = (r, isCheckout) => {\r\n const e = r;\r\n e.timestamp = nowTimestamp();\r\n if (mutationBuffers[0]?.isFrozen() &&\r\n e.type !== EventType.FullSnapshot &&\r\n !(e.type === EventType.IncrementalSnapshot &&\r\n e.data.source === IncrementalSource.Mutation)) {\r\n mutationBuffers.forEach((buf) => buf.unfreeze());\r\n }\r\n if (inEmittingFrame) {\r\n emit?.(eventProcessor(e), isCheckout);\r\n }\r\n else if (passEmitsToParent) {\r\n const message = {\r\n type: 'rrweb',\r\n event: eventProcessor(e),\r\n origin: window.location.origin,\r\n isCheckout,\r\n };\r\n window.parent.postMessage(message, '*');\r\n }\r\n if (e.type === EventType.FullSnapshot) {\r\n lastFullSnapshotEvent = e;\r\n incrementalSnapshotCount = 0;\r\n }\r\n else if (e.type === EventType.IncrementalSnapshot) {\r\n if (e.data.source === IncrementalSource.Mutation &&\r\n e.data.isAttachIframe) {\r\n return;\r\n }\r\n incrementalSnapshotCount++;\r\n const exceedCount = checkoutEveryNth && incrementalSnapshotCount >= checkoutEveryNth;\r\n const exceedTime = checkoutEveryNms &&\r\n lastFullSnapshotEvent &&\r\n e.timestamp - lastFullSnapshotEvent.timestamp > checkoutEveryNms;\r\n if (exceedCount || exceedTime) {\r\n takeFullSnapshot(true);\r\n }\r\n }\r\n };\r\n _wrappedEmit = wrappedEmit;\r\n const wrappedMutationEmit = (m) => {\r\n wrappedEmit({\r\n type: EventType.IncrementalSnapshot,\r\n data: {\r\n source: IncrementalSource.Mutation,\r\n ...m,\r\n },\r\n });\r\n };\r\n const wrappedScrollEmit = (p) => wrappedEmit({\r\n type: EventType.IncrementalSnapshot,\r\n data: {\r\n source: IncrementalSource.Scroll,\r\n ...p,\r\n },\r\n });\r\n const wrappedCanvasMutationEmit = (p) => wrappedEmit({\r\n type: EventType.IncrementalSnapshot,\r\n data: {\r\n source: IncrementalSource.CanvasMutation,\r\n ...p,\r\n },\r\n });\r\n const wrappedAdoptedStyleSheetEmit = (a) => wrappedEmit({\r\n type: EventType.IncrementalSnapshot,\r\n data: {\r\n source: IncrementalSource.AdoptedStyleSheet,\r\n ...a,\r\n },\r\n });\r\n const stylesheetManager = new StylesheetManager({\r\n mutationCb: wrappedMutationEmit,\r\n adoptedStyleSheetCb: wrappedAdoptedStyleSheetEmit,\r\n });\r\n const iframeManager = typeof __RRWEB_EXCLUDE_IFRAME__ === 'boolean' && __RRWEB_EXCLUDE_IFRAME__\r\n ? new IframeManagerNoop()\r\n : new IframeManager({\r\n mirror,\r\n mutationCb: wrappedMutationEmit,\r\n stylesheetManager: stylesheetManager,\r\n recordCrossOriginIframes,\r\n wrappedEmit,\r\n });\r\n for (const plugin of plugins || []) {\r\n if (plugin.getMirror)\r\n plugin.getMirror({\r\n nodeMirror: mirror,\r\n crossOriginIframeMirror: iframeManager.crossOriginIframeMirror,\r\n crossOriginIframeStyleMirror: iframeManager.crossOriginIframeStyleMirror,\r\n });\r\n }\r\n const processedNodeManager = new ProcessedNodeManager();\r\n const canvasManager = _getCanvasManager(getCanvasManager, {\r\n mirror,\r\n win: window,\r\n mutationCb: (p) => wrappedEmit({\r\n type: EventType.IncrementalSnapshot,\r\n data: {\r\n source: IncrementalSource.CanvasMutation,\r\n ...p,\r\n },\r\n }),\r\n recordCanvas,\r\n blockClass,\r\n blockSelector,\r\n unblockSelector,\r\n maxCanvasSize,\r\n sampling: sampling['canvas'],\r\n dataURLOptions,\r\n errorHandler,\r\n });\r\n const shadowDomManager = typeof __RRWEB_EXCLUDE_SHADOW_DOM__ === 'boolean' &&\r\n __RRWEB_EXCLUDE_SHADOW_DOM__\r\n ? new ShadowDomManagerNoop()\r\n : new ShadowDomManager({\r\n mutationCb: wrappedMutationEmit,\r\n scrollCb: wrappedScrollEmit,\r\n bypassOptions: {\r\n onMutation,\r\n blockClass,\r\n blockSelector,\r\n unblockSelector,\r\n maskAllText,\r\n maskTextClass,\r\n unmaskTextClass,\r\n maskTextSelector,\r\n unmaskTextSelector,\r\n inlineStylesheet,\r\n maskInputOptions,\r\n dataURLOptions,\r\n maskAttributeFn,\r\n maskTextFn,\r\n maskInputFn,\r\n recordCanvas,\r\n inlineImages,\r\n sampling,\r\n slimDOMOptions,\r\n iframeManager,\r\n stylesheetManager,\r\n canvasManager,\r\n keepIframeSrcFn,\r\n processedNodeManager,\r\n },\r\n mirror,\r\n });\r\n const takeFullSnapshot = (isCheckout = false) => {\r\n wrappedEmit({\r\n type: EventType.Meta,\r\n data: {\r\n href: window.location.href,\r\n width: getWindowWidth(),\r\n height: getWindowHeight(),\r\n },\r\n }, isCheckout);\r\n stylesheetManager.reset();\r\n shadowDomManager.init();\r\n mutationBuffers.forEach((buf) => buf.lock());\r\n const node = snapshot(document, {\r\n mirror,\r\n blockClass,\r\n blockSelector,\r\n unblockSelector,\r\n maskAllText,\r\n maskTextClass,\r\n unmaskTextClass,\r\n maskTextSelector,\r\n unmaskTextSelector,\r\n inlineStylesheet,\r\n maskAllInputs: maskInputOptions,\r\n maskAttributeFn,\r\n maskInputFn,\r\n maskTextFn,\r\n slimDOM: slimDOMOptions,\r\n dataURLOptions,\r\n recordCanvas,\r\n inlineImages,\r\n onSerialize: (n) => {\r\n if (isSerializedIframe(n, mirror)) {\r\n iframeManager.addIframe(n);\r\n }\r\n if (isSerializedStylesheet(n, mirror)) {\r\n stylesheetManager.trackLinkElement(n);\r\n }\r\n if (hasShadowRoot(n)) {\r\n shadowDomManager.addShadowRoot(n.shadowRoot, document);\r\n }\r\n },\r\n onIframeLoad: (iframe, childSn) => {\r\n iframeManager.attachIframe(iframe, childSn);\r\n shadowDomManager.observeAttachShadow(iframe);\r\n },\r\n onStylesheetLoad: (linkEl, childSn) => {\r\n stylesheetManager.attachLinkElement(linkEl, childSn);\r\n },\r\n keepIframeSrcFn,\r\n });\r\n if (!node) {\r\n return console.warn('Failed to snapshot the document');\r\n }\r\n wrappedEmit({\r\n type: EventType.FullSnapshot,\r\n data: {\r\n node,\r\n initialOffset: getWindowScroll(window),\r\n },\r\n });\r\n mutationBuffers.forEach((buf) => buf.unlock());\r\n if (document.adoptedStyleSheets && document.adoptedStyleSheets.length > 0)\r\n stylesheetManager.adoptStyleSheets(document.adoptedStyleSheets, mirror.getId(document));\r\n };\r\n _takeFullSnapshot = takeFullSnapshot;\r\n try {\r\n const handlers = [];\r\n const observe = (doc) => {\r\n return callbackWrapper(initObservers)({\r\n onMutation,\r\n mutationCb: wrappedMutationEmit,\r\n mousemoveCb: (positions, source) => wrappedEmit({\r\n type: EventType.IncrementalSnapshot,\r\n data: {\r\n source,\r\n positions,\r\n },\r\n }),\r\n mouseInteractionCb: (d) => wrappedEmit({\r\n type: EventType.IncrementalSnapshot,\r\n data: {\r\n source: IncrementalSource.MouseInteraction,\r\n ...d,\r\n },\r\n }),\r\n scrollCb: wrappedScrollEmit,\r\n viewportResizeCb: (d) => wrappedEmit({\r\n type: EventType.IncrementalSnapshot,\r\n data: {\r\n source: IncrementalSource.ViewportResize,\r\n ...d,\r\n },\r\n }),\r\n inputCb: (v) => wrappedEmit({\r\n type: EventType.IncrementalSnapshot,\r\n data: {\r\n source: IncrementalSource.Input,\r\n ...v,\r\n },\r\n }),\r\n mediaInteractionCb: (p) => wrappedEmit({\r\n type: EventType.IncrementalSnapshot,\r\n data: {\r\n source: IncrementalSource.MediaInteraction,\r\n ...p,\r\n },\r\n }),\r\n styleSheetRuleCb: (r) => wrappedEmit({\r\n type: EventType.IncrementalSnapshot,\r\n data: {\r\n source: IncrementalSource.StyleSheetRule,\r\n ...r,\r\n },\r\n }),\r\n styleDeclarationCb: (r) => wrappedEmit({\r\n type: EventType.IncrementalSnapshot,\r\n data: {\r\n source: IncrementalSource.StyleDeclaration,\r\n ...r,\r\n },\r\n }),\r\n canvasMutationCb: wrappedCanvasMutationEmit,\r\n fontCb: (p) => wrappedEmit({\r\n type: EventType.IncrementalSnapshot,\r\n data: {\r\n source: IncrementalSource.Font,\r\n ...p,\r\n },\r\n }),\r\n selectionCb: (p) => {\r\n wrappedEmit({\r\n type: EventType.IncrementalSnapshot,\r\n data: {\r\n source: IncrementalSource.Selection,\r\n ...p,\r\n },\r\n });\r\n },\r\n customElementCb: (c) => {\r\n wrappedEmit({\r\n type: EventType.IncrementalSnapshot,\r\n data: {\r\n source: IncrementalSource.CustomElement,\r\n ...c,\r\n },\r\n });\r\n },\r\n blockClass,\r\n ignoreClass,\r\n ignoreSelector,\r\n maskAllText,\r\n maskTextClass,\r\n unmaskTextClass,\r\n maskTextSelector,\r\n unmaskTextSelector,\r\n maskInputOptions,\r\n inlineStylesheet,\r\n sampling,\r\n recordCanvas,\r\n inlineImages,\r\n userTriggeredOnInput,\r\n collectFonts,\r\n doc,\r\n maskAttributeFn,\r\n maskInputFn,\r\n maskTextFn,\r\n keepIframeSrcFn,\r\n blockSelector,\r\n unblockSelector,\r\n slimDOMOptions,\r\n dataURLOptions,\r\n mirror,\r\n iframeManager,\r\n stylesheetManager,\r\n shadowDomManager,\r\n processedNodeManager,\r\n canvasManager,\r\n ignoreCSSAttributes,\r\n plugins: plugins\r\n ?.filter((p) => p.observer)\r\n ?.map((p) => ({\r\n observer: p.observer,\r\n options: p.options,\r\n callback: (payload) => wrappedEmit({\r\n type: EventType.Plugin,\r\n data: {\r\n plugin: p.name,\r\n payload,\r\n },\r\n }),\r\n })) || [],\r\n }, {});\r\n };\r\n iframeManager.addLoadListener((iframeEl) => {\r\n try {\r\n handlers.push(observe(iframeEl.contentDocument));\r\n }\r\n catch (error) {\r\n console.warn(error);\r\n }\r\n });\r\n const init = () => {\r\n takeFullSnapshot();\r\n handlers.push(observe(document));\r\n };\r\n if (document.readyState === 'interactive' ||\r\n document.readyState === 'complete') {\r\n init();\r\n }\r\n else {\r\n handlers.push(on('DOMContentLoaded', () => {\r\n wrappedEmit({\r\n type: EventType.DomContentLoaded,\r\n data: {},\r\n });\r\n if (recordAfter === 'DOMContentLoaded')\r\n init();\r\n }));\r\n handlers.push(on('load', () => {\r\n wrappedEmit({\r\n type: EventType.Load,\r\n data: {},\r\n });\r\n if (recordAfter === 'load')\r\n init();\r\n }, window));\r\n }\r\n return () => {\r\n handlers.forEach((h) => h());\r\n processedNodeManager.destroy();\r\n _takeFullSnapshot = undefined;\r\n unregisterErrorHandler();\r\n };\r\n }\r\n catch (error) {\r\n console.warn(error);\r\n }\r\n}\r\nfunction addCustomEvent(tag, payload) {\r\n if (!_wrappedEmit) {\r\n throw new Error('please add custom event after start recording');\r\n }\r\n wrappedEmit({\r\n type: EventType.Custom,\r\n data: {\r\n tag,\r\n payload,\r\n },\r\n });\r\n}\r\nfunction freezePage() {\r\n mutationBuffers.forEach((buf) => buf.freeze());\r\n}\r\nfunction takeFullSnapshot(isCheckout) {\r\n if (!_takeFullSnapshot) {\r\n throw new Error('please take full snapshot after start recording');\r\n }\r\n _takeFullSnapshot(isCheckout);\r\n}\r\nrecord.mirror = mirror;\r\nrecord.takeFullSnapshot = takeFullSnapshot;\r\nfunction _getCanvasManager(getCanvasManagerFn, options) {\r\n try {\r\n return getCanvasManagerFn\r\n ? getCanvasManagerFn(options)\r\n : new CanvasManagerNoop();\r\n }\r\n catch {\r\n console.warn('Unable to initialize CanvasManager');\r\n return new CanvasManagerNoop();\r\n }\r\n}\n\nexport { addCustomEvent, record as default, freezePage, mirror, takeFullSnapshot };\n", "type ClassOption = string | RegExp;\n\n/** Duplicate this from @sentry-internal/rrweb so we can export this as well. */\nexport const ReplayEventTypeDomContentLoaded = 0;\nexport const ReplayEventTypeLoad = 1;\nexport const ReplayEventTypeFullSnapshot = 2;\nexport const ReplayEventTypeIncrementalSnapshot = 3;\nexport const ReplayEventTypeMeta = 4;\nexport const ReplayEventTypeCustom = 5;\nexport const ReplayEventTypePlugin = 6;\n\nexport type ReplayEventType =\n | typeof ReplayEventTypeDomContentLoaded\n | typeof ReplayEventTypeLoad\n | typeof ReplayEventTypeFullSnapshot\n | typeof ReplayEventTypeIncrementalSnapshot\n | typeof ReplayEventTypeMeta\n | typeof ReplayEventTypeCustom\n | typeof ReplayEventTypePlugin;\n\n/**\n * This is a partial copy of rrweb's eventWithTime type which only contains the properties\n * we specifcally need in the SDK.\n */\nexport type ReplayEventWithTime = {\n type: ReplayEventType;\n data: unknown;\n timestamp: number;\n delay?: number;\n};\n\n/**\n * This is a partial copy of rrweb's recording options which only contains the properties\n * we specifically us in the SDK. Users can specify additional properties, hence we add the\n * Record union type.\n */\nexport type RrwebRecordOptions = {\n maskAllText?: boolean;\n maskAllInputs?: boolean;\n blockClass?: ClassOption;\n ignoreClass?: string;\n maskTextClass?: ClassOption;\n maskTextSelector?: string;\n blockSelector?: string;\n maskInputOptions?: Record;\n} & Record;\n\nexport interface CanvasManagerInterface {\n reset(): void;\n freeze(): void;\n unfreeze(): void;\n lock(): void;\n unlock(): void;\n snapshot(): void;\n}\n\nexport interface CanvasManagerOptions {\n recordCanvas: boolean;\n enableManualSnapshot?: boolean;\n blockClass: string | RegExp;\n blockSelector: string | null;\n unblockSelector: string | null;\n sampling?: 'all' | number;\n dataURLOptions: Partial<{\n type: string;\n quality: number;\n }>;\n mutationCb: (p: any) => void;\n win: typeof globalThis & Window;\n mirror: any;\n}\n", "/**\n * Converts a timestamp to ms, if it was in s, or keeps it as ms.\n */\nexport function timestampToMs(timestamp: number): number {\n const isMs = timestamp > 9999999999;\n return isMs ? timestamp : timestamp * 1000;\n}\n\n/**\n * Converts a timestamp to s, if it was in ms, or keeps it as s.\n */\nexport function timestampToS(timestamp: number): number {\n const isMs = timestamp > 9999999999;\n return isMs ? timestamp / 1000 : timestamp;\n}\n", "import { EventType } from '@sentry-internal/rrweb';\nimport type { Breadcrumb } from '@sentry/types';\nimport { normalize } from '@sentry/utils';\n\nimport type { ReplayContainer } from '../../types';\n\n/**\n * Add a breadcrumb event to replay.\n */\nexport function addBreadcrumbEvent(replay: ReplayContainer, breadcrumb: Breadcrumb): void {\n if (breadcrumb.category === 'sentry.transaction') {\n return;\n }\n\n if (['ui.click', 'ui.input'].includes(breadcrumb.category as string)) {\n replay.triggerUserActivity();\n } else {\n replay.checkAndHandleExpiredSession();\n }\n\n replay.addUpdate(() => {\n // This should never reject\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n replay.throttledAddEvent({\n type: EventType.Custom,\n // TODO: We were converting from ms to seconds for breadcrumbs, spans,\n // but maybe we should just keep them as milliseconds\n timestamp: (breadcrumb.timestamp || 0) * 1000,\n data: {\n tag: 'breadcrumb',\n // normalize to max. 10 depth and 1_000 properties per object\n payload: normalize(breadcrumb, 10, 1_000),\n },\n });\n\n // Do not flush after console log messages\n return breadcrumb.category === 'console';\n });\n}\n", "import type { INode } from '@sentry-internal/rrweb-snapshot';\n\nconst INTERACTIVE_SELECTOR = 'button,a';\n\n/** Get the closest interactive parent element, or else return the given element. */\nexport function getClosestInteractive(element: Element): Element {\n const closestInteractive = element.closest(INTERACTIVE_SELECTOR);\n return closestInteractive || element;\n}\n\n/**\n * For clicks, we check if the target is inside of a button or link\n * If so, we use this as the target instead\n * This is useful because if you click on the image in ,\n * The target will be the image, not the button, which we don't want here\n */\nexport function getClickTargetNode(event: Event | MouseEvent | Node): Node | INode | null {\n const target = getTargetNode(event);\n\n if (!target || !(target instanceof Element)) {\n return target;\n }\n\n return getClosestInteractive(target);\n}\n\n/** Get the event target node. */\nexport function getTargetNode(event: Node | { target: EventTarget | null }): Node | INode | null {\n if (isEventWithTarget(event)) {\n return event.target as Node | null;\n }\n\n return event;\n}\n\nfunction isEventWithTarget(event: unknown): event is { target: EventTarget | null } {\n return typeof event === 'object' && !!event && 'target' in event;\n}\n", "import { fill } from '@sentry/utils';\n\nimport { WINDOW } from '../../constants';\n\ntype WindowOpenHandler = () => void;\n\nlet handlers: undefined | WindowOpenHandler[];\n\n/**\n * Register a handler to be called when `window.open()` is called.\n * Returns a cleanup function.\n */\nexport function onWindowOpen(cb: WindowOpenHandler): () => void {\n // Ensure to only register this once\n if (!handlers) {\n handlers = [];\n monkeyPatchWindowOpen();\n }\n\n handlers.push(cb);\n\n return () => {\n const pos = handlers ? handlers.indexOf(cb) : -1;\n if (pos > -1) {\n (handlers as WindowOpenHandler[]).splice(pos, 1);\n }\n };\n}\n\nfunction monkeyPatchWindowOpen(): void {\n fill(WINDOW, 'open', function (originalWindowOpen: () => void): () => void {\n return function (...args: unknown[]): void {\n if (handlers) {\n try {\n handlers.forEach(handler => handler());\n } catch (e) {\n // ignore errors in here\n }\n }\n\n return originalWindowOpen.apply(WINDOW, args);\n };\n });\n}\n", "import { IncrementalSource, MouseInteractions, record } from '@sentry-internal/rrweb';\nimport type { Breadcrumb } from '@sentry/types';\n\nimport { WINDOW } from '../constants';\nimport type {\n RecordingEvent,\n ReplayClickDetector,\n ReplayContainer,\n ReplayMultiClickFrame,\n ReplaySlowClickFrame,\n SlowClickConfig,\n} from '../types';\nimport { ReplayEventTypeIncrementalSnapshot } from '../types';\nimport { timestampToS } from '../util/timestamp';\nimport { addBreadcrumbEvent } from './util/addBreadcrumbEvent';\nimport { getClosestInteractive } from './util/domUtils';\nimport { onWindowOpen } from './util/onWindowOpen';\n\ntype ClickBreadcrumb = Breadcrumb & {\n timestamp: number;\n};\n\ninterface Click {\n timestamp: number;\n mutationAfter?: number;\n scrollAfter?: number;\n clickBreadcrumb: ClickBreadcrumb;\n clickCount: number;\n node: HTMLElement;\n}\n\ntype IncrementalRecordingEvent = RecordingEvent & {\n type: typeof ReplayEventTypeIncrementalSnapshot;\n data: { source: IncrementalSource };\n};\n\ntype IncrementalMouseInteractionRecordingEvent = IncrementalRecordingEvent & {\n type: typeof ReplayEventTypeIncrementalSnapshot;\n data: { type: MouseInteractions; id: number };\n};\n\n/** Handle a click. */\nexport function handleClick(clickDetector: ReplayClickDetector, clickBreadcrumb: Breadcrumb, node: HTMLElement): void {\n clickDetector.handleClick(clickBreadcrumb, node);\n}\n\n/** A click detector class that can be used to detect slow or rage clicks on elements. */\nexport class ClickDetector implements ReplayClickDetector {\n // protected for testing\n protected _lastMutation: number;\n protected _lastScroll: number;\n\n private _clicks: Click[];\n private _teardown: undefined | (() => void);\n\n private _threshold: number;\n private _scollTimeout: number;\n private _timeout: number;\n private _ignoreSelector: string;\n\n private _replay: ReplayContainer;\n private _checkClickTimeout?: ReturnType;\n private _addBreadcrumbEvent: typeof addBreadcrumbEvent;\n\n public constructor(\n replay: ReplayContainer,\n slowClickConfig: SlowClickConfig,\n // Just for easier testing\n _addBreadcrumbEvent = addBreadcrumbEvent,\n ) {\n this._lastMutation = 0;\n this._lastScroll = 0;\n this._clicks = [];\n\n // We want everything in s, but options are in ms\n this._timeout = slowClickConfig.timeout / 1000;\n this._threshold = slowClickConfig.threshold / 1000;\n this._scollTimeout = slowClickConfig.scrollTimeout / 1000;\n this._replay = replay;\n this._ignoreSelector = slowClickConfig.ignoreSelector;\n this._addBreadcrumbEvent = _addBreadcrumbEvent;\n }\n\n /** Register click detection handlers on mutation or scroll. */\n public addListeners(): void {\n const cleanupWindowOpen = onWindowOpen(() => {\n // Treat window.open as mutation\n this._lastMutation = nowInSeconds();\n });\n\n this._teardown = () => {\n cleanupWindowOpen();\n\n this._clicks = [];\n this._lastMutation = 0;\n this._lastScroll = 0;\n };\n }\n\n /** Clean up listeners. */\n public removeListeners(): void {\n if (this._teardown) {\n this._teardown();\n }\n\n if (this._checkClickTimeout) {\n clearTimeout(this._checkClickTimeout);\n }\n }\n\n /** @inheritDoc */\n public handleClick(breadcrumb: Breadcrumb, node: HTMLElement): void {\n if (ignoreElement(node, this._ignoreSelector) || !isClickBreadcrumb(breadcrumb)) {\n return;\n }\n\n const newClick: Click = {\n timestamp: timestampToS(breadcrumb.timestamp),\n clickBreadcrumb: breadcrumb,\n // Set this to 0 so we know it originates from the click breadcrumb\n clickCount: 0,\n node,\n };\n\n // If there was a click in the last 1s on the same element, ignore it - only keep a single reference per second\n if (\n this._clicks.some(click => click.node === newClick.node && Math.abs(click.timestamp - newClick.timestamp) < 1)\n ) {\n return;\n }\n\n this._clicks.push(newClick);\n\n // If this is the first new click, set a timeout to check for multi clicks\n if (this._clicks.length === 1) {\n this._scheduleCheckClicks();\n }\n }\n\n /** @inheritDoc */\n public registerMutation(timestamp = Date.now()): void {\n this._lastMutation = timestampToS(timestamp);\n }\n\n /** @inheritDoc */\n public registerScroll(timestamp = Date.now()): void {\n this._lastScroll = timestampToS(timestamp);\n }\n\n /** @inheritDoc */\n public registerClick(element: HTMLElement): void {\n const node = getClosestInteractive(element);\n this._handleMultiClick(node as HTMLElement);\n }\n\n /** Count multiple clicks on elements. */\n private _handleMultiClick(node: HTMLElement): void {\n this._getClicks(node).forEach(click => {\n click.clickCount++;\n });\n }\n\n /** Get all pending clicks for a given node. */\n private _getClicks(node: HTMLElement): Click[] {\n return this._clicks.filter(click => click.node === node);\n }\n\n /** Check the clicks that happened. */\n private _checkClicks(): void {\n const timedOutClicks: Click[] = [];\n\n const now = nowInSeconds();\n\n this._clicks.forEach(click => {\n if (!click.mutationAfter && this._lastMutation) {\n click.mutationAfter = click.timestamp <= this._lastMutation ? this._lastMutation - click.timestamp : undefined;\n }\n if (!click.scrollAfter && this._lastScroll) {\n click.scrollAfter = click.timestamp <= this._lastScroll ? this._lastScroll - click.timestamp : undefined;\n }\n\n // All of these are in seconds!\n if (click.timestamp + this._timeout <= now) {\n timedOutClicks.push(click);\n }\n });\n\n // Remove \"old\" clicks\n for (const click of timedOutClicks) {\n const pos = this._clicks.indexOf(click);\n\n if (pos > -1) {\n this._generateBreadcrumbs(click);\n this._clicks.splice(pos, 1);\n }\n }\n\n // Trigger new check, unless no clicks left\n if (this._clicks.length) {\n this._scheduleCheckClicks();\n }\n }\n\n /** Generate matching breadcrumb(s) for the click. */\n private _generateBreadcrumbs(click: Click): void {\n const replay = this._replay;\n const hadScroll = click.scrollAfter && click.scrollAfter <= this._scollTimeout;\n const hadMutation = click.mutationAfter && click.mutationAfter <= this._threshold;\n\n const isSlowClick = !hadScroll && !hadMutation;\n const { clickCount, clickBreadcrumb } = click;\n\n // Slow click\n if (isSlowClick) {\n // If `mutationAfter` is set, it means a mutation happened after the threshold, but before the timeout\n // If not, it means we just timed out without scroll & mutation\n const timeAfterClickMs = Math.min(click.mutationAfter || this._timeout, this._timeout) * 1000;\n const endReason = timeAfterClickMs < this._timeout * 1000 ? 'mutation' : 'timeout';\n\n const breadcrumb: ReplaySlowClickFrame = {\n type: 'default',\n message: clickBreadcrumb.message,\n timestamp: clickBreadcrumb.timestamp,\n category: 'ui.slowClickDetected',\n data: {\n ...clickBreadcrumb.data,\n url: WINDOW.location.href,\n route: replay.getCurrentRoute(),\n timeAfterClickMs,\n endReason,\n // If clickCount === 0, it means multiClick was not correctly captured here\n // - we still want to send 1 in this case\n clickCount: clickCount || 1,\n },\n };\n\n this._addBreadcrumbEvent(replay, breadcrumb);\n return;\n }\n\n // Multi click\n if (clickCount > 1) {\n const breadcrumb: ReplayMultiClickFrame = {\n type: 'default',\n message: clickBreadcrumb.message,\n timestamp: clickBreadcrumb.timestamp,\n category: 'ui.multiClick',\n data: {\n ...clickBreadcrumb.data,\n url: WINDOW.location.href,\n route: replay.getCurrentRoute(),\n clickCount,\n metric: true,\n },\n };\n\n this._addBreadcrumbEvent(replay, breadcrumb);\n }\n }\n\n /** Schedule to check current clicks. */\n private _scheduleCheckClicks(): void {\n if (this._checkClickTimeout) {\n clearTimeout(this._checkClickTimeout);\n }\n\n this._checkClickTimeout = setTimeout(() => this._checkClicks(), 1000);\n }\n}\n\nconst SLOW_CLICK_TAGS = ['A', 'BUTTON', 'INPUT'];\n\n/** exported for tests only */\nexport function ignoreElement(node: HTMLElement, ignoreSelector: string): boolean {\n if (!SLOW_CLICK_TAGS.includes(node.tagName)) {\n return true;\n }\n\n // If tag, we only want to consider input[type='submit'] & input[type='button']\n if (node.tagName === 'INPUT' && !['submit', 'button'].includes(node.getAttribute('type') || '')) {\n return true;\n }\n\n // If tag, detect special variants that may not lead to an action\n // If target !== _self, we may open the link somewhere else, which would lead to no action\n // Also, when downloading a file, we may not leave the page, but still not trigger an action\n if (\n node.tagName === 'A' &&\n (node.hasAttribute('download') || (node.hasAttribute('target') && node.getAttribute('target') !== '_self'))\n ) {\n return true;\n }\n\n if (ignoreSelector && node.matches(ignoreSelector)) {\n return true;\n }\n\n return false;\n}\n\nfunction isClickBreadcrumb(breadcrumb: Breadcrumb): breadcrumb is ClickBreadcrumb {\n return !!(breadcrumb.data && typeof breadcrumb.data.nodeId === 'number' && breadcrumb.timestamp);\n}\n\n// This is good enough for us, and is easier to test/mock than `timestampInSeconds`\nfunction nowInSeconds(): number {\n return Date.now() / 1000;\n}\n\n/** Update the click detector based on a recording event of rrweb. */\nexport function updateClickDetectorForRecordingEvent(clickDetector: ReplayClickDetector, event: RecordingEvent): void {\n try {\n // note: We only consider incremental snapshots here\n // This means that any full snapshot is ignored for mutation detection - the reason is that we simply cannot know if a mutation happened here.\n // E.g. think that we are buffering, an error happens and we take a full snapshot because we switched to session mode -\n // in this scenario, we would not know if a dead click happened because of the error, which is a key dead click scenario.\n // Instead, by ignoring full snapshots, we have the risk that we generate a false positive\n // (if a mutation _did_ happen but was \"swallowed\" by the full snapshot)\n // But this should be more unlikely as we'd generally capture the incremental snapshot right away\n\n if (!isIncrementalEvent(event)) {\n return;\n }\n\n const { source } = event.data;\n if (source === IncrementalSource.Mutation) {\n clickDetector.registerMutation(event.timestamp);\n }\n\n if (source === IncrementalSource.Scroll) {\n clickDetector.registerScroll(event.timestamp);\n }\n\n if (isIncrementalMouseInteraction(event)) {\n const { type, id } = event.data;\n const node = record.mirror.getNode(id);\n\n if (node instanceof HTMLElement && type === MouseInteractions.Click) {\n clickDetector.registerClick(node);\n }\n }\n } catch {\n // ignore errors here, e.g. if accessing something that does not exist\n }\n}\n\nfunction isIncrementalEvent(event: RecordingEvent): event is IncrementalRecordingEvent {\n return event.type === ReplayEventTypeIncrementalSnapshot;\n}\n\nfunction isIncrementalMouseInteraction(\n event: IncrementalRecordingEvent,\n): event is IncrementalMouseInteractionRecordingEvent {\n return event.data.source === IncrementalSource.MouseInteraction;\n}\n", "import type { ReplayBreadcrumbFrame } from '../types/replayFrame';\n\n/**\n * Create a breadcrumb for a replay.\n */\nexport function createBreadcrumb(\n breadcrumb: Omit & Partial>,\n): ReplayBreadcrumbFrame {\n return {\n timestamp: Date.now() / 1000,\n type: 'default',\n ...breadcrumb,\n };\n}\n", "var NodeType;\r\n(function (NodeType) {\r\n NodeType[NodeType[\"Document\"] = 0] = \"Document\";\r\n NodeType[NodeType[\"DocumentType\"] = 1] = \"DocumentType\";\r\n NodeType[NodeType[\"Element\"] = 2] = \"Element\";\r\n NodeType[NodeType[\"Text\"] = 3] = \"Text\";\r\n NodeType[NodeType[\"CDATA\"] = 4] = \"CDATA\";\r\n NodeType[NodeType[\"Comment\"] = 5] = \"Comment\";\r\n})(NodeType || (NodeType = {}));\n\nfunction isElement(n) {\r\n return n.nodeType === n.ELEMENT_NODE;\r\n}\r\nfunction isShadowRoot(n) {\r\n const host = n?.host;\r\n return Boolean(host?.shadowRoot === n);\r\n}\r\nfunction isNativeShadowDom(shadowRoot) {\r\n return Object.prototype.toString.call(shadowRoot) === '[object ShadowRoot]';\r\n}\r\nfunction fixBrowserCompatibilityIssuesInCSS(cssText) {\r\n if (cssText.includes(' background-clip: text;') &&\r\n !cssText.includes(' -webkit-background-clip: text;')) {\r\n cssText = cssText.replace(' background-clip: text;', ' -webkit-background-clip: text; background-clip: text;');\r\n }\r\n return cssText;\r\n}\r\nfunction escapeImportStatement(rule) {\r\n const { cssText } = rule;\r\n if (cssText.split('\"').length < 3)\r\n return cssText;\r\n const statement = ['@import', `url(${JSON.stringify(rule.href)})`];\r\n if (rule.layerName === '') {\r\n statement.push(`layer`);\r\n }\r\n else if (rule.layerName) {\r\n statement.push(`layer(${rule.layerName})`);\r\n }\r\n if (rule.supportsText) {\r\n statement.push(`supports(${rule.supportsText})`);\r\n }\r\n if (rule.media.length) {\r\n statement.push(rule.media.mediaText);\r\n }\r\n return statement.join(' ') + ';';\r\n}\r\nfunction stringifyStylesheet(s) {\r\n try {\r\n const rules = s.rules || s.cssRules;\r\n return rules\r\n ? fixBrowserCompatibilityIssuesInCSS(Array.from(rules, stringifyRule).join(''))\r\n : null;\r\n }\r\n catch (error) {\r\n return null;\r\n }\r\n}\r\nfunction stringifyRule(rule) {\r\n let importStringified;\r\n if (isCSSImportRule(rule)) {\r\n try {\r\n importStringified =\r\n stringifyStylesheet(rule.styleSheet) ||\r\n escapeImportStatement(rule);\r\n }\r\n catch (error) {\r\n }\r\n }\r\n else if (isCSSStyleRule(rule) && rule.selectorText.includes(':')) {\r\n return fixSafariColons(rule.cssText);\r\n }\r\n return importStringified || rule.cssText;\r\n}\r\nfunction fixSafariColons(cssStringified) {\r\n const regex = /(\\[(?:[\\w-]+)[^\\\\])(:(?:[\\w-]+)\\])/gm;\r\n return cssStringified.replace(regex, '$1\\\\$2');\r\n}\r\nfunction isCSSImportRule(rule) {\r\n return 'styleSheet' in rule;\r\n}\r\nfunction isCSSStyleRule(rule) {\r\n return 'selectorText' in rule;\r\n}\r\nclass Mirror {\r\n constructor() {\r\n this.idNodeMap = new Map();\r\n this.nodeMetaMap = new WeakMap();\r\n }\r\n getId(n) {\r\n if (!n)\r\n return -1;\r\n const id = this.getMeta(n)?.id;\r\n return id ?? -1;\r\n }\r\n getNode(id) {\r\n return this.idNodeMap.get(id) || null;\r\n }\r\n getIds() {\r\n return Array.from(this.idNodeMap.keys());\r\n }\r\n getMeta(n) {\r\n return this.nodeMetaMap.get(n) || null;\r\n }\r\n removeNodeFromMap(n) {\r\n const id = this.getId(n);\r\n this.idNodeMap.delete(id);\r\n if (n.childNodes) {\r\n n.childNodes.forEach((childNode) => this.removeNodeFromMap(childNode));\r\n }\r\n }\r\n has(id) {\r\n return this.idNodeMap.has(id);\r\n }\r\n hasNode(node) {\r\n return this.nodeMetaMap.has(node);\r\n }\r\n add(n, meta) {\r\n const id = meta.id;\r\n this.idNodeMap.set(id, n);\r\n this.nodeMetaMap.set(n, meta);\r\n }\r\n replace(id, n) {\r\n const oldNode = this.getNode(id);\r\n if (oldNode) {\r\n const meta = this.nodeMetaMap.get(oldNode);\r\n if (meta)\r\n this.nodeMetaMap.set(n, meta);\r\n }\r\n this.idNodeMap.set(id, n);\r\n }\r\n reset() {\r\n this.idNodeMap = new Map();\r\n this.nodeMetaMap = new WeakMap();\r\n }\r\n}\r\nfunction createMirror() {\r\n return new Mirror();\r\n}\r\nfunction shouldMaskInput({ maskInputOptions, tagName, type, }) {\r\n if (tagName === 'OPTION') {\r\n tagName = 'SELECT';\r\n }\r\n return Boolean(maskInputOptions[tagName.toLowerCase()] ||\r\n (type && maskInputOptions[type]) ||\r\n type === 'password' ||\r\n (tagName === 'INPUT' && !type && maskInputOptions['text']));\r\n}\r\nfunction maskInputValue({ isMasked, element, value, maskInputFn, }) {\r\n let text = value || '';\r\n if (!isMasked) {\r\n return text;\r\n }\r\n if (maskInputFn) {\r\n text = maskInputFn(text, element);\r\n }\r\n return '*'.repeat(text.length);\r\n}\r\nfunction toLowerCase(str) {\r\n return str.toLowerCase();\r\n}\r\nfunction toUpperCase(str) {\r\n return str.toUpperCase();\r\n}\r\nconst ORIGINAL_ATTRIBUTE_NAME = '__rrweb_original__';\r\nfunction is2DCanvasBlank(canvas) {\r\n const ctx = canvas.getContext('2d');\r\n if (!ctx)\r\n return true;\r\n const chunkSize = 50;\r\n for (let x = 0; x < canvas.width; x += chunkSize) {\r\n for (let y = 0; y < canvas.height; y += chunkSize) {\r\n const getImageData = ctx.getImageData;\r\n const originalGetImageData = ORIGINAL_ATTRIBUTE_NAME in getImageData\r\n ? getImageData[ORIGINAL_ATTRIBUTE_NAME]\r\n : getImageData;\r\n const pixelBuffer = new Uint32Array(originalGetImageData.call(ctx, x, y, Math.min(chunkSize, canvas.width - x), Math.min(chunkSize, canvas.height - y)).data.buffer);\r\n if (pixelBuffer.some((pixel) => pixel !== 0))\r\n return false;\r\n }\r\n }\r\n return true;\r\n}\r\nfunction isNodeMetaEqual(a, b) {\r\n if (!a || !b || a.type !== b.type)\r\n return false;\r\n if (a.type === NodeType.Document)\r\n return a.compatMode === b.compatMode;\r\n else if (a.type === NodeType.DocumentType)\r\n return (a.name === b.name &&\r\n a.publicId === b.publicId &&\r\n a.systemId === b.systemId);\r\n else if (a.type === NodeType.Comment ||\r\n a.type === NodeType.Text ||\r\n a.type === NodeType.CDATA)\r\n return a.textContent === b.textContent;\r\n else if (a.type === NodeType.Element)\r\n return (a.tagName === b.tagName &&\r\n JSON.stringify(a.attributes) ===\r\n JSON.stringify(b.attributes) &&\r\n a.isSVG === b.isSVG &&\r\n a.needBlock === b.needBlock);\r\n return false;\r\n}\r\nfunction getInputType(element) {\r\n const type = element.type;\r\n return element.hasAttribute('data-rr-is-password')\r\n ? 'password'\r\n : type\r\n ?\r\n toLowerCase(type)\r\n : null;\r\n}\r\nfunction getInputValue(el, tagName, type) {\r\n if (tagName === 'INPUT' && (type === 'radio' || type === 'checkbox')) {\r\n return el.getAttribute('value') || '';\r\n }\r\n return el.value;\r\n}\n\nlet _id = 1;\r\nconst tagNameRegex = new RegExp('[^a-z0-9-_:]');\r\nconst IGNORED_NODE = -2;\r\nfunction genId() {\r\n return _id++;\r\n}\r\nfunction getValidTagName(element) {\r\n if (element instanceof HTMLFormElement) {\r\n return 'form';\r\n }\r\n const processedTagName = toLowerCase(element.tagName);\r\n if (tagNameRegex.test(processedTagName)) {\r\n return 'div';\r\n }\r\n return processedTagName;\r\n}\r\nfunction extractOrigin(url) {\r\n let origin = '';\r\n if (url.indexOf('//') > -1) {\r\n origin = url.split('/').slice(0, 3).join('/');\r\n }\r\n else {\r\n origin = url.split('/')[0];\r\n }\r\n origin = origin.split('?')[0];\r\n return origin;\r\n}\r\nlet canvasService;\r\nlet canvasCtx;\r\nconst URL_IN_CSS_REF = /url\\((?:(')([^']*)'|(\")(.*?)\"|([^)]*))\\)/gm;\r\nconst URL_PROTOCOL_MATCH = /^(?:[a-z+]+:)?\\/\\//i;\r\nconst URL_WWW_MATCH = /^www\\..*/i;\r\nconst DATA_URI = /^(data:)([^,]*),(.*)/i;\r\nfunction absoluteToStylesheet(cssText, href) {\r\n return (cssText || '').replace(URL_IN_CSS_REF, (origin, quote1, path1, quote2, path2, path3) => {\r\n const filePath = path1 || path2 || path3;\r\n const maybeQuote = quote1 || quote2 || '';\r\n if (!filePath) {\r\n return origin;\r\n }\r\n if (URL_PROTOCOL_MATCH.test(filePath) || URL_WWW_MATCH.test(filePath)) {\r\n return `url(${maybeQuote}${filePath}${maybeQuote})`;\r\n }\r\n if (DATA_URI.test(filePath)) {\r\n return `url(${maybeQuote}${filePath}${maybeQuote})`;\r\n }\r\n if (filePath[0] === '/') {\r\n return `url(${maybeQuote}${extractOrigin(href) + filePath}${maybeQuote})`;\r\n }\r\n const stack = href.split('/');\r\n const parts = filePath.split('/');\r\n stack.pop();\r\n for (const part of parts) {\r\n if (part === '.') {\r\n continue;\r\n }\r\n else if (part === '..') {\r\n stack.pop();\r\n }\r\n else {\r\n stack.push(part);\r\n }\r\n }\r\n return `url(${maybeQuote}${stack.join('/')}${maybeQuote})`;\r\n });\r\n}\r\nconst SRCSET_NOT_SPACES = /^[^ \\t\\n\\r\\u000c]+/;\r\nconst SRCSET_COMMAS_OR_SPACES = /^[, \\t\\n\\r\\u000c]+/;\r\nfunction getAbsoluteSrcsetString(doc, attributeValue) {\r\n if (attributeValue.trim() === '') {\r\n return attributeValue;\r\n }\r\n let pos = 0;\r\n function collectCharacters(regEx) {\r\n let chars;\r\n const match = regEx.exec(attributeValue.substring(pos));\r\n if (match) {\r\n chars = match[0];\r\n pos += chars.length;\r\n return chars;\r\n }\r\n return '';\r\n }\r\n const output = [];\r\n while (true) {\r\n collectCharacters(SRCSET_COMMAS_OR_SPACES);\r\n if (pos >= attributeValue.length) {\r\n break;\r\n }\r\n let url = collectCharacters(SRCSET_NOT_SPACES);\r\n if (url.slice(-1) === ',') {\r\n url = absoluteToDoc(doc, url.substring(0, url.length - 1));\r\n output.push(url);\r\n }\r\n else {\r\n let descriptorsStr = '';\r\n url = absoluteToDoc(doc, url);\r\n let inParens = false;\r\n while (true) {\r\n const c = attributeValue.charAt(pos);\r\n if (c === '') {\r\n output.push((url + descriptorsStr).trim());\r\n break;\r\n }\r\n else if (!inParens) {\r\n if (c === ',') {\r\n pos += 1;\r\n output.push((url + descriptorsStr).trim());\r\n break;\r\n }\r\n else if (c === '(') {\r\n inParens = true;\r\n }\r\n }\r\n else {\r\n if (c === ')') {\r\n inParens = false;\r\n }\r\n }\r\n descriptorsStr += c;\r\n pos += 1;\r\n }\r\n }\r\n }\r\n return output.join(', ');\r\n}\r\nfunction absoluteToDoc(doc, attributeValue) {\r\n if (!attributeValue || attributeValue.trim() === '') {\r\n return attributeValue;\r\n }\r\n const a = doc.createElement('a');\r\n a.href = attributeValue;\r\n return a.href;\r\n}\r\nfunction isSVGElement(el) {\r\n return Boolean(el.tagName === 'svg' || el.ownerSVGElement);\r\n}\r\nfunction getHref() {\r\n const a = document.createElement('a');\r\n a.href = '';\r\n return a.href;\r\n}\r\nfunction transformAttribute(doc, tagName, name, value, element, maskAttributeFn) {\r\n if (!value) {\r\n return value;\r\n }\r\n if (name === 'src' ||\r\n (name === 'href' && !(tagName === 'use' && value[0] === '#'))) {\r\n return absoluteToDoc(doc, value);\r\n }\r\n else if (name === 'xlink:href' && value[0] !== '#') {\r\n return absoluteToDoc(doc, value);\r\n }\r\n else if (name === 'background' &&\r\n (tagName === 'table' || tagName === 'td' || tagName === 'th')) {\r\n return absoluteToDoc(doc, value);\r\n }\r\n else if (name === 'srcset') {\r\n return getAbsoluteSrcsetString(doc, value);\r\n }\r\n else if (name === 'style') {\r\n return absoluteToStylesheet(value, getHref());\r\n }\r\n else if (tagName === 'object' && name === 'data') {\r\n return absoluteToDoc(doc, value);\r\n }\r\n if (typeof maskAttributeFn === 'function') {\r\n return maskAttributeFn(name, value, element);\r\n }\r\n return value;\r\n}\r\nfunction ignoreAttribute(tagName, name, _value) {\r\n return (tagName === 'video' || tagName === 'audio') && name === 'autoplay';\r\n}\r\nfunction _isBlockedElement(element, blockClass, blockSelector, unblockSelector) {\r\n try {\r\n if (unblockSelector && element.matches(unblockSelector)) {\r\n return false;\r\n }\r\n if (typeof blockClass === 'string') {\r\n if (element.classList.contains(blockClass)) {\r\n return true;\r\n }\r\n }\r\n else {\r\n for (let eIndex = element.classList.length; eIndex--;) {\r\n const className = element.classList[eIndex];\r\n if (blockClass.test(className)) {\r\n return true;\r\n }\r\n }\r\n }\r\n if (blockSelector) {\r\n return element.matches(blockSelector);\r\n }\r\n }\r\n catch (e) {\r\n }\r\n return false;\r\n}\r\nfunction elementClassMatchesRegex(el, regex) {\r\n for (let eIndex = el.classList.length; eIndex--;) {\r\n const className = el.classList[eIndex];\r\n if (regex.test(className)) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n}\r\nfunction classMatchesRegex(node, regex, checkAncestors) {\r\n if (!node)\r\n return false;\r\n if (checkAncestors) {\r\n return (distanceToMatch(node, (node) => elementClassMatchesRegex(node, regex)) >= 0);\r\n }\r\n else if (node.nodeType === node.ELEMENT_NODE) {\r\n return elementClassMatchesRegex(node, regex);\r\n }\r\n return false;\r\n}\r\nfunction distanceToMatch(node, matchPredicate, limit = Infinity, distance = 0) {\r\n if (!node)\r\n return -1;\r\n if (node.nodeType !== node.ELEMENT_NODE)\r\n return -1;\r\n if (distance > limit)\r\n return -1;\r\n if (matchPredicate(node))\r\n return distance;\r\n return distanceToMatch(node.parentNode, matchPredicate, limit, distance + 1);\r\n}\r\nfunction createMatchPredicate(className, selector) {\r\n return (node) => {\r\n const el = node;\r\n if (el === null)\r\n return false;\r\n try {\r\n if (className) {\r\n if (typeof className === 'string') {\r\n if (el.matches(`.${className}`))\r\n return true;\r\n }\r\n else if (elementClassMatchesRegex(el, className)) {\r\n return true;\r\n }\r\n }\r\n if (selector && el.matches(selector))\r\n return true;\r\n return false;\r\n }\r\n catch {\r\n return false;\r\n }\r\n };\r\n}\r\nfunction needMaskingText(node, maskTextClass, maskTextSelector, unmaskTextClass, unmaskTextSelector, maskAllText) {\r\n try {\r\n const el = node.nodeType === node.ELEMENT_NODE\r\n ? node\r\n : node.parentElement;\r\n if (el === null)\r\n return false;\r\n if (el.tagName === 'INPUT') {\r\n const autocomplete = el.getAttribute('autocomplete');\r\n const disallowedAutocompleteValues = [\r\n 'current-password',\r\n 'new-password',\r\n 'cc-number',\r\n 'cc-exp',\r\n 'cc-exp-month',\r\n 'cc-exp-year',\r\n 'cc-csc',\r\n ];\r\n if (disallowedAutocompleteValues.includes(autocomplete)) {\r\n return true;\r\n }\r\n }\r\n let maskDistance = -1;\r\n let unmaskDistance = -1;\r\n if (maskAllText) {\r\n unmaskDistance = distanceToMatch(el, createMatchPredicate(unmaskTextClass, unmaskTextSelector));\r\n if (unmaskDistance < 0) {\r\n return true;\r\n }\r\n maskDistance = distanceToMatch(el, createMatchPredicate(maskTextClass, maskTextSelector), unmaskDistance >= 0 ? unmaskDistance : Infinity);\r\n }\r\n else {\r\n maskDistance = distanceToMatch(el, createMatchPredicate(maskTextClass, maskTextSelector));\r\n if (maskDistance < 0) {\r\n return false;\r\n }\r\n unmaskDistance = distanceToMatch(el, createMatchPredicate(unmaskTextClass, unmaskTextSelector), maskDistance >= 0 ? maskDistance : Infinity);\r\n }\r\n return maskDistance >= 0\r\n ? unmaskDistance >= 0\r\n ? maskDistance <= unmaskDistance\r\n : true\r\n : unmaskDistance >= 0\r\n ? false\r\n : !!maskAllText;\r\n }\r\n catch (e) {\r\n }\r\n return !!maskAllText;\r\n}\r\nfunction onceIframeLoaded(iframeEl, listener, iframeLoadTimeout) {\r\n const win = iframeEl.contentWindow;\r\n if (!win) {\r\n return;\r\n }\r\n let fired = false;\r\n let readyState;\r\n try {\r\n readyState = win.document.readyState;\r\n }\r\n catch (error) {\r\n return;\r\n }\r\n if (readyState !== 'complete') {\r\n const timer = setTimeout(() => {\r\n if (!fired) {\r\n listener();\r\n fired = true;\r\n }\r\n }, iframeLoadTimeout);\r\n iframeEl.addEventListener('load', () => {\r\n clearTimeout(timer);\r\n fired = true;\r\n listener();\r\n });\r\n return;\r\n }\r\n const blankUrl = 'about:blank';\r\n if (win.location.href !== blankUrl ||\r\n iframeEl.src === blankUrl ||\r\n iframeEl.src === '') {\r\n setTimeout(listener, 0);\r\n return iframeEl.addEventListener('load', listener);\r\n }\r\n iframeEl.addEventListener('load', listener);\r\n}\r\nfunction onceStylesheetLoaded(link, listener, styleSheetLoadTimeout) {\r\n let fired = false;\r\n let styleSheetLoaded;\r\n try {\r\n styleSheetLoaded = link.sheet;\r\n }\r\n catch (error) {\r\n return;\r\n }\r\n if (styleSheetLoaded)\r\n return;\r\n const timer = setTimeout(() => {\r\n if (!fired) {\r\n listener();\r\n fired = true;\r\n }\r\n }, styleSheetLoadTimeout);\r\n link.addEventListener('load', () => {\r\n clearTimeout(timer);\r\n fired = true;\r\n listener();\r\n });\r\n}\r\nfunction serializeNode(n, options) {\r\n const { doc, mirror, blockClass, blockSelector, unblockSelector, maskAllText, maskAttributeFn, maskTextClass, unmaskTextClass, maskTextSelector, unmaskTextSelector, inlineStylesheet, maskInputOptions = {}, maskTextFn, maskInputFn, dataURLOptions = {}, inlineImages, recordCanvas, keepIframeSrcFn, newlyAddedElement = false, } = options;\r\n const rootId = getRootId(doc, mirror);\r\n switch (n.nodeType) {\r\n case n.DOCUMENT_NODE:\r\n if (n.compatMode !== 'CSS1Compat') {\r\n return {\r\n type: NodeType.Document,\r\n childNodes: [],\r\n compatMode: n.compatMode,\r\n };\r\n }\r\n else {\r\n return {\r\n type: NodeType.Document,\r\n childNodes: [],\r\n };\r\n }\r\n case n.DOCUMENT_TYPE_NODE:\r\n return {\r\n type: NodeType.DocumentType,\r\n name: n.name,\r\n publicId: n.publicId,\r\n systemId: n.systemId,\r\n rootId,\r\n };\r\n case n.ELEMENT_NODE:\r\n return serializeElementNode(n, {\r\n doc,\r\n blockClass,\r\n blockSelector,\r\n unblockSelector,\r\n inlineStylesheet,\r\n maskAttributeFn,\r\n maskInputOptions,\r\n maskInputFn,\r\n dataURLOptions,\r\n inlineImages,\r\n recordCanvas,\r\n keepIframeSrcFn,\r\n newlyAddedElement,\r\n rootId,\r\n maskAllText,\r\n maskTextClass,\r\n unmaskTextClass,\r\n maskTextSelector,\r\n unmaskTextSelector,\r\n });\r\n case n.TEXT_NODE:\r\n return serializeTextNode(n, {\r\n maskAllText,\r\n maskTextClass,\r\n unmaskTextClass,\r\n maskTextSelector,\r\n unmaskTextSelector,\r\n maskTextFn,\r\n maskInputOptions,\r\n maskInputFn,\r\n rootId,\r\n });\r\n case n.CDATA_SECTION_NODE:\r\n return {\r\n type: NodeType.CDATA,\r\n textContent: '',\r\n rootId,\r\n };\r\n case n.COMMENT_NODE:\r\n return {\r\n type: NodeType.Comment,\r\n textContent: n.textContent || '',\r\n rootId,\r\n };\r\n default:\r\n return false;\r\n }\r\n}\r\nfunction getRootId(doc, mirror) {\r\n if (!mirror.hasNode(doc))\r\n return undefined;\r\n const docId = mirror.getId(doc);\r\n return docId === 1 ? undefined : docId;\r\n}\r\nfunction serializeTextNode(n, options) {\r\n const { maskAllText, maskTextClass, unmaskTextClass, maskTextSelector, unmaskTextSelector, maskTextFn, maskInputOptions, maskInputFn, rootId, } = options;\r\n const parentTagName = n.parentNode && n.parentNode.tagName;\r\n let textContent = n.textContent;\r\n const isStyle = parentTagName === 'STYLE' ? true : undefined;\r\n const isScript = parentTagName === 'SCRIPT' ? true : undefined;\r\n const isTextarea = parentTagName === 'TEXTAREA' ? true : undefined;\r\n if (isStyle && textContent) {\r\n try {\r\n if (n.nextSibling || n.previousSibling) {\r\n }\r\n else if (n.parentNode.sheet?.cssRules) {\r\n textContent = stringifyStylesheet(n.parentNode.sheet);\r\n }\r\n }\r\n catch (err) {\r\n console.warn(`Cannot get CSS styles from text's parentNode. Error: ${err}`, n);\r\n }\r\n textContent = absoluteToStylesheet(textContent, getHref());\r\n }\r\n if (isScript) {\r\n textContent = 'SCRIPT_PLACEHOLDER';\r\n }\r\n const forceMask = needMaskingText(n, maskTextClass, maskTextSelector, unmaskTextClass, unmaskTextSelector, maskAllText);\r\n if (!isStyle && !isScript && !isTextarea && textContent && forceMask) {\r\n textContent = maskTextFn\r\n ? maskTextFn(textContent, n.parentElement)\r\n : textContent.replace(/[\\S]/g, '*');\r\n }\r\n if (isTextarea && textContent && (maskInputOptions.textarea || forceMask)) {\r\n textContent = maskInputFn\r\n ? maskInputFn(textContent, n.parentNode)\r\n : textContent.replace(/[\\S]/g, '*');\r\n }\r\n if (parentTagName === 'OPTION' && textContent) {\r\n const isInputMasked = shouldMaskInput({\r\n type: null,\r\n tagName: parentTagName,\r\n maskInputOptions,\r\n });\r\n textContent = maskInputValue({\r\n isMasked: needMaskingText(n, maskTextClass, maskTextSelector, unmaskTextClass, unmaskTextSelector, isInputMasked),\r\n element: n,\r\n value: textContent,\r\n maskInputFn,\r\n });\r\n }\r\n return {\r\n type: NodeType.Text,\r\n textContent: textContent || '',\r\n isStyle,\r\n rootId,\r\n };\r\n}\r\nfunction serializeElementNode(n, options) {\r\n const { doc, blockClass, blockSelector, unblockSelector, inlineStylesheet, maskInputOptions = {}, maskAttributeFn, maskInputFn, dataURLOptions = {}, inlineImages, recordCanvas, keepIframeSrcFn, newlyAddedElement = false, rootId, maskAllText, maskTextClass, unmaskTextClass, maskTextSelector, unmaskTextSelector, } = options;\r\n const needBlock = _isBlockedElement(n, blockClass, blockSelector, unblockSelector);\r\n const tagName = getValidTagName(n);\r\n let attributes = {};\r\n const len = n.attributes.length;\r\n for (let i = 0; i < len; i++) {\r\n const attr = n.attributes[i];\r\n if (attr.name && !ignoreAttribute(tagName, attr.name, attr.value)) {\r\n attributes[attr.name] = transformAttribute(doc, tagName, toLowerCase(attr.name), attr.value, n, maskAttributeFn);\r\n }\r\n }\r\n if (tagName === 'link' && inlineStylesheet) {\r\n const stylesheet = Array.from(doc.styleSheets).find((s) => {\r\n return s.href === n.href;\r\n });\r\n let cssText = null;\r\n if (stylesheet) {\r\n cssText = stringifyStylesheet(stylesheet);\r\n }\r\n if (cssText) {\r\n delete attributes.rel;\r\n delete attributes.href;\r\n attributes._cssText = absoluteToStylesheet(cssText, stylesheet.href);\r\n }\r\n }\r\n if (tagName === 'style' &&\r\n n.sheet &&\r\n !(n.innerText || n.textContent || '').trim().length) {\r\n const cssText = stringifyStylesheet(n.sheet);\r\n if (cssText) {\r\n attributes._cssText = absoluteToStylesheet(cssText, getHref());\r\n }\r\n }\r\n if (tagName === 'input' ||\r\n tagName === 'textarea' ||\r\n tagName === 'select' ||\r\n tagName === 'option') {\r\n const el = n;\r\n const type = getInputType(el);\r\n const value = getInputValue(el, toUpperCase(tagName), type);\r\n const checked = el.checked;\r\n if (type !== 'submit' && type !== 'button' && value) {\r\n const forceMask = needMaskingText(el, maskTextClass, maskTextSelector, unmaskTextClass, unmaskTextSelector, shouldMaskInput({\r\n type,\r\n tagName: toUpperCase(tagName),\r\n maskInputOptions,\r\n }));\r\n attributes.value = maskInputValue({\r\n isMasked: forceMask,\r\n element: el,\r\n value,\r\n maskInputFn,\r\n });\r\n }\r\n if (checked) {\r\n attributes.checked = checked;\r\n }\r\n }\r\n if (tagName === 'option') {\r\n if (n.selected && !maskInputOptions['select']) {\r\n attributes.selected = true;\r\n }\r\n else {\r\n delete attributes.selected;\r\n }\r\n }\r\n if (tagName === 'canvas' && recordCanvas) {\r\n if (n.__context === '2d') {\r\n if (!is2DCanvasBlank(n)) {\r\n attributes.rr_dataURL = n.toDataURL(dataURLOptions.type, dataURLOptions.quality);\r\n }\r\n }\r\n else if (!('__context' in n)) {\r\n const canvasDataURL = n.toDataURL(dataURLOptions.type, dataURLOptions.quality);\r\n const blankCanvas = document.createElement('canvas');\r\n blankCanvas.width = n.width;\r\n blankCanvas.height = n.height;\r\n const blankCanvasDataURL = blankCanvas.toDataURL(dataURLOptions.type, dataURLOptions.quality);\r\n if (canvasDataURL !== blankCanvasDataURL) {\r\n attributes.rr_dataURL = canvasDataURL;\r\n }\r\n }\r\n }\r\n if (tagName === 'img' && inlineImages) {\r\n if (!canvasService) {\r\n canvasService = doc.createElement('canvas');\r\n canvasCtx = canvasService.getContext('2d');\r\n }\r\n const image = n;\r\n const oldValue = image.crossOrigin;\r\n image.crossOrigin = 'anonymous';\r\n const recordInlineImage = () => {\r\n image.removeEventListener('load', recordInlineImage);\r\n try {\r\n canvasService.width = image.naturalWidth;\r\n canvasService.height = image.naturalHeight;\r\n canvasCtx.drawImage(image, 0, 0);\r\n attributes.rr_dataURL = canvasService.toDataURL(dataURLOptions.type, dataURLOptions.quality);\r\n }\r\n catch (err) {\r\n console.warn(`Cannot inline img src=${image.currentSrc}! Error: ${err}`);\r\n }\r\n oldValue\r\n ? (attributes.crossOrigin = oldValue)\r\n : image.removeAttribute('crossorigin');\r\n };\r\n if (image.complete && image.naturalWidth !== 0)\r\n recordInlineImage();\r\n else\r\n image.addEventListener('load', recordInlineImage);\r\n }\r\n if (tagName === 'audio' || tagName === 'video') {\r\n attributes.rr_mediaState = n.paused\r\n ? 'paused'\r\n : 'played';\r\n attributes.rr_mediaCurrentTime = n.currentTime;\r\n }\r\n if (!newlyAddedElement) {\r\n if (n.scrollLeft) {\r\n attributes.rr_scrollLeft = n.scrollLeft;\r\n }\r\n if (n.scrollTop) {\r\n attributes.rr_scrollTop = n.scrollTop;\r\n }\r\n }\r\n if (needBlock) {\r\n const { width, height } = n.getBoundingClientRect();\r\n attributes = {\r\n class: attributes.class,\r\n rr_width: `${width}px`,\r\n rr_height: `${height}px`,\r\n };\r\n }\r\n if (tagName === 'iframe' && !keepIframeSrcFn(attributes.src)) {\r\n if (!n.contentDocument) {\r\n attributes.rr_src = attributes.src;\r\n }\r\n delete attributes.src;\r\n }\r\n let isCustomElement;\r\n try {\r\n if (customElements.get(tagName))\r\n isCustomElement = true;\r\n }\r\n catch (e) {\r\n }\r\n return {\r\n type: NodeType.Element,\r\n tagName,\r\n attributes,\r\n childNodes: [],\r\n isSVG: isSVGElement(n) || undefined,\r\n needBlock,\r\n rootId,\r\n isCustom: isCustomElement,\r\n };\r\n}\r\nfunction lowerIfExists(maybeAttr) {\r\n if (maybeAttr === undefined || maybeAttr === null) {\r\n return '';\r\n }\r\n else {\r\n return maybeAttr.toLowerCase();\r\n }\r\n}\r\nfunction slimDOMExcluded(sn, slimDOMOptions) {\r\n if (slimDOMOptions.comment && sn.type === NodeType.Comment) {\r\n return true;\r\n }\r\n else if (sn.type === NodeType.Element) {\r\n if (slimDOMOptions.script &&\r\n (sn.tagName === 'script' ||\r\n (sn.tagName === 'link' &&\r\n (sn.attributes.rel === 'preload' ||\r\n sn.attributes.rel === 'modulepreload') &&\r\n sn.attributes.as === 'script') ||\r\n (sn.tagName === 'link' &&\r\n sn.attributes.rel === 'prefetch' &&\r\n typeof sn.attributes.href === 'string' &&\r\n sn.attributes.href.endsWith('.js')))) {\r\n return true;\r\n }\r\n else if (slimDOMOptions.headFavicon &&\r\n ((sn.tagName === 'link' && sn.attributes.rel === 'shortcut icon') ||\r\n (sn.tagName === 'meta' &&\r\n (lowerIfExists(sn.attributes.name).match(/^msapplication-tile(image|color)$/) ||\r\n lowerIfExists(sn.attributes.name) === 'application-name' ||\r\n lowerIfExists(sn.attributes.rel) === 'icon' ||\r\n lowerIfExists(sn.attributes.rel) === 'apple-touch-icon' ||\r\n lowerIfExists(sn.attributes.rel) === 'shortcut icon')))) {\r\n return true;\r\n }\r\n else if (sn.tagName === 'meta') {\r\n if (slimDOMOptions.headMetaDescKeywords &&\r\n lowerIfExists(sn.attributes.name).match(/^description|keywords$/)) {\r\n return true;\r\n }\r\n else if (slimDOMOptions.headMetaSocial &&\r\n (lowerIfExists(sn.attributes.property).match(/^(og|twitter|fb):/) ||\r\n lowerIfExists(sn.attributes.name).match(/^(og|twitter):/) ||\r\n lowerIfExists(sn.attributes.name) === 'pinterest')) {\r\n return true;\r\n }\r\n else if (slimDOMOptions.headMetaRobots &&\r\n (lowerIfExists(sn.attributes.name) === 'robots' ||\r\n lowerIfExists(sn.attributes.name) === 'googlebot' ||\r\n lowerIfExists(sn.attributes.name) === 'bingbot')) {\r\n return true;\r\n }\r\n else if (slimDOMOptions.headMetaHttpEquiv &&\r\n sn.attributes['http-equiv'] !== undefined) {\r\n return true;\r\n }\r\n else if (slimDOMOptions.headMetaAuthorship &&\r\n (lowerIfExists(sn.attributes.name) === 'author' ||\r\n lowerIfExists(sn.attributes.name) === 'generator' ||\r\n lowerIfExists(sn.attributes.name) === 'framework' ||\r\n lowerIfExists(sn.attributes.name) === 'publisher' ||\r\n lowerIfExists(sn.attributes.name) === 'progid' ||\r\n lowerIfExists(sn.attributes.property).match(/^article:/) ||\r\n lowerIfExists(sn.attributes.property).match(/^product:/))) {\r\n return true;\r\n }\r\n else if (slimDOMOptions.headMetaVerification &&\r\n (lowerIfExists(sn.attributes.name) === 'google-site-verification' ||\r\n lowerIfExists(sn.attributes.name) === 'yandex-verification' ||\r\n lowerIfExists(sn.attributes.name) === 'csrf-token' ||\r\n lowerIfExists(sn.attributes.name) === 'p:domain_verify' ||\r\n lowerIfExists(sn.attributes.name) === 'verify-v1' ||\r\n lowerIfExists(sn.attributes.name) === 'verification' ||\r\n lowerIfExists(sn.attributes.name) === 'shopify-checkout-api-token')) {\r\n return true;\r\n }\r\n }\r\n }\r\n return false;\r\n}\r\nfunction serializeNodeWithId(n, options) {\r\n const { doc, mirror, blockClass, blockSelector, unblockSelector, maskAllText, maskTextClass, unmaskTextClass, maskTextSelector, unmaskTextSelector, skipChild = false, inlineStylesheet = true, maskInputOptions = {}, maskAttributeFn, maskTextFn, maskInputFn, slimDOMOptions, dataURLOptions = {}, inlineImages = false, recordCanvas = false, onSerialize, onIframeLoad, iframeLoadTimeout = 5000, onStylesheetLoad, stylesheetLoadTimeout = 5000, keepIframeSrcFn = () => false, newlyAddedElement = false, } = options;\r\n let { preserveWhiteSpace = true } = options;\r\n const _serializedNode = serializeNode(n, {\r\n doc,\r\n mirror,\r\n blockClass,\r\n blockSelector,\r\n maskAllText,\r\n unblockSelector,\r\n maskTextClass,\r\n unmaskTextClass,\r\n maskTextSelector,\r\n unmaskTextSelector,\r\n inlineStylesheet,\r\n maskInputOptions,\r\n maskAttributeFn,\r\n maskTextFn,\r\n maskInputFn,\r\n dataURLOptions,\r\n inlineImages,\r\n recordCanvas,\r\n keepIframeSrcFn,\r\n newlyAddedElement,\r\n });\r\n if (!_serializedNode) {\r\n console.warn(n, 'not serialized');\r\n return null;\r\n }\r\n let id;\r\n if (mirror.hasNode(n)) {\r\n id = mirror.getId(n);\r\n }\r\n else if (slimDOMExcluded(_serializedNode, slimDOMOptions) ||\r\n (!preserveWhiteSpace &&\r\n _serializedNode.type === NodeType.Text &&\r\n !_serializedNode.isStyle &&\r\n !_serializedNode.textContent.replace(/^\\s+|\\s+$/gm, '').length)) {\r\n id = IGNORED_NODE;\r\n }\r\n else {\r\n id = genId();\r\n }\r\n const serializedNode = Object.assign(_serializedNode, { id });\r\n mirror.add(n, serializedNode);\r\n if (id === IGNORED_NODE) {\r\n return null;\r\n }\r\n if (onSerialize) {\r\n onSerialize(n);\r\n }\r\n let recordChild = !skipChild;\r\n if (serializedNode.type === NodeType.Element) {\r\n recordChild = recordChild && !serializedNode.needBlock;\r\n delete serializedNode.needBlock;\r\n const shadowRoot = n.shadowRoot;\r\n if (shadowRoot && isNativeShadowDom(shadowRoot))\r\n serializedNode.isShadowHost = true;\r\n }\r\n if ((serializedNode.type === NodeType.Document ||\r\n serializedNode.type === NodeType.Element) &&\r\n recordChild) {\r\n if (slimDOMOptions.headWhitespace &&\r\n serializedNode.type === NodeType.Element &&\r\n serializedNode.tagName === 'head') {\r\n preserveWhiteSpace = false;\r\n }\r\n const bypassOptions = {\r\n doc,\r\n mirror,\r\n blockClass,\r\n blockSelector,\r\n maskAllText,\r\n unblockSelector,\r\n maskTextClass,\r\n unmaskTextClass,\r\n maskTextSelector,\r\n unmaskTextSelector,\r\n skipChild,\r\n inlineStylesheet,\r\n maskInputOptions,\r\n maskAttributeFn,\r\n maskTextFn,\r\n maskInputFn,\r\n slimDOMOptions,\r\n dataURLOptions,\r\n inlineImages,\r\n recordCanvas,\r\n preserveWhiteSpace,\r\n onSerialize,\r\n onIframeLoad,\r\n iframeLoadTimeout,\r\n onStylesheetLoad,\r\n stylesheetLoadTimeout,\r\n keepIframeSrcFn,\r\n };\r\n for (const childN of Array.from(n.childNodes)) {\r\n const serializedChildNode = serializeNodeWithId(childN, bypassOptions);\r\n if (serializedChildNode) {\r\n serializedNode.childNodes.push(serializedChildNode);\r\n }\r\n }\r\n if (isElement(n) && n.shadowRoot) {\r\n for (const childN of Array.from(n.shadowRoot.childNodes)) {\r\n const serializedChildNode = serializeNodeWithId(childN, bypassOptions);\r\n if (serializedChildNode) {\r\n isNativeShadowDom(n.shadowRoot) &&\r\n (serializedChildNode.isShadow = true);\r\n serializedNode.childNodes.push(serializedChildNode);\r\n }\r\n }\r\n }\r\n }\r\n if (n.parentNode &&\r\n isShadowRoot(n.parentNode) &&\r\n isNativeShadowDom(n.parentNode)) {\r\n serializedNode.isShadow = true;\r\n }\r\n if (serializedNode.type === NodeType.Element &&\r\n serializedNode.tagName === 'iframe') {\r\n onceIframeLoaded(n, () => {\r\n const iframeDoc = n.contentDocument;\r\n if (iframeDoc && onIframeLoad) {\r\n const serializedIframeNode = serializeNodeWithId(iframeDoc, {\r\n doc: iframeDoc,\r\n mirror,\r\n blockClass,\r\n blockSelector,\r\n unblockSelector,\r\n maskAllText,\r\n maskTextClass,\r\n unmaskTextClass,\r\n maskTextSelector,\r\n unmaskTextSelector,\r\n skipChild: false,\r\n inlineStylesheet,\r\n maskInputOptions,\r\n maskAttributeFn,\r\n maskTextFn,\r\n maskInputFn,\r\n slimDOMOptions,\r\n dataURLOptions,\r\n inlineImages,\r\n recordCanvas,\r\n preserveWhiteSpace,\r\n onSerialize,\r\n onIframeLoad,\r\n iframeLoadTimeout,\r\n onStylesheetLoad,\r\n stylesheetLoadTimeout,\r\n keepIframeSrcFn,\r\n });\r\n if (serializedIframeNode) {\r\n onIframeLoad(n, serializedIframeNode);\r\n }\r\n }\r\n }, iframeLoadTimeout);\r\n }\r\n if (serializedNode.type === NodeType.Element &&\r\n serializedNode.tagName === 'link' &&\r\n serializedNode.attributes.rel === 'stylesheet') {\r\n onceStylesheetLoaded(n, () => {\r\n if (onStylesheetLoad) {\r\n const serializedLinkNode = serializeNodeWithId(n, {\r\n doc,\r\n mirror,\r\n blockClass,\r\n blockSelector,\r\n unblockSelector,\r\n maskAllText,\r\n maskTextClass,\r\n unmaskTextClass,\r\n maskTextSelector,\r\n unmaskTextSelector,\r\n skipChild: false,\r\n inlineStylesheet,\r\n maskInputOptions,\r\n maskAttributeFn,\r\n maskTextFn,\r\n maskInputFn,\r\n slimDOMOptions,\r\n dataURLOptions,\r\n inlineImages,\r\n recordCanvas,\r\n preserveWhiteSpace,\r\n onSerialize,\r\n onIframeLoad,\r\n iframeLoadTimeout,\r\n onStylesheetLoad,\r\n stylesheetLoadTimeout,\r\n keepIframeSrcFn,\r\n });\r\n if (serializedLinkNode) {\r\n onStylesheetLoad(n, serializedLinkNode);\r\n }\r\n }\r\n }, stylesheetLoadTimeout);\r\n }\r\n return serializedNode;\r\n}\r\nfunction snapshot(n, options) {\r\n const { mirror = new Mirror(), blockClass = 'rr-block', blockSelector = null, unblockSelector = null, maskAllText = false, maskTextClass = 'rr-mask', unmaskTextClass = null, maskTextSelector = null, unmaskTextSelector = null, inlineStylesheet = true, inlineImages = false, recordCanvas = false, maskAllInputs = false, maskAttributeFn, maskTextFn, maskInputFn, slimDOM = false, dataURLOptions, preserveWhiteSpace, onSerialize, onIframeLoad, iframeLoadTimeout, onStylesheetLoad, stylesheetLoadTimeout, keepIframeSrcFn = () => false, } = options || {};\r\n const maskInputOptions = maskAllInputs === true\r\n ? {\r\n color: true,\r\n date: true,\r\n 'datetime-local': true,\r\n email: true,\r\n month: true,\r\n number: true,\r\n range: true,\r\n search: true,\r\n tel: true,\r\n text: true,\r\n time: true,\r\n url: true,\r\n week: true,\r\n textarea: true,\r\n select: true,\r\n }\r\n : maskAllInputs === false\r\n ? {}\r\n : maskAllInputs;\r\n const slimDOMOptions = slimDOM === true || slimDOM === 'all'\r\n ?\r\n {\r\n script: true,\r\n comment: true,\r\n headFavicon: true,\r\n headWhitespace: true,\r\n headMetaDescKeywords: slimDOM === 'all',\r\n headMetaSocial: true,\r\n headMetaRobots: true,\r\n headMetaHttpEquiv: true,\r\n headMetaAuthorship: true,\r\n headMetaVerification: true,\r\n }\r\n : slimDOM === false\r\n ? {}\r\n : slimDOM;\r\n return serializeNodeWithId(n, {\r\n doc: n,\r\n mirror,\r\n blockClass,\r\n blockSelector,\r\n unblockSelector,\r\n maskAllText,\r\n maskTextClass,\r\n unmaskTextClass,\r\n maskTextSelector,\r\n unmaskTextSelector,\r\n skipChild: false,\r\n inlineStylesheet,\r\n maskInputOptions,\r\n maskAttributeFn,\r\n maskTextFn,\r\n maskInputFn,\r\n slimDOMOptions,\r\n dataURLOptions,\r\n inlineImages,\r\n recordCanvas,\r\n preserveWhiteSpace,\r\n onSerialize,\r\n onIframeLoad,\r\n iframeLoadTimeout,\r\n onStylesheetLoad,\r\n stylesheetLoadTimeout,\r\n keepIframeSrcFn,\r\n newlyAddedElement: false,\r\n });\r\n}\r\nfunction visitSnapshot(node, onVisit) {\r\n function walk(current) {\r\n onVisit(current);\r\n if (current.type === NodeType.Document ||\r\n current.type === NodeType.Element) {\r\n current.childNodes.forEach(walk);\r\n }\r\n }\r\n walk(node);\r\n}\r\nfunction cleanupSnapshot() {\r\n _id = 1;\r\n}\n\nconst commentre = /\\/\\*[^*]*\\*+([^/*][^*]*\\*+)*\\//g;\r\nfunction parse(css, options = {}) {\r\n let lineno = 1;\r\n let column = 1;\r\n function updatePosition(str) {\r\n const lines = str.match(/\\n/g);\r\n if (lines) {\r\n lineno += lines.length;\r\n }\r\n const i = str.lastIndexOf('\\n');\r\n column = i === -1 ? column + str.length : str.length - i;\r\n }\r\n function position() {\r\n const start = { line: lineno, column };\r\n return (node) => {\r\n node.position = new Position(start);\r\n whitespace();\r\n return node;\r\n };\r\n }\r\n class Position {\r\n constructor(start) {\r\n this.start = start;\r\n this.end = { line: lineno, column };\r\n this.source = options.source;\r\n }\r\n }\r\n Position.prototype.content = css;\r\n const errorsList = [];\r\n function error(msg) {\r\n const err = new Error(`${options.source || ''}:${lineno}:${column}: ${msg}`);\r\n err.reason = msg;\r\n err.filename = options.source;\r\n err.line = lineno;\r\n err.column = column;\r\n err.source = css;\r\n if (options.silent) {\r\n errorsList.push(err);\r\n }\r\n else {\r\n throw err;\r\n }\r\n }\r\n function stylesheet() {\r\n const rulesList = rules();\r\n return {\r\n type: 'stylesheet',\r\n stylesheet: {\r\n source: options.source,\r\n rules: rulesList,\r\n parsingErrors: errorsList,\r\n },\r\n };\r\n }\r\n function open() {\r\n return match(/^{\\s*/);\r\n }\r\n function close() {\r\n return match(/^}/);\r\n }\r\n function rules() {\r\n let node;\r\n const rules = [];\r\n whitespace();\r\n comments(rules);\r\n while (css.length && css.charAt(0) !== '}' && (node = atrule() || rule())) {\r\n if (node) {\r\n rules.push(node);\r\n comments(rules);\r\n }\r\n }\r\n return rules;\r\n }\r\n function match(re) {\r\n const m = re.exec(css);\r\n if (!m) {\r\n return;\r\n }\r\n const str = m[0];\r\n updatePosition(str);\r\n css = css.slice(str.length);\r\n return m;\r\n }\r\n function whitespace() {\r\n match(/^\\s*/);\r\n }\r\n function comments(rules = []) {\r\n let c;\r\n while ((c = comment())) {\r\n if (c) {\r\n rules.push(c);\r\n }\r\n c = comment();\r\n }\r\n return rules;\r\n }\r\n function comment() {\r\n const pos = position();\r\n if ('/' !== css.charAt(0) || '*' !== css.charAt(1)) {\r\n return;\r\n }\r\n let i = 2;\r\n while ('' !== css.charAt(i) &&\r\n ('*' !== css.charAt(i) || '/' !== css.charAt(i + 1))) {\r\n ++i;\r\n }\r\n i += 2;\r\n if ('' === css.charAt(i - 1)) {\r\n return error('End of comment missing');\r\n }\r\n const str = css.slice(2, i - 2);\r\n column += 2;\r\n updatePosition(str);\r\n css = css.slice(i);\r\n column += 2;\r\n return pos({\r\n type: 'comment',\r\n comment: str,\r\n });\r\n }\r\n function selector() {\r\n whitespace();\r\n while (css[0] == '}') {\r\n error('extra closing bracket');\r\n css = css.slice(1);\r\n whitespace();\r\n }\r\n const m = match(/^((\"(?:\\\\\"|[^\"])*\"|'(?:\\\\'|[^'])*'|[^{])+)/);\r\n if (!m) {\r\n return;\r\n }\r\n const cleanedInput = m[0]\r\n .trim()\r\n .replace(/\\/\\*([^*]|[\\r\\n]|(\\*+([^*/]|[\\r\\n])))*\\*\\/+/g, '')\r\n .replace(/\"(?:\\\\\"|[^\"])*\"|'(?:\\\\'|[^'])*'/g, (m) => {\r\n return m.replace(/,/g, '\\u200C');\r\n });\r\n return customSplit(cleanedInput).map((s) => s.replace(/\\u200C/g, ',').trim());\r\n }\r\n function customSplit(input) {\r\n const result = [];\r\n let currentSegment = '';\r\n let depthParentheses = 0;\r\n let depthBrackets = 0;\r\n let currentStringChar = null;\r\n for (const char of input) {\r\n const hasStringEscape = currentSegment.endsWith('\\\\');\r\n if (currentStringChar) {\r\n if (currentStringChar === char && !hasStringEscape) {\r\n currentStringChar = null;\r\n }\r\n }\r\n else if (char === '(') {\r\n depthParentheses++;\r\n }\r\n else if (char === ')') {\r\n depthParentheses--;\r\n }\r\n else if (char === '[') {\r\n depthBrackets++;\r\n }\r\n else if (char === ']') {\r\n depthBrackets--;\r\n }\r\n else if ('\\'\"'.includes(char)) {\r\n currentStringChar = char;\r\n }\r\n if (char === ',' && depthParentheses === 0 && depthBrackets === 0) {\r\n result.push(currentSegment);\r\n currentSegment = '';\r\n }\r\n else {\r\n currentSegment += char;\r\n }\r\n }\r\n if (currentSegment) {\r\n result.push(currentSegment);\r\n }\r\n return result;\r\n }\r\n function declaration() {\r\n const pos = position();\r\n const propMatch = match(/^(\\*?[-#\\/\\*\\\\\\w]+(\\[[0-9a-z_-]+\\])?)\\s*/);\r\n if (!propMatch) {\r\n return;\r\n }\r\n const prop = trim(propMatch[0]);\r\n if (!match(/^:\\s*/)) {\r\n return error(`property missing ':'`);\r\n }\r\n const val = match(/^((?:'(?:\\\\'|.)*?'|\"(?:\\\\\"|.)*?\"|\\([^\\)]*?\\)|[^};])+)/);\r\n const ret = pos({\r\n type: 'declaration',\r\n property: prop.replace(commentre, ''),\r\n value: val ? trim(val[0]).replace(commentre, '') : '',\r\n });\r\n match(/^[;\\s]*/);\r\n return ret;\r\n }\r\n function declarations() {\r\n const decls = [];\r\n if (!open()) {\r\n return error(`missing '{'`);\r\n }\r\n comments(decls);\r\n let decl;\r\n while ((decl = declaration())) {\r\n if (decl !== false) {\r\n decls.push(decl);\r\n comments(decls);\r\n }\r\n decl = declaration();\r\n }\r\n if (!close()) {\r\n return error(`missing '}'`);\r\n }\r\n return decls;\r\n }\r\n function keyframe() {\r\n let m;\r\n const vals = [];\r\n const pos = position();\r\n while ((m = match(/^((\\d+\\.\\d+|\\.\\d+|\\d+)%?|[a-z]+)\\s*/))) {\r\n vals.push(m[1]);\r\n match(/^,\\s*/);\r\n }\r\n if (!vals.length) {\r\n return;\r\n }\r\n return pos({\r\n type: 'keyframe',\r\n values: vals,\r\n declarations: declarations(),\r\n });\r\n }\r\n function atkeyframes() {\r\n const pos = position();\r\n let m = match(/^@([-\\w]+)?keyframes\\s*/);\r\n if (!m) {\r\n return;\r\n }\r\n const vendor = m[1];\r\n m = match(/^([-\\w]+)\\s*/);\r\n if (!m) {\r\n return error('@keyframes missing name');\r\n }\r\n const name = m[1];\r\n if (!open()) {\r\n return error(`@keyframes missing '{'`);\r\n }\r\n let frame;\r\n let frames = comments();\r\n while ((frame = keyframe())) {\r\n frames.push(frame);\r\n frames = frames.concat(comments());\r\n }\r\n if (!close()) {\r\n return error(`@keyframes missing '}'`);\r\n }\r\n return pos({\r\n type: 'keyframes',\r\n name,\r\n vendor,\r\n keyframes: frames,\r\n });\r\n }\r\n function atsupports() {\r\n const pos = position();\r\n const m = match(/^@supports *([^{]+)/);\r\n if (!m) {\r\n return;\r\n }\r\n const supports = trim(m[1]);\r\n if (!open()) {\r\n return error(`@supports missing '{'`);\r\n }\r\n const style = comments().concat(rules());\r\n if (!close()) {\r\n return error(`@supports missing '}'`);\r\n }\r\n return pos({\r\n type: 'supports',\r\n supports,\r\n rules: style,\r\n });\r\n }\r\n function athost() {\r\n const pos = position();\r\n const m = match(/^@host\\s*/);\r\n if (!m) {\r\n return;\r\n }\r\n if (!open()) {\r\n return error(`@host missing '{'`);\r\n }\r\n const style = comments().concat(rules());\r\n if (!close()) {\r\n return error(`@host missing '}'`);\r\n }\r\n return pos({\r\n type: 'host',\r\n rules: style,\r\n });\r\n }\r\n function atmedia() {\r\n const pos = position();\r\n const m = match(/^@media *([^{]+)/);\r\n if (!m) {\r\n return;\r\n }\r\n const media = trim(m[1]);\r\n if (!open()) {\r\n return error(`@media missing '{'`);\r\n }\r\n const style = comments().concat(rules());\r\n if (!close()) {\r\n return error(`@media missing '}'`);\r\n }\r\n return pos({\r\n type: 'media',\r\n media,\r\n rules: style,\r\n });\r\n }\r\n function atcustommedia() {\r\n const pos = position();\r\n const m = match(/^@custom-media\\s+(--[^\\s]+)\\s*([^{;]+);/);\r\n if (!m) {\r\n return;\r\n }\r\n return pos({\r\n type: 'custom-media',\r\n name: trim(m[1]),\r\n media: trim(m[2]),\r\n });\r\n }\r\n function atpage() {\r\n const pos = position();\r\n const m = match(/^@page */);\r\n if (!m) {\r\n return;\r\n }\r\n const sel = selector() || [];\r\n if (!open()) {\r\n return error(`@page missing '{'`);\r\n }\r\n let decls = comments();\r\n let decl;\r\n while ((decl = declaration())) {\r\n decls.push(decl);\r\n decls = decls.concat(comments());\r\n }\r\n if (!close()) {\r\n return error(`@page missing '}'`);\r\n }\r\n return pos({\r\n type: 'page',\r\n selectors: sel,\r\n declarations: decls,\r\n });\r\n }\r\n function atdocument() {\r\n const pos = position();\r\n const m = match(/^@([-\\w]+)?document *([^{]+)/);\r\n if (!m) {\r\n return;\r\n }\r\n const vendor = trim(m[1]);\r\n const doc = trim(m[2]);\r\n if (!open()) {\r\n return error(`@document missing '{'`);\r\n }\r\n const style = comments().concat(rules());\r\n if (!close()) {\r\n return error(`@document missing '}'`);\r\n }\r\n return pos({\r\n type: 'document',\r\n document: doc,\r\n vendor,\r\n rules: style,\r\n });\r\n }\r\n function atfontface() {\r\n const pos = position();\r\n const m = match(/^@font-face\\s*/);\r\n if (!m) {\r\n return;\r\n }\r\n if (!open()) {\r\n return error(`@font-face missing '{'`);\r\n }\r\n let decls = comments();\r\n let decl;\r\n while ((decl = declaration())) {\r\n decls.push(decl);\r\n decls = decls.concat(comments());\r\n }\r\n if (!close()) {\r\n return error(`@font-face missing '}'`);\r\n }\r\n return pos({\r\n type: 'font-face',\r\n declarations: decls,\r\n });\r\n }\r\n const atimport = _compileAtrule('import');\r\n const atcharset = _compileAtrule('charset');\r\n const atnamespace = _compileAtrule('namespace');\r\n function _compileAtrule(name) {\r\n const re = new RegExp('^@' + name + '\\\\s*([^;]+);');\r\n return () => {\r\n const pos = position();\r\n const m = match(re);\r\n if (!m) {\r\n return;\r\n }\r\n const ret = { type: name };\r\n ret[name] = m[1].trim();\r\n return pos(ret);\r\n };\r\n }\r\n function atrule() {\r\n if (css[0] !== '@') {\r\n return;\r\n }\r\n return (atkeyframes() ||\r\n atmedia() ||\r\n atcustommedia() ||\r\n atsupports() ||\r\n atimport() ||\r\n atcharset() ||\r\n atnamespace() ||\r\n atdocument() ||\r\n atpage() ||\r\n athost() ||\r\n atfontface());\r\n }\r\n function rule() {\r\n const pos = position();\r\n const sel = selector();\r\n if (!sel) {\r\n return error('selector missing');\r\n }\r\n comments();\r\n return pos({\r\n type: 'rule',\r\n selectors: sel,\r\n declarations: declarations(),\r\n });\r\n }\r\n return addParent(stylesheet());\r\n}\r\nfunction trim(str) {\r\n return str ? str.replace(/^\\s+|\\s+$/g, '') : '';\r\n}\r\nfunction addParent(obj, parent) {\r\n const isNode = obj && typeof obj.type === 'string';\r\n const childParent = isNode ? obj : parent;\r\n for (const k of Object.keys(obj)) {\r\n const value = obj[k];\r\n if (Array.isArray(value)) {\r\n value.forEach((v) => {\r\n addParent(v, childParent);\r\n });\r\n }\r\n else if (value && typeof value === 'object') {\r\n addParent(value, childParent);\r\n }\r\n }\r\n if (isNode) {\r\n Object.defineProperty(obj, 'parent', {\r\n configurable: true,\r\n writable: true,\r\n enumerable: false,\r\n value: parent || null,\r\n });\r\n }\r\n return obj;\r\n}\n\nconst tagMap = {\r\n script: 'noscript',\r\n altglyph: 'altGlyph',\r\n altglyphdef: 'altGlyphDef',\r\n altglyphitem: 'altGlyphItem',\r\n animatecolor: 'animateColor',\r\n animatemotion: 'animateMotion',\r\n animatetransform: 'animateTransform',\r\n clippath: 'clipPath',\r\n feblend: 'feBlend',\r\n fecolormatrix: 'feColorMatrix',\r\n fecomponenttransfer: 'feComponentTransfer',\r\n fecomposite: 'feComposite',\r\n feconvolvematrix: 'feConvolveMatrix',\r\n fediffuselighting: 'feDiffuseLighting',\r\n fedisplacementmap: 'feDisplacementMap',\r\n fedistantlight: 'feDistantLight',\r\n fedropshadow: 'feDropShadow',\r\n feflood: 'feFlood',\r\n fefunca: 'feFuncA',\r\n fefuncb: 'feFuncB',\r\n fefuncg: 'feFuncG',\r\n fefuncr: 'feFuncR',\r\n fegaussianblur: 'feGaussianBlur',\r\n feimage: 'feImage',\r\n femerge: 'feMerge',\r\n femergenode: 'feMergeNode',\r\n femorphology: 'feMorphology',\r\n feoffset: 'feOffset',\r\n fepointlight: 'fePointLight',\r\n fespecularlighting: 'feSpecularLighting',\r\n fespotlight: 'feSpotLight',\r\n fetile: 'feTile',\r\n feturbulence: 'feTurbulence',\r\n foreignobject: 'foreignObject',\r\n glyphref: 'glyphRef',\r\n lineargradient: 'linearGradient',\r\n radialgradient: 'radialGradient',\r\n};\r\nfunction getTagName(n) {\r\n let tagName = tagMap[n.tagName] ? tagMap[n.tagName] : n.tagName;\r\n if (tagName === 'link' && n.attributes._cssText) {\r\n tagName = 'style';\r\n }\r\n return tagName;\r\n}\r\nfunction escapeRegExp(str) {\r\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\r\n}\r\nconst HOVER_SELECTOR = /([^\\\\]):hover/;\r\nconst HOVER_SELECTOR_GLOBAL = new RegExp(HOVER_SELECTOR.source, 'g');\r\nfunction addHoverClass(cssText, cache) {\r\n const cachedStyle = cache?.stylesWithHoverClass.get(cssText);\r\n if (cachedStyle)\r\n return cachedStyle;\r\n if (cssText.length >= 1000000) {\r\n return cssText;\r\n }\r\n const ast = parse(cssText, {\r\n silent: true,\r\n });\r\n if (!ast.stylesheet) {\r\n return cssText;\r\n }\r\n const selectors = [];\r\n ast.stylesheet.rules.forEach((rule) => {\r\n if ('selectors' in rule) {\r\n (rule.selectors || []).forEach((selector) => {\r\n if (HOVER_SELECTOR.test(selector)) {\r\n selectors.push(selector);\r\n }\r\n });\r\n }\r\n });\r\n if (selectors.length === 0) {\r\n return cssText;\r\n }\r\n const selectorMatcher = new RegExp(selectors\r\n .filter((selector, index) => selectors.indexOf(selector) === index)\r\n .sort((a, b) => b.length - a.length)\r\n .map((selector) => {\r\n return escapeRegExp(selector);\r\n })\r\n .join('|'), 'g');\r\n const result = cssText.replace(selectorMatcher, (selector) => {\r\n const newSelector = selector.replace(HOVER_SELECTOR_GLOBAL, '$1.\\\\:hover');\r\n return `${selector}, ${newSelector}`;\r\n });\r\n cache?.stylesWithHoverClass.set(cssText, result);\r\n return result;\r\n}\r\nfunction createCache() {\r\n const stylesWithHoverClass = new Map();\r\n return {\r\n stylesWithHoverClass,\r\n };\r\n}\r\nfunction buildNode(n, options) {\r\n const { doc, hackCss, cache } = options;\r\n switch (n.type) {\r\n case NodeType.Document:\r\n return doc.implementation.createDocument(null, '', null);\r\n case NodeType.DocumentType:\r\n return doc.implementation.createDocumentType(n.name || 'html', n.publicId, n.systemId);\r\n case NodeType.Element: {\r\n const tagName = getTagName(n);\r\n let node;\r\n if (n.isSVG) {\r\n node = doc.createElementNS('http://www.w3.org/2000/svg', tagName);\r\n }\r\n else {\r\n if (n.isCustom &&\r\n doc.defaultView?.customElements &&\r\n !doc.defaultView.customElements.get(n.tagName))\r\n doc.defaultView.customElements.define(n.tagName, class extends doc.defaultView.HTMLElement {\r\n });\r\n node = doc.createElement(tagName);\r\n }\r\n const specialAttributes = {};\r\n for (const name in n.attributes) {\r\n if (!Object.prototype.hasOwnProperty.call(n.attributes, name)) {\r\n continue;\r\n }\r\n let value = n.attributes[name];\r\n if (tagName === 'option' &&\r\n name === 'selected' &&\r\n value === false) {\r\n continue;\r\n }\r\n if (value === null) {\r\n continue;\r\n }\r\n if (value === true)\r\n value = '';\r\n if (name.startsWith('rr_')) {\r\n specialAttributes[name] = value;\r\n continue;\r\n }\r\n const isTextarea = tagName === 'textarea' && name === 'value';\r\n const isRemoteOrDynamicCss = tagName === 'style' && name === '_cssText';\r\n if (isRemoteOrDynamicCss && hackCss && typeof value === 'string') {\r\n value = addHoverClass(value, cache);\r\n }\r\n if ((isTextarea || isRemoteOrDynamicCss) && typeof value === 'string') {\r\n const child = doc.createTextNode(value);\r\n for (const c of Array.from(node.childNodes)) {\r\n if (c.nodeType === node.TEXT_NODE) {\r\n node.removeChild(c);\r\n }\r\n }\r\n node.appendChild(child);\r\n continue;\r\n }\r\n try {\r\n if (n.isSVG && name === 'xlink:href') {\r\n node.setAttributeNS('http://www.w3.org/1999/xlink', name, value.toString());\r\n }\r\n else if (name === 'onload' ||\r\n name === 'onclick' ||\r\n name.substring(0, 7) === 'onmouse') {\r\n node.setAttribute('_' + name, value.toString());\r\n }\r\n else if (tagName === 'meta' &&\r\n n.attributes['http-equiv'] === 'Content-Security-Policy' &&\r\n name === 'content') {\r\n node.setAttribute('csp-content', value.toString());\r\n continue;\r\n }\r\n else if (tagName === 'link' &&\r\n (n.attributes.rel === 'preload' ||\r\n n.attributes.rel === 'modulepreload') &&\r\n n.attributes.as === 'script') {\r\n }\r\n else if (tagName === 'link' &&\r\n n.attributes.rel === 'prefetch' &&\r\n typeof n.attributes.href === 'string' &&\r\n n.attributes.href.endsWith('.js')) {\r\n }\r\n else if (tagName === 'img' &&\r\n n.attributes.srcset &&\r\n n.attributes.rr_dataURL) {\r\n node.setAttribute('rrweb-original-srcset', n.attributes.srcset);\r\n }\r\n else {\r\n node.setAttribute(name, value.toString());\r\n }\r\n }\r\n catch (error) {\r\n }\r\n }\r\n for (const name in specialAttributes) {\r\n const value = specialAttributes[name];\r\n if (tagName === 'canvas' && name === 'rr_dataURL') {\r\n const image = document.createElement('img');\r\n image.onload = () => {\r\n const ctx = node.getContext('2d');\r\n if (ctx) {\r\n ctx.drawImage(image, 0, 0, image.width, image.height);\r\n }\r\n };\r\n image.src = value.toString();\r\n if (node.RRNodeType)\r\n node.rr_dataURL = value.toString();\r\n }\r\n else if (tagName === 'img' && name === 'rr_dataURL') {\r\n const image = node;\r\n if (!image.currentSrc.startsWith('data:')) {\r\n image.setAttribute('rrweb-original-src', n.attributes.src);\r\n image.src = value.toString();\r\n }\r\n }\r\n if (name === 'rr_width') {\r\n node.style.setProperty('width', value.toString());\r\n }\r\n else if (name === 'rr_height') {\r\n node.style.setProperty('height', value.toString());\r\n }\r\n else if (name === 'rr_mediaCurrentTime' &&\r\n typeof value === 'number') {\r\n node.currentTime = value;\r\n }\r\n else if (name === 'rr_mediaState') {\r\n switch (value) {\r\n case 'played':\r\n node\r\n .play()\r\n .catch((e) => console.warn('media playback error', e));\r\n break;\r\n case 'paused':\r\n node.pause();\r\n break;\r\n }\r\n }\r\n }\r\n if (n.isShadowHost) {\r\n if (!node.shadowRoot) {\r\n node.attachShadow({ mode: 'open' });\r\n }\r\n else {\r\n while (node.shadowRoot.firstChild) {\r\n node.shadowRoot.removeChild(node.shadowRoot.firstChild);\r\n }\r\n }\r\n }\r\n return node;\r\n }\r\n case NodeType.Text:\r\n return doc.createTextNode(n.isStyle && hackCss\r\n ? addHoverClass(n.textContent, cache)\r\n : n.textContent);\r\n case NodeType.CDATA:\r\n return doc.createCDATASection(n.textContent);\r\n case NodeType.Comment:\r\n return doc.createComment(n.textContent);\r\n default:\r\n return null;\r\n }\r\n}\r\nfunction buildNodeWithSN(n, options) {\r\n const { doc, mirror, skipChild = false, hackCss = true, afterAppend, cache, } = options;\r\n if (mirror.has(n.id)) {\r\n const nodeInMirror = mirror.getNode(n.id);\r\n const meta = mirror.getMeta(nodeInMirror);\r\n if (isNodeMetaEqual(meta, n))\r\n return mirror.getNode(n.id);\r\n }\r\n let node = buildNode(n, { doc, hackCss, cache });\r\n if (!node) {\r\n return null;\r\n }\r\n if (n.rootId && mirror.getNode(n.rootId) !== doc) {\r\n mirror.replace(n.rootId, doc);\r\n }\r\n if (n.type === NodeType.Document) {\r\n doc.close();\r\n doc.open();\r\n if (n.compatMode === 'BackCompat' &&\r\n n.childNodes &&\r\n n.childNodes[0].type !== NodeType.DocumentType) {\r\n if (n.childNodes[0].type === NodeType.Element &&\r\n 'xmlns' in n.childNodes[0].attributes &&\r\n n.childNodes[0].attributes.xmlns === 'http://www.w3.org/1999/xhtml') {\r\n doc.write('');\r\n }\r\n else {\r\n doc.write('');\r\n }\r\n }\r\n node = doc;\r\n }\r\n mirror.add(node, n);\r\n if ((n.type === NodeType.Document || n.type === NodeType.Element) &&\r\n !skipChild) {\r\n for (const childN of n.childNodes) {\r\n const childNode = buildNodeWithSN(childN, {\r\n doc,\r\n mirror,\r\n skipChild: false,\r\n hackCss,\r\n afterAppend,\r\n cache,\r\n });\r\n if (!childNode) {\r\n console.warn('Failed to rebuild', childN);\r\n continue;\r\n }\r\n if (childN.isShadow && isElement(node) && node.shadowRoot) {\r\n node.shadowRoot.appendChild(childNode);\r\n }\r\n else if (n.type === NodeType.Document &&\r\n childN.type == NodeType.Element) {\r\n const htmlElement = childNode;\r\n let body = null;\r\n htmlElement.childNodes.forEach((child) => {\r\n if (child.nodeName === 'BODY')\r\n body = child;\r\n });\r\n if (body) {\r\n htmlElement.removeChild(body);\r\n node.appendChild(childNode);\r\n htmlElement.appendChild(body);\r\n }\r\n else {\r\n node.appendChild(childNode);\r\n }\r\n }\r\n else {\r\n node.appendChild(childNode);\r\n }\r\n if (afterAppend) {\r\n afterAppend(childNode, childN.id);\r\n }\r\n }\r\n }\r\n return node;\r\n}\r\nfunction visit(mirror, onVisit) {\r\n function walk(node) {\r\n onVisit(node);\r\n }\r\n for (const id of mirror.getIds()) {\r\n if (mirror.has(id)) {\r\n walk(mirror.getNode(id));\r\n }\r\n }\r\n}\r\nfunction handleScroll(node, mirror) {\r\n const n = mirror.getMeta(node);\r\n if (n?.type !== NodeType.Element) {\r\n return;\r\n }\r\n const el = node;\r\n for (const name in n.attributes) {\r\n if (!(Object.prototype.hasOwnProperty.call(n.attributes, name) &&\r\n name.startsWith('rr_'))) {\r\n continue;\r\n }\r\n const value = n.attributes[name];\r\n if (name === 'rr_scrollLeft') {\r\n el.scrollLeft = value;\r\n }\r\n if (name === 'rr_scrollTop') {\r\n el.scrollTop = value;\r\n }\r\n }\r\n}\r\nfunction rebuild(n, options) {\r\n const { doc, onVisit, hackCss = true, afterAppend, cache, mirror = new Mirror(), } = options;\r\n const node = buildNodeWithSN(n, {\r\n doc,\r\n mirror,\r\n skipChild: false,\r\n hackCss,\r\n afterAppend,\r\n cache,\r\n });\r\n visit(mirror, (visitedNode) => {\r\n if (onVisit) {\r\n onVisit(visitedNode);\r\n }\r\n handleScroll(visitedNode, mirror);\r\n });\r\n return node;\r\n}\n\nexport { IGNORED_NODE, Mirror, NodeType, addHoverClass, buildNodeWithSN, classMatchesRegex, cleanupSnapshot, createCache, createMatchPredicate, createMirror, distanceToMatch, escapeImportStatement, fixSafariColons, genId, getInputType, getInputValue, ignoreAttribute, is2DCanvasBlank, isCSSImportRule, isCSSStyleRule, isElement, isNativeShadowDom, isNodeMetaEqual, isShadowRoot, maskInputValue, needMaskingText, rebuild, serializeNodeWithId, shouldMaskInput, snapshot, stringifyRule, stringifyStylesheet, toLowerCase, toUpperCase, transformAttribute, visitSnapshot };\n", "// Note that these are the serialized attributes and not attributes directly on\n// the DOM Node. Attributes we are interested in:\nconst ATTRIBUTES_TO_RECORD = new Set([\n 'id',\n 'class',\n 'aria-label',\n 'role',\n 'name',\n 'alt',\n 'title',\n 'data-test-id',\n 'data-testid',\n 'disabled',\n 'aria-disabled',\n 'data-sentry-component',\n]);\n\n/**\n * Inclusion list of attributes that we want to record from the DOM element\n */\nexport function getAttributesToRecord(attributes: Record): Record {\n const obj: Record = {};\n for (const key in attributes) {\n if (ATTRIBUTES_TO_RECORD.has(key)) {\n let normalizedKey = key;\n\n if (key === 'data-testid' || key === 'data-test-id') {\n normalizedKey = 'testId';\n }\n\n obj[normalizedKey] = attributes[key];\n }\n }\n\n return obj;\n}\n", "import { record } from '@sentry-internal/rrweb';\nimport type { serializedElementNodeWithId, serializedNodeWithId } from '@sentry-internal/rrweb-snapshot';\nimport { NodeType } from '@sentry-internal/rrweb-snapshot';\nimport type { Breadcrumb, HandlerDataDom } from '@sentry/types';\nimport { htmlTreeAsString } from '@sentry/utils';\n\nimport type { ReplayContainer } from '../types';\nimport { createBreadcrumb } from '../util/createBreadcrumb';\nimport { handleClick } from './handleClick';\nimport { addBreadcrumbEvent } from './util/addBreadcrumbEvent';\nimport { getClickTargetNode, getTargetNode } from './util/domUtils';\nimport { getAttributesToRecord } from './util/getAttributesToRecord';\n\nexport const handleDomListener: (replay: ReplayContainer) => (handlerData: HandlerDataDom) => void = (\n replay: ReplayContainer,\n) => {\n return (handlerData: HandlerDataDom): void => {\n if (!replay.isEnabled()) {\n return;\n }\n\n const result = handleDom(handlerData);\n\n if (!result) {\n return;\n }\n\n const isClick = handlerData.name === 'click';\n const event = isClick ? (handlerData.event as PointerEvent) : undefined;\n // Ignore clicks if ctrl/alt/meta/shift keys are held down as they alter behavior of clicks (e.g. open in new tab)\n if (\n isClick &&\n replay.clickDetector &&\n event &&\n event.target &&\n !event.altKey &&\n !event.metaKey &&\n !event.ctrlKey &&\n !event.shiftKey\n ) {\n handleClick(\n replay.clickDetector,\n result as Breadcrumb & { timestamp: number; data: { nodeId: number } },\n getClickTargetNode(handlerData.event as Event) as HTMLElement,\n );\n }\n\n addBreadcrumbEvent(replay, result);\n };\n};\n\n/** Get the base DOM breadcrumb. */\nexport function getBaseDomBreadcrumb(target: Node | null, message: string): Breadcrumb {\n const nodeId = record.mirror.getId(target);\n const node = nodeId && record.mirror.getNode(nodeId);\n const meta = node && record.mirror.getMeta(node);\n const element = meta && isElement(meta) ? meta : null;\n\n return {\n message,\n data: element\n ? {\n nodeId,\n node: {\n id: nodeId,\n tagName: element.tagName,\n textContent: Array.from(element.childNodes)\n .map((node: serializedNodeWithId) => node.type === NodeType.Text && node.textContent)\n .filter(Boolean) // filter out empty values\n .map(text => (text as string).trim())\n .join(''),\n attributes: getAttributesToRecord(element.attributes),\n },\n }\n : {},\n };\n}\n\n/**\n * An event handler to react to DOM events.\n * Exported for tests.\n */\nexport function handleDom(handlerData: HandlerDataDom): Breadcrumb | null {\n const { target, message } = getDomTarget(handlerData);\n\n return createBreadcrumb({\n category: `ui.${handlerData.name}`,\n ...getBaseDomBreadcrumb(target, message),\n });\n}\n\nfunction getDomTarget(handlerData: HandlerDataDom): { target: Node | null; message: string } {\n const isClick = handlerData.name === 'click';\n\n let message: string | undefined;\n let target: Node | null = null;\n\n // Accessing event.target can throw (see getsentry/raven-js#838, #768)\n try {\n target = isClick ? getClickTargetNode(handlerData.event as Event) : getTargetNode(handlerData.event as Event);\n message = htmlTreeAsString(target, { maxStringLength: 200 }) || '';\n } catch (e) {\n message = '';\n }\n\n return { target, message };\n}\n\nfunction isElement(node: serializedNodeWithId): node is serializedElementNodeWithId {\n return node.type === NodeType.Element;\n}\n", "import type { Breadcrumb } from '@sentry/types';\nimport { htmlTreeAsString } from '@sentry/utils';\n\nimport type { ReplayContainer } from '../types';\nimport { createBreadcrumb } from '../util/createBreadcrumb';\nimport { getBaseDomBreadcrumb } from './handleDom';\nimport { addBreadcrumbEvent } from './util/addBreadcrumbEvent';\n\n/** Handle keyboard events & create breadcrumbs. */\nexport function handleKeyboardEvent(replay: ReplayContainer, event: KeyboardEvent): void {\n if (!replay.isEnabled()) {\n return;\n }\n\n // Update user activity, but do not restart recording as it can create\n // noisy/low-value replays (e.g. user comes back from idle, hits alt-tab, new\n // session with a single \"keydown\" breadcrumb is created)\n replay.updateUserActivity();\n\n const breadcrumb = getKeyboardBreadcrumb(event);\n\n if (!breadcrumb) {\n return;\n }\n\n addBreadcrumbEvent(replay, breadcrumb);\n}\n\n/** exported only for tests */\nexport function getKeyboardBreadcrumb(event: KeyboardEvent): Breadcrumb | null {\n const { metaKey, shiftKey, ctrlKey, altKey, key, target } = event;\n\n // never capture for input fields\n if (!target || isInputElement(target as HTMLElement) || !key) {\n return null;\n }\n\n // Note: We do not consider shift here, as that means \"uppercase\"\n const hasModifierKey = metaKey || ctrlKey || altKey;\n const isCharacterKey = key.length === 1; // other keys like Escape, Tab, etc have a longer length\n\n // Do not capture breadcrumb if only a word key is pressed\n // This could leak e.g. user input\n if (!hasModifierKey && isCharacterKey) {\n return null;\n }\n\n const message = htmlTreeAsString(target, { maxStringLength: 200 }) || '';\n const baseBreadcrumb = getBaseDomBreadcrumb(target as Node, message);\n\n return createBreadcrumb({\n category: 'ui.keyDown',\n message,\n data: {\n ...baseBreadcrumb.data,\n metaKey,\n shiftKey,\n ctrlKey,\n altKey,\n key,\n },\n });\n}\n\nfunction isInputElement(target: HTMLElement): boolean {\n return target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable;\n}\n", "import { record } from '@sentry-internal/rrweb';\nimport { browserPerformanceTimeOrigin } from '@sentry/utils';\n\nimport { WINDOW } from '../constants';\nimport type {\n AllPerformanceEntry,\n AllPerformanceEntryData,\n ExperimentalPerformanceResourceTiming,\n LargestContentfulPaintData,\n NavigationData,\n PaintData,\n ReplayPerformanceEntry,\n ResourceData,\n} from '../types';\n\n// Map entryType -> function to normalize data for event\nconst ENTRY_TYPES: Record<\n string,\n (entry: AllPerformanceEntry) => null | ReplayPerformanceEntry\n> = {\n // @ts-expect-error TODO: entry type does not fit the create* functions entry type\n resource: createResourceEntry,\n paint: createPaintEntry,\n // @ts-expect-error TODO: entry type does not fit the create* functions entry type\n navigation: createNavigationEntry,\n};\n\n/**\n * Create replay performance entries from the browser performance entries.\n */\nexport function createPerformanceEntries(\n entries: AllPerformanceEntry[],\n): ReplayPerformanceEntry[] {\n return entries.map(createPerformanceEntry).filter(Boolean) as ReplayPerformanceEntry[];\n}\n\nfunction createPerformanceEntry(entry: AllPerformanceEntry): ReplayPerformanceEntry | null {\n if (!ENTRY_TYPES[entry.entryType]) {\n return null;\n }\n\n return ENTRY_TYPES[entry.entryType](entry);\n}\n\nfunction getAbsoluteTime(time: number): number {\n // browserPerformanceTimeOrigin can be undefined if `performance` or\n // `performance.now` doesn't exist, but this is already checked by this integration\n return ((browserPerformanceTimeOrigin || WINDOW.performance.timeOrigin) + time) / 1000;\n}\n\nfunction createPaintEntry(entry: PerformancePaintTiming): ReplayPerformanceEntry {\n const { duration, entryType, name, startTime } = entry;\n\n const start = getAbsoluteTime(startTime);\n return {\n type: entryType,\n name,\n start,\n end: start + duration,\n data: undefined,\n };\n}\n\nfunction createNavigationEntry(entry: PerformanceNavigationTiming): ReplayPerformanceEntry | null {\n const {\n entryType,\n name,\n decodedBodySize,\n duration,\n domComplete,\n encodedBodySize,\n domContentLoadedEventStart,\n domContentLoadedEventEnd,\n domInteractive,\n loadEventStart,\n loadEventEnd,\n redirectCount,\n startTime,\n transferSize,\n type,\n } = entry;\n\n // Ignore entries with no duration, they do not seem to be useful and cause dupes\n if (duration === 0) {\n return null;\n }\n\n return {\n type: `${entryType}.${type}`,\n start: getAbsoluteTime(startTime),\n end: getAbsoluteTime(domComplete),\n name,\n data: {\n size: transferSize,\n decodedBodySize,\n encodedBodySize,\n duration,\n domInteractive,\n domContentLoadedEventStart,\n domContentLoadedEventEnd,\n loadEventStart,\n loadEventEnd,\n domComplete,\n redirectCount,\n },\n };\n}\n\nfunction createResourceEntry(\n entry: ExperimentalPerformanceResourceTiming,\n): ReplayPerformanceEntry | null {\n const {\n entryType,\n initiatorType,\n name,\n responseEnd,\n startTime,\n decodedBodySize,\n encodedBodySize,\n responseStatus,\n transferSize,\n } = entry;\n\n // Core SDK handles these\n if (['fetch', 'xmlhttprequest'].includes(initiatorType)) {\n return null;\n }\n\n return {\n type: `${entryType}.${initiatorType}`,\n start: getAbsoluteTime(startTime),\n end: getAbsoluteTime(responseEnd),\n name,\n data: {\n size: transferSize,\n statusCode: responseStatus,\n decodedBodySize,\n encodedBodySize,\n },\n };\n}\n\n/**\n * Add a LCP event to the replay based on an LCP metric.\n */\nexport function getLargestContentfulPaint(metric: {\n value: number;\n entries: PerformanceEntry[];\n}): ReplayPerformanceEntry {\n const entries = metric.entries;\n const lastEntry = entries[entries.length - 1] as (PerformanceEntry & { element?: Element }) | undefined;\n const element = lastEntry ? lastEntry.element : undefined;\n\n const value = metric.value;\n\n const end = getAbsoluteTime(value);\n\n const data: ReplayPerformanceEntry = {\n type: 'largest-contentful-paint',\n name: 'largest-contentful-paint',\n start: end,\n end,\n data: {\n value,\n size: value,\n nodeId: element ? record.mirror.getId(element) : undefined,\n },\n };\n\n return data;\n}\n", "import { addLcpInstrumentationHandler, addPerformanceInstrumentationHandler } from '@sentry-internal/tracing';\n\nimport type { ReplayContainer } from '../types';\nimport { getLargestContentfulPaint } from '../util/createPerformanceEntries';\n\n/**\n * Sets up a PerformanceObserver to listen to all performance entry types.\n * Returns a callback to stop observing.\n */\nexport function setupPerformanceObserver(replay: ReplayContainer): () => void {\n function addPerformanceEntry(entry: PerformanceEntry): void {\n // It is possible for entries to come up multiple times\n if (!replay.performanceEntries.includes(entry)) {\n replay.performanceEntries.push(entry);\n }\n }\n\n function onEntries({ entries }: { entries: PerformanceEntry[] }): void {\n entries.forEach(addPerformanceEntry);\n }\n\n const clearCallbacks: (() => void)[] = [];\n\n (['navigation', 'paint', 'resource'] as const).forEach(type => {\n clearCallbacks.push(addPerformanceInstrumentationHandler(type, onEntries));\n });\n\n clearCallbacks.push(\n addLcpInstrumentationHandler(({ metric }) => {\n replay.replayPerformanceEntries.push(getLargestContentfulPaint(metric));\n }),\n );\n\n // A callback to cleanup all handlers\n return () => {\n clearCallbacks.forEach(clearCallback => clearCallback());\n };\n}\n", "declare const __DEBUG_BUILD__: boolean;\n\n/**\n * This serves as a build time flag that will be true by default, but false in non-debug builds or if users replace `__SENTRY_DEBUG__` in their generated code.\n *\n * ATTENTION: This constant must never cross package boundaries (i.e. be exported) to guarantee that it can be used for tree shaking.\n */\nexport const DEBUG_BUILD = __DEBUG_BUILD__;\n", "export default `var t=Uint8Array,n=Uint16Array,r=Int32Array,e=new t([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),i=new t([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),a=new t([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),s=function(t,e){for(var i=new n(31),a=0;a<31;++a)i[a]=e+=1<>1|(21845&c)<<1;v=(61680&(v=(52428&v)>>2|(13107&v)<<2))>>4|(3855&v)<<4,u[c]=((65280&v)>>8|(255&v)<<8)>>1}var d=function(t,r,e){for(var i=t.length,a=0,s=new n(r);a>h]=l}else for(o=new n(i),a=0;a>15-t[a]);return o},g=new t(288);for(c=0;c<144;++c)g[c]=8;for(c=144;c<256;++c)g[c]=9;for(c=256;c<280;++c)g[c]=7;for(c=280;c<288;++c)g[c]=8;var w=new t(32);for(c=0;c<32;++c)w[c]=5;var p=d(g,9,0),y=d(w,5,0),m=function(t){return(t+7)/8|0},b=function(n,r,e){return(null==r||r<0)&&(r=0),(null==e||e>n.length)&&(e=n.length),new t(n.subarray(r,e))},M=[\"unexpected EOF\",\"invalid block type\",\"invalid length/literal\",\"invalid distance\",\"stream finished\",\"no stream handler\",,\"no callback\",\"invalid UTF-8 data\",\"extra field too long\",\"date not in range 1980-2099\",\"filename too long\",\"stream finishing\",\"invalid zip data\"],E=function(t,n,r){var e=new Error(n||M[t]);if(e.code=t,Error.captureStackTrace&&Error.captureStackTrace(e,E),!r)throw e;return e},z=function(t,n,r){r<<=7&n;var e=n/8|0;t[e]|=r,t[e+1]|=r>>8},A=function(t,n,r){r<<=7&n;var e=n/8|0;t[e]|=r,t[e+1]|=r>>8,t[e+2]|=r>>16},_=function(r,e){for(var i=[],a=0;ad&&(d=o[a].s);var g=new n(d+1),w=x(i[c-1],g,0);if(w>e){a=0;var p=0,y=w-e,m=1<e))break;p+=m-(1<>=y;p>0;){var M=o[a].s;g[M]=0&&p;--a){var E=o[a].s;g[E]==e&&(--g[E],++p)}w=e}return{t:new t(g),l:w}},x=function(t,n,r){return-1==t.s?Math.max(x(t.l,n,r+1),x(t.r,n,r+1)):n[t.s]=r},D=function(t){for(var r=t.length;r&&!t[--r];);for(var e=new n(++r),i=0,a=t[0],s=1,o=function(t){e[i++]=t},f=1;f<=r;++f)if(t[f]==a&&f!=r)++s;else{if(!a&&s>2){for(;s>138;s-=138)o(32754);s>2&&(o(s>10?s-11<<5|28690:s-3<<5|12305),s=0)}else if(s>3){for(o(a),--s;s>6;s-=6)o(8304);s>2&&(o(s-3<<5|8208),s=0)}for(;s--;)o(a);s=1,a=t[f]}return{c:e.subarray(0,i),n:r}},T=function(t,n){for(var r=0,e=0;e>8,t[i+2]=255^t[i],t[i+3]=255^t[i+1];for(var a=0;a4&&!H[a[K-1]];--K);var N,P,Q,R,V=v+5<<3,W=T(f,g)+T(h,w)+l,X=T(f,M)+T(h,C)+l+14+3*K+T(q,H)+2*q[16]+3*q[17]+7*q[18];if(c>=0&&V<=W&&V<=X)return k(r,m,t.subarray(c,c+v));if(z(r,m,1+(X15&&(z(r,m,tt[B]>>5&127),m+=tt[B]>>12)}}}else N=p,P=g,Q=y,R=w;for(B=0;B255){A(r,m,N[(nt=rt>>18&31)+257]),m+=P[nt+257],nt>7&&(z(r,m,rt>>23&31),m+=e[nt]);var et=31&rt;A(r,m,Q[et]),m+=R[et],et>3&&(A(r,m,rt>>5&8191),m+=i[et])}else A(r,m,N[rt]),m+=P[rt]}return A(r,m,N[256]),m+P[256]},U=new r([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),F=new t(0),I=function(){for(var t=new Int32Array(256),n=0;n<256;++n){for(var r=n,e=9;--e;)r=(1&r&&-306674912)^r>>>1;t[n]=r}return t}(),S=function(){var t=1,n=0;return{p:function(r){for(var e=t,i=n,a=0|r.length,s=0;s!=a;){for(var o=Math.min(s+2655,a);s>16),i=(65535&i)+15*(i>>16)}t=e,n=i},d:function(){return(255&(t%=65521))<<24|(65280&t)<<8|(255&(n%=65521))<<8|n>>8}}},L=function(a,s,o,f,u){if(!u&&(u={l:1},s.dictionary)){var c=s.dictionary.subarray(-32768),v=new t(c.length+a.length);v.set(c),v.set(a,c.length),a=v,u.w=c.length}return function(a,s,o,f,u,c){var v=c.z||a.length,d=new t(f+v+5*(1+Math.ceil(v/7e3))+u),g=d.subarray(f,d.length-u),w=c.l,p=7&(c.r||0);if(s){p&&(g[0]=c.r>>3);for(var y=U[s-1],M=y>>13,E=8191&y,z=(1<7e3||q>24576)&&(N>423||!w)){p=C(a,g,0,F,I,S,O,q,G,j-G,p),q=L=O=0,G=j;for(var P=0;P<286;++P)I[P]=0;for(P=0;P<30;++P)S[P]=0}var Q=2,R=0,V=E,W=J-K&32767;if(N>2&&H==T(j-W))for(var X=Math.min(M,N)-1,Y=Math.min(32767,j),Z=Math.min(258,N);W<=Y&&--V&&J!=K;){if(a[j+Q]==a[j+Q-W]){for(var $=0;$Q){if(Q=$,R=W,$>X)break;var tt=Math.min(W,$-2),nt=0;for(P=0;Pnt&&(nt=et,K=rt)}}}W+=(J=K)-(K=A[J])&32767}if(R){F[q++]=268435456|h[Q]<<18|l[R];var it=31&h[Q],at=31&l[R];O+=e[it]+i[at],++I[257+it],++S[at],B=j+Q,++L}else F[q++]=a[j],++I[a[j]]}}for(j=Math.max(j,B);j=v&&(g[p/8|0]=w,st=v),p=k(g,p+1,a.subarray(j,st))}c.i=v}return b(d,0,f+m(p)+u)}(a,null==s.level?6:s.level,null==s.mem?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(a.length)))):12+s.mem,o,f,u)},O=function(t,n,r){for(;r;++n)t[n]=r,r>>>=8},j=function(){function n(n,r){if(\"function\"==typeof n&&(r=n,n={}),this.ondata=r,this.o=n||{},this.s={l:0,i:32768,w:32768,z:32768},this.b=new t(98304),this.o.dictionary){var e=this.o.dictionary.subarray(-32768);this.b.set(e,32768-e.length),this.s.i=32768-e.length}}return n.prototype.p=function(t,n){this.ondata(L(t,this.o,0,0,this.s),n)},n.prototype.push=function(n,r){this.ondata||E(5),this.s.l&&E(4);var e=n.length+this.s.z;if(e>this.b.length){if(e>2*this.b.length-32768){var i=new t(-32768&e);i.set(this.b.subarray(0,this.s.z)),this.b=i}var a=this.b.length-this.s.z;a&&(this.b.set(n.subarray(0,a),this.s.z),this.s.z=this.b.length,this.p(this.b,!1)),this.b.set(this.b.subarray(-32768)),this.b.set(n.subarray(a),32768),this.s.z=n.length-a+32768,this.s.i=32766,this.s.w=32768}else this.b.set(n,this.s.z),this.s.z+=n.length;this.s.l=1&r,(this.s.z>this.s.w+8191||r)&&(this.p(this.b,r||!1),this.s.w=this.s.i,this.s.i-=2)},n}();function q(t,n){n||(n={});var r=function(){var t=-1;return{p:function(n){for(var r=t,e=0;e>>8;t=r},d:function(){return~t}}}(),e=t.length;r.p(t);var i,a=L(t,n,10+((i=n).filename?i.filename.length+1:0),8),s=a.length;return function(t,n){var r=n.filename;if(t[0]=31,t[1]=139,t[2]=8,t[8]=n.level<2?4:9==n.level?2:0,t[9]=3,0!=n.mtime&&O(t,4,Math.floor(new Date(n.mtime||Date.now())/1e3)),r){t[3]=8;for(var e=0;e<=r.length;++e)t[e+10]=r.charCodeAt(e)}}(a,n),O(a,s-8,r.d()),O(a,s-4,e),a}var B=function(){function t(t,n){this.c=S(),this.v=1,j.call(this,t,n)}return t.prototype.push=function(t,n){this.c.p(t),j.prototype.push.call(this,t,n)},t.prototype.p=function(t,n){var r=L(t,this.o,this.v&&(this.o.dictionary?6:2),n&&4,this.s);this.v&&(function(t,n){var r=n.level,e=0==r?0:r<6?1:9==r?3:2;if(t[0]=120,t[1]=e<<6|(n.dictionary&&32),t[1]|=31-(t[0]<<8|t[1])%31,n.dictionary){var i=S();i.p(n.dictionary),O(t,2,i.d())}}(r,this.o),this.v=0),n&&O(r,r.length-4,this.c.d()),this.ondata(r,n)},t}(),G=\"undefined\"!=typeof TextEncoder&&new TextEncoder,H=\"undefined\"!=typeof TextDecoder&&new TextDecoder;try{H.decode(F,{stream:!0})}catch(t){}var J=function(){function t(t){this.ondata=t}return t.prototype.push=function(t,n){this.ondata||E(5),this.d&&E(4),this.ondata(K(t),this.d=n||!1)},t}();function K(n,r){if(r){for(var e=new t(n.length),i=0;i>1)),o=0,f=function(t){s[o++]=t};for(i=0;is.length){var h=new t(o+8+(a-i<<1));h.set(s),s=h}var l=n.charCodeAt(i);l<128||r?f(l):l<2048?(f(192|l>>6),f(128|63&l)):l>55295&&l<57344?(f(240|(l=65536+(1047552&l)|1023&n.charCodeAt(++i))>>18),f(128|l>>12&63),f(128|l>>6&63),f(128|63&l)):(f(224|l>>12),f(128|l>>6&63),f(128|63&l))}return b(s,0,o)}const N=new class{constructor(){this._init()}clear(){this._init()}addEvent(t){if(!t)throw new Error(\"Adding invalid event\");const n=this._hasEvents?\",\":\"\";this.stream.push(n+t),this._hasEvents=!0}finish(){this.stream.push(\"]\",!0);const t=function(t){let n=0;for(let r=0,e=t.length;r{this._deflatedData.push(t)},this.stream=new J(((t,n)=>{this.deflate.push(t,n)})),this.stream.push(\"[\")}},P={clear:()=>{N.clear()},addEvent:t=>N.addEvent(t),finish:()=>N.finish(),compress:t=>function(t){return q(K(t))}(t)};addEventListener(\"message\",(function(t){const n=t.data.method,r=t.data.id,e=t.data.arg;if(n in P&&\"function\"==typeof P[n])try{const t=P[n](e);postMessage({id:r,method:n,success:!0,response:t})}catch(t){postMessage({id:r,method:n,success:!1,response:t.message}),console.error(t)}})),postMessage({id:void 0,method:\"init\",success:!0,response:void 0});`;\n", "import r from\"./worker\";function e(){const e=new Blob([r]);return URL.createObjectURL(e)}export{e as getWorkerURL};\n", "import { addBreadcrumb } from '@sentry/core';\nimport { logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\n\n/**\n * Log a message in debug mode, and add a breadcrumb when _experiment.traceInternals is enabled.\n */\nexport function logInfo(message: string, shouldAddBreadcrumb?: boolean): void {\n if (!DEBUG_BUILD) {\n return;\n }\n\n logger.info(message);\n\n if (shouldAddBreadcrumb) {\n addLogBreadcrumb(message);\n }\n}\n\n/**\n * Log a message, and add a breadcrumb in the next tick.\n * This is necessary when the breadcrumb may be added before the replay is initialized.\n */\nexport function logInfoNextTick(message: string, shouldAddBreadcrumb?: boolean): void {\n if (!DEBUG_BUILD) {\n return;\n }\n\n logger.info(message);\n\n if (shouldAddBreadcrumb) {\n // Wait a tick here to avoid race conditions for some initial logs\n // which may be added before replay is initialized\n setTimeout(() => {\n addLogBreadcrumb(message);\n }, 0);\n }\n}\n\nfunction addLogBreadcrumb(message: string): void {\n addBreadcrumb(\n {\n category: 'console',\n data: {\n logger: 'replay',\n },\n level: 'info',\n message,\n },\n { level: 'info' },\n );\n}\n", "import { REPLAY_MAX_EVENT_BUFFER_SIZE } from '../constants';\n\n/** This error indicates that the event buffer size exceeded the limit.. */\nexport class EventBufferSizeExceededError extends Error {\n public constructor() {\n super(`Event buffer exceeded maximum size of ${REPLAY_MAX_EVENT_BUFFER_SIZE}.`);\n }\n}\n", "import { REPLAY_MAX_EVENT_BUFFER_SIZE } from '../constants';\nimport type { AddEventResult, EventBuffer, EventBufferType, RecordingEvent } from '../types';\nimport { timestampToMs } from '../util/timestamp';\nimport { EventBufferSizeExceededError } from './error';\n\n/**\n * A basic event buffer that does not do any compression.\n * Used as fallback if the compression worker cannot be loaded or is disabled.\n */\nexport class EventBufferArray implements EventBuffer {\n /** All the events that are buffered to be sent. */\n public events: RecordingEvent[];\n\n /** @inheritdoc */\n public hasCheckout: boolean;\n\n private _totalSize: number;\n\n public constructor() {\n this.events = [];\n this._totalSize = 0;\n this.hasCheckout = false;\n }\n\n /** @inheritdoc */\n public get hasEvents(): boolean {\n return this.events.length > 0;\n }\n\n /** @inheritdoc */\n public get type(): EventBufferType {\n return 'sync';\n }\n\n /** @inheritdoc */\n public destroy(): void {\n this.events = [];\n }\n\n /** @inheritdoc */\n public async addEvent(event: RecordingEvent): Promise {\n const eventSize = JSON.stringify(event).length;\n this._totalSize += eventSize;\n if (this._totalSize > REPLAY_MAX_EVENT_BUFFER_SIZE) {\n throw new EventBufferSizeExceededError();\n }\n\n this.events.push(event);\n }\n\n /** @inheritdoc */\n public finish(): Promise {\n return new Promise(resolve => {\n // Make a copy of the events array reference and immediately clear the\n // events member so that we do not lose new events while uploading\n // attachment.\n const eventsRet = this.events;\n this.clear();\n resolve(JSON.stringify(eventsRet));\n });\n }\n\n /** @inheritdoc */\n public clear(): void {\n this.events = [];\n this._totalSize = 0;\n this.hasCheckout = false;\n }\n\n /** @inheritdoc */\n public getEarliestTimestamp(): number | null {\n const timestamp = this.events.map(event => event.timestamp).sort()[0];\n\n if (!timestamp) {\n return null;\n }\n\n return timestampToMs(timestamp);\n }\n}\n", "import { logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { WorkerRequest, WorkerResponse } from '../types';\nimport { logInfo } from '../util/log';\n\n/**\n * Event buffer that uses a web worker to compress events.\n * Exported only for testing.\n */\nexport class WorkerHandler {\n private _worker: Worker;\n private _id: number;\n private _ensureReadyPromise?: Promise;\n\n public constructor(worker: Worker) {\n this._worker = worker;\n this._id = 0;\n }\n\n /**\n * Ensure the worker is ready (or not).\n * This will either resolve when the worker is ready, or reject if an error occured.\n */\n public ensureReady(): Promise {\n // Ensure we only check once\n if (this._ensureReadyPromise) {\n return this._ensureReadyPromise;\n }\n\n this._ensureReadyPromise = new Promise((resolve, reject) => {\n this._worker.addEventListener(\n 'message',\n ({ data }: MessageEvent) => {\n if ((data as WorkerResponse).success) {\n resolve();\n } else {\n reject();\n }\n },\n { once: true },\n );\n\n this._worker.addEventListener(\n 'error',\n error => {\n reject(error);\n },\n { once: true },\n );\n });\n\n return this._ensureReadyPromise;\n }\n\n /**\n * Destroy the worker.\n */\n public destroy(): void {\n logInfo('[Replay] Destroying compression worker');\n this._worker.terminate();\n }\n\n /**\n * Post message to worker and wait for response before resolving promise.\n */\n public postMessage(method: WorkerRequest['method'], arg?: WorkerRequest['arg']): Promise {\n const id = this._getAndIncrementId();\n\n return new Promise((resolve, reject) => {\n const listener = ({ data }: MessageEvent): void => {\n const response = data as WorkerResponse;\n if (response.method !== method) {\n return;\n }\n\n // There can be multiple listeners for a single method, the id ensures\n // that the response matches the caller.\n if (response.id !== id) {\n return;\n }\n\n // At this point, we'll always want to remove listener regardless of result status\n this._worker.removeEventListener('message', listener);\n\n if (!response.success) {\n // TODO: Do some error handling, not sure what\n DEBUG_BUILD && logger.error('[Replay]', response.response);\n\n reject(new Error('Error in compression worker'));\n return;\n }\n\n resolve(response.response as T);\n };\n\n // Note: we can't use `once` option because it's possible it needs to\n // listen to multiple messages\n this._worker.addEventListener('message', listener);\n this._worker.postMessage({ id, method, arg });\n });\n }\n\n /** Get the current ID and increment it for the next call. */\n private _getAndIncrementId(): number {\n return this._id++;\n }\n}\n", "import type { ReplayRecordingData } from '@sentry/types';\n\nimport { logger } from '@sentry/utils';\nimport { REPLAY_MAX_EVENT_BUFFER_SIZE } from '../constants';\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { AddEventResult, EventBuffer, EventBufferType, RecordingEvent } from '../types';\nimport { timestampToMs } from '../util/timestamp';\nimport { WorkerHandler } from './WorkerHandler';\nimport { EventBufferSizeExceededError } from './error';\n\n/**\n * Event buffer that uses a web worker to compress events.\n * Exported only for testing.\n */\nexport class EventBufferCompressionWorker implements EventBuffer {\n /** @inheritdoc */\n public hasCheckout: boolean;\n\n private _worker: WorkerHandler;\n private _earliestTimestamp: number | null;\n private _totalSize;\n\n public constructor(worker: Worker) {\n this._worker = new WorkerHandler(worker);\n this._earliestTimestamp = null;\n this._totalSize = 0;\n this.hasCheckout = false;\n }\n\n /** @inheritdoc */\n public get hasEvents(): boolean {\n return !!this._earliestTimestamp;\n }\n\n /** @inheritdoc */\n public get type(): EventBufferType {\n return 'worker';\n }\n\n /**\n * Ensure the worker is ready (or not).\n * This will either resolve when the worker is ready, or reject if an error occured.\n */\n public ensureReady(): Promise {\n return this._worker.ensureReady();\n }\n\n /**\n * Destroy the event buffer.\n */\n public destroy(): void {\n this._worker.destroy();\n }\n\n /**\n * Add an event to the event buffer.\n *\n * Returns true if event was successfuly received and processed by worker.\n */\n public addEvent(event: RecordingEvent): Promise {\n const timestamp = timestampToMs(event.timestamp);\n if (!this._earliestTimestamp || timestamp < this._earliestTimestamp) {\n this._earliestTimestamp = timestamp;\n }\n\n const data = JSON.stringify(event);\n this._totalSize += data.length;\n\n if (this._totalSize > REPLAY_MAX_EVENT_BUFFER_SIZE) {\n return Promise.reject(new EventBufferSizeExceededError());\n }\n\n return this._sendEventToWorker(data);\n }\n\n /**\n * Finish the event buffer and return the compressed data.\n */\n public finish(): Promise {\n return this._finishRequest();\n }\n\n /** @inheritdoc */\n public clear(): void {\n this._earliestTimestamp = null;\n this._totalSize = 0;\n this.hasCheckout = false;\n\n // We do not wait on this, as we assume the order of messages is consistent for the worker\n this._worker.postMessage('clear').then(null, e => {\n DEBUG_BUILD && logger.warn('[Replay] Sending \"clear\" message to worker failed', e);\n });\n }\n\n /** @inheritdoc */\n public getEarliestTimestamp(): number | null {\n return this._earliestTimestamp;\n }\n\n /**\n * Send the event to the worker.\n */\n private _sendEventToWorker(data: string): Promise {\n return this._worker.postMessage('addEvent', data);\n }\n\n /**\n * Finish the request and return the compressed data from the worker.\n */\n private async _finishRequest(): Promise {\n const response = await this._worker.postMessage('finish');\n\n this._earliestTimestamp = null;\n this._totalSize = 0;\n\n return response;\n }\n}\n", "import type { ReplayRecordingData } from '@sentry/types';\nimport { logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { AddEventResult, EventBuffer, EventBufferType, RecordingEvent } from '../types';\nimport { logInfo } from '../util/log';\nimport { EventBufferArray } from './EventBufferArray';\nimport { EventBufferCompressionWorker } from './EventBufferCompressionWorker';\n\n/**\n * This proxy will try to use the compression worker, and fall back to use the simple buffer if an error occurs there.\n * This can happen e.g. if the worker cannot be loaded.\n * Exported only for testing.\n */\nexport class EventBufferProxy implements EventBuffer {\n private _fallback: EventBufferArray;\n private _compression: EventBufferCompressionWorker;\n private _used: EventBuffer;\n private _ensureWorkerIsLoadedPromise: Promise;\n\n public constructor(worker: Worker) {\n this._fallback = new EventBufferArray();\n this._compression = new EventBufferCompressionWorker(worker);\n this._used = this._fallback;\n\n this._ensureWorkerIsLoadedPromise = this._ensureWorkerIsLoaded();\n }\n\n /** @inheritdoc */\n public get type(): EventBufferType {\n return this._used.type;\n }\n\n /** @inheritDoc */\n public get hasEvents(): boolean {\n return this._used.hasEvents;\n }\n\n /** @inheritdoc */\n public get hasCheckout(): boolean {\n return this._used.hasCheckout;\n }\n /** @inheritdoc */\n public set hasCheckout(value: boolean) {\n this._used.hasCheckout = value;\n }\n\n /** @inheritDoc */\n public destroy(): void {\n this._fallback.destroy();\n this._compression.destroy();\n }\n\n /** @inheritdoc */\n public clear(): void {\n return this._used.clear();\n }\n\n /** @inheritdoc */\n public getEarliestTimestamp(): number | null {\n return this._used.getEarliestTimestamp();\n }\n\n /**\n * Add an event to the event buffer.\n *\n * Returns true if event was successfully added.\n */\n public addEvent(event: RecordingEvent): Promise {\n return this._used.addEvent(event);\n }\n\n /** @inheritDoc */\n public async finish(): Promise {\n // Ensure the worker is loaded, so the sent event is compressed\n await this.ensureWorkerIsLoaded();\n\n return this._used.finish();\n }\n\n /** Ensure the worker has loaded. */\n public ensureWorkerIsLoaded(): Promise {\n return this._ensureWorkerIsLoadedPromise;\n }\n\n /** Actually check if the worker has been loaded. */\n private async _ensureWorkerIsLoaded(): Promise {\n try {\n await this._compression.ensureReady();\n } catch (error) {\n // If the worker fails to load, we fall back to the simple buffer.\n // Nothing more to do from our side here\n logInfo('[Replay] Failed to load the compression worker, falling back to simple buffer');\n return;\n }\n\n // Now we need to switch over the array buffer to the compression worker\n await this._switchToCompressionWorker();\n }\n\n /** Switch the used buffer to the compression worker. */\n private async _switchToCompressionWorker(): Promise {\n const { events, hasCheckout } = this._fallback;\n\n const addEventPromises: Promise[] = [];\n for (const event of events) {\n addEventPromises.push(this._compression.addEvent(event));\n }\n\n this._compression.hasCheckout = hasCheckout;\n\n // We switch over to the new buffer immediately - any further events will be added\n // after the previously buffered ones\n this._used = this._compression;\n\n // Wait for original events to be re-added before resolving\n try {\n await Promise.all(addEventPromises);\n } catch (error) {\n DEBUG_BUILD && logger.warn('[Replay] Failed to add events when switching buffers.', error);\n }\n }\n}\n", "import { getWorkerURL } from '@sentry-internal/replay-worker';\n\nimport type { EventBuffer } from '../types';\nimport { logInfo } from '../util/log';\nimport { EventBufferArray } from './EventBufferArray';\nimport { EventBufferProxy } from './EventBufferProxy';\n\ninterface CreateEventBufferParams {\n useCompression: boolean;\n workerUrl?: string;\n}\n\n// Treeshakable guard to remove the code of the included compression worker\ndeclare const __SENTRY_EXCLUDE_REPLAY_WORKER__: boolean;\n\n/**\n * Create an event buffer for replays.\n */\nexport function createEventBuffer({\n useCompression,\n workerUrl: customWorkerUrl,\n}: CreateEventBufferParams): EventBuffer {\n if (\n useCompression &&\n // eslint-disable-next-line no-restricted-globals\n window.Worker\n ) {\n const worker = _loadWorker(customWorkerUrl);\n\n if (worker) {\n return worker;\n }\n }\n\n logInfo('[Replay] Using simple buffer');\n return new EventBufferArray();\n}\n\nfunction _loadWorker(customWorkerUrl?: string): EventBufferProxy | void {\n try {\n const workerUrl = customWorkerUrl || _getWorkerUrl();\n\n if (!workerUrl) {\n return;\n }\n\n logInfo(`[Replay] Using compression worker${customWorkerUrl ? ` from ${customWorkerUrl}` : ''}`);\n const worker = new Worker(workerUrl);\n return new EventBufferProxy(worker);\n } catch (error) {\n logInfo('[Replay] Failed to create compression worker');\n // Fall back to use simple event buffer array\n }\n}\n\nfunction _getWorkerUrl(): string {\n if (typeof __SENTRY_EXCLUDE_REPLAY_WORKER__ === 'undefined' || !__SENTRY_EXCLUDE_REPLAY_WORKER__) {\n return getWorkerURL();\n }\n\n return '';\n}\n", "import { WINDOW } from '../constants';\n\n/** If sessionStorage is available. */\nexport function hasSessionStorage(): boolean {\n try {\n // This can throw, e.g. when being accessed in a sandboxed iframe\n return 'sessionStorage' in WINDOW && !!WINDOW.sessionStorage;\n } catch {\n return false;\n }\n}\n", "import { REPLAY_SESSION_KEY, WINDOW } from '../../src/constants';\nimport type { ReplayContainer } from '../../src/types';\nimport { hasSessionStorage } from '../util/hasSessionStorage';\n\n/**\n * Removes the session from Session Storage and unsets session in replay instance\n */\nexport function clearSession(replay: ReplayContainer): void {\n deleteSession();\n replay.session = undefined;\n}\n\n/**\n * Deletes a session from storage\n */\nfunction deleteSession(): void {\n if (!hasSessionStorage()) {\n return;\n }\n\n try {\n WINDOW.sessionStorage.removeItem(REPLAY_SESSION_KEY);\n } catch {\n // Ignore potential SecurityError exceptions\n }\n}\n", "/**\n * Given a sample rate, returns true if replay should be sampled.\n *\n * 1.0 = 100% sampling\n * 0.0 = 0% sampling\n */\nexport function isSampled(sampleRate?: number): boolean {\n if (sampleRate === undefined) {\n return false;\n }\n\n // Math.random() returns a number in range of 0 to 1 (inclusive of 0, but not 1)\n return Math.random() < sampleRate;\n}\n", "import { uuid4 } from '@sentry/utils';\n\nimport type { Sampled, Session } from '../types';\n\n/**\n * Get a session with defaults & applied sampling.\n */\nexport function makeSession(session: Partial & { sampled: Sampled }): Session {\n const now = Date.now();\n const id = session.id || uuid4();\n // Note that this means we cannot set a started/lastActivity of `0`, but this should not be relevant outside of tests.\n const started = session.started || now;\n const lastActivity = session.lastActivity || now;\n const segmentId = session.segmentId || 0;\n const sampled = session.sampled;\n const previousSessionId = session.previousSessionId;\n\n return {\n id,\n started,\n lastActivity,\n segmentId,\n sampled,\n previousSessionId,\n };\n}\n", "import { REPLAY_SESSION_KEY, WINDOW } from '../constants';\nimport type { Session } from '../types';\nimport { hasSessionStorage } from '../util/hasSessionStorage';\n\n/**\n * Save a session to session storage.\n */\nexport function saveSession(session: Session): void {\n if (!hasSessionStorage()) {\n return;\n }\n\n try {\n WINDOW.sessionStorage.setItem(REPLAY_SESSION_KEY, JSON.stringify(session));\n } catch {\n // Ignore potential SecurityError exceptions\n }\n}\n", "import type { Sampled, Session, SessionOptions } from '../types';\nimport { isSampled } from '../util/isSampled';\nimport { makeSession } from './Session';\nimport { saveSession } from './saveSession';\n\n/**\n * Get the sampled status for a session based on sample rates & current sampled status.\n */\nexport function getSessionSampleType(sessionSampleRate: number, allowBuffering: boolean): Sampled {\n return isSampled(sessionSampleRate) ? 'session' : allowBuffering ? 'buffer' : false;\n}\n\n/**\n * Create a new session, which in its current implementation is a Sentry event\n * that all replays will be saved to as attachments. Currently, we only expect\n * one of these Sentry events per \"replay session\".\n */\nexport function createSession(\n { sessionSampleRate, allowBuffering, stickySession = false }: SessionOptions,\n { previousSessionId }: { previousSessionId?: string } = {},\n): Session {\n const sampled = getSessionSampleType(sessionSampleRate, allowBuffering);\n const session = makeSession({\n sampled,\n previousSessionId,\n });\n\n if (stickySession) {\n saveSession(session);\n }\n\n return session;\n}\n", "import { REPLAY_SESSION_KEY, WINDOW } from '../constants';\nimport type { Session } from '../types';\nimport { hasSessionStorage } from '../util/hasSessionStorage';\nimport { logInfoNextTick } from '../util/log';\nimport { makeSession } from './Session';\n\n/**\n * Fetches a session from storage\n */\nexport function fetchSession(traceInternals?: boolean): Session | null {\n if (!hasSessionStorage()) {\n return null;\n }\n\n try {\n // This can throw if cookies are disabled\n const sessionStringFromStorage = WINDOW.sessionStorage.getItem(REPLAY_SESSION_KEY);\n\n if (!sessionStringFromStorage) {\n return null;\n }\n\n const sessionObj = JSON.parse(sessionStringFromStorage) as Session;\n\n logInfoNextTick('[Replay] Loading existing session', traceInternals);\n\n return makeSession(sessionObj);\n } catch {\n return null;\n }\n}\n", "/**\n * Given an initial timestamp and an expiry duration, checks to see if current\n * time should be considered as expired.\n */\nexport function isExpired(\n initialTime: null | number,\n expiry: undefined | number,\n targetTime: number = +new Date(),\n): boolean {\n // Always expired if < 0\n if (initialTime === null || expiry === undefined || expiry < 0) {\n return true;\n }\n\n // Never expires if == 0\n if (expiry === 0) {\n return false;\n }\n\n return initialTime + expiry <= targetTime;\n}\n", "import type { Session } from '../types';\nimport { isExpired } from './isExpired';\n\n/**\n * Checks to see if session is expired\n */\nexport function isSessionExpired(\n session: Session,\n {\n maxReplayDuration,\n sessionIdleExpire,\n targetTime = Date.now(),\n }: { maxReplayDuration: number; sessionIdleExpire: number; targetTime?: number },\n): boolean {\n return (\n // First, check that maximum session length has not been exceeded\n isExpired(session.started, maxReplayDuration, targetTime) ||\n // check that the idle timeout has not been exceeded (i.e. user has\n // performed an action within the last `sessionIdleExpire` ms)\n isExpired(session.lastActivity, sessionIdleExpire, targetTime)\n );\n}\n", "import type { Session } from '../types';\nimport { isSessionExpired } from '../util/isSessionExpired';\n\n/** If the session should be refreshed or not. */\nexport function shouldRefreshSession(\n session: Session,\n { sessionIdleExpire, maxReplayDuration }: { sessionIdleExpire: number; maxReplayDuration: number },\n): boolean {\n // If not expired, all good, just keep the session\n if (!isSessionExpired(session, { sessionIdleExpire, maxReplayDuration })) {\n return false;\n }\n\n // If we are buffering & haven't ever flushed yet, always continue\n if (session.sampled === 'buffer' && session.segmentId === 0) {\n return false;\n }\n\n return true;\n}\n", "import type { Session, SessionOptions } from '../types';\nimport { logInfoNextTick } from '../util/log';\nimport { createSession } from './createSession';\nimport { fetchSession } from './fetchSession';\nimport { shouldRefreshSession } from './shouldRefreshSession';\n\n/**\n * Get or create a session, when initializing the replay.\n * Returns a session that may be unsampled.\n */\nexport function loadOrCreateSession(\n {\n traceInternals,\n sessionIdleExpire,\n maxReplayDuration,\n previousSessionId,\n }: {\n sessionIdleExpire: number;\n maxReplayDuration: number;\n traceInternals?: boolean;\n previousSessionId?: string;\n },\n sessionOptions: SessionOptions,\n): Session {\n const existingSession = sessionOptions.stickySession && fetchSession(traceInternals);\n\n // No session exists yet, just create a new one\n if (!existingSession) {\n logInfoNextTick('[Replay] Creating new session', traceInternals);\n return createSession(sessionOptions, { previousSessionId });\n }\n\n if (!shouldRefreshSession(existingSession, { sessionIdleExpire, maxReplayDuration })) {\n return existingSession;\n }\n\n logInfoNextTick('[Replay] Session in sessionStorage is expired, creating new one...');\n return createSession(sessionOptions, { previousSessionId: existingSession.id });\n}\n", "import { EventType } from '@sentry-internal/rrweb';\nimport { getClient } from '@sentry/core';\nimport { logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\nimport { EventBufferSizeExceededError } from '../eventBuffer/error';\nimport type { AddEventResult, RecordingEvent, ReplayContainer, ReplayFrameEvent, ReplayPluginOptions } from '../types';\nimport { logInfo } from './log';\nimport { timestampToMs } from './timestamp';\n\nfunction isCustomEvent(event: RecordingEvent): event is ReplayFrameEvent {\n return event.type === EventType.Custom;\n}\n\n/**\n * Add an event to the event buffer.\n * In contrast to `addEvent`, this does not return a promise & does not wait for the adding of the event to succeed/fail.\n * Instead this returns `true` if we tried to add the event, else false.\n * It returns `false` e.g. if we are paused, disabled, or out of the max replay duration.\n *\n * `isCheckout` is true if this is either the very first event, or an event triggered by `checkoutEveryNms`.\n */\nexport function addEventSync(replay: ReplayContainer, event: RecordingEvent, isCheckout?: boolean): boolean {\n if (!shouldAddEvent(replay, event)) {\n return false;\n }\n\n // This should never reject\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n _addEvent(replay, event, isCheckout);\n\n return true;\n}\n\n/**\n * Add an event to the event buffer.\n * Resolves to `null` if no event was added, else to `void`.\n *\n * `isCheckout` is true if this is either the very first event, or an event triggered by `checkoutEveryNms`.\n */\nexport function addEvent(\n replay: ReplayContainer,\n event: RecordingEvent,\n isCheckout?: boolean,\n): Promise {\n if (!shouldAddEvent(replay, event)) {\n return Promise.resolve(null);\n }\n\n return _addEvent(replay, event, isCheckout);\n}\n\nasync function _addEvent(\n replay: ReplayContainer,\n event: RecordingEvent,\n isCheckout?: boolean,\n): Promise {\n if (!replay.eventBuffer) {\n return null;\n }\n\n try {\n if (isCheckout && replay.recordingMode === 'buffer') {\n replay.eventBuffer.clear();\n }\n\n if (isCheckout) {\n replay.eventBuffer.hasCheckout = true;\n }\n\n const replayOptions = replay.getOptions();\n\n const eventAfterPossibleCallback = maybeApplyCallback(event, replayOptions.beforeAddRecordingEvent);\n\n if (!eventAfterPossibleCallback) {\n return;\n }\n\n return await replay.eventBuffer.addEvent(eventAfterPossibleCallback);\n } catch (error) {\n const reason = error && error instanceof EventBufferSizeExceededError ? 'addEventSizeExceeded' : 'addEvent';\n\n DEBUG_BUILD && logger.error(error);\n await replay.stop({ reason });\n\n const client = getClient();\n\n if (client) {\n client.recordDroppedEvent('internal_sdk_error', 'replay');\n }\n }\n}\n\n/** Exported only for tests. */\nexport function shouldAddEvent(replay: ReplayContainer, event: RecordingEvent): boolean {\n if (!replay.eventBuffer || replay.isPaused() || !replay.isEnabled()) {\n return false;\n }\n\n const timestampInMs = timestampToMs(event.timestamp);\n\n // Throw out events that happen more than 5 minutes ago. This can happen if\n // page has been left open and idle for a long period of time and user\n // comes back to trigger a new session. The performance entries rely on\n // `performance.timeOrigin`, which is when the page first opened.\n if (timestampInMs + replay.timeouts.sessionIdlePause < Date.now()) {\n return false;\n }\n\n // Throw out events that are +60min from the initial timestamp\n if (timestampInMs > replay.getContext().initialTimestamp + replay.getOptions().maxReplayDuration) {\n logInfo(\n `[Replay] Skipping event with timestamp ${timestampInMs} because it is after maxReplayDuration`,\n replay.getOptions()._experiments.traceInternals,\n );\n return false;\n }\n\n return true;\n}\n\nfunction maybeApplyCallback(\n event: RecordingEvent,\n callback: ReplayPluginOptions['beforeAddRecordingEvent'],\n): RecordingEvent | null | undefined {\n try {\n if (typeof callback === 'function' && isCustomEvent(event)) {\n return callback(event);\n }\n } catch (error) {\n DEBUG_BUILD &&\n logger.error('[Replay] An error occured in the `beforeAddRecordingEvent` callback, skipping the event...', error);\n return null;\n }\n\n return event;\n}\n", "import type { ErrorEvent, Event, FeedbackEvent, ReplayEvent, TransactionEvent } from '@sentry/types';\n\n/** If the event is an error event */\nexport function isErrorEvent(event: Event): event is ErrorEvent {\n return !event.type;\n}\n\n/** If the event is a transaction event */\nexport function isTransactionEvent(event: Event): event is TransactionEvent {\n return event.type === 'transaction';\n}\n\n/** If the event is an replay event */\nexport function isReplayEvent(event: Event): event is ReplayEvent {\n return event.type === 'replay_event';\n}\n\n/** If the event is a feedback event */\nexport function isFeedbackEvent(event: Event): event is FeedbackEvent {\n return event.type === 'feedback';\n}\n", "import { getClient } from '@sentry/core';\nimport type { ErrorEvent, Event, TransactionEvent, Transport, TransportMakeRequestResponse } from '@sentry/types';\n\nimport type { ReplayContainer } from '../types';\nimport { isErrorEvent, isTransactionEvent } from '../util/eventUtils';\n\ntype AfterSendEventCallback = (event: Event, sendResponse: TransportMakeRequestResponse | void) => void;\n\n/**\n * Returns a listener to be added to `client.on('afterSendErrorEvent, listener)`.\n */\nexport function handleAfterSendEvent(replay: ReplayContainer): AfterSendEventCallback {\n // Custom transports may still be returning `Promise`, which means we cannot expect the status code to be available there\n // TODO (v8): remove this check as it will no longer be necessary\n const enforceStatusCode = isBaseTransportSend();\n\n return (event: Event, sendResponse: TransportMakeRequestResponse | void) => {\n if (!replay.isEnabled() || (!isErrorEvent(event) && !isTransactionEvent(event))) {\n return;\n }\n\n const statusCode = sendResponse && sendResponse.statusCode;\n\n // We only want to do stuff on successful error sending, otherwise you get error replays without errors attached\n // If not using the base transport, we allow `undefined` response (as a custom transport may not implement this correctly yet)\n // If we do use the base transport, we skip if we encountered an non-OK status code\n if (enforceStatusCode && (!statusCode || statusCode < 200 || statusCode >= 300)) {\n return;\n }\n\n if (isTransactionEvent(event)) {\n handleTransactionEvent(replay, event);\n return;\n }\n\n handleErrorEvent(replay, event);\n };\n}\n\nfunction handleTransactionEvent(replay: ReplayContainer, event: TransactionEvent): void {\n const replayContext = replay.getContext();\n\n // Collect traceIds in _context regardless of `recordingMode`\n // In error mode, _context gets cleared on every checkout\n // We limit to max. 100 transactions linked\n if (event.contexts && event.contexts.trace && event.contexts.trace.trace_id && replayContext.traceIds.size < 100) {\n replayContext.traceIds.add(event.contexts.trace.trace_id as string);\n }\n}\n\nfunction handleErrorEvent(replay: ReplayContainer, event: ErrorEvent): void {\n const replayContext = replay.getContext();\n\n // Add error to list of errorIds of replay. This is ok to do even if not\n // sampled because context will get reset at next checkout.\n // XXX: There is also a race condition where it's possible to capture an\n // error to Sentry before Replay SDK has loaded, but response returns after\n // it was loaded, and this gets called.\n // We limit to max. 100 errors linked\n if (event.event_id && replayContext.errorIds.size < 100) {\n replayContext.errorIds.add(event.event_id);\n }\n\n // If error event is tagged with replay id it means it was sampled (when in buffer mode)\n // Need to be very careful that this does not cause an infinite loop\n if (replay.recordingMode !== 'buffer' || !event.tags || !event.tags.replayId) {\n return;\n }\n\n const { beforeErrorSampling } = replay.getOptions();\n if (typeof beforeErrorSampling === 'function' && !beforeErrorSampling(event)) {\n return;\n }\n\n setTimeout(() => {\n // Capture current event buffer as new replay\n // This should never reject\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n replay.sendBufferedReplayOrFlush();\n });\n}\n\nfunction isBaseTransportSend(): boolean {\n const client = getClient();\n if (!client) {\n return false;\n }\n\n const transport = client.getTransport();\n if (!transport) {\n return false;\n }\n\n return (\n (transport.send as Transport['send'] & { __sentry__baseTransport__?: true }).__sentry__baseTransport__ || false\n );\n}\n", "import type { ErrorEvent, Event } from '@sentry/types';\n\nimport type { ReplayContainer } from '../types';\nimport { createBreadcrumb } from '../util/createBreadcrumb';\nimport { isErrorEvent } from '../util/eventUtils';\nimport { addBreadcrumbEvent } from './util/addBreadcrumbEvent';\n\ntype BeforeSendEventCallback = (event: Event) => void;\n\n/**\n * Returns a listener to be added to `client.on('afterSendErrorEvent, listener)`.\n */\nexport function handleBeforeSendEvent(replay: ReplayContainer): BeforeSendEventCallback {\n return (event: Event) => {\n if (!replay.isEnabled() || !isErrorEvent(event)) {\n return;\n }\n\n handleHydrationError(replay, event);\n };\n}\n\nfunction handleHydrationError(replay: ReplayContainer, event: ErrorEvent): void {\n const exceptionValue = event.exception && event.exception.values && event.exception.values[0].value;\n if (typeof exceptionValue !== 'string') {\n return;\n }\n\n if (\n // Only matches errors in production builds of react-dom\n // Example https://reactjs.org/docs/error-decoder.html?invariant=423\n exceptionValue.match(/reactjs\\.org\\/docs\\/error-decoder\\.html\\?invariant=(418|419|422|423|425)/) ||\n // Development builds of react-dom\n // Error 1: Hydration failed because the initial UI does not match what was rendered on the server.\n // Error 2: Text content does not match server-rendered HTML. Warning: Text content did not match.\n exceptionValue.match(/(does not match server-rendered HTML|Hydration failed because)/i)\n ) {\n const breadcrumb = createBreadcrumb({\n category: 'replay.hydrate-error',\n });\n addBreadcrumbEvent(replay, breadcrumb);\n }\n}\n", "import type { Event, EventHint } from '@sentry/types';\n\n/**\n * Returns true if we think the given event is an error originating inside of rrweb.\n */\nexport function isRrwebError(event: Event, hint: EventHint): boolean {\n if (event.type || !event.exception || !event.exception.values || !event.exception.values.length) {\n return false;\n }\n\n // @ts-expect-error this may be set by rrweb when it finds errors\n if (hint.originalException && hint.originalException.__rrweb__) {\n return true;\n }\n\n return false;\n}\n", "import { EventType } from '@sentry-internal/rrweb';\nimport type { FeedbackEvent } from '@sentry/types';\n\nimport type { ReplayBreadcrumbFrameEvent, ReplayContainer } from '../../types';\n\n/**\n * Add a feedback breadcrumb event to replay.\n */\nexport function addFeedbackBreadcrumb(replay: ReplayContainer, event: FeedbackEvent): void {\n replay.triggerUserActivity();\n replay.addUpdate(() => {\n if (!event.timestamp) {\n // Ignore events that don't have timestamps (this shouldn't happen, more of a typing issue)\n // Return true here so that we don't flush\n return true;\n }\n\n // This should never reject\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n replay.throttledAddEvent({\n type: EventType.Custom,\n timestamp: event.timestamp * 1000,\n data: {\n tag: 'breadcrumb',\n payload: {\n timestamp: event.timestamp,\n type: 'default',\n category: 'sentry.feedback',\n data: {\n feedbackId: event.event_id,\n },\n },\n },\n } as ReplayBreadcrumbFrameEvent);\n\n return false;\n });\n}\n", "import type { Event } from '@sentry/types';\n\nimport { UNABLE_TO_SEND_REPLAY } from '../../constants';\nimport type { ReplayContainer } from '../../types';\nimport { isSampled } from '../../util/isSampled';\n\n/**\n * Determine if event should be sampled (only applies in buffer mode).\n * When an event is captured by `hanldleGlobalEvent`, when in buffer mode\n * we determine if we want to sample the error or not.\n */\nexport function shouldSampleForBufferEvent(replay: ReplayContainer, event: Event): boolean {\n if (replay.recordingMode !== 'buffer') {\n return false;\n }\n\n // ignore this error because otherwise we could loop indefinitely with\n // trying to capture replay and failing\n if (event.message === UNABLE_TO_SEND_REPLAY) {\n return false;\n }\n\n // Require the event to be an error event & to have an exception\n if (!event.exception || event.type) {\n return false;\n }\n\n return isSampled(replay.getOptions().errorSampleRate);\n}\n", "import type { Event, EventHint } from '@sentry/types';\nimport { logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { ReplayContainer } from '../types';\nimport { isErrorEvent, isFeedbackEvent, isReplayEvent, isTransactionEvent } from '../util/eventUtils';\nimport { isRrwebError } from '../util/isRrwebError';\nimport { handleAfterSendEvent } from './handleAfterSendEvent';\nimport { addFeedbackBreadcrumb } from './util/addFeedbackBreadcrumb';\nimport { shouldSampleForBufferEvent } from './util/shouldSampleForBufferEvent';\n\n/**\n * Returns a listener to be added to `addEventProcessor(listener)`.\n */\nexport function handleGlobalEventListener(\n replay: ReplayContainer,\n includeAfterSendEventHandling = false,\n): (event: Event, hint: EventHint) => Event | null {\n const afterSendHandler = includeAfterSendEventHandling ? handleAfterSendEvent(replay) : undefined;\n\n return Object.assign(\n (event: Event, hint: EventHint) => {\n // Do nothing if replay has been disabled\n if (!replay.isEnabled()) {\n return event;\n }\n\n if (isReplayEvent(event)) {\n // Replays have separate set of breadcrumbs, do not include breadcrumbs\n // from core SDK\n delete event.breadcrumbs;\n return event;\n }\n\n // We only want to handle errors, transactions, and feedbacks, nothing else\n if (!isErrorEvent(event) && !isTransactionEvent(event) && !isFeedbackEvent(event)) {\n return event;\n }\n\n // Ensure we do not add replay_id if the session is expired\n const isSessionActive = replay.checkAndHandleExpiredSession();\n if (!isSessionActive) {\n return event;\n }\n\n if (isFeedbackEvent(event)) {\n // This should never reject\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n replay.flush();\n event.contexts.feedback.replay_id = replay.getSessionId();\n // Add a replay breadcrumb for this piece of feedback\n addFeedbackBreadcrumb(replay, event);\n return event;\n }\n\n // Unless `captureExceptions` is enabled, we want to ignore errors coming from rrweb\n // As there can be a bunch of stuff going wrong in internals there, that we don't want to bubble up to users\n if (isRrwebError(event, hint) && !replay.getOptions()._experiments.captureExceptions) {\n DEBUG_BUILD && logger.log('[Replay] Ignoring error from rrweb internals', event);\n return null;\n }\n\n // When in buffer mode, we decide to sample here.\n // Later, in `handleAfterSendEvent`, if the replayId is set, we know that we sampled\n // And convert the buffer session to a full session\n const isErrorEventSampled = shouldSampleForBufferEvent(replay, event);\n\n // Tag errors if it has been sampled in buffer mode, or if it is session mode\n // Only tag transactions if in session mode\n const shouldTagReplayId = isErrorEventSampled || replay.recordingMode === 'session';\n\n if (shouldTagReplayId) {\n event.tags = { ...event.tags, replayId: replay.getSessionId() };\n }\n\n // In cases where a custom client is used that does not support the new hooks (yet),\n // we manually call this hook method here\n if (afterSendHandler) {\n // Pretend the error had a 200 response so we always capture it\n afterSendHandler(event, { statusCode: 200 });\n }\n\n return event;\n },\n { id: 'Replay' },\n );\n}\n", "import { EventType } from '@sentry-internal/rrweb';\n\nimport type { AddEventResult, AllEntryData, ReplayContainer, ReplayPerformanceEntry } from '../types';\n\n/**\n * Create a \"span\" for each performance entry.\n */\nexport function createPerformanceSpans(\n replay: ReplayContainer,\n entries: ReplayPerformanceEntry[],\n): Promise[] {\n return entries.map(({ type, start, end, name, data }) => {\n const response = replay.throttledAddEvent({\n type: EventType.Custom,\n timestamp: start,\n data: {\n tag: 'performanceSpan',\n payload: {\n op: type,\n description: name,\n startTimestamp: start,\n endTimestamp: end,\n data,\n },\n },\n });\n\n // If response is a string, it means its either THROTTLED or SKIPPED\n return typeof response === 'string' ? Promise.resolve(null) : response;\n });\n}\n", "import type { HandlerDataHistory } from '@sentry/types';\n\nimport type { HistoryData, ReplayContainer, ReplayPerformanceEntry } from '../types';\nimport { createPerformanceSpans } from '../util/createPerformanceSpans';\n\nfunction handleHistory(handlerData: HandlerDataHistory): ReplayPerformanceEntry {\n const { from, to } = handlerData;\n\n const now = Date.now() / 1000;\n\n return {\n type: 'navigation.push',\n start: now,\n end: now,\n name: to,\n data: {\n previous: from,\n },\n };\n}\n\n/**\n * Returns a listener to be added to `addHistoryInstrumentationHandler(listener)`.\n */\nexport function handleHistorySpanListener(replay: ReplayContainer): (handlerData: HandlerDataHistory) => void {\n return (handlerData: HandlerDataHistory) => {\n if (!replay.isEnabled()) {\n return;\n }\n\n const result = handleHistory(handlerData);\n\n if (result === null) {\n return;\n }\n\n // Need to collect visited URLs\n replay.getContext().urls.push(result.name);\n replay.triggerUserActivity();\n\n replay.addUpdate(() => {\n createPerformanceSpans(replay, [result]);\n // Returning false to flush\n return false;\n });\n };\n}\n", "import { getClient, isSentryRequestUrl } from '@sentry/core';\n\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { ReplayContainer } from '../types';\n\n/**\n * Check whether a given request URL should be filtered out. This is so we\n * don't log Sentry ingest requests.\n */\nexport function shouldFilterRequest(replay: ReplayContainer, url: string): boolean {\n // If we enabled the `traceInternals` experiment, we want to trace everything\n if (DEBUG_BUILD && replay.getOptions()._experiments.traceInternals) {\n return false;\n }\n\n return isSentryRequestUrl(url, getClient());\n}\n", "import type { NetworkRequestData, ReplayContainer, ReplayPerformanceEntry } from '../../types';\nimport { createPerformanceSpans } from '../../util/createPerformanceSpans';\nimport { shouldFilterRequest } from '../../util/shouldFilterRequest';\n\n/** Add a performance entry breadcrumb */\nexport function addNetworkBreadcrumb(\n replay: ReplayContainer,\n result: ReplayPerformanceEntry | null,\n): void {\n if (!replay.isEnabled()) {\n return;\n }\n\n if (result === null) {\n return;\n }\n\n if (shouldFilterRequest(replay, result.name)) {\n return;\n }\n\n replay.addUpdate(() => {\n createPerformanceSpans(replay, [result]);\n // Returning true will cause `addUpdate` to not flush\n // We do not want network requests to cause a flush. This will prevent\n // recurring/polling requests from keeping the replay session alive.\n return true;\n });\n}\n", "import type { HandlerDataFetch } from '@sentry/types';\n\nimport type { NetworkRequestData, ReplayContainer, ReplayPerformanceEntry } from '../types';\nimport { addNetworkBreadcrumb } from './util/addNetworkBreadcrumb';\n\n/** only exported for tests */\nexport function handleFetch(handlerData: HandlerDataFetch): null | ReplayPerformanceEntry {\n const { startTimestamp, endTimestamp, fetchData, response } = handlerData;\n\n if (!endTimestamp) {\n return null;\n }\n\n // This is only used as a fallback, so we know the body sizes are never set here\n const { method, url } = fetchData;\n\n return {\n type: 'resource.fetch',\n start: startTimestamp / 1000,\n end: endTimestamp / 1000,\n name: url,\n data: {\n method,\n statusCode: response ? (response as Response).status : undefined,\n },\n };\n}\n\n/**\n * Returns a listener to be added to `addFetchInstrumentationHandler(listener)`.\n */\nexport function handleFetchSpanListener(replay: ReplayContainer): (handlerData: HandlerDataFetch) => void {\n return (handlerData: HandlerDataFetch) => {\n if (!replay.isEnabled()) {\n return;\n }\n\n const result = handleFetch(handlerData);\n\n addNetworkBreadcrumb(replay, result);\n };\n}\n", "import type { HandlerDataXhr } from '@sentry/types';\nimport { SENTRY_XHR_DATA_KEY } from '@sentry/utils';\n\nimport type { NetworkRequestData, ReplayContainer, ReplayPerformanceEntry } from '../types';\nimport { addNetworkBreadcrumb } from './util/addNetworkBreadcrumb';\n\n/** only exported for tests */\nexport function handleXhr(handlerData: HandlerDataXhr): ReplayPerformanceEntry | null {\n const { startTimestamp, endTimestamp, xhr } = handlerData;\n\n const sentryXhrData = xhr[SENTRY_XHR_DATA_KEY];\n\n if (!startTimestamp || !endTimestamp || !sentryXhrData) {\n return null;\n }\n\n // This is only used as a fallback, so we know the body sizes are never set here\n const { method, url, status_code: statusCode } = sentryXhrData;\n\n if (url === undefined) {\n return null;\n }\n\n return {\n type: 'resource.xhr',\n name: url,\n start: startTimestamp / 1000,\n end: endTimestamp / 1000,\n data: {\n method,\n statusCode,\n },\n };\n}\n\n/**\n * Returns a listener to be added to `addXhrInstrumentationHandler(listener)`.\n */\nexport function handleXhrSpanListener(replay: ReplayContainer): (handlerData: HandlerDataXhr) => void {\n return (handlerData: HandlerDataXhr) => {\n if (!replay.isEnabled()) {\n return;\n }\n\n const result = handleXhr(handlerData);\n\n addNetworkBreadcrumb(replay, result);\n };\n}\n", "import type { TextEncoderInternal } from '@sentry/types';\nimport { dropUndefinedKeys, logger, stringMatchesSomePattern } from '@sentry/utils';\n\nimport { NETWORK_BODY_MAX_SIZE, WINDOW } from '../../constants';\nimport { DEBUG_BUILD } from '../../debug-build';\nimport type {\n NetworkBody,\n NetworkMetaWarning,\n NetworkRequestData,\n ReplayNetworkRequestData,\n ReplayNetworkRequestOrResponse,\n ReplayPerformanceEntry,\n} from '../../types';\n\n/** Get the size of a body. */\nexport function getBodySize(\n body: RequestInit['body'],\n textEncoder: TextEncoder | TextEncoderInternal,\n): number | undefined {\n if (!body) {\n return undefined;\n }\n\n try {\n if (typeof body === 'string') {\n return textEncoder.encode(body).length;\n }\n\n if (body instanceof URLSearchParams) {\n return textEncoder.encode(body.toString()).length;\n }\n\n if (body instanceof FormData) {\n const formDataStr = _serializeFormData(body);\n return textEncoder.encode(formDataStr).length;\n }\n\n if (body instanceof Blob) {\n return body.size;\n }\n\n if (body instanceof ArrayBuffer) {\n return body.byteLength;\n }\n\n // Currently unhandled types: ArrayBufferView, ReadableStream\n } catch {\n // just return undefined\n }\n\n return undefined;\n}\n\n/** Convert a Content-Length header to number/undefined. */\nexport function parseContentLengthHeader(header: string | null | undefined): number | undefined {\n if (!header) {\n return undefined;\n }\n\n const size = parseInt(header, 10);\n return isNaN(size) ? undefined : size;\n}\n\n/** Get the string representation of a body. */\nexport function getBodyString(body: unknown): [string | undefined, NetworkMetaWarning?] {\n try {\n if (typeof body === 'string') {\n return [body];\n }\n\n if (body instanceof URLSearchParams) {\n return [body.toString()];\n }\n\n if (body instanceof FormData) {\n return [_serializeFormData(body)];\n }\n\n if (!body) {\n return [undefined];\n }\n } catch {\n DEBUG_BUILD && logger.warn('[Replay] Failed to serialize body', body);\n return [undefined, 'BODY_PARSE_ERROR'];\n }\n\n DEBUG_BUILD && logger.info('[Replay] Skipping network body because of body type', body);\n\n return [undefined, 'UNPARSEABLE_BODY_TYPE'];\n}\n\n/** Merge a warning into an existing network request/response. */\nexport function mergeWarning(\n info: ReplayNetworkRequestOrResponse | undefined,\n warning: NetworkMetaWarning,\n): ReplayNetworkRequestOrResponse {\n if (!info) {\n return {\n headers: {},\n size: undefined,\n _meta: {\n warnings: [warning],\n },\n };\n }\n\n const newMeta = { ...info._meta };\n const existingWarnings = newMeta.warnings || [];\n newMeta.warnings = [...existingWarnings, warning];\n\n info._meta = newMeta;\n return info;\n}\n\n/** Convert ReplayNetworkRequestData to a PerformanceEntry. */\nexport function makeNetworkReplayBreadcrumb(\n type: string,\n data: ReplayNetworkRequestData | null,\n): ReplayPerformanceEntry | null {\n if (!data) {\n return null;\n }\n\n const { startTimestamp, endTimestamp, url, method, statusCode, request, response } = data;\n\n const result: ReplayPerformanceEntry = {\n type,\n start: startTimestamp / 1000,\n end: endTimestamp / 1000,\n name: url,\n data: dropUndefinedKeys({\n method,\n statusCode,\n request,\n response,\n }),\n };\n\n return result;\n}\n\n/** Build the request or response part of a replay network breadcrumb that was skipped. */\nexport function buildSkippedNetworkRequestOrResponse(bodySize: number | undefined): ReplayNetworkRequestOrResponse {\n return {\n headers: {},\n size: bodySize,\n _meta: {\n warnings: ['URL_SKIPPED'],\n },\n };\n}\n\n/** Build the request or response part of a replay network breadcrumb. */\nexport function buildNetworkRequestOrResponse(\n headers: Record,\n bodySize: number | undefined,\n body: string | undefined,\n): ReplayNetworkRequestOrResponse | undefined {\n if (!bodySize && Object.keys(headers).length === 0) {\n return undefined;\n }\n\n if (!bodySize) {\n return {\n headers,\n };\n }\n\n if (!body) {\n return {\n headers,\n size: bodySize,\n };\n }\n\n const info: ReplayNetworkRequestOrResponse = {\n headers,\n size: bodySize,\n };\n\n const { body: normalizedBody, warnings } = normalizeNetworkBody(body);\n info.body = normalizedBody;\n if (warnings && warnings.length > 0) {\n info._meta = {\n warnings,\n };\n }\n\n return info;\n}\n\n/** Filter a set of headers */\nexport function getAllowedHeaders(headers: Record, allowedHeaders: string[]): Record {\n return Object.keys(headers).reduce((filteredHeaders: Record, key: string) => {\n const normalizedKey = key.toLowerCase();\n // Avoid putting empty strings into the headers\n if (allowedHeaders.includes(normalizedKey) && headers[key]) {\n filteredHeaders[normalizedKey] = headers[key];\n }\n return filteredHeaders;\n }, {});\n}\n\nfunction _serializeFormData(formData: FormData): string {\n // This is a bit simplified, but gives us a decent estimate\n // This converts e.g. { name: 'Anne Smith', age: 13 } to 'name=Anne+Smith&age=13'\n // @ts-expect-error passing FormData to URLSearchParams actually works\n return new URLSearchParams(formData).toString();\n}\n\nfunction normalizeNetworkBody(body: string | undefined): {\n body: NetworkBody | undefined;\n warnings?: NetworkMetaWarning[];\n} {\n if (!body || typeof body !== 'string') {\n return {\n body,\n };\n }\n\n const exceedsSizeLimit = body.length > NETWORK_BODY_MAX_SIZE;\n const isProbablyJson = _strIsProbablyJson(body);\n\n if (exceedsSizeLimit) {\n const truncatedBody = body.slice(0, NETWORK_BODY_MAX_SIZE);\n\n if (isProbablyJson) {\n return {\n body: truncatedBody,\n warnings: ['MAYBE_JSON_TRUNCATED'],\n };\n }\n\n return {\n body: `${truncatedBody}…`,\n warnings: ['TEXT_TRUNCATED'],\n };\n }\n\n if (isProbablyJson) {\n try {\n const jsonBody = JSON.parse(body);\n return {\n body: jsonBody,\n };\n } catch {\n // fall back to just send the body as string\n }\n }\n\n return {\n body,\n };\n}\n\nfunction _strIsProbablyJson(str: string): boolean {\n const first = str[0];\n const last = str[str.length - 1];\n\n // Simple check: If this does not start & end with {} or [], it's not JSON\n return (first === '[' && last === ']') || (first === '{' && last === '}');\n}\n\n/** Match an URL against a list of strings/Regex. */\nexport function urlMatches(url: string, urls: (string | RegExp)[]): boolean {\n const fullUrl = getFullUrl(url);\n\n return stringMatchesSomePattern(fullUrl, urls);\n}\n\n/** exported for tests */\nexport function getFullUrl(url: string, baseURI = WINDOW.document.baseURI): string {\n // Short circuit for common cases:\n if (url.startsWith('http://') || url.startsWith('https://') || url.startsWith(WINDOW.location.origin)) {\n return url;\n }\n const fixedUrl = new URL(url, baseURI);\n\n // If these do not match, we are not dealing with a relative URL, so just return it\n if (fixedUrl.origin !== new URL(baseURI).origin) {\n return url;\n }\n\n const fullUrl = fixedUrl.href;\n\n // Remove trailing slashes, if they don't match the original URL\n if (!url.endsWith('/') && fullUrl.endsWith('/')) {\n return fullUrl.slice(0, -1);\n }\n\n return fullUrl;\n}\n", "import type { Breadcrumb, FetchBreadcrumbData, TextEncoderInternal } from '@sentry/types';\nimport { logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../../debug-build';\nimport type {\n FetchHint,\n NetworkMetaWarning,\n ReplayContainer,\n ReplayNetworkOptions,\n ReplayNetworkRequestData,\n ReplayNetworkRequestOrResponse,\n} from '../../types';\nimport { addNetworkBreadcrumb } from './addNetworkBreadcrumb';\nimport {\n buildNetworkRequestOrResponse,\n buildSkippedNetworkRequestOrResponse,\n getAllowedHeaders,\n getBodySize,\n getBodyString,\n makeNetworkReplayBreadcrumb,\n mergeWarning,\n parseContentLengthHeader,\n urlMatches,\n} from './networkUtils';\n\n/**\n * Capture a fetch breadcrumb to a replay.\n * This adds additional data (where approriate).\n */\nexport async function captureFetchBreadcrumbToReplay(\n breadcrumb: Breadcrumb & { data: FetchBreadcrumbData },\n hint: Partial,\n options: ReplayNetworkOptions & {\n textEncoder: TextEncoderInternal;\n replay: ReplayContainer;\n },\n): Promise {\n try {\n const data = await _prepareFetchData(breadcrumb, hint, options);\n\n // Create a replay performance entry from this breadcrumb\n const result = makeNetworkReplayBreadcrumb('resource.fetch', data);\n addNetworkBreadcrumb(options.replay, result);\n } catch (error) {\n DEBUG_BUILD && logger.error('[Replay] Failed to capture fetch breadcrumb', error);\n }\n}\n\n/**\n * Enrich a breadcrumb with additional data.\n * This has to be sync & mutate the given breadcrumb,\n * as the breadcrumb is afterwards consumed by other handlers.\n */\nexport function enrichFetchBreadcrumb(\n breadcrumb: Breadcrumb & { data: FetchBreadcrumbData },\n hint: Partial,\n options: { textEncoder: TextEncoderInternal },\n): void {\n const { input, response } = hint;\n\n const body = input ? _getFetchRequestArgBody(input) : undefined;\n const reqSize = getBodySize(body, options.textEncoder);\n\n const resSize = response ? parseContentLengthHeader(response.headers.get('content-length')) : undefined;\n\n if (reqSize !== undefined) {\n breadcrumb.data.request_body_size = reqSize;\n }\n if (resSize !== undefined) {\n breadcrumb.data.response_body_size = resSize;\n }\n}\n\nasync function _prepareFetchData(\n breadcrumb: Breadcrumb & { data: FetchBreadcrumbData },\n hint: Partial,\n options: ReplayNetworkOptions & {\n textEncoder: TextEncoderInternal;\n },\n): Promise {\n const now = Date.now();\n const { startTimestamp = now, endTimestamp = now } = hint;\n\n const {\n url,\n method,\n status_code: statusCode = 0,\n request_body_size: requestBodySize,\n response_body_size: responseBodySize,\n } = breadcrumb.data;\n\n const captureDetails =\n urlMatches(url, options.networkDetailAllowUrls) && !urlMatches(url, options.networkDetailDenyUrls);\n\n const request = captureDetails\n ? _getRequestInfo(options, hint.input, requestBodySize)\n : buildSkippedNetworkRequestOrResponse(requestBodySize);\n const response = await _getResponseInfo(captureDetails, options, hint.response, responseBodySize);\n\n return {\n startTimestamp,\n endTimestamp,\n url,\n method,\n statusCode,\n request,\n response,\n };\n}\n\nfunction _getRequestInfo(\n { networkCaptureBodies, networkRequestHeaders }: ReplayNetworkOptions,\n input: FetchHint['input'] | undefined,\n requestBodySize?: number,\n): ReplayNetworkRequestOrResponse | undefined {\n const headers = input ? getRequestHeaders(input, networkRequestHeaders) : {};\n\n if (!networkCaptureBodies) {\n return buildNetworkRequestOrResponse(headers, requestBodySize, undefined);\n }\n\n // We only want to transmit string or string-like bodies\n const requestBody = _getFetchRequestArgBody(input);\n const [bodyStr, warning] = getBodyString(requestBody);\n const data = buildNetworkRequestOrResponse(headers, requestBodySize, bodyStr);\n\n if (warning) {\n return mergeWarning(data, warning);\n }\n\n return data;\n}\n\n/** Exported only for tests. */\nexport async function _getResponseInfo(\n captureDetails: boolean,\n {\n networkCaptureBodies,\n textEncoder,\n networkResponseHeaders,\n }: Pick & {\n textEncoder: TextEncoderInternal;\n },\n response: Response | undefined,\n responseBodySize?: number,\n): Promise {\n if (!captureDetails && responseBodySize !== undefined) {\n return buildSkippedNetworkRequestOrResponse(responseBodySize);\n }\n\n const headers = response ? getAllHeaders(response.headers, networkResponseHeaders) : {};\n\n if (!response || (!networkCaptureBodies && responseBodySize !== undefined)) {\n return buildNetworkRequestOrResponse(headers, responseBodySize, undefined);\n }\n\n const [bodyText, warning] = await _parseFetchResponseBody(response);\n const result = getResponseData(bodyText, {\n networkCaptureBodies,\n textEncoder,\n responseBodySize,\n captureDetails,\n headers,\n });\n\n if (warning) {\n return mergeWarning(result, warning);\n }\n\n return result;\n}\n\nfunction getResponseData(\n bodyText: string | undefined,\n {\n networkCaptureBodies,\n textEncoder,\n responseBodySize,\n captureDetails,\n headers,\n }: {\n captureDetails: boolean;\n networkCaptureBodies: boolean;\n responseBodySize: number | undefined;\n headers: Record;\n textEncoder: TextEncoderInternal;\n },\n): ReplayNetworkRequestOrResponse | undefined {\n try {\n const size =\n bodyText && bodyText.length && responseBodySize === undefined\n ? getBodySize(bodyText, textEncoder)\n : responseBodySize;\n\n if (!captureDetails) {\n return buildSkippedNetworkRequestOrResponse(size);\n }\n\n if (networkCaptureBodies) {\n return buildNetworkRequestOrResponse(headers, size, bodyText);\n }\n\n return buildNetworkRequestOrResponse(headers, size, undefined);\n } catch (error) {\n DEBUG_BUILD && logger.warn('[Replay] Failed to serialize response body', error);\n // fallback\n return buildNetworkRequestOrResponse(headers, responseBodySize, undefined);\n }\n}\n\nasync function _parseFetchResponseBody(response: Response): Promise<[string | undefined, NetworkMetaWarning?]> {\n const res = _tryCloneResponse(response);\n\n if (!res) {\n return [undefined, 'BODY_PARSE_ERROR'];\n }\n\n try {\n const text = await _tryGetResponseText(res);\n return [text];\n } catch (error) {\n DEBUG_BUILD && logger.warn('[Replay] Failed to get text body from response', error);\n return [undefined, 'BODY_PARSE_ERROR'];\n }\n}\n\nfunction _getFetchRequestArgBody(fetchArgs: unknown[] = []): RequestInit['body'] | undefined {\n // We only support getting the body from the fetch options\n if (fetchArgs.length !== 2 || typeof fetchArgs[1] !== 'object') {\n return undefined;\n }\n\n return (fetchArgs[1] as RequestInit).body;\n}\n\nfunction getAllHeaders(headers: Headers, allowedHeaders: string[]): Record {\n const allHeaders: Record = {};\n\n allowedHeaders.forEach(header => {\n if (headers.get(header)) {\n allHeaders[header] = headers.get(header) as string;\n }\n });\n\n return allHeaders;\n}\n\nfunction getRequestHeaders(fetchArgs: unknown[], allowedHeaders: string[]): Record {\n if (fetchArgs.length === 1 && typeof fetchArgs[0] !== 'string') {\n return getHeadersFromOptions(fetchArgs[0] as Request | RequestInit, allowedHeaders);\n }\n\n if (fetchArgs.length === 2) {\n return getHeadersFromOptions(fetchArgs[1] as Request | RequestInit, allowedHeaders);\n }\n\n return {};\n}\n\nfunction getHeadersFromOptions(\n input: Request | RequestInit | undefined,\n allowedHeaders: string[],\n): Record {\n if (!input) {\n return {};\n }\n\n const headers = input.headers;\n\n if (!headers) {\n return {};\n }\n\n if (headers instanceof Headers) {\n return getAllHeaders(headers, allowedHeaders);\n }\n\n // We do not support this, as it is not really documented (anymore?)\n if (Array.isArray(headers)) {\n return {};\n }\n\n return getAllowedHeaders(headers, allowedHeaders);\n}\n\nfunction _tryCloneResponse(response: Response): Response | void {\n try {\n // We have to clone this, as the body can only be read once\n return response.clone();\n } catch (error) {\n // this can throw if the response was already consumed before\n DEBUG_BUILD && logger.warn('[Replay] Failed to clone response body', error);\n }\n}\n\n/**\n * Get the response body of a fetch request, or timeout after 500ms.\n * Fetch can return a streaming body, that may not resolve (or not for a long time).\n * If that happens, we rather abort after a short time than keep waiting for this.\n */\nfunction _tryGetResponseText(response: Response): Promise {\n return new Promise((resolve, reject) => {\n const timeout = setTimeout(() => reject(new Error('Timeout while trying to read response body')), 500);\n\n _getResponseText(response)\n .then(\n txt => resolve(txt),\n reason => reject(reason),\n )\n .finally(() => clearTimeout(timeout));\n });\n\n return _getResponseText(response);\n}\n\nasync function _getResponseText(response: Response): Promise {\n // Force this to be a promise, just to be safe\n // eslint-disable-next-line no-return-await\n return await response.text();\n}\n", "import type { Breadcrumb, TextEncoderInternal, XhrBreadcrumbData } from '@sentry/types';\nimport { SENTRY_XHR_DATA_KEY, logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../../debug-build';\nimport type {\n NetworkMetaWarning,\n ReplayContainer,\n ReplayNetworkOptions,\n ReplayNetworkRequestData,\n XhrHint,\n} from '../../types';\nimport { addNetworkBreadcrumb } from './addNetworkBreadcrumb';\nimport {\n buildNetworkRequestOrResponse,\n buildSkippedNetworkRequestOrResponse,\n getAllowedHeaders,\n getBodySize,\n getBodyString,\n makeNetworkReplayBreadcrumb,\n mergeWarning,\n parseContentLengthHeader,\n urlMatches,\n} from './networkUtils';\n\n/**\n * Capture an XHR breadcrumb to a replay.\n * This adds additional data (where approriate).\n */\nexport async function captureXhrBreadcrumbToReplay(\n breadcrumb: Breadcrumb & { data: XhrBreadcrumbData },\n hint: Partial,\n options: ReplayNetworkOptions & { replay: ReplayContainer },\n): Promise {\n try {\n const data = _prepareXhrData(breadcrumb, hint, options);\n\n // Create a replay performance entry from this breadcrumb\n const result = makeNetworkReplayBreadcrumb('resource.xhr', data);\n addNetworkBreadcrumb(options.replay, result);\n } catch (error) {\n DEBUG_BUILD && logger.error('[Replay] Failed to capture xhr breadcrumb', error);\n }\n}\n\n/**\n * Enrich a breadcrumb with additional data.\n * This has to be sync & mutate the given breadcrumb,\n * as the breadcrumb is afterwards consumed by other handlers.\n */\nexport function enrichXhrBreadcrumb(\n breadcrumb: Breadcrumb & { data: XhrBreadcrumbData },\n hint: Partial,\n options: { textEncoder: TextEncoderInternal },\n): void {\n const { xhr, input } = hint;\n\n if (!xhr) {\n return;\n }\n\n const reqSize = getBodySize(input, options.textEncoder);\n const resSize = xhr.getResponseHeader('content-length')\n ? parseContentLengthHeader(xhr.getResponseHeader('content-length'))\n : _getBodySize(xhr.response, xhr.responseType, options.textEncoder);\n\n if (reqSize !== undefined) {\n breadcrumb.data.request_body_size = reqSize;\n }\n if (resSize !== undefined) {\n breadcrumb.data.response_body_size = resSize;\n }\n}\n\nfunction _prepareXhrData(\n breadcrumb: Breadcrumb & { data: XhrBreadcrumbData },\n hint: Partial,\n options: ReplayNetworkOptions,\n): ReplayNetworkRequestData | null {\n const now = Date.now();\n const { startTimestamp = now, endTimestamp = now, input, xhr } = hint;\n\n const {\n url,\n method,\n status_code: statusCode = 0,\n request_body_size: requestBodySize,\n response_body_size: responseBodySize,\n } = breadcrumb.data;\n\n if (!url) {\n return null;\n }\n\n if (!xhr || !urlMatches(url, options.networkDetailAllowUrls) || urlMatches(url, options.networkDetailDenyUrls)) {\n const request = buildSkippedNetworkRequestOrResponse(requestBodySize);\n const response = buildSkippedNetworkRequestOrResponse(responseBodySize);\n return {\n startTimestamp,\n endTimestamp,\n url,\n method,\n statusCode,\n request,\n response,\n };\n }\n\n const xhrInfo = xhr[SENTRY_XHR_DATA_KEY];\n const networkRequestHeaders = xhrInfo\n ? getAllowedHeaders(xhrInfo.request_headers, options.networkRequestHeaders)\n : {};\n const networkResponseHeaders = getAllowedHeaders(getResponseHeaders(xhr), options.networkResponseHeaders);\n\n const [requestBody, requestWarning] = options.networkCaptureBodies ? getBodyString(input) : [undefined];\n const [responseBody, responseWarning] = options.networkCaptureBodies ? _getXhrResponseBody(xhr) : [undefined];\n\n const request = buildNetworkRequestOrResponse(networkRequestHeaders, requestBodySize, requestBody);\n const response = buildNetworkRequestOrResponse(networkResponseHeaders, responseBodySize, responseBody);\n\n return {\n startTimestamp,\n endTimestamp,\n url,\n method,\n statusCode,\n request: requestWarning ? mergeWarning(request, requestWarning) : request,\n response: responseWarning ? mergeWarning(response, responseWarning) : response,\n };\n}\n\nfunction getResponseHeaders(xhr: XMLHttpRequest): Record {\n const headers = xhr.getAllResponseHeaders();\n\n if (!headers) {\n return {};\n }\n\n return headers.split('\\r\\n').reduce((acc: Record, line: string) => {\n const [key, value] = line.split(': ');\n acc[key.toLowerCase()] = value;\n return acc;\n }, {});\n}\n\nfunction _getXhrResponseBody(xhr: XMLHttpRequest): [string | undefined, NetworkMetaWarning?] {\n // We collect errors that happen, but only log them if we can't get any response body\n const errors: unknown[] = [];\n\n try {\n return [xhr.responseText];\n } catch (e) {\n errors.push(e);\n }\n\n // Try to manually parse the response body, if responseText fails\n try {\n return _parseXhrResponse(xhr.response, xhr.responseType);\n } catch (e) {\n errors.push(e);\n }\n\n DEBUG_BUILD && logger.warn('[Replay] Failed to get xhr response body', ...errors);\n\n return [undefined];\n}\n\n/**\n * Get the string representation of the XHR response.\n * Based on MDN, these are the possible types of the response:\n * string\n * ArrayBuffer\n * Blob\n * Document\n * POJO\n *\n * Exported only for tests.\n */\nexport function _parseXhrResponse(\n body: XMLHttpRequest['response'],\n responseType: XMLHttpRequest['responseType'],\n): [string | undefined, NetworkMetaWarning?] {\n try {\n if (typeof body === 'string') {\n return [body];\n }\n\n if (body instanceof Document) {\n return [body.body.outerHTML];\n }\n\n if (responseType === 'json' && body && typeof body === 'object') {\n return [JSON.stringify(body)];\n }\n\n if (!body) {\n return [undefined];\n }\n } catch {\n DEBUG_BUILD && logger.warn('[Replay] Failed to serialize body', body);\n return [undefined, 'BODY_PARSE_ERROR'];\n }\n\n DEBUG_BUILD && logger.info('[Replay] Skipping network body because of body type', body);\n\n return [undefined, 'UNPARSEABLE_BODY_TYPE'];\n}\n\nfunction _getBodySize(\n body: XMLHttpRequest['response'],\n responseType: XMLHttpRequest['responseType'],\n textEncoder: TextEncoder | TextEncoderInternal,\n): number | undefined {\n try {\n const bodyStr = responseType === 'json' && body && typeof body === 'object' ? JSON.stringify(body) : body;\n return getBodySize(bodyStr, textEncoder);\n } catch {\n return undefined;\n }\n}\n", "import { getClient } from '@sentry/core';\nimport type {\n Breadcrumb,\n BreadcrumbHint,\n FetchBreadcrumbData,\n TextEncoderInternal,\n XhrBreadcrumbData,\n} from '@sentry/types';\nimport { addFetchInstrumentationHandler, addXhrInstrumentationHandler, logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { FetchHint, ReplayContainer, ReplayNetworkOptions, XhrHint } from '../types';\nimport { handleFetchSpanListener } from './handleFetch';\nimport { handleXhrSpanListener } from './handleXhr';\nimport { captureFetchBreadcrumbToReplay, enrichFetchBreadcrumb } from './util/fetchUtils';\nimport { captureXhrBreadcrumbToReplay, enrichXhrBreadcrumb } from './util/xhrUtils';\n\ninterface ExtendedNetworkBreadcrumbsOptions extends ReplayNetworkOptions {\n replay: ReplayContainer;\n textEncoder: TextEncoderInternal;\n}\n\n/**\n * This method does two things:\n * - It enriches the regular XHR/fetch breadcrumbs with request/response size data\n * - It captures the XHR/fetch breadcrumbs to the replay\n * (enriching it with further data that is _not_ added to the regular breadcrumbs)\n */\nexport function handleNetworkBreadcrumbs(replay: ReplayContainer): void {\n const client = getClient();\n\n try {\n const textEncoder = new TextEncoder();\n\n const {\n networkDetailAllowUrls,\n networkDetailDenyUrls,\n networkCaptureBodies,\n networkRequestHeaders,\n networkResponseHeaders,\n } = replay.getOptions();\n\n const options: ExtendedNetworkBreadcrumbsOptions = {\n replay,\n textEncoder,\n networkDetailAllowUrls,\n networkDetailDenyUrls,\n networkCaptureBodies,\n networkRequestHeaders,\n networkResponseHeaders,\n };\n\n if (client && client.on) {\n client.on('beforeAddBreadcrumb', (breadcrumb, hint) => beforeAddNetworkBreadcrumb(options, breadcrumb, hint));\n } else {\n // Fallback behavior\n addFetchInstrumentationHandler(handleFetchSpanListener(replay));\n addXhrInstrumentationHandler(handleXhrSpanListener(replay));\n }\n } catch {\n // Do nothing\n }\n}\n\n/** just exported for tests */\nexport function beforeAddNetworkBreadcrumb(\n options: ExtendedNetworkBreadcrumbsOptions,\n breadcrumb: Breadcrumb,\n hint?: BreadcrumbHint,\n): void {\n if (!breadcrumb.data) {\n return;\n }\n\n try {\n if (_isXhrBreadcrumb(breadcrumb) && _isXhrHint(hint)) {\n // This has to be sync, as we need to ensure the breadcrumb is enriched in the same tick\n // Because the hook runs synchronously, and the breadcrumb is afterwards passed on\n // So any async mutations to it will not be reflected in the final breadcrumb\n enrichXhrBreadcrumb(breadcrumb, hint, options);\n\n // This call should not reject\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n captureXhrBreadcrumbToReplay(breadcrumb, hint, options);\n }\n\n if (_isFetchBreadcrumb(breadcrumb) && _isFetchHint(hint)) {\n // This has to be sync, as we need to ensure the breadcrumb is enriched in the same tick\n // Because the hook runs synchronously, and the breadcrumb is afterwards passed on\n // So any async mutations to it will not be reflected in the final breadcrumb\n enrichFetchBreadcrumb(breadcrumb, hint, options);\n\n // This call should not reject\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n captureFetchBreadcrumbToReplay(breadcrumb, hint, options);\n }\n } catch (e) {\n DEBUG_BUILD && logger.warn('Error when enriching network breadcrumb');\n }\n}\n\nfunction _isXhrBreadcrumb(breadcrumb: Breadcrumb): breadcrumb is Breadcrumb & { data: XhrBreadcrumbData } {\n return breadcrumb.category === 'xhr';\n}\n\nfunction _isFetchBreadcrumb(breadcrumb: Breadcrumb): breadcrumb is Breadcrumb & { data: FetchBreadcrumbData } {\n return breadcrumb.category === 'fetch';\n}\n\nfunction _isXhrHint(hint?: BreadcrumbHint): hint is XhrHint {\n return hint && hint.xhr;\n}\n\nfunction _isFetchHint(hint?: BreadcrumbHint): hint is FetchHint {\n return hint && hint.response;\n}\n", "import type { Breadcrumb, Scope } from '@sentry/types';\nimport { normalize } from '@sentry/utils';\n\nimport { CONSOLE_ARG_MAX_SIZE } from '../constants';\nimport type { ReplayContainer } from '../types';\nimport type { ReplayFrame } from '../types/replayFrame';\nimport { createBreadcrumb } from '../util/createBreadcrumb';\nimport { addBreadcrumbEvent } from './util/addBreadcrumbEvent';\n\nlet _LAST_BREADCRUMB: null | Breadcrumb = null;\n\ntype BreadcrumbWithCategory = Required>;\n\nfunction isBreadcrumbWithCategory(breadcrumb: Breadcrumb): breadcrumb is BreadcrumbWithCategory {\n return !!breadcrumb.category;\n}\n\nexport const handleScopeListener: (replay: ReplayContainer) => (scope: Scope) => void =\n (replay: ReplayContainer) =>\n (scope: Scope): void => {\n if (!replay.isEnabled()) {\n return;\n }\n\n const result = handleScope(scope);\n\n if (!result) {\n return;\n }\n\n addBreadcrumbEvent(replay, result);\n };\n\n/**\n * An event handler to handle scope changes.\n */\nexport function handleScope(scope: Scope): Breadcrumb | null {\n // TODO (v8): Remove this guard. This was put in place because we introduced\n // Scope.getLastBreadcrumb mid-v7 which caused incompatibilities with older SDKs.\n // For now, we'll just return null if the method doesn't exist but we should eventually\n // get rid of this guard.\n const newBreadcrumb = scope.getLastBreadcrumb && scope.getLastBreadcrumb();\n\n // Listener can be called when breadcrumbs have not changed, so we store the\n // reference to the last crumb and only return a crumb if it has changed\n if (_LAST_BREADCRUMB === newBreadcrumb || !newBreadcrumb) {\n return null;\n }\n\n _LAST_BREADCRUMB = newBreadcrumb;\n\n if (\n !isBreadcrumbWithCategory(newBreadcrumb) ||\n ['fetch', 'xhr', 'sentry.event', 'sentry.transaction'].includes(newBreadcrumb.category) ||\n newBreadcrumb.category.startsWith('ui.')\n ) {\n return null;\n }\n\n if (newBreadcrumb.category === 'console') {\n return normalizeConsoleBreadcrumb(newBreadcrumb);\n }\n\n return createBreadcrumb(newBreadcrumb);\n}\n\n/** exported for tests only */\nexport function normalizeConsoleBreadcrumb(\n breadcrumb: Omit & BreadcrumbWithCategory,\n): ReplayFrame {\n const args = breadcrumb.data && breadcrumb.data.arguments;\n\n if (!Array.isArray(args) || args.length === 0) {\n return createBreadcrumb(breadcrumb);\n }\n\n let isTruncated = false;\n\n // Avoid giant args captures\n const normalizedArgs = args.map(arg => {\n if (!arg) {\n return arg;\n }\n if (typeof arg === 'string') {\n if (arg.length > CONSOLE_ARG_MAX_SIZE) {\n isTruncated = true;\n return `${arg.slice(0, CONSOLE_ARG_MAX_SIZE)}…`;\n }\n\n return arg;\n }\n if (typeof arg === 'object') {\n try {\n const normalizedArg = normalize(arg, 7);\n const stringified = JSON.stringify(normalizedArg);\n if (stringified.length > CONSOLE_ARG_MAX_SIZE) {\n isTruncated = true;\n // We use the pretty printed JSON string here as a base\n return `${JSON.stringify(normalizedArg, null, 2).slice(0, CONSOLE_ARG_MAX_SIZE)}…`;\n }\n return normalizedArg;\n } catch {\n // fall back to default\n }\n }\n\n return arg;\n });\n\n return createBreadcrumb({\n ...breadcrumb,\n data: {\n ...breadcrumb.data,\n arguments: normalizedArgs,\n ...(isTruncated ? { _meta: { warnings: ['CONSOLE_ARG_TRUNCATED'] } } : {}),\n },\n });\n}\n", "import type { BaseClient } from '@sentry/core';\nimport { getCurrentScope } from '@sentry/core';\nimport { addEventProcessor, getClient } from '@sentry/core';\nimport type { Client, DynamicSamplingContext } from '@sentry/types';\nimport { addClickKeypressInstrumentationHandler, addHistoryInstrumentationHandler } from '@sentry/utils';\n\nimport { handleAfterSendEvent } from '../coreHandlers/handleAfterSendEvent';\nimport { handleBeforeSendEvent } from '../coreHandlers/handleBeforeSendEvent';\nimport { handleDomListener } from '../coreHandlers/handleDom';\nimport { handleGlobalEventListener } from '../coreHandlers/handleGlobalEvent';\nimport { handleHistorySpanListener } from '../coreHandlers/handleHistory';\nimport { handleNetworkBreadcrumbs } from '../coreHandlers/handleNetworkBreadcrumbs';\nimport { handleScopeListener } from '../coreHandlers/handleScope';\nimport type { ReplayContainer } from '../types';\n\n/**\n * Add global listeners that cannot be removed.\n */\nexport function addGlobalListeners(replay: ReplayContainer): void {\n // Listeners from core SDK //\n const scope = getCurrentScope();\n const client = getClient();\n\n scope.addScopeListener(handleScopeListener(replay));\n addClickKeypressInstrumentationHandler(handleDomListener(replay));\n addHistoryInstrumentationHandler(handleHistorySpanListener(replay));\n handleNetworkBreadcrumbs(replay);\n\n // Tag all (non replay) events that get sent to Sentry with the current\n // replay ID so that we can reference them later in the UI\n const eventProcessor = handleGlobalEventListener(replay, !hasHooks(client));\n if (client && client.addEventProcessor) {\n client.addEventProcessor(eventProcessor);\n } else {\n addEventProcessor(eventProcessor);\n }\n\n // If a custom client has no hooks yet, we continue to use the \"old\" implementation\n if (hasHooks(client)) {\n client.on('beforeSendEvent', handleBeforeSendEvent(replay));\n client.on('afterSendEvent', handleAfterSendEvent(replay));\n client.on('createDsc', (dsc: DynamicSamplingContext) => {\n const replayId = replay.getSessionId();\n // We do not want to set the DSC when in buffer mode, as that means the replay has not been sent (yet)\n if (replayId && replay.isEnabled() && replay.recordingMode === 'session') {\n // Ensure to check that the session is still active - it could have expired in the meanwhile\n const isSessionActive = replay.checkAndHandleExpiredSession();\n if (isSessionActive) {\n dsc.replay_id = replayId;\n }\n }\n });\n\n client.on('startTransaction', transaction => {\n replay.lastTransaction = transaction;\n });\n\n // We may be missing the initial startTransaction due to timing issues,\n // so we capture it on finish again.\n client.on('finishTransaction', transaction => {\n replay.lastTransaction = transaction;\n });\n\n // We want to flush replay\n client.on('beforeSendFeedback', (feedbackEvent, options) => {\n const replayId = replay.getSessionId();\n if (options && options.includeReplay && replay.isEnabled() && replayId) {\n // This should never reject\n if (feedbackEvent.contexts && feedbackEvent.contexts.feedback) {\n feedbackEvent.contexts.feedback.replay_id = replayId;\n }\n }\n });\n }\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction hasHooks(client: Client | undefined): client is BaseClient {\n return !!(client && client.on);\n}\n", "import { WINDOW } from '../constants';\nimport type { AddEventResult, MemoryData, ReplayContainer, ReplayPerformanceEntry } from '../types';\nimport { createPerformanceSpans } from './createPerformanceSpans';\n\ntype ReplayMemoryEntry = ReplayPerformanceEntry & { data: { memory: MemoryInfo } };\n\ninterface MemoryInfo {\n jsHeapSizeLimit: number;\n totalJSHeapSize: number;\n usedJSHeapSize: number;\n}\n\n/**\n * Create a \"span\" for the total amount of memory being used by JS objects\n * (including v8 internal objects).\n */\nexport async function addMemoryEntry(replay: ReplayContainer): Promise> {\n // window.performance.memory is a non-standard API and doesn't work on all browsers, so we try-catch this\n try {\n return Promise.all(\n createPerformanceSpans(replay, [\n // @ts-expect-error memory doesn't exist on type Performance as the API is non-standard (we check that it exists above)\n createMemoryEntry(WINDOW.performance.memory),\n ]),\n );\n } catch (error) {\n // Do nothing\n return [];\n }\n}\n\nfunction createMemoryEntry(memoryEntry: MemoryInfo): ReplayMemoryEntry {\n const { jsHeapSizeLimit, totalJSHeapSize, usedJSHeapSize } = memoryEntry;\n // we don't want to use `getAbsoluteTime` because it adds the event time to the\n // time origin, so we get the current timestamp instead\n const time = Date.now() / 1000;\n return {\n type: 'memory',\n name: 'memory',\n start: time,\n end: time,\n data: {\n memory: {\n jsHeapSizeLimit,\n totalJSHeapSize,\n usedJSHeapSize,\n },\n },\n };\n}\n", "type DebouncedCallback = {\n (): void | unknown;\n flush: () => void | unknown;\n cancel: () => void;\n};\ntype CallbackFunction = () => unknown;\ntype DebounceOptions = { maxWait?: number };\n\n/**\n * Heavily simplified debounce function based on lodash.debounce.\n *\n * This function takes a callback function (@param fun) and delays its invocation\n * by @param wait milliseconds. Optionally, a maxWait can be specified in @param options,\n * which ensures that the callback is invoked at least once after the specified max. wait time.\n *\n * @param func the function whose invocation is to be debounced\n * @param wait the minimum time until the function is invoked after it was called once\n * @param options the options object, which can contain the `maxWait` property\n *\n * @returns the debounced version of the function, which needs to be called at least once to start the\n * debouncing process. Subsequent calls will reset the debouncing timer and, in case @paramfunc\n * was already invoked in the meantime, return @param func's return value.\n * The debounced function has two additional properties:\n * - `flush`: Invokes the debounced function immediately and returns its return value\n * - `cancel`: Cancels the debouncing process and resets the debouncing timer\n */\nexport function debounce(func: CallbackFunction, wait: number, options?: DebounceOptions): DebouncedCallback {\n let callbackReturnValue: unknown;\n\n let timerId: ReturnType | undefined;\n let maxTimerId: ReturnType | undefined;\n\n const maxWait = options && options.maxWait ? Math.max(options.maxWait, wait) : 0;\n\n function invokeFunc(): unknown {\n cancelTimers();\n callbackReturnValue = func();\n return callbackReturnValue;\n }\n\n function cancelTimers(): void {\n timerId !== undefined && clearTimeout(timerId);\n maxTimerId !== undefined && clearTimeout(maxTimerId);\n timerId = maxTimerId = undefined;\n }\n\n function flush(): unknown {\n if (timerId !== undefined || maxTimerId !== undefined) {\n return invokeFunc();\n }\n return callbackReturnValue;\n }\n\n function debounced(): unknown {\n if (timerId) {\n clearTimeout(timerId);\n }\n timerId = setTimeout(invokeFunc, wait);\n\n if (maxWait && maxTimerId === undefined) {\n maxTimerId = setTimeout(invokeFunc, maxWait);\n }\n\n return callbackReturnValue;\n }\n\n debounced.cancel = cancelTimers;\n debounced.flush = flush;\n return debounced;\n}\n", "import { EventType } from '@sentry-internal/rrweb';\nimport { logger } from '@sentry/utils';\n\nimport { updateClickDetectorForRecordingEvent } from '../coreHandlers/handleClick';\nimport { DEBUG_BUILD } from '../debug-build';\nimport { saveSession } from '../session/saveSession';\nimport type { RecordingEvent, ReplayContainer, ReplayOptionFrameEvent } from '../types';\nimport { addEventSync } from './addEvent';\nimport { logInfo } from './log';\n\ntype RecordingEmitCallback = (event: RecordingEvent, isCheckout?: boolean) => void;\n\n/**\n * Handler for recording events.\n *\n * Adds to event buffer, and has varying flushing behaviors if the event was a checkout.\n */\nexport function getHandleRecordingEmit(replay: ReplayContainer): RecordingEmitCallback {\n let hadFirstEvent = false;\n\n return (event: RecordingEvent, _isCheckout?: boolean) => {\n // If this is false, it means session is expired, create and a new session and wait for checkout\n if (!replay.checkAndHandleExpiredSession()) {\n DEBUG_BUILD && logger.warn('[Replay] Received replay event after session expired.');\n\n return;\n }\n\n // `_isCheckout` is only set when the checkout is due to `checkoutEveryNms`\n // We also want to treat the first event as a checkout, so we handle this specifically here\n const isCheckout = _isCheckout || !hadFirstEvent;\n hadFirstEvent = true;\n\n if (replay.clickDetector) {\n updateClickDetectorForRecordingEvent(replay.clickDetector, event);\n }\n\n // The handler returns `true` if we do not want to trigger debounced flush, `false` if we want to debounce flush.\n replay.addUpdate(() => {\n // The session is always started immediately on pageload/init, but for\n // error-only replays, it should reflect the most recent checkout\n // when an error occurs. Clear any state that happens before this current\n // checkout. This needs to happen before `addEvent()` which updates state\n // dependent on this reset.\n if (replay.recordingMode === 'buffer' && isCheckout) {\n replay.setInitialState();\n }\n\n // If the event is not added (e.g. due to being paused, disabled, or out of the max replay duration),\n // Skip all further steps\n if (!addEventSync(replay, event, isCheckout)) {\n // Return true to skip scheduling a debounced flush\n return true;\n }\n\n // Different behavior for full snapshots (type=2), ignore other event types\n // See https://github.com/rrweb-io/rrweb/blob/d8f9290ca496712aa1e7d472549480c4e7876594/packages/rrweb/src/types.ts#L16\n if (!isCheckout) {\n return false;\n }\n\n // Additionally, create a meta event that will capture certain SDK settings.\n // In order to handle buffer mode, this needs to either be done when we\n // receive checkout events or at flush time.\n //\n // `isCheckout` is always true, but want to be explicit that it should\n // only be added for checkouts\n addSettingsEvent(replay, isCheckout);\n\n // If there is a previousSessionId after a full snapshot occurs, then\n // the replay session was started due to session expiration. The new session\n // is started before triggering a new checkout and contains the id\n // of the previous session. Do not immediately flush in this case\n // to avoid capturing only the checkout and instead the replay will\n // be captured if they perform any follow-up actions.\n if (replay.session && replay.session.previousSessionId) {\n return true;\n }\n\n // When in buffer mode, make sure we adjust the session started date to the current earliest event of the buffer\n // this should usually be the timestamp of the checkout event, but to be safe...\n if (replay.recordingMode === 'buffer' && replay.session && replay.eventBuffer) {\n const earliestEvent = replay.eventBuffer.getEarliestTimestamp();\n if (earliestEvent) {\n logInfo(\n `[Replay] Updating session start time to earliest event in buffer to ${new Date(earliestEvent)}`,\n replay.getOptions()._experiments.traceInternals,\n );\n\n replay.session.started = earliestEvent;\n\n if (replay.getOptions().stickySession) {\n saveSession(replay.session);\n }\n }\n }\n\n if (replay.recordingMode === 'session') {\n // If the full snapshot is due to an initial load, we will not have\n // a previous session ID. In this case, we want to buffer events\n // for a set amount of time before flushing. This can help avoid\n // capturing replays of users that immediately close the window.\n\n // This should never reject\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n void replay.flush();\n }\n\n return true;\n });\n };\n}\n\n/**\n * Exported for tests\n */\nexport function createOptionsEvent(replay: ReplayContainer): ReplayOptionFrameEvent {\n const options = replay.getOptions();\n return {\n type: EventType.Custom,\n timestamp: Date.now(),\n data: {\n tag: 'options',\n payload: {\n shouldRecordCanvas: replay.isRecordingCanvas(),\n sessionSampleRate: options.sessionSampleRate,\n errorSampleRate: options.errorSampleRate,\n useCompressionOption: options.useCompression,\n blockAllMedia: options.blockAllMedia,\n maskAllText: options.maskAllText,\n maskAllInputs: options.maskAllInputs,\n useCompression: replay.eventBuffer ? replay.eventBuffer.type === 'worker' : false,\n networkDetailHasUrls: options.networkDetailAllowUrls.length > 0,\n networkCaptureBodies: options.networkCaptureBodies,\n networkRequestHasHeaders: options.networkRequestHeaders.length > 0,\n networkResponseHasHeaders: options.networkResponseHeaders.length > 0,\n },\n },\n };\n}\n\n/**\n * Add a \"meta\" event that contains a simplified view on current configuration\n * options. This should only be included on the first segment of a recording.\n */\nfunction addSettingsEvent(replay: ReplayContainer, isCheckout?: boolean): void {\n // Only need to add this event when sending the first segment\n if (!isCheckout || !replay.session || replay.session.segmentId !== 0) {\n return;\n }\n\n addEventSync(replay, createOptionsEvent(replay), false);\n}\n", "import type { DsnComponents, ReplayEnvelope, ReplayEvent, ReplayRecordingData } from '@sentry/types';\nimport { createEnvelope, createEventEnvelopeHeaders, getSdkMetadataForEnvelopeHeader } from '@sentry/utils';\n\n/**\n * Create a replay envelope ready to be sent.\n * This includes both the replay event, as well as the recording data.\n */\nexport function createReplayEnvelope(\n replayEvent: ReplayEvent,\n recordingData: ReplayRecordingData,\n dsn: DsnComponents,\n tunnel?: string,\n): ReplayEnvelope {\n return createEnvelope(\n createEventEnvelopeHeaders(replayEvent, getSdkMetadataForEnvelopeHeader(replayEvent), tunnel, dsn),\n [\n [{ type: 'replay_event' }, replayEvent],\n [\n {\n type: 'replay_recording',\n // If string then we need to encode to UTF8, otherwise will have\n // wrong size. TextEncoder has similar browser support to\n // MutationObserver, although it does not accept IE11.\n length:\n typeof recordingData === 'string' ? new TextEncoder().encode(recordingData).length : recordingData.length,\n },\n recordingData,\n ],\n ],\n );\n}\n", "import type { ReplayRecordingData } from '@sentry/types';\n\n/**\n * Prepare the recording data ready to be sent.\n */\nexport function prepareRecordingData({\n recordingData,\n headers,\n}: {\n recordingData: ReplayRecordingData;\n headers: Record;\n}): ReplayRecordingData {\n let payloadWithSequence;\n\n // XXX: newline is needed to separate sequence id from events\n const replayHeaders = `${JSON.stringify(headers)}\n`;\n\n if (typeof recordingData === 'string') {\n payloadWithSequence = `${replayHeaders}${recordingData}`;\n } else {\n const enc = new TextEncoder();\n // XXX: newline is needed to separate sequence id from events\n const sequence = enc.encode(replayHeaders);\n // Merge the two Uint8Arrays\n payloadWithSequence = new Uint8Array(sequence.length + recordingData.length);\n payloadWithSequence.set(sequence);\n payloadWithSequence.set(recordingData, sequence.length);\n }\n\n return payloadWithSequence;\n}\n", "import type { IntegrationIndex, Scope } from '@sentry/core';\nimport { getIsolationScope } from '@sentry/core';\nimport { prepareEvent } from '@sentry/core';\nimport type { Client, EventHint, ReplayEvent } from '@sentry/types';\n\n/**\n * Prepare a replay event & enrich it with the SDK metadata.\n */\nexport async function prepareReplayEvent({\n client,\n scope,\n replayId: event_id,\n event,\n}: {\n client: Client & { _integrations?: IntegrationIndex };\n scope: Scope;\n replayId: string;\n event: ReplayEvent;\n}): Promise {\n const integrations =\n typeof client._integrations === 'object' && client._integrations !== null && !Array.isArray(client._integrations)\n ? Object.keys(client._integrations)\n : undefined;\n\n const eventHint: EventHint = { event_id, integrations };\n\n if (client.emit) {\n client.emit('preprocessEvent', event, eventHint);\n }\n\n const preparedEvent = (await prepareEvent(\n client.getOptions(),\n event,\n eventHint,\n scope,\n client,\n getIsolationScope(),\n )) as ReplayEvent | null;\n\n // If e.g. a global event processor returned null\n if (!preparedEvent) {\n return null;\n }\n\n // This normally happens in browser client \"_prepareEvent\"\n // but since we do not use this private method from the client, but rather the plain import\n // we need to do this manually.\n preparedEvent.platform = preparedEvent.platform || 'javascript';\n\n // extract the SDK name because `client._prepareEvent` doesn't add it to the event\n const metadata = client.getSdkMetadata && client.getSdkMetadata();\n const { name, version } = (metadata && metadata.sdk) || {};\n\n preparedEvent.sdk = {\n ...preparedEvent.sdk,\n name: name || 'sentry.javascript.unknown',\n version: version || '0.0.0',\n };\n\n return preparedEvent;\n}\n", "import { getClient, getCurrentScope } from '@sentry/core';\nimport type { ReplayEvent, TransportMakeRequestResponse } from '@sentry/types';\nimport type { RateLimits } from '@sentry/utils';\nimport { isRateLimited, updateRateLimits } from '@sentry/utils';\n\nimport { REPLAY_EVENT_NAME, UNABLE_TO_SEND_REPLAY } from '../constants';\nimport type { SendReplayData } from '../types';\nimport { createReplayEnvelope } from './createReplayEnvelope';\nimport { logInfo } from './log';\nimport { prepareRecordingData } from './prepareRecordingData';\nimport { prepareReplayEvent } from './prepareReplayEvent';\n\n/**\n * Send replay attachment using `fetch()`\n */\nexport async function sendReplayRequest({\n recordingData,\n replayId,\n segmentId: segment_id,\n eventContext,\n timestamp,\n session,\n}: SendReplayData): Promise {\n const preparedRecordingData = prepareRecordingData({\n recordingData,\n headers: {\n segment_id,\n },\n });\n\n const { urls, errorIds, traceIds, initialTimestamp } = eventContext;\n\n const client = getClient();\n const scope = getCurrentScope();\n const transport = client && client.getTransport();\n const dsn = client && client.getDsn();\n\n if (!client || !transport || !dsn || !session.sampled) {\n return;\n }\n\n const baseEvent: ReplayEvent = {\n type: REPLAY_EVENT_NAME,\n replay_start_timestamp: initialTimestamp / 1000,\n timestamp: timestamp / 1000,\n error_ids: errorIds,\n trace_ids: traceIds,\n urls,\n replay_id: replayId,\n segment_id,\n replay_type: session.sampled,\n };\n\n const replayEvent = await prepareReplayEvent({ scope, client, replayId, event: baseEvent });\n\n if (!replayEvent) {\n // Taken from baseclient's `_processEvent` method, where this is handled for errors/transactions\n client.recordDroppedEvent('event_processor', 'replay', baseEvent);\n logInfo('An event processor returned `null`, will not send event.');\n return;\n }\n\n /*\n For reference, the fully built event looks something like this:\n {\n \"type\": \"replay_event\",\n \"timestamp\": 1670837008.634,\n \"error_ids\": [\n \"errorId\"\n ],\n \"trace_ids\": [\n \"traceId\"\n ],\n \"urls\": [\n \"https://example.com\"\n ],\n \"replay_id\": \"eventId\",\n \"segment_id\": 3,\n \"replay_type\": \"error\",\n \"platform\": \"javascript\",\n \"event_id\": \"eventId\",\n \"environment\": \"production\",\n \"sdk\": {\n \"integrations\": [\n \"BrowserTracing\",\n \"Replay\"\n ],\n \"name\": \"sentry.javascript.browser\",\n \"version\": \"7.25.0\"\n },\n \"sdkProcessingMetadata\": {},\n \"contexts\": {\n },\n }\n */\n\n // Prevent this data (which, if it exists, was used in earlier steps in the processing pipeline) from being sent to\n // sentry. (Note: Our use of this property comes and goes with whatever we might be debugging, whatever hacks we may\n // have temporarily added, etc. Even if we don't happen to be using it at some point in the future, let's not get rid\n // of this `delete`, lest we miss putting it back in the next time the property is in use.)\n delete replayEvent.sdkProcessingMetadata;\n\n const envelope = createReplayEnvelope(replayEvent, preparedRecordingData, dsn, client.getOptions().tunnel);\n\n let response: void | TransportMakeRequestResponse;\n\n try {\n response = await transport.send(envelope);\n } catch (err) {\n const error = new Error(UNABLE_TO_SEND_REPLAY);\n\n try {\n // In case browsers don't allow this property to be writable\n // @ts-expect-error This needs lib es2022 and newer\n error.cause = err;\n } catch {\n // nothing to do\n }\n throw error;\n }\n\n // TODO (v8): we can remove this guard once transport.send's type signature doesn't include void anymore\n if (!response) {\n return response;\n }\n\n // If the status code is invalid, we want to immediately stop & not retry\n if (typeof response.statusCode === 'number' && (response.statusCode < 200 || response.statusCode >= 300)) {\n throw new TransportStatusCodeError(response.statusCode);\n }\n\n const rateLimits = updateRateLimits({}, response);\n if (isRateLimited(rateLimits, 'replay')) {\n throw new RateLimitError(rateLimits);\n }\n\n return response;\n}\n\n/**\n * This error indicates that the transport returned an invalid status code.\n */\nexport class TransportStatusCodeError extends Error {\n public constructor(statusCode: number) {\n super(`Transport returned status code ${statusCode}`);\n }\n}\n\n/**\n * This error indicates that we hit a rate limit API error.\n */\nexport class RateLimitError extends Error {\n public rateLimits: RateLimits;\n\n public constructor(rateLimits: RateLimits) {\n super('Rate limit hit');\n this.rateLimits = rateLimits;\n }\n}\n", "import { captureException, setContext } from '@sentry/core';\n\nimport { RETRY_BASE_INTERVAL, RETRY_MAX_COUNT, UNABLE_TO_SEND_REPLAY } from '../constants';\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { SendReplayData } from '../types';\nimport { RateLimitError, TransportStatusCodeError, sendReplayRequest } from './sendReplayRequest';\n\n/**\n * Finalize and send the current replay event to Sentry\n */\nexport async function sendReplay(\n replayData: SendReplayData,\n retryConfig = {\n count: 0,\n interval: RETRY_BASE_INTERVAL,\n },\n): Promise {\n const { recordingData, options } = replayData;\n\n // short circuit if there's no events to upload (this shouldn't happen as _runFlush makes this check)\n if (!recordingData.length) {\n return;\n }\n\n try {\n await sendReplayRequest(replayData);\n return true;\n } catch (err) {\n if (err instanceof TransportStatusCodeError || err instanceof RateLimitError) {\n throw err;\n }\n\n // Capture error for every failed replay\n setContext('Replays', {\n _retryCount: retryConfig.count,\n });\n\n if (DEBUG_BUILD && options._experiments && options._experiments.captureExceptions) {\n captureException(err);\n }\n\n // If an error happened here, it's likely that uploading the attachment\n // failed, we'll can retry with the same events payload\n if (retryConfig.count >= RETRY_MAX_COUNT) {\n const error = new Error(`${UNABLE_TO_SEND_REPLAY} - max retries exceeded`);\n\n try {\n // In case browsers don't allow this property to be writable\n // @ts-expect-error This needs lib es2022 and newer\n error.cause = err;\n } catch {\n // nothing to do\n }\n\n throw error;\n }\n\n // will retry in intervals of 5, 10, 30\n retryConfig.interval *= ++retryConfig.count;\n\n return new Promise((resolve, reject) => {\n setTimeout(async () => {\n try {\n await sendReplay(replayData, retryConfig);\n resolve(true);\n } catch (err) {\n reject(err);\n }\n }, retryConfig.interval);\n });\n }\n}\n", "export const THROTTLED = '__THROTTLED';\nexport const SKIPPED = '__SKIPPED';\n\n/**\n * Create a throttled function off a given function.\n * When calling the throttled function, it will call the original function only\n * if it hasn't been called more than `maxCount` times in the last `durationSeconds`.\n *\n * Returns `THROTTLED` if throttled for the first time, after that `SKIPPED`,\n * or else the return value of the original function.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function throttle any>(\n fn: T,\n maxCount: number,\n durationSeconds: number,\n): (...rest: Parameters) => ReturnType | typeof THROTTLED | typeof SKIPPED {\n const counter = new Map();\n\n const _cleanup = (now: number): void => {\n const threshold = now - durationSeconds;\n counter.forEach((_value, key) => {\n if (key < threshold) {\n counter.delete(key);\n }\n });\n };\n\n const _getTotalCount = (): number => {\n return [...counter.values()].reduce((a, b) => a + b, 0);\n };\n\n let isThrottled = false;\n\n return (...rest: Parameters): ReturnType | typeof THROTTLED | typeof SKIPPED => {\n // Date in second-precision, which we use as basis for the throttling\n const now = Math.floor(Date.now() / 1000);\n\n // First, make sure to delete any old entries\n _cleanup(now);\n\n // If already over limit, do nothing\n if (_getTotalCount() >= maxCount) {\n const wasThrottled = isThrottled;\n isThrottled = true;\n return wasThrottled ? SKIPPED : THROTTLED;\n }\n\n isThrottled = false;\n const count = counter.get(now) || 0;\n counter.set(now, count + 1);\n\n return fn(...rest);\n };\n}\n", "/* eslint-disable max-lines */ // TODO: We might want to split this file up\nimport { EventType, record } from '@sentry-internal/rrweb';\nimport {\n SEMANTIC_ATTRIBUTE_SENTRY_SOURCE,\n captureException,\n getClient,\n getCurrentScope,\n spanToJSON,\n} from '@sentry/core';\nimport type { ReplayRecordingMode, Transaction } from '@sentry/types';\nimport { logger } from '@sentry/utils';\n\nimport {\n BUFFER_CHECKOUT_TIME,\n SESSION_IDLE_EXPIRE_DURATION,\n SESSION_IDLE_PAUSE_DURATION,\n SLOW_CLICK_SCROLL_TIMEOUT,\n SLOW_CLICK_THRESHOLD,\n WINDOW,\n} from './constants';\nimport { ClickDetector } from './coreHandlers/handleClick';\nimport { handleKeyboardEvent } from './coreHandlers/handleKeyboardEvent';\nimport { setupPerformanceObserver } from './coreHandlers/performanceObserver';\nimport { DEBUG_BUILD } from './debug-build';\nimport { createEventBuffer } from './eventBuffer';\nimport { clearSession } from './session/clearSession';\nimport { loadOrCreateSession } from './session/loadOrCreateSession';\nimport { saveSession } from './session/saveSession';\nimport { shouldRefreshSession } from './session/shouldRefreshSession';\n\nimport type {\n AddEventResult,\n AddUpdateCallback,\n AllPerformanceEntry,\n AllPerformanceEntryData,\n EventBuffer,\n InternalEventContext,\n PopEventContext,\n RecordingEvent,\n RecordingOptions,\n ReplayBreadcrumbFrame,\n ReplayCanvasIntegrationOptions,\n ReplayContainer as ReplayContainerInterface,\n ReplayPerformanceEntry,\n ReplayPluginOptions,\n SendBufferedReplayOptions,\n Session,\n SlowClickConfig,\n Timeouts,\n} from './types';\nimport { ReplayEventTypeCustom } from './types';\nimport { addEvent, addEventSync } from './util/addEvent';\nimport { addGlobalListeners } from './util/addGlobalListeners';\nimport { addMemoryEntry } from './util/addMemoryEntry';\nimport { createBreadcrumb } from './util/createBreadcrumb';\nimport { createPerformanceEntries } from './util/createPerformanceEntries';\nimport { createPerformanceSpans } from './util/createPerformanceSpans';\nimport { debounce } from './util/debounce';\nimport { getHandleRecordingEmit } from './util/handleRecordingEmit';\nimport { isExpired } from './util/isExpired';\nimport { isSessionExpired } from './util/isSessionExpired';\nimport { logInfo, logInfoNextTick } from './util/log';\nimport { sendReplay } from './util/sendReplay';\nimport type { SKIPPED } from './util/throttle';\nimport { THROTTLED, throttle } from './util/throttle';\n\n/**\n * The main replay container class, which holds all the state and methods for recording and sending replays.\n */\nexport class ReplayContainer implements ReplayContainerInterface {\n public eventBuffer: EventBuffer | null;\n\n public performanceEntries: AllPerformanceEntry[];\n\n public replayPerformanceEntries: ReplayPerformanceEntry[];\n\n public session: Session | undefined;\n\n public clickDetector: ClickDetector | undefined;\n\n /**\n * Recording can happen in one of three modes:\n * - session: Record the whole session, sending it continuously\n * - buffer: Always keep the last 60s of recording, requires:\n * - having replaysOnErrorSampleRate > 0 to capture replay when an error occurs\n * - or calling `flush()` to send the replay\n */\n public recordingMode: ReplayRecordingMode;\n\n /**\n * The current or last active transcation.\n * This is only available when performance is enabled.\n */\n public lastTransaction?: Transaction;\n\n /**\n * These are here so we can overwrite them in tests etc.\n * @hidden\n */\n public readonly timeouts: Timeouts;\n\n private _throttledAddEvent: (\n event: RecordingEvent,\n isCheckout?: boolean,\n ) => typeof THROTTLED | typeof SKIPPED | Promise;\n\n /**\n * Options to pass to `rrweb.record()`\n */\n private readonly _recordingOptions: RecordingOptions;\n\n private readonly _options: ReplayPluginOptions;\n\n private _performanceCleanupCallback?: () => void;\n\n private _debouncedFlush: ReturnType;\n private _flushLock: Promise | undefined;\n\n /**\n * Timestamp of the last user activity. This lives across sessions.\n */\n private _lastActivity: number;\n\n /**\n * Is the integration currently active?\n */\n private _isEnabled: boolean;\n\n /**\n * Paused is a state where:\n * - DOM Recording is not listening at all\n * - Nothing will be added to event buffer (e.g. core SDK events)\n */\n private _isPaused: boolean;\n\n /**\n * Have we attached listeners to the core SDK?\n * Note we have to track this as there is no way to remove instrumentation handlers.\n */\n private _hasInitializedCoreListeners: boolean;\n\n /**\n * Function to stop recording\n */\n private _stopRecording: ReturnType | undefined;\n\n private _context: InternalEventContext;\n\n /**\n * Internal use for canvas recording options\n */\n private _canvas: ReplayCanvasIntegrationOptions | undefined;\n\n public constructor({\n options,\n recordingOptions,\n }: {\n options: ReplayPluginOptions;\n recordingOptions: RecordingOptions;\n }) {\n this.eventBuffer = null;\n this.performanceEntries = [];\n this.replayPerformanceEntries = [];\n this.recordingMode = 'session';\n this.timeouts = {\n sessionIdlePause: SESSION_IDLE_PAUSE_DURATION,\n sessionIdleExpire: SESSION_IDLE_EXPIRE_DURATION,\n } as const;\n this._lastActivity = Date.now();\n this._isEnabled = false;\n this._isPaused = false;\n this._hasInitializedCoreListeners = false;\n this._context = {\n errorIds: new Set(),\n traceIds: new Set(),\n urls: [],\n initialTimestamp: Date.now(),\n initialUrl: '',\n };\n\n this._recordingOptions = recordingOptions;\n this._options = options;\n\n this._debouncedFlush = debounce(() => this._flush(), this._options.flushMinDelay, {\n maxWait: this._options.flushMaxDelay,\n });\n\n this._throttledAddEvent = throttle(\n (event: RecordingEvent, isCheckout?: boolean) => addEvent(this, event, isCheckout),\n // Max 300 events...\n 300,\n // ... per 5s\n 5,\n );\n\n const { slowClickTimeout, slowClickIgnoreSelectors } = this.getOptions();\n\n const slowClickConfig: SlowClickConfig | undefined = slowClickTimeout\n ? {\n threshold: Math.min(SLOW_CLICK_THRESHOLD, slowClickTimeout),\n timeout: slowClickTimeout,\n scrollTimeout: SLOW_CLICK_SCROLL_TIMEOUT,\n ignoreSelector: slowClickIgnoreSelectors ? slowClickIgnoreSelectors.join(',') : '',\n }\n : undefined;\n\n if (slowClickConfig) {\n this.clickDetector = new ClickDetector(this, slowClickConfig);\n }\n }\n\n /** Get the event context. */\n public getContext(): InternalEventContext {\n return this._context;\n }\n\n /** If recording is currently enabled. */\n public isEnabled(): boolean {\n return this._isEnabled;\n }\n\n /** If recording is currently paused. */\n public isPaused(): boolean {\n return this._isPaused;\n }\n\n /**\n * Determine if canvas recording is enabled\n */\n public isRecordingCanvas(): boolean {\n return Boolean(this._canvas);\n }\n\n /** Get the replay integration options. */\n public getOptions(): ReplayPluginOptions {\n return this._options;\n }\n\n /**\n * Initializes the plugin based on sampling configuration. Should not be\n * called outside of constructor.\n */\n public initializeSampling(previousSessionId?: string): void {\n const { errorSampleRate, sessionSampleRate } = this._options;\n\n // If neither sample rate is > 0, then do nothing - user will need to call one of\n // `start()` or `startBuffering` themselves.\n if (errorSampleRate <= 0 && sessionSampleRate <= 0) {\n return;\n }\n\n // Otherwise if there is _any_ sample rate set, try to load an existing\n // session, or create a new one.\n this._initializeSessionForSampling(previousSessionId);\n\n if (!this.session) {\n // This should not happen, something wrong has occurred\n this._handleException(new Error('Unable to initialize and create session'));\n return;\n }\n\n if (this.session.sampled === false) {\n // This should only occur if `errorSampleRate` is 0 and was unsampled for\n // session-based replay. In this case there is nothing to do.\n return;\n }\n\n // If segmentId > 0, it means we've previously already captured this session\n // In this case, we still want to continue in `session` recording mode\n this.recordingMode = this.session.sampled === 'buffer' && this.session.segmentId === 0 ? 'buffer' : 'session';\n\n logInfoNextTick(\n `[Replay] Starting replay in ${this.recordingMode} mode`,\n this._options._experiments.traceInternals,\n );\n\n this._initializeRecording();\n }\n\n /**\n * Start a replay regardless of sampling rate. Calling this will always\n * create a new session. Will throw an error if replay is already in progress.\n *\n * Creates or loads a session, attaches listeners to varying events (DOM,\n * _performanceObserver, Recording, Sentry SDK, etc)\n */\n public start(): void {\n if (this._isEnabled && this.recordingMode === 'session') {\n throw new Error('Replay recording is already in progress');\n }\n\n if (this._isEnabled && this.recordingMode === 'buffer') {\n throw new Error('Replay buffering is in progress, call `flush()` to save the replay');\n }\n\n logInfoNextTick('[Replay] Starting replay in session mode', this._options._experiments.traceInternals);\n\n // Required as user activity is initially set in\n // constructor, so if `start()` is called after\n // session idle expiration, a replay will not be\n // created due to an idle timeout.\n this._updateUserActivity();\n\n const session = loadOrCreateSession(\n {\n maxReplayDuration: this._options.maxReplayDuration,\n sessionIdleExpire: this.timeouts.sessionIdleExpire,\n traceInternals: this._options._experiments.traceInternals,\n },\n {\n stickySession: this._options.stickySession,\n // This is intentional: create a new session-based replay when calling `start()`\n sessionSampleRate: 1,\n allowBuffering: false,\n },\n );\n\n this.session = session;\n\n this._initializeRecording();\n }\n\n /**\n * Start replay buffering. Buffers until `flush()` is called or, if\n * `replaysOnErrorSampleRate` > 0, an error occurs.\n */\n public startBuffering(): void {\n if (this._isEnabled) {\n throw new Error('Replay recording is already in progress');\n }\n\n logInfoNextTick('[Replay] Starting replay in buffer mode', this._options._experiments.traceInternals);\n\n const session = loadOrCreateSession(\n {\n sessionIdleExpire: this.timeouts.sessionIdleExpire,\n maxReplayDuration: this._options.maxReplayDuration,\n traceInternals: this._options._experiments.traceInternals,\n },\n {\n stickySession: this._options.stickySession,\n sessionSampleRate: 0,\n allowBuffering: true,\n },\n );\n\n this.session = session;\n\n this.recordingMode = 'buffer';\n this._initializeRecording();\n }\n\n /**\n * Start recording.\n *\n * Note that this will cause a new DOM checkout\n */\n public startRecording(): void {\n try {\n const canvasOptions = this._canvas;\n\n this._stopRecording = record({\n ...this._recordingOptions,\n // When running in error sampling mode, we need to overwrite `checkoutEveryNms`\n // Without this, it would record forever, until an error happens, which we don't want\n // instead, we'll always keep the last 60 seconds of replay before an error happened\n ...(this.recordingMode === 'buffer' && { checkoutEveryNms: BUFFER_CHECKOUT_TIME }),\n emit: getHandleRecordingEmit(this),\n onMutation: this._onMutationHandler,\n ...(canvasOptions\n ? {\n recordCanvas: canvasOptions.recordCanvas,\n getCanvasManager: canvasOptions.getCanvasManager,\n sampling: canvasOptions.sampling,\n dataURLOptions: canvasOptions.dataURLOptions,\n }\n : {}),\n });\n } catch (err) {\n this._handleException(err);\n }\n }\n\n /**\n * Stops the recording, if it was running.\n *\n * Returns true if it was previously stopped, or is now stopped,\n * otherwise false.\n */\n public stopRecording(): boolean {\n try {\n if (this._stopRecording) {\n this._stopRecording();\n this._stopRecording = undefined;\n }\n\n return true;\n } catch (err) {\n this._handleException(err);\n return false;\n }\n }\n\n /**\n * Currently, this needs to be manually called (e.g. for tests). Sentry SDK\n * does not support a teardown\n */\n public async stop({ forceFlush = false, reason }: { forceFlush?: boolean; reason?: string } = {}): Promise {\n if (!this._isEnabled) {\n return;\n }\n\n // We can't move `_isEnabled` after awaiting a flush, otherwise we can\n // enter into an infinite loop when `stop()` is called while flushing.\n this._isEnabled = false;\n\n try {\n logInfo(\n `[Replay] Stopping Replay${reason ? ` triggered by ${reason}` : ''}`,\n this._options._experiments.traceInternals,\n );\n\n this._removeListeners();\n this.stopRecording();\n\n this._debouncedFlush.cancel();\n // See comment above re: `_isEnabled`, we \"force\" a flush, ignoring the\n // `_isEnabled` state of the plugin since it was disabled above.\n if (forceFlush) {\n await this._flush({ force: true });\n }\n\n // After flush, destroy event buffer\n this.eventBuffer && this.eventBuffer.destroy();\n this.eventBuffer = null;\n\n // Clear session from session storage, note this means if a new session\n // is started after, it will not have `previousSessionId`\n clearSession(this);\n } catch (err) {\n this._handleException(err);\n }\n }\n\n /**\n * Pause some replay functionality. See comments for `_isPaused`.\n * This differs from stop as this only stops DOM recording, it is\n * not as thorough of a shutdown as `stop()`.\n */\n public pause(): void {\n if (this._isPaused) {\n return;\n }\n\n this._isPaused = true;\n this.stopRecording();\n\n logInfo('[Replay] Pausing replay', this._options._experiments.traceInternals);\n }\n\n /**\n * Resumes recording, see notes for `pause().\n *\n * Note that calling `startRecording()` here will cause a\n * new DOM checkout.`\n */\n public resume(): void {\n if (!this._isPaused || !this._checkSession()) {\n return;\n }\n\n this._isPaused = false;\n this.startRecording();\n\n logInfo('[Replay] Resuming replay', this._options._experiments.traceInternals);\n }\n\n /**\n * If not in \"session\" recording mode, flush event buffer which will create a new replay.\n * Unless `continueRecording` is false, the replay will continue to record and\n * behave as a \"session\"-based replay.\n *\n * Otherwise, queue up a flush.\n */\n public async sendBufferedReplayOrFlush({ continueRecording = true }: SendBufferedReplayOptions = {}): Promise {\n if (this.recordingMode === 'session') {\n return this.flushImmediate();\n }\n\n const activityTime = Date.now();\n\n logInfo('[Replay] Converting buffer to session', this._options._experiments.traceInternals);\n\n // Allow flush to complete before resuming as a session recording, otherwise\n // the checkout from `startRecording` may be included in the payload.\n // Prefer to keep the error replay as a separate (and smaller) segment\n // than the session replay.\n await this.flushImmediate();\n\n const hasStoppedRecording = this.stopRecording();\n\n if (!continueRecording || !hasStoppedRecording) {\n return;\n }\n\n // To avoid race conditions where this is called multiple times, we check here again that we are still buffering\n if ((this.recordingMode as ReplayRecordingMode) === 'session') {\n return;\n }\n\n // Re-start recording in session-mode\n this.recordingMode = 'session';\n\n // Once this session ends, we do not want to refresh it\n if (this.session) {\n this._updateUserActivity(activityTime);\n this._updateSessionActivity(activityTime);\n this._maybeSaveSession();\n }\n\n this.startRecording();\n }\n\n /**\n * We want to batch uploads of replay events. Save events only if\n * `` milliseconds have elapsed since the last event\n * *OR* if `` milliseconds have elapsed.\n *\n * Accepts a callback to perform side-effects and returns true to stop batch\n * processing and hand back control to caller.\n */\n public addUpdate(cb: AddUpdateCallback): void {\n // We need to always run `cb` (e.g. in the case of `this.recordingMode == 'buffer'`)\n const cbResult = cb();\n\n // If this option is turned on then we will only want to call `flush`\n // explicitly\n if (this.recordingMode === 'buffer') {\n return;\n }\n\n // If callback is true, we do not want to continue with flushing -- the\n // caller will need to handle it.\n if (cbResult === true) {\n return;\n }\n\n // addUpdate is called quite frequently - use _debouncedFlush so that it\n // respects the flush delays and does not flush immediately\n this._debouncedFlush();\n }\n\n /**\n * Updates the user activity timestamp and resumes recording. This should be\n * called in an event handler for a user action that we consider as the user\n * being \"active\" (e.g. a mouse click).\n */\n public triggerUserActivity(): void {\n this._updateUserActivity();\n\n // This case means that recording was once stopped due to inactivity.\n // Ensure that recording is resumed.\n if (!this._stopRecording) {\n // Create a new session, otherwise when the user action is flushed, it\n // will get rejected due to an expired session.\n if (!this._checkSession()) {\n return;\n }\n\n // Note: This will cause a new DOM checkout\n this.resume();\n return;\n }\n\n // Otherwise... recording was never suspended, continue as normalish\n this.checkAndHandleExpiredSession();\n\n this._updateSessionActivity();\n }\n\n /**\n * Updates the user activity timestamp *without* resuming\n * recording. Some user events (e.g. keydown) can be create\n * low-value replays that only contain the keypress as a\n * breadcrumb. Instead this would require other events to\n * create a new replay after a session has expired.\n */\n public updateUserActivity(): void {\n this._updateUserActivity();\n this._updateSessionActivity();\n }\n\n /**\n * Only flush if `this.recordingMode === 'session'`\n */\n public conditionalFlush(): Promise {\n if (this.recordingMode === 'buffer') {\n return Promise.resolve();\n }\n\n return this.flushImmediate();\n }\n\n /**\n * Flush using debounce flush\n */\n public flush(): Promise {\n return this._debouncedFlush() as Promise;\n }\n\n /**\n * Always flush via `_debouncedFlush` so that we do not have flushes triggered\n * from calling both `flush` and `_debouncedFlush`. Otherwise, there could be\n * cases of mulitple flushes happening closely together.\n */\n public flushImmediate(): Promise {\n this._debouncedFlush();\n // `.flush` is provided by the debounced function, analogously to lodash.debounce\n return this._debouncedFlush.flush() as Promise;\n }\n\n /**\n * Cancels queued up flushes.\n */\n public cancelFlush(): void {\n this._debouncedFlush.cancel();\n }\n\n /** Get the current sesion (=replay) ID */\n public getSessionId(): string | undefined {\n return this.session && this.session.id;\n }\n\n /**\n * Checks if recording should be stopped due to user inactivity. Otherwise\n * check if session is expired and create a new session if so. Triggers a new\n * full snapshot on new session.\n *\n * Returns true if session is not expired, false otherwise.\n * @hidden\n */\n public checkAndHandleExpiredSession(): boolean | void {\n // Prevent starting a new session if the last user activity is older than\n // SESSION_IDLE_PAUSE_DURATION. Otherwise non-user activity can trigger a new\n // session+recording. This creates noisy replays that do not have much\n // content in them.\n if (\n this._lastActivity &&\n isExpired(this._lastActivity, this.timeouts.sessionIdlePause) &&\n this.session &&\n this.session.sampled === 'session'\n ) {\n // Pause recording only for session-based replays. Otherwise, resuming\n // will create a new replay and will conflict with users who only choose\n // to record error-based replays only. (e.g. the resumed replay will not\n // contain a reference to an error)\n this.pause();\n return;\n }\n\n // --- There is recent user activity --- //\n // This will create a new session if expired, based on expiry length\n if (!this._checkSession()) {\n // Check session handles the refreshing itself\n return false;\n }\n\n return true;\n }\n\n /**\n * Capture some initial state that can change throughout the lifespan of the\n * replay. This is required because otherwise they would be captured at the\n * first flush.\n */\n public setInitialState(): void {\n const urlPath = `${WINDOW.location.pathname}${WINDOW.location.hash}${WINDOW.location.search}`;\n const url = `${WINDOW.location.origin}${urlPath}`;\n\n this.performanceEntries = [];\n this.replayPerformanceEntries = [];\n\n // Reset _context as well\n this._clearContext();\n\n this._context.initialUrl = url;\n this._context.initialTimestamp = Date.now();\n this._context.urls.push(url);\n }\n\n /**\n * Add a breadcrumb event, that may be throttled.\n * If it was throttled, we add a custom breadcrumb to indicate that.\n */\n public throttledAddEvent(\n event: RecordingEvent,\n isCheckout?: boolean,\n ): typeof THROTTLED | typeof SKIPPED | Promise {\n const res = this._throttledAddEvent(event, isCheckout);\n\n // If this is THROTTLED, it means we have throttled the event for the first time\n // In this case, we want to add a breadcrumb indicating that something was skipped\n if (res === THROTTLED) {\n const breadcrumb = createBreadcrumb({\n category: 'replay.throttled',\n });\n\n this.addUpdate(() => {\n // Return `false` if the event _was_ added, as that means we schedule a flush\n return !addEventSync(this, {\n type: ReplayEventTypeCustom,\n timestamp: breadcrumb.timestamp || 0,\n data: {\n tag: 'breadcrumb',\n payload: breadcrumb,\n metric: true,\n },\n });\n });\n }\n\n return res;\n }\n\n /**\n * This will get the parametrized route name of the current page.\n * This is only available if performance is enabled, and if an instrumented router is used.\n */\n public getCurrentRoute(): string | undefined {\n // eslint-disable-next-line deprecation/deprecation\n const lastTransaction = this.lastTransaction || getCurrentScope().getTransaction();\n\n const attributes = (lastTransaction && spanToJSON(lastTransaction).data) || {};\n const source = attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];\n if (!lastTransaction || !source || !['route', 'custom'].includes(source)) {\n return undefined;\n }\n\n return spanToJSON(lastTransaction).description;\n }\n\n /**\n * Initialize and start all listeners to varying events (DOM,\n * Performance Observer, Recording, Sentry SDK, etc)\n */\n private _initializeRecording(): void {\n this.setInitialState();\n\n // this method is generally called on page load or manually - in both cases\n // we should treat it as an activity\n this._updateSessionActivity();\n\n this.eventBuffer = createEventBuffer({\n useCompression: this._options.useCompression,\n workerUrl: this._options.workerUrl,\n });\n\n this._removeListeners();\n this._addListeners();\n\n // Need to set as enabled before we start recording, as `record()` can trigger a flush with a new checkout\n this._isEnabled = true;\n this._isPaused = false;\n\n this.startRecording();\n }\n\n /** A wrapper to conditionally capture exceptions. */\n private _handleException(error: unknown): void {\n DEBUG_BUILD && logger.error('[Replay]', error);\n\n if (DEBUG_BUILD && this._options._experiments && this._options._experiments.captureExceptions) {\n captureException(error);\n }\n }\n\n /**\n * Loads (or refreshes) the current session.\n */\n private _initializeSessionForSampling(previousSessionId?: string): void {\n // Whenever there is _any_ error sample rate, we always allow buffering\n // Because we decide on sampling when an error occurs, we need to buffer at all times if sampling for errors\n const allowBuffering = this._options.errorSampleRate > 0;\n\n const session = loadOrCreateSession(\n {\n sessionIdleExpire: this.timeouts.sessionIdleExpire,\n maxReplayDuration: this._options.maxReplayDuration,\n traceInternals: this._options._experiments.traceInternals,\n previousSessionId,\n },\n {\n stickySession: this._options.stickySession,\n sessionSampleRate: this._options.sessionSampleRate,\n allowBuffering,\n },\n );\n\n this.session = session;\n }\n\n /**\n * Checks and potentially refreshes the current session.\n * Returns false if session is not recorded.\n */\n private _checkSession(): boolean {\n // If there is no session yet, we do not want to refresh anything\n // This should generally not happen, but to be safe....\n if (!this.session) {\n return false;\n }\n\n const currentSession = this.session;\n\n if (\n shouldRefreshSession(currentSession, {\n sessionIdleExpire: this.timeouts.sessionIdleExpire,\n maxReplayDuration: this._options.maxReplayDuration,\n })\n ) {\n // This should never reject\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this._refreshSession(currentSession);\n return false;\n }\n\n return true;\n }\n\n /**\n * Refresh a session with a new one.\n * This stops the current session (without forcing a flush, as that would never work since we are expired),\n * and then does a new sampling based on the refreshed session.\n */\n private async _refreshSession(session: Session): Promise {\n if (!this._isEnabled) {\n return;\n }\n await this.stop({ reason: 'refresh session' });\n this.initializeSampling(session.id);\n }\n\n /**\n * Adds listeners to record events for the replay\n */\n private _addListeners(): void {\n try {\n WINDOW.document.addEventListener('visibilitychange', this._handleVisibilityChange);\n WINDOW.addEventListener('blur', this._handleWindowBlur);\n WINDOW.addEventListener('focus', this._handleWindowFocus);\n WINDOW.addEventListener('keydown', this._handleKeyboardEvent);\n\n if (this.clickDetector) {\n this.clickDetector.addListeners();\n }\n\n // There is no way to remove these listeners, so ensure they are only added once\n if (!this._hasInitializedCoreListeners) {\n addGlobalListeners(this);\n\n this._hasInitializedCoreListeners = true;\n }\n } catch (err) {\n this._handleException(err);\n }\n\n this._performanceCleanupCallback = setupPerformanceObserver(this);\n }\n\n /**\n * Cleans up listeners that were created in `_addListeners`\n */\n private _removeListeners(): void {\n try {\n WINDOW.document.removeEventListener('visibilitychange', this._handleVisibilityChange);\n\n WINDOW.removeEventListener('blur', this._handleWindowBlur);\n WINDOW.removeEventListener('focus', this._handleWindowFocus);\n WINDOW.removeEventListener('keydown', this._handleKeyboardEvent);\n\n if (this.clickDetector) {\n this.clickDetector.removeListeners();\n }\n\n if (this._performanceCleanupCallback) {\n this._performanceCleanupCallback();\n }\n } catch (err) {\n this._handleException(err);\n }\n }\n\n /**\n * Handle when visibility of the page content changes. Opening a new tab will\n * cause the state to change to hidden because of content of current page will\n * be hidden. Likewise, moving a different window to cover the contents of the\n * page will also trigger a change to a hidden state.\n */\n private _handleVisibilityChange: () => void = () => {\n if (WINDOW.document.visibilityState === 'visible') {\n this._doChangeToForegroundTasks();\n } else {\n this._doChangeToBackgroundTasks();\n }\n };\n\n /**\n * Handle when page is blurred\n */\n private _handleWindowBlur: () => void = () => {\n const breadcrumb = createBreadcrumb({\n category: 'ui.blur',\n });\n\n // Do not count blur as a user action -- it's part of the process of them\n // leaving the page\n this._doChangeToBackgroundTasks(breadcrumb);\n };\n\n /**\n * Handle when page is focused\n */\n private _handleWindowFocus: () => void = () => {\n const breadcrumb = createBreadcrumb({\n category: 'ui.focus',\n });\n\n // Do not count focus as a user action -- instead wait until they focus and\n // interactive with page\n this._doChangeToForegroundTasks(breadcrumb);\n };\n\n /** Ensure page remains active when a key is pressed. */\n private _handleKeyboardEvent: (event: KeyboardEvent) => void = (event: KeyboardEvent) => {\n handleKeyboardEvent(this, event);\n };\n\n /**\n * Tasks to run when we consider a page to be hidden (via blurring and/or visibility)\n */\n private _doChangeToBackgroundTasks(breadcrumb?: ReplayBreadcrumbFrame): void {\n if (!this.session) {\n return;\n }\n\n const expired = isSessionExpired(this.session, {\n maxReplayDuration: this._options.maxReplayDuration,\n sessionIdleExpire: this.timeouts.sessionIdleExpire,\n });\n\n if (expired) {\n return;\n }\n\n if (breadcrumb) {\n this._createCustomBreadcrumb(breadcrumb);\n }\n\n // Send replay when the page/tab becomes hidden. There is no reason to send\n // replay if it becomes visible, since no actions we care about were done\n // while it was hidden\n // This should never reject\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n void this.conditionalFlush();\n }\n\n /**\n * Tasks to run when we consider a page to be visible (via focus and/or visibility)\n */\n private _doChangeToForegroundTasks(breadcrumb?: ReplayBreadcrumbFrame): void {\n if (!this.session) {\n return;\n }\n\n const isSessionActive = this.checkAndHandleExpiredSession();\n\n if (!isSessionActive) {\n // If the user has come back to the page within SESSION_IDLE_PAUSE_DURATION\n // ms, we will re-use the existing session, otherwise create a new\n // session\n logInfo('[Replay] Document has become active, but session has expired');\n return;\n }\n\n if (breadcrumb) {\n this._createCustomBreadcrumb(breadcrumb);\n }\n }\n\n /**\n * Update user activity (across session lifespans)\n */\n private _updateUserActivity(_lastActivity: number = Date.now()): void {\n this._lastActivity = _lastActivity;\n }\n\n /**\n * Updates the session's last activity timestamp\n */\n private _updateSessionActivity(_lastActivity: number = Date.now()): void {\n if (this.session) {\n this.session.lastActivity = _lastActivity;\n this._maybeSaveSession();\n }\n }\n\n /**\n * Helper to create (and buffer) a replay breadcrumb from a core SDK breadcrumb\n */\n private _createCustomBreadcrumb(breadcrumb: ReplayBreadcrumbFrame): void {\n this.addUpdate(() => {\n // This should never reject\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.throttledAddEvent({\n type: EventType.Custom,\n timestamp: breadcrumb.timestamp || 0,\n data: {\n tag: 'breadcrumb',\n payload: breadcrumb,\n },\n });\n });\n }\n\n /**\n * Observed performance events are added to `this.performanceEntries`. These\n * are included in the replay event before it is finished and sent to Sentry.\n */\n private _addPerformanceEntries(): Promise> {\n const performanceEntries = createPerformanceEntries(this.performanceEntries).concat(this.replayPerformanceEntries);\n\n this.performanceEntries = [];\n this.replayPerformanceEntries = [];\n\n return Promise.all(createPerformanceSpans(this, performanceEntries));\n }\n\n /**\n * Clear _context\n */\n private _clearContext(): void {\n // XXX: `initialTimestamp` and `initialUrl` do not get cleared\n this._context.errorIds.clear();\n this._context.traceIds.clear();\n this._context.urls = [];\n }\n\n /** Update the initial timestamp based on the buffer content. */\n private _updateInitialTimestampFromEventBuffer(): void {\n const { session, eventBuffer } = this;\n if (!session || !eventBuffer) {\n return;\n }\n\n // we only ever update this on the initial segment\n if (session.segmentId) {\n return;\n }\n\n const earliestEvent = eventBuffer.getEarliestTimestamp();\n if (earliestEvent && earliestEvent < this._context.initialTimestamp) {\n this._context.initialTimestamp = earliestEvent;\n }\n }\n\n /**\n * Return and clear _context\n */\n private _popEventContext(): PopEventContext {\n const _context = {\n initialTimestamp: this._context.initialTimestamp,\n initialUrl: this._context.initialUrl,\n errorIds: Array.from(this._context.errorIds),\n traceIds: Array.from(this._context.traceIds),\n urls: this._context.urls,\n };\n\n this._clearContext();\n\n return _context;\n }\n\n /**\n * Flushes replay event buffer to Sentry.\n *\n * Performance events are only added right before flushing - this is\n * due to the buffered performance observer events.\n *\n * Should never be called directly, only by `flush`\n */\n private async _runFlush(): Promise {\n const replayId = this.getSessionId();\n\n if (!this.session || !this.eventBuffer || !replayId) {\n DEBUG_BUILD && logger.error('[Replay] No session or eventBuffer found to flush.');\n return;\n }\n\n await this._addPerformanceEntries();\n\n // Check eventBuffer again, as it could have been stopped in the meanwhile\n if (!this.eventBuffer || !this.eventBuffer.hasEvents) {\n return;\n }\n\n // Only attach memory event if eventBuffer is not empty\n await addMemoryEntry(this);\n\n // Check eventBuffer again, as it could have been stopped in the meanwhile\n if (!this.eventBuffer) {\n return;\n }\n\n // if this changed in the meanwhile, e.g. because the session was refreshed or similar, we abort here\n if (replayId !== this.getSessionId()) {\n return;\n }\n\n try {\n // This uses the data from the eventBuffer, so we need to call this before `finish()\n this._updateInitialTimestampFromEventBuffer();\n\n const timestamp = Date.now();\n\n // Check total duration again, to avoid sending outdated stuff\n // We leave 30s wiggle room to accomodate late flushing etc.\n // This _could_ happen when the browser is suspended during flushing, in which case we just want to stop\n if (timestamp - this._context.initialTimestamp > this._options.maxReplayDuration + 30_000) {\n throw new Error('Session is too long, not sending replay');\n }\n\n const eventContext = this._popEventContext();\n // Always increment segmentId regardless of outcome of sending replay\n const segmentId = this.session.segmentId++;\n this._maybeSaveSession();\n\n // Note this empties the event buffer regardless of outcome of sending replay\n const recordingData = await this.eventBuffer.finish();\n\n await sendReplay({\n replayId,\n recordingData,\n segmentId,\n eventContext,\n session: this.session,\n options: this.getOptions(),\n timestamp,\n });\n } catch (err) {\n this._handleException(err);\n\n // This means we retried 3 times and all of them failed,\n // or we ran into a problem we don't want to retry, like rate limiting.\n // In this case, we want to completely stop the replay - otherwise, we may get inconsistent segments\n // This should never reject\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.stop({ reason: 'sendReplay' });\n\n const client = getClient();\n\n if (client) {\n client.recordDroppedEvent('send_error', 'replay');\n }\n }\n }\n\n /**\n * Flush recording data to Sentry. Creates a lock so that only a single flush\n * can be active at a time. Do not call this directly.\n */\n private _flush = async ({\n force = false,\n }: {\n /**\n * If true, flush while ignoring the `_isEnabled` state of\n * Replay integration. (By default, flush is noop if integration\n * is stopped).\n */\n force?: boolean;\n } = {}): Promise => {\n if (!this._isEnabled && !force) {\n // This can happen if e.g. the replay was stopped because of exceeding the retry limit\n return;\n }\n\n if (!this.checkAndHandleExpiredSession()) {\n DEBUG_BUILD && logger.error('[Replay] Attempting to finish replay event after session expired.');\n return;\n }\n\n if (!this.session) {\n // should never happen, as we would have bailed out before\n return;\n }\n\n const start = this.session.started;\n const now = Date.now();\n const duration = now - start;\n\n // A flush is about to happen, cancel any queued flushes\n this._debouncedFlush.cancel();\n\n // If session is too short, or too long (allow some wiggle room over maxReplayDuration), do not send it\n // This _should_ not happen, but it may happen if flush is triggered due to a page activity change or similar\n const tooShort = duration < this._options.minReplayDuration;\n const tooLong = duration > this._options.maxReplayDuration + 5_000;\n if (tooShort || tooLong) {\n logInfo(\n `[Replay] Session duration (${Math.floor(duration / 1000)}s) is too ${\n tooShort ? 'short' : 'long'\n }, not sending replay.`,\n this._options._experiments.traceInternals,\n );\n\n if (tooShort) {\n this._debouncedFlush();\n }\n return;\n }\n\n const eventBuffer = this.eventBuffer;\n if (eventBuffer && this.session.segmentId === 0 && !eventBuffer.hasCheckout) {\n logInfo('[Replay] Flushing initial segment without checkout.', this._options._experiments.traceInternals);\n // TODO FN: Evaluate if we want to stop here, or remove this again?\n }\n\n // this._flushLock acts as a lock so that future calls to `_flush()`\n // will be blocked until this promise resolves\n if (!this._flushLock) {\n this._flushLock = this._runFlush();\n await this._flushLock;\n this._flushLock = undefined;\n return;\n }\n\n // Wait for previous flush to finish, then call the debounced `_flush()`.\n // It's possible there are other flush requests queued and waiting for it\n // to resolve. We want to reduce all outstanding requests (as well as any\n // new flush requests that occur within a second of the locked flush\n // completing) into a single flush.\n\n try {\n await this._flushLock;\n } catch (err) {\n DEBUG_BUILD && logger.error(err);\n } finally {\n this._debouncedFlush();\n }\n };\n\n /** Save the session, if it is sticky */\n private _maybeSaveSession(): void {\n if (this.session && this._options.stickySession) {\n saveSession(this.session);\n }\n }\n\n /** Handler for rrweb.record.onMutation */\n private _onMutationHandler = (mutations: unknown[]): boolean => {\n const count = mutations.length;\n\n const mutationLimit = this._options.mutationLimit;\n const mutationBreadcrumbLimit = this._options.mutationBreadcrumbLimit;\n const overMutationLimit = mutationLimit && count > mutationLimit;\n\n // Create a breadcrumb if a lot of mutations happen at the same time\n // We can show this in the UI as an information with potential performance improvements\n if (count > mutationBreadcrumbLimit || overMutationLimit) {\n const breadcrumb = createBreadcrumb({\n category: 'replay.mutations',\n data: {\n count,\n limit: overMutationLimit,\n },\n });\n this._createCustomBreadcrumb(breadcrumb);\n }\n\n // Stop replay if over the mutation limit\n if (overMutationLimit) {\n // This should never reject\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.stop({ reason: 'mutationLimit', forceFlush: this.recordingMode === 'session' });\n return false;\n }\n\n // `true` means we use the regular mutation handling by rrweb\n return true;\n };\n}\n", "import { consoleSandbox } from '@sentry/utils';\n\nimport type { DeprecatedPrivacyOptions, ReplayIntegrationPrivacyOptions } from '../types';\n\ntype GetPrivacyOptions = Required> &\n Omit;\ninterface GetPrivacyReturn {\n maskTextSelector: string;\n unmaskTextSelector: string;\n blockSelector: string;\n unblockSelector: string;\n ignoreSelector: string;\n\n blockClass?: RegExp;\n maskTextClass?: RegExp;\n}\n\nfunction getOption(\n selectors: string[],\n defaultSelectors: string[],\n deprecatedClassOption?: string | RegExp,\n deprecatedSelectorOption?: string,\n): string {\n const deprecatedSelectors = typeof deprecatedSelectorOption === 'string' ? deprecatedSelectorOption.split(',') : [];\n\n const allSelectors = [\n ...selectors,\n // @deprecated\n ...deprecatedSelectors,\n\n // sentry defaults\n ...defaultSelectors,\n ];\n\n // @deprecated\n if (typeof deprecatedClassOption !== 'undefined') {\n // NOTE: No support for RegExp\n if (typeof deprecatedClassOption === 'string') {\n allSelectors.push(`.${deprecatedClassOption}`);\n }\n\n consoleSandbox(() => {\n // eslint-disable-next-line no-console\n console.warn(\n '[Replay] You are using a deprecated configuration item for privacy. Read the documentation on how to use the new privacy configuration.',\n );\n });\n }\n\n return allSelectors.join(',');\n}\n\n/**\n * Returns privacy related configuration for use in rrweb\n */\nexport function getPrivacyOptions({\n mask,\n unmask,\n block,\n unblock,\n ignore,\n\n // eslint-disable-next-line deprecation/deprecation\n blockClass,\n // eslint-disable-next-line deprecation/deprecation\n blockSelector,\n // eslint-disable-next-line deprecation/deprecation\n maskTextClass,\n // eslint-disable-next-line deprecation/deprecation\n maskTextSelector,\n // eslint-disable-next-line deprecation/deprecation\n ignoreClass,\n}: GetPrivacyOptions): GetPrivacyReturn {\n const defaultBlockedElements = ['base[href=\"/\"]'];\n\n const maskSelector = getOption(mask, ['.sentry-mask', '[data-sentry-mask]'], maskTextClass, maskTextSelector);\n const unmaskSelector = getOption(unmask, ['.sentry-unmask', '[data-sentry-unmask]']);\n\n const options: GetPrivacyReturn = {\n // We are making the decision to make text and input selectors the same\n maskTextSelector: maskSelector,\n unmaskTextSelector: unmaskSelector,\n\n blockSelector: getOption(\n block,\n ['.sentry-block', '[data-sentry-block]', ...defaultBlockedElements],\n blockClass,\n blockSelector,\n ),\n unblockSelector: getOption(unblock, ['.sentry-unblock', '[data-sentry-unblock]']),\n ignoreSelector: getOption(ignore, ['.sentry-ignore', '[data-sentry-ignore]', 'input[type=\"file\"]'], ignoreClass),\n };\n\n if (blockClass instanceof RegExp) {\n options.blockClass = blockClass;\n }\n\n if (maskTextClass instanceof RegExp) {\n options.maskTextClass = maskTextClass;\n }\n\n return options;\n}\n", "import type { getPrivacyOptions } from './getPrivacyOptions';\n\ninterface MaskAttributeParams {\n maskAttributes: string[];\n maskAllText: boolean;\n privacyOptions: ReturnType;\n key: string;\n value: string;\n el: HTMLElement;\n}\n\n/**\n * Masks an attribute if necessary, otherwise return attribute value as-is.\n */\nexport function maskAttribute({\n el,\n key,\n maskAttributes,\n maskAllText,\n privacyOptions,\n value,\n}: MaskAttributeParams): string {\n // We only mask attributes if `maskAllText` is true\n if (!maskAllText) {\n return value;\n }\n\n // unmaskTextSelector takes precendence\n if (privacyOptions.unmaskTextSelector && el.matches(privacyOptions.unmaskTextSelector)) {\n return value;\n }\n\n if (\n maskAttributes.includes(key) ||\n // Need to mask `value` attribute for `` if it's a button-like\n // type\n (key === 'value' && el.tagName === 'INPUT' && ['submit', 'button'].includes(el.getAttribute('type') || ''))\n ) {\n return value.replace(/[\\S]/g, '*');\n }\n\n return value;\n}\n", "import { getClient } from '@sentry/core';\nimport type { BrowserClientReplayOptions, Integration, IntegrationFn } from '@sentry/types';\nimport { consoleSandbox, dropUndefinedKeys, isBrowser } from '@sentry/utils';\n\nimport {\n DEFAULT_FLUSH_MAX_DELAY,\n DEFAULT_FLUSH_MIN_DELAY,\n MAX_REPLAY_DURATION,\n MIN_REPLAY_DURATION,\n MIN_REPLAY_DURATION_LIMIT,\n} from './constants';\nimport { ReplayContainer } from './replay';\nimport type {\n RecordingOptions,\n ReplayCanvasIntegrationOptions,\n ReplayConfiguration,\n ReplayPluginOptions,\n SendBufferedReplayOptions,\n} from './types';\nimport { getPrivacyOptions } from './util/getPrivacyOptions';\nimport { maskAttribute } from './util/maskAttribute';\n\nconst MEDIA_SELECTORS =\n 'img,image,svg,video,object,picture,embed,map,audio,link[rel=\"icon\"],link[rel=\"apple-touch-icon\"]';\n\nconst DEFAULT_NETWORK_HEADERS = ['content-length', 'content-type', 'accept'];\n\nlet _initialized = false;\n\ntype InitialReplayPluginOptions = Omit &\n Partial>;\n\nexport const replayIntegration = ((options?: ReplayConfiguration) => {\n // eslint-disable-next-line deprecation/deprecation\n return new Replay(options);\n}) satisfies IntegrationFn;\n\n/**\n * The main replay integration class, to be passed to `init({ integrations: [] })`.\n * @deprecated Use `replayIntegration()` instead.\n */\nexport class Replay implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'Replay';\n\n /**\n * @inheritDoc\n */\n public name: string;\n\n /**\n * Options to pass to `rrweb.record()`\n */\n private readonly _recordingOptions: RecordingOptions;\n\n /**\n * Initial options passed to the replay integration, merged with default values.\n * Note: `sessionSampleRate` and `errorSampleRate` are not required here, as they\n * can only be finally set when setupOnce() is called.\n *\n * @private\n */\n private readonly _initialOptions: InitialReplayPluginOptions;\n\n private _replay?: ReplayContainer;\n\n public constructor({\n flushMinDelay = DEFAULT_FLUSH_MIN_DELAY,\n flushMaxDelay = DEFAULT_FLUSH_MAX_DELAY,\n minReplayDuration = MIN_REPLAY_DURATION,\n maxReplayDuration = MAX_REPLAY_DURATION,\n stickySession = true,\n useCompression = true,\n workerUrl,\n _experiments = {},\n sessionSampleRate,\n errorSampleRate,\n maskAllText = true,\n maskAllInputs = true,\n blockAllMedia = true,\n\n mutationBreadcrumbLimit = 750,\n mutationLimit = 10_000,\n\n slowClickTimeout = 7_000,\n slowClickIgnoreSelectors = [],\n\n networkDetailAllowUrls = [],\n networkDetailDenyUrls = [],\n networkCaptureBodies = true,\n networkRequestHeaders = [],\n networkResponseHeaders = [],\n\n mask = [],\n maskAttributes = ['title', 'placeholder'],\n unmask = [],\n block = [],\n unblock = [],\n ignore = [],\n maskFn,\n\n beforeAddRecordingEvent,\n beforeErrorSampling,\n\n // eslint-disable-next-line deprecation/deprecation\n blockClass,\n // eslint-disable-next-line deprecation/deprecation\n blockSelector,\n // eslint-disable-next-line deprecation/deprecation\n maskInputOptions,\n // eslint-disable-next-line deprecation/deprecation\n maskTextClass,\n // eslint-disable-next-line deprecation/deprecation\n maskTextSelector,\n // eslint-disable-next-line deprecation/deprecation\n ignoreClass,\n }: ReplayConfiguration = {}) {\n // eslint-disable-next-line deprecation/deprecation\n this.name = Replay.id;\n\n const privacyOptions = getPrivacyOptions({\n mask,\n unmask,\n block,\n unblock,\n ignore,\n blockClass,\n blockSelector,\n maskTextClass,\n maskTextSelector,\n ignoreClass,\n });\n\n this._recordingOptions = {\n maskAllInputs,\n maskAllText,\n maskInputOptions: { ...(maskInputOptions || {}), password: true },\n maskTextFn: maskFn,\n maskInputFn: maskFn,\n maskAttributeFn: (key: string, value: string, el: HTMLElement): string =>\n maskAttribute({\n maskAttributes,\n maskAllText,\n privacyOptions,\n key,\n value,\n el,\n }),\n\n ...privacyOptions,\n\n // Our defaults\n slimDOMOptions: 'all',\n inlineStylesheet: true,\n // Disable inline images as it will increase segment/replay size\n inlineImages: false,\n // collect fonts, but be aware that `sentry.io` needs to be an allowed\n // origin for playback\n collectFonts: true,\n errorHandler: (err: Error & { __rrweb__?: boolean }) => {\n try {\n err.__rrweb__ = true;\n } catch (error) {\n // ignore errors here\n // this can happen if the error is frozen or does not allow mutation for other reasons\n }\n },\n };\n\n this._initialOptions = {\n flushMinDelay,\n flushMaxDelay,\n minReplayDuration: Math.min(minReplayDuration, MIN_REPLAY_DURATION_LIMIT),\n maxReplayDuration: Math.min(maxReplayDuration, MAX_REPLAY_DURATION),\n stickySession,\n sessionSampleRate,\n errorSampleRate,\n useCompression,\n workerUrl,\n blockAllMedia,\n maskAllInputs,\n maskAllText,\n mutationBreadcrumbLimit,\n mutationLimit,\n slowClickTimeout,\n slowClickIgnoreSelectors,\n networkDetailAllowUrls,\n networkDetailDenyUrls,\n networkCaptureBodies,\n networkRequestHeaders: _getMergedNetworkHeaders(networkRequestHeaders),\n networkResponseHeaders: _getMergedNetworkHeaders(networkResponseHeaders),\n beforeAddRecordingEvent,\n beforeErrorSampling,\n\n _experiments,\n };\n\n if (typeof sessionSampleRate === 'number') {\n // eslint-disable-next-line\n console.warn(\n `[Replay] You are passing \\`sessionSampleRate\\` to the Replay integration.\nThis option is deprecated and will be removed soon.\nInstead, configure \\`replaysSessionSampleRate\\` directly in the SDK init options, e.g.:\nSentry.init({ replaysSessionSampleRate: ${sessionSampleRate} })`,\n );\n\n this._initialOptions.sessionSampleRate = sessionSampleRate;\n }\n\n if (typeof errorSampleRate === 'number') {\n // eslint-disable-next-line\n console.warn(\n `[Replay] You are passing \\`errorSampleRate\\` to the Replay integration.\nThis option is deprecated and will be removed soon.\nInstead, configure \\`replaysOnErrorSampleRate\\` directly in the SDK init options, e.g.:\nSentry.init({ replaysOnErrorSampleRate: ${errorSampleRate} })`,\n );\n\n this._initialOptions.errorSampleRate = errorSampleRate;\n }\n\n if (this._initialOptions.blockAllMedia) {\n // `blockAllMedia` is a more user friendly option to configure blocking\n // embedded media elements\n this._recordingOptions.blockSelector = !this._recordingOptions.blockSelector\n ? MEDIA_SELECTORS\n : `${this._recordingOptions.blockSelector},${MEDIA_SELECTORS}`;\n }\n\n if (this._isInitialized && isBrowser()) {\n throw new Error('Multiple Sentry Session Replay instances are not supported');\n }\n\n this._isInitialized = true;\n }\n\n /** If replay has already been initialized */\n protected get _isInitialized(): boolean {\n return _initialized;\n }\n\n /** Update _isInitialized */\n protected set _isInitialized(value: boolean) {\n _initialized = value;\n }\n\n /**\n * Setup and initialize replay container\n */\n public setupOnce(): void {\n if (!isBrowser()) {\n return;\n }\n\n this._setup();\n\n // Once upon a time, we tried to create a transaction in `setupOnce` and it would\n // potentially create a transaction before some native SDK integrations have run\n // and applied their own global event processor. An example is:\n // https://github.com/getsentry/sentry-javascript/blob/b47ceafbdac7f8b99093ce6023726ad4687edc48/packages/browser/src/integrations/useragent.ts\n //\n // So we call `this._initialize()` in next event loop as a workaround to wait for other\n // global event processors to finish. This is no longer needed, but keeping it\n // here to avoid any future issues.\n setTimeout(() => this._initialize());\n }\n\n /**\n * Start a replay regardless of sampling rate. Calling this will always\n * create a new session. Will throw an error if replay is already in progress.\n *\n * Creates or loads a session, attaches listeners to varying events (DOM,\n * PerformanceObserver, Recording, Sentry SDK, etc)\n */\n public start(): void {\n if (!this._replay) {\n return;\n }\n\n this._replay.start();\n }\n\n /**\n * Start replay buffering. Buffers until `flush()` is called or, if\n * `replaysOnErrorSampleRate` > 0, until an error occurs.\n */\n public startBuffering(): void {\n if (!this._replay) {\n return;\n }\n\n this._replay.startBuffering();\n }\n\n /**\n * Currently, this needs to be manually called (e.g. for tests). Sentry SDK\n * does not support a teardown\n */\n public stop(): Promise {\n if (!this._replay) {\n return Promise.resolve();\n }\n\n return this._replay.stop({ forceFlush: this._replay.recordingMode === 'session' });\n }\n\n /**\n * If not in \"session\" recording mode, flush event buffer which will create a new replay.\n * Unless `continueRecording` is false, the replay will continue to record and\n * behave as a \"session\"-based replay.\n *\n * Otherwise, queue up a flush.\n */\n public flush(options?: SendBufferedReplayOptions): Promise {\n if (!this._replay || !this._replay.isEnabled()) {\n return Promise.resolve();\n }\n\n return this._replay.sendBufferedReplayOrFlush(options);\n }\n\n /**\n * Get the current session ID.\n */\n public getReplayId(): string | undefined {\n if (!this._replay || !this._replay.isEnabled()) {\n return;\n }\n\n return this._replay.getSessionId();\n }\n\n /**\n * Initializes replay.\n */\n protected _initialize(): void {\n if (!this._replay) {\n return;\n }\n\n // We have to run this in _initialize, because this runs in setTimeout\n // So when this runs all integrations have been added\n // Before this, we cannot access integrations on the client,\n // so we need to mutate the options here\n this._maybeLoadFromReplayCanvasIntegration();\n\n this._replay.initializeSampling();\n }\n\n /** Setup the integration. */\n private _setup(): void {\n // Client is not available in constructor, so we need to wait until setupOnce\n const finalOptions = loadReplayOptionsFromClient(this._initialOptions);\n\n this._replay = new ReplayContainer({\n options: finalOptions,\n recordingOptions: this._recordingOptions,\n });\n }\n\n /** Get canvas options from ReplayCanvas integration, if it is also added. */\n private _maybeLoadFromReplayCanvasIntegration(): void {\n // To save bundle size, we skip checking for stuff here\n // and instead just try-catch everything - as generally this should all be defined\n /* eslint-disable @typescript-eslint/no-non-null-assertion */\n try {\n const client = getClient()!;\n const canvasIntegration = client.getIntegrationByName!('ReplayCanvas') as Integration & {\n getOptions(): ReplayCanvasIntegrationOptions;\n };\n if (!canvasIntegration) {\n return;\n }\n\n this._replay!['_canvas'] = canvasIntegration.getOptions();\n } catch {\n // ignore errors here\n }\n /* eslint-enable @typescript-eslint/no-non-null-assertion */\n }\n}\n\n/** Parse Replay-related options from SDK options */\nfunction loadReplayOptionsFromClient(initialOptions: InitialReplayPluginOptions): ReplayPluginOptions {\n const client = getClient();\n const opt = client && (client.getOptions() as BrowserClientReplayOptions);\n\n const finalOptions = { sessionSampleRate: 0, errorSampleRate: 0, ...dropUndefinedKeys(initialOptions) };\n\n if (!opt) {\n consoleSandbox(() => {\n // eslint-disable-next-line no-console\n console.warn('SDK client is not available.');\n });\n return finalOptions;\n }\n\n if (\n initialOptions.sessionSampleRate == null && // TODO remove once deprecated rates are removed\n initialOptions.errorSampleRate == null && // TODO remove once deprecated rates are removed\n opt.replaysSessionSampleRate == null &&\n opt.replaysOnErrorSampleRate == null\n ) {\n consoleSandbox(() => {\n // eslint-disable-next-line no-console\n console.warn(\n 'Replay is disabled because neither `replaysSessionSampleRate` nor `replaysOnErrorSampleRate` are set.',\n );\n });\n }\n\n if (typeof opt.replaysSessionSampleRate === 'number') {\n finalOptions.sessionSampleRate = opt.replaysSessionSampleRate;\n }\n\n if (typeof opt.replaysOnErrorSampleRate === 'number') {\n finalOptions.errorSampleRate = opt.replaysOnErrorSampleRate;\n }\n\n return finalOptions;\n}\n\nfunction _getMergedNetworkHeaders(headers: string[]): string[] {\n return [...DEFAULT_NETWORK_HEADERS, ...headers.map(header => header.toLowerCase())];\n}\n", "import { getClient } from '@sentry/core';\nimport type { replayIntegration } from '../integration';\n\n/**\n * This is a small utility to get a type-safe instance of the Replay integration.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function getReplay(): ReturnType | undefined {\n const client = getClient();\n return (\n client && client.getIntegrationByName && client.getIntegrationByName>('Replay')\n );\n}\n", "// eslint-disable-next-line deprecation/deprecation\nimport { Replay as InternalReplay, replayIntegration as internalReplayIntegration } from './integration';\nimport type {\n CanvasManagerInterface as InternalCanvasManagerInterface,\n CanvasManagerOptions as InternalCanvasManagerOptions,\n ReplayBreadcrumbFrame as InternalReplayBreadcrumbFrame,\n ReplayBreadcrumbFrameEvent as InternalReplayBreadcrumbFrameEvent,\n ReplayConfiguration as InternalReplayConfiguration,\n ReplayEventType as InternalReplayEventType,\n ReplayEventWithTime as InternalReplayEventWithTime,\n ReplayFrame as InternalReplayFrame,\n ReplayFrameEvent as InternalReplayFrameEvent,\n ReplayOptionFrameEvent as InternalReplayOptionFrameEvent,\n ReplaySpanFrame as InternalReplaySpanFrame,\n ReplaySpanFrameEvent as InternalReplaySpanFrameEvent,\n} from './types';\nimport { getReplay as internalGetReplay } from './util/getReplay';\n\n/** @deprecated Use the export from `@sentry/replay` or from framework-specific SDKs like `@sentry/react` or `@sentry/vue` */\nconst getReplay = internalGetReplay;\n\n/** @deprecated Use the export from `@sentry/replay` or from framework-specific SDKs like `@sentry/react` or `@sentry/vue` */\nconst replayIntegration = internalReplayIntegration;\n\n/** @deprecated Use the export from `@sentry/replay` or from framework-specific SDKs like `@sentry/react` or `@sentry/vue` */\n// eslint-disable-next-line deprecation/deprecation\nclass Replay extends InternalReplay {}\n\n// eslint-disable-next-line deprecation/deprecation\nexport { replayIntegration, getReplay, Replay, internalReplayIntegration, internalGetReplay, InternalReplay };\n\n/** @deprecated Use the export from `@sentry/replay` or from framework-specific SDKs like `@sentry/react` or `@sentry/vue` */\ntype ReplayConfiguration = InternalReplayConfiguration;\n\n/** @deprecated Use the export from `@sentry/replay` or from framework-specific SDKs like `@sentry/react` or `@sentry/vue` */\ntype ReplayEventType = InternalReplayEventType;\n\n/** @deprecated Use the export from `@sentry/replay` or from framework-specific SDKs like `@sentry/react` or `@sentry/vue` */\ntype ReplayEventWithTime = InternalReplayEventWithTime;\n\n/** @deprecated Use the export from `@sentry/replay` or from framework-specific SDKs like `@sentry/react` or `@sentry/vue` */\ntype ReplayBreadcrumbFrame = InternalReplayBreadcrumbFrame;\n\n/** @deprecated Use the export from `@sentry/replay` or from framework-specific SDKs like `@sentry/react` or `@sentry/vue` */\ntype ReplayBreadcrumbFrameEvent = InternalReplayBreadcrumbFrameEvent;\n\n/** @deprecated Use the export from `@sentry/replay` or from framework-specific SDKs like `@sentry/react` or `@sentry/vue` */\ntype ReplayOptionFrameEvent = InternalReplayOptionFrameEvent;\n\n/** @deprecated Use the export from `@sentry/replay` or from framework-specific SDKs like `@sentry/react` or `@sentry/vue` */\ntype ReplayFrame = InternalReplayFrame;\n\n/** @deprecated Use the export from `@sentry/replay` or from framework-specific SDKs like `@sentry/react` or `@sentry/vue` */\ntype ReplayFrameEvent = InternalReplayFrameEvent;\n\n/** @deprecated Use the export from `@sentry/replay` or from framework-specific SDKs like `@sentry/react` or `@sentry/vue` */\ntype ReplaySpanFrame = InternalReplaySpanFrame;\n\n/** @deprecated Use the export from `@sentry/replay` or from framework-specific SDKs like `@sentry/react` or `@sentry/vue` */\ntype ReplaySpanFrameEvent = InternalReplaySpanFrameEvent;\n\n/** @deprecated Use the export from `@sentry/replay` or from framework-specific SDKs like `@sentry/react` or `@sentry/vue` */\ntype CanvasManagerInterface = InternalCanvasManagerInterface;\n\n/** @deprecated Use the export from `@sentry/replay` or from framework-specific SDKs like `@sentry/react` or `@sentry/vue` */\ntype CanvasManagerOptions = InternalCanvasManagerOptions;\n\nexport type {\n // eslint-disable-next-line deprecation/deprecation\n CanvasManagerInterface,\n // eslint-disable-next-line deprecation/deprecation\n CanvasManagerOptions,\n // eslint-disable-next-line deprecation/deprecation\n ReplayBreadcrumbFrame,\n // eslint-disable-next-line deprecation/deprecation\n ReplayBreadcrumbFrameEvent,\n // eslint-disable-next-line deprecation/deprecation\n ReplayConfiguration,\n // eslint-disable-next-line deprecation/deprecation\n ReplayEventType,\n // eslint-disable-next-line deprecation/deprecation\n ReplayEventWithTime,\n // eslint-disable-next-line deprecation/deprecation\n ReplayFrame,\n // eslint-disable-next-line deprecation/deprecation\n ReplayFrameEvent,\n // eslint-disable-next-line deprecation/deprecation\n ReplayOptionFrameEvent,\n // eslint-disable-next-line deprecation/deprecation\n ReplaySpanFrame,\n // eslint-disable-next-line deprecation/deprecation\n ReplaySpanFrameEvent,\n InternalCanvasManagerInterface,\n InternalCanvasManagerOptions,\n InternalReplayBreadcrumbFrame,\n InternalReplayBreadcrumbFrameEvent,\n InternalReplayConfiguration,\n InternalReplayEventType,\n InternalReplayEventWithTime,\n InternalReplayFrame,\n InternalReplayFrameEvent,\n InternalReplayOptionFrameEvent,\n InternalReplaySpanFrame,\n InternalReplaySpanFrameEvent,\n};\n\n// TODO (v8): Remove deprecated types\nexport * from './types/deprecated';\n", "var NodeType;\r\n(function (NodeType) {\r\n NodeType[NodeType[\"Document\"] = 0] = \"Document\";\r\n NodeType[NodeType[\"DocumentType\"] = 1] = \"DocumentType\";\r\n NodeType[NodeType[\"Element\"] = 2] = \"Element\";\r\n NodeType[NodeType[\"Text\"] = 3] = \"Text\";\r\n NodeType[NodeType[\"CDATA\"] = 4] = \"CDATA\";\r\n NodeType[NodeType[\"Comment\"] = 5] = \"Comment\";\r\n})(NodeType || (NodeType = {}));\n\nfunction isElement(n) {\r\n return n.nodeType === n.ELEMENT_NODE;\r\n}\r\nfunction isShadowRoot(n) {\r\n const host = n?.host;\r\n return Boolean(host?.shadowRoot === n);\r\n}\r\nfunction isNativeShadowDom(shadowRoot) {\r\n return Object.prototype.toString.call(shadowRoot) === '[object ShadowRoot]';\r\n}\r\nfunction fixBrowserCompatibilityIssuesInCSS(cssText) {\r\n if (cssText.includes(' background-clip: text;') &&\r\n !cssText.includes(' -webkit-background-clip: text;')) {\r\n cssText = cssText.replace(' background-clip: text;', ' -webkit-background-clip: text; background-clip: text;');\r\n }\r\n return cssText;\r\n}\r\nfunction escapeImportStatement(rule) {\r\n const { cssText } = rule;\r\n if (cssText.split('\"').length < 3)\r\n return cssText;\r\n const statement = ['@import', `url(${JSON.stringify(rule.href)})`];\r\n if (rule.layerName === '') {\r\n statement.push(`layer`);\r\n }\r\n else if (rule.layerName) {\r\n statement.push(`layer(${rule.layerName})`);\r\n }\r\n if (rule.supportsText) {\r\n statement.push(`supports(${rule.supportsText})`);\r\n }\r\n if (rule.media.length) {\r\n statement.push(rule.media.mediaText);\r\n }\r\n return statement.join(' ') + ';';\r\n}\r\nfunction stringifyStylesheet(s) {\r\n try {\r\n const rules = s.rules || s.cssRules;\r\n return rules\r\n ? fixBrowserCompatibilityIssuesInCSS(Array.from(rules, stringifyRule).join(''))\r\n : null;\r\n }\r\n catch (error) {\r\n return null;\r\n }\r\n}\r\nfunction stringifyRule(rule) {\r\n let importStringified;\r\n if (isCSSImportRule(rule)) {\r\n try {\r\n importStringified =\r\n stringifyStylesheet(rule.styleSheet) ||\r\n escapeImportStatement(rule);\r\n }\r\n catch (error) {\r\n }\r\n }\r\n else if (isCSSStyleRule(rule) && rule.selectorText.includes(':')) {\r\n return fixSafariColons(rule.cssText);\r\n }\r\n return importStringified || rule.cssText;\r\n}\r\nfunction fixSafariColons(cssStringified) {\r\n const regex = /(\\[(?:[\\w-]+)[^\\\\])(:(?:[\\w-]+)\\])/gm;\r\n return cssStringified.replace(regex, '$1\\\\$2');\r\n}\r\nfunction isCSSImportRule(rule) {\r\n return 'styleSheet' in rule;\r\n}\r\nfunction isCSSStyleRule(rule) {\r\n return 'selectorText' in rule;\r\n}\r\nclass Mirror {\r\n constructor() {\r\n this.idNodeMap = new Map();\r\n this.nodeMetaMap = new WeakMap();\r\n }\r\n getId(n) {\r\n if (!n)\r\n return -1;\r\n const id = this.getMeta(n)?.id;\r\n return id ?? -1;\r\n }\r\n getNode(id) {\r\n return this.idNodeMap.get(id) || null;\r\n }\r\n getIds() {\r\n return Array.from(this.idNodeMap.keys());\r\n }\r\n getMeta(n) {\r\n return this.nodeMetaMap.get(n) || null;\r\n }\r\n removeNodeFromMap(n) {\r\n const id = this.getId(n);\r\n this.idNodeMap.delete(id);\r\n if (n.childNodes) {\r\n n.childNodes.forEach((childNode) => this.removeNodeFromMap(childNode));\r\n }\r\n }\r\n has(id) {\r\n return this.idNodeMap.has(id);\r\n }\r\n hasNode(node) {\r\n return this.nodeMetaMap.has(node);\r\n }\r\n add(n, meta) {\r\n const id = meta.id;\r\n this.idNodeMap.set(id, n);\r\n this.nodeMetaMap.set(n, meta);\r\n }\r\n replace(id, n) {\r\n const oldNode = this.getNode(id);\r\n if (oldNode) {\r\n const meta = this.nodeMetaMap.get(oldNode);\r\n if (meta)\r\n this.nodeMetaMap.set(n, meta);\r\n }\r\n this.idNodeMap.set(id, n);\r\n }\r\n reset() {\r\n this.idNodeMap = new Map();\r\n this.nodeMetaMap = new WeakMap();\r\n }\r\n}\r\nfunction createMirror() {\r\n return new Mirror();\r\n}\r\nfunction shouldMaskInput({ maskInputOptions, tagName, type, }) {\r\n if (tagName === 'OPTION') {\r\n tagName = 'SELECT';\r\n }\r\n return Boolean(maskInputOptions[tagName.toLowerCase()] ||\r\n (type && maskInputOptions[type]) ||\r\n type === 'password' ||\r\n (tagName === 'INPUT' && !type && maskInputOptions['text']));\r\n}\r\nfunction maskInputValue({ isMasked, element, value, maskInputFn, }) {\r\n let text = value || '';\r\n if (!isMasked) {\r\n return text;\r\n }\r\n if (maskInputFn) {\r\n text = maskInputFn(text, element);\r\n }\r\n return '*'.repeat(text.length);\r\n}\r\nfunction toLowerCase(str) {\r\n return str.toLowerCase();\r\n}\r\nfunction toUpperCase(str) {\r\n return str.toUpperCase();\r\n}\r\nconst ORIGINAL_ATTRIBUTE_NAME = '__rrweb_original__';\r\nfunction is2DCanvasBlank(canvas) {\r\n const ctx = canvas.getContext('2d');\r\n if (!ctx)\r\n return true;\r\n const chunkSize = 50;\r\n for (let x = 0; x < canvas.width; x += chunkSize) {\r\n for (let y = 0; y < canvas.height; y += chunkSize) {\r\n const getImageData = ctx.getImageData;\r\n const originalGetImageData = ORIGINAL_ATTRIBUTE_NAME in getImageData\r\n ? getImageData[ORIGINAL_ATTRIBUTE_NAME]\r\n : getImageData;\r\n const pixelBuffer = new Uint32Array(originalGetImageData.call(ctx, x, y, Math.min(chunkSize, canvas.width - x), Math.min(chunkSize, canvas.height - y)).data.buffer);\r\n if (pixelBuffer.some((pixel) => pixel !== 0))\r\n return false;\r\n }\r\n }\r\n return true;\r\n}\r\nfunction isNodeMetaEqual(a, b) {\r\n if (!a || !b || a.type !== b.type)\r\n return false;\r\n if (a.type === NodeType.Document)\r\n return a.compatMode === b.compatMode;\r\n else if (a.type === NodeType.DocumentType)\r\n return (a.name === b.name &&\r\n a.publicId === b.publicId &&\r\n a.systemId === b.systemId);\r\n else if (a.type === NodeType.Comment ||\r\n a.type === NodeType.Text ||\r\n a.type === NodeType.CDATA)\r\n return a.textContent === b.textContent;\r\n else if (a.type === NodeType.Element)\r\n return (a.tagName === b.tagName &&\r\n JSON.stringify(a.attributes) ===\r\n JSON.stringify(b.attributes) &&\r\n a.isSVG === b.isSVG &&\r\n a.needBlock === b.needBlock);\r\n return false;\r\n}\r\nfunction getInputType(element) {\r\n const type = element.type;\r\n return element.hasAttribute('data-rr-is-password')\r\n ? 'password'\r\n : type\r\n ?\r\n toLowerCase(type)\r\n : null;\r\n}\r\nfunction getInputValue(el, tagName, type) {\r\n if (tagName === 'INPUT' && (type === 'radio' || type === 'checkbox')) {\r\n return el.getAttribute('value') || '';\r\n }\r\n return el.value;\r\n}\n\nlet _id = 1;\r\nconst tagNameRegex = new RegExp('[^a-z0-9-_:]');\r\nconst IGNORED_NODE = -2;\r\nfunction genId() {\r\n return _id++;\r\n}\r\nfunction getValidTagName(element) {\r\n if (element instanceof HTMLFormElement) {\r\n return 'form';\r\n }\r\n const processedTagName = toLowerCase(element.tagName);\r\n if (tagNameRegex.test(processedTagName)) {\r\n return 'div';\r\n }\r\n return processedTagName;\r\n}\r\nfunction extractOrigin(url) {\r\n let origin = '';\r\n if (url.indexOf('//') > -1) {\r\n origin = url.split('/').slice(0, 3).join('/');\r\n }\r\n else {\r\n origin = url.split('/')[0];\r\n }\r\n origin = origin.split('?')[0];\r\n return origin;\r\n}\r\nlet canvasService;\r\nlet canvasCtx;\r\nconst URL_IN_CSS_REF = /url\\((?:(')([^']*)'|(\")(.*?)\"|([^)]*))\\)/gm;\r\nconst URL_PROTOCOL_MATCH = /^(?:[a-z+]+:)?\\/\\//i;\r\nconst URL_WWW_MATCH = /^www\\..*/i;\r\nconst DATA_URI = /^(data:)([^,]*),(.*)/i;\r\nfunction absoluteToStylesheet(cssText, href) {\r\n return (cssText || '').replace(URL_IN_CSS_REF, (origin, quote1, path1, quote2, path2, path3) => {\r\n const filePath = path1 || path2 || path3;\r\n const maybeQuote = quote1 || quote2 || '';\r\n if (!filePath) {\r\n return origin;\r\n }\r\n if (URL_PROTOCOL_MATCH.test(filePath) || URL_WWW_MATCH.test(filePath)) {\r\n return `url(${maybeQuote}${filePath}${maybeQuote})`;\r\n }\r\n if (DATA_URI.test(filePath)) {\r\n return `url(${maybeQuote}${filePath}${maybeQuote})`;\r\n }\r\n if (filePath[0] === '/') {\r\n return `url(${maybeQuote}${extractOrigin(href) + filePath}${maybeQuote})`;\r\n }\r\n const stack = href.split('/');\r\n const parts = filePath.split('/');\r\n stack.pop();\r\n for (const part of parts) {\r\n if (part === '.') {\r\n continue;\r\n }\r\n else if (part === '..') {\r\n stack.pop();\r\n }\r\n else {\r\n stack.push(part);\r\n }\r\n }\r\n return `url(${maybeQuote}${stack.join('/')}${maybeQuote})`;\r\n });\r\n}\r\nconst SRCSET_NOT_SPACES = /^[^ \\t\\n\\r\\u000c]+/;\r\nconst SRCSET_COMMAS_OR_SPACES = /^[, \\t\\n\\r\\u000c]+/;\r\nfunction getAbsoluteSrcsetString(doc, attributeValue) {\r\n if (attributeValue.trim() === '') {\r\n return attributeValue;\r\n }\r\n let pos = 0;\r\n function collectCharacters(regEx) {\r\n let chars;\r\n const match = regEx.exec(attributeValue.substring(pos));\r\n if (match) {\r\n chars = match[0];\r\n pos += chars.length;\r\n return chars;\r\n }\r\n return '';\r\n }\r\n const output = [];\r\n while (true) {\r\n collectCharacters(SRCSET_COMMAS_OR_SPACES);\r\n if (pos >= attributeValue.length) {\r\n break;\r\n }\r\n let url = collectCharacters(SRCSET_NOT_SPACES);\r\n if (url.slice(-1) === ',') {\r\n url = absoluteToDoc(doc, url.substring(0, url.length - 1));\r\n output.push(url);\r\n }\r\n else {\r\n let descriptorsStr = '';\r\n url = absoluteToDoc(doc, url);\r\n let inParens = false;\r\n while (true) {\r\n const c = attributeValue.charAt(pos);\r\n if (c === '') {\r\n output.push((url + descriptorsStr).trim());\r\n break;\r\n }\r\n else if (!inParens) {\r\n if (c === ',') {\r\n pos += 1;\r\n output.push((url + descriptorsStr).trim());\r\n break;\r\n }\r\n else if (c === '(') {\r\n inParens = true;\r\n }\r\n }\r\n else {\r\n if (c === ')') {\r\n inParens = false;\r\n }\r\n }\r\n descriptorsStr += c;\r\n pos += 1;\r\n }\r\n }\r\n }\r\n return output.join(', ');\r\n}\r\nfunction absoluteToDoc(doc, attributeValue) {\r\n if (!attributeValue || attributeValue.trim() === '') {\r\n return attributeValue;\r\n }\r\n const a = doc.createElement('a');\r\n a.href = attributeValue;\r\n return a.href;\r\n}\r\nfunction isSVGElement(el) {\r\n return Boolean(el.tagName === 'svg' || el.ownerSVGElement);\r\n}\r\nfunction getHref() {\r\n const a = document.createElement('a');\r\n a.href = '';\r\n return a.href;\r\n}\r\nfunction transformAttribute(doc, tagName, name, value, element, maskAttributeFn) {\r\n if (!value) {\r\n return value;\r\n }\r\n if (name === 'src' ||\r\n (name === 'href' && !(tagName === 'use' && value[0] === '#'))) {\r\n return absoluteToDoc(doc, value);\r\n }\r\n else if (name === 'xlink:href' && value[0] !== '#') {\r\n return absoluteToDoc(doc, value);\r\n }\r\n else if (name === 'background' &&\r\n (tagName === 'table' || tagName === 'td' || tagName === 'th')) {\r\n return absoluteToDoc(doc, value);\r\n }\r\n else if (name === 'srcset') {\r\n return getAbsoluteSrcsetString(doc, value);\r\n }\r\n else if (name === 'style') {\r\n return absoluteToStylesheet(value, getHref());\r\n }\r\n else if (tagName === 'object' && name === 'data') {\r\n return absoluteToDoc(doc, value);\r\n }\r\n if (typeof maskAttributeFn === 'function') {\r\n return maskAttributeFn(name, value, element);\r\n }\r\n return value;\r\n}\r\nfunction ignoreAttribute(tagName, name, _value) {\r\n return (tagName === 'video' || tagName === 'audio') && name === 'autoplay';\r\n}\r\nfunction _isBlockedElement(element, blockClass, blockSelector, unblockSelector) {\r\n try {\r\n if (unblockSelector && element.matches(unblockSelector)) {\r\n return false;\r\n }\r\n if (typeof blockClass === 'string') {\r\n if (element.classList.contains(blockClass)) {\r\n return true;\r\n }\r\n }\r\n else {\r\n for (let eIndex = element.classList.length; eIndex--;) {\r\n const className = element.classList[eIndex];\r\n if (blockClass.test(className)) {\r\n return true;\r\n }\r\n }\r\n }\r\n if (blockSelector) {\r\n return element.matches(blockSelector);\r\n }\r\n }\r\n catch (e) {\r\n }\r\n return false;\r\n}\r\nfunction elementClassMatchesRegex(el, regex) {\r\n for (let eIndex = el.classList.length; eIndex--;) {\r\n const className = el.classList[eIndex];\r\n if (regex.test(className)) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n}\r\nfunction distanceToMatch(node, matchPredicate, limit = Infinity, distance = 0) {\r\n if (!node)\r\n return -1;\r\n if (node.nodeType !== node.ELEMENT_NODE)\r\n return -1;\r\n if (distance > limit)\r\n return -1;\r\n if (matchPredicate(node))\r\n return distance;\r\n return distanceToMatch(node.parentNode, matchPredicate, limit, distance + 1);\r\n}\r\nfunction createMatchPredicate(className, selector) {\r\n return (node) => {\r\n const el = node;\r\n if (el === null)\r\n return false;\r\n try {\r\n if (className) {\r\n if (typeof className === 'string') {\r\n if (el.matches(`.${className}`))\r\n return true;\r\n }\r\n else if (elementClassMatchesRegex(el, className)) {\r\n return true;\r\n }\r\n }\r\n if (selector && el.matches(selector))\r\n return true;\r\n return false;\r\n }\r\n catch {\r\n return false;\r\n }\r\n };\r\n}\r\nfunction needMaskingText(node, maskTextClass, maskTextSelector, unmaskTextClass, unmaskTextSelector, maskAllText) {\r\n try {\r\n const el = node.nodeType === node.ELEMENT_NODE\r\n ? node\r\n : node.parentElement;\r\n if (el === null)\r\n return false;\r\n if (el.tagName === 'INPUT') {\r\n const autocomplete = el.getAttribute('autocomplete');\r\n const disallowedAutocompleteValues = [\r\n 'current-password',\r\n 'new-password',\r\n 'cc-number',\r\n 'cc-exp',\r\n 'cc-exp-month',\r\n 'cc-exp-year',\r\n 'cc-csc',\r\n ];\r\n if (disallowedAutocompleteValues.includes(autocomplete)) {\r\n return true;\r\n }\r\n }\r\n let maskDistance = -1;\r\n let unmaskDistance = -1;\r\n if (maskAllText) {\r\n unmaskDistance = distanceToMatch(el, createMatchPredicate(unmaskTextClass, unmaskTextSelector));\r\n if (unmaskDistance < 0) {\r\n return true;\r\n }\r\n maskDistance = distanceToMatch(el, createMatchPredicate(maskTextClass, maskTextSelector), unmaskDistance >= 0 ? unmaskDistance : Infinity);\r\n }\r\n else {\r\n maskDistance = distanceToMatch(el, createMatchPredicate(maskTextClass, maskTextSelector));\r\n if (maskDistance < 0) {\r\n return false;\r\n }\r\n unmaskDistance = distanceToMatch(el, createMatchPredicate(unmaskTextClass, unmaskTextSelector), maskDistance >= 0 ? maskDistance : Infinity);\r\n }\r\n return maskDistance >= 0\r\n ? unmaskDistance >= 0\r\n ? maskDistance <= unmaskDistance\r\n : true\r\n : unmaskDistance >= 0\r\n ? false\r\n : !!maskAllText;\r\n }\r\n catch (e) {\r\n }\r\n return !!maskAllText;\r\n}\r\nfunction onceIframeLoaded(iframeEl, listener, iframeLoadTimeout) {\r\n const win = iframeEl.contentWindow;\r\n if (!win) {\r\n return;\r\n }\r\n let fired = false;\r\n let readyState;\r\n try {\r\n readyState = win.document.readyState;\r\n }\r\n catch (error) {\r\n return;\r\n }\r\n if (readyState !== 'complete') {\r\n const timer = setTimeout(() => {\r\n if (!fired) {\r\n listener();\r\n fired = true;\r\n }\r\n }, iframeLoadTimeout);\r\n iframeEl.addEventListener('load', () => {\r\n clearTimeout(timer);\r\n fired = true;\r\n listener();\r\n });\r\n return;\r\n }\r\n const blankUrl = 'about:blank';\r\n if (win.location.href !== blankUrl ||\r\n iframeEl.src === blankUrl ||\r\n iframeEl.src === '') {\r\n setTimeout(listener, 0);\r\n return iframeEl.addEventListener('load', listener);\r\n }\r\n iframeEl.addEventListener('load', listener);\r\n}\r\nfunction onceStylesheetLoaded(link, listener, styleSheetLoadTimeout) {\r\n let fired = false;\r\n let styleSheetLoaded;\r\n try {\r\n styleSheetLoaded = link.sheet;\r\n }\r\n catch (error) {\r\n return;\r\n }\r\n if (styleSheetLoaded)\r\n return;\r\n const timer = setTimeout(() => {\r\n if (!fired) {\r\n listener();\r\n fired = true;\r\n }\r\n }, styleSheetLoadTimeout);\r\n link.addEventListener('load', () => {\r\n clearTimeout(timer);\r\n fired = true;\r\n listener();\r\n });\r\n}\r\nfunction serializeNode(n, options) {\r\n const { doc, mirror, blockClass, blockSelector, unblockSelector, maskAllText, maskAttributeFn, maskTextClass, unmaskTextClass, maskTextSelector, unmaskTextSelector, inlineStylesheet, maskInputOptions = {}, maskTextFn, maskInputFn, dataURLOptions = {}, inlineImages, recordCanvas, keepIframeSrcFn, newlyAddedElement = false, } = options;\r\n const rootId = getRootId(doc, mirror);\r\n switch (n.nodeType) {\r\n case n.DOCUMENT_NODE:\r\n if (n.compatMode !== 'CSS1Compat') {\r\n return {\r\n type: NodeType.Document,\r\n childNodes: [],\r\n compatMode: n.compatMode,\r\n };\r\n }\r\n else {\r\n return {\r\n type: NodeType.Document,\r\n childNodes: [],\r\n };\r\n }\r\n case n.DOCUMENT_TYPE_NODE:\r\n return {\r\n type: NodeType.DocumentType,\r\n name: n.name,\r\n publicId: n.publicId,\r\n systemId: n.systemId,\r\n rootId,\r\n };\r\n case n.ELEMENT_NODE:\r\n return serializeElementNode(n, {\r\n doc,\r\n blockClass,\r\n blockSelector,\r\n unblockSelector,\r\n inlineStylesheet,\r\n maskAttributeFn,\r\n maskInputOptions,\r\n maskInputFn,\r\n dataURLOptions,\r\n inlineImages,\r\n recordCanvas,\r\n keepIframeSrcFn,\r\n newlyAddedElement,\r\n rootId,\r\n maskAllText,\r\n maskTextClass,\r\n unmaskTextClass,\r\n maskTextSelector,\r\n unmaskTextSelector,\r\n });\r\n case n.TEXT_NODE:\r\n return serializeTextNode(n, {\r\n maskAllText,\r\n maskTextClass,\r\n unmaskTextClass,\r\n maskTextSelector,\r\n unmaskTextSelector,\r\n maskTextFn,\r\n maskInputOptions,\r\n maskInputFn,\r\n rootId,\r\n });\r\n case n.CDATA_SECTION_NODE:\r\n return {\r\n type: NodeType.CDATA,\r\n textContent: '',\r\n rootId,\r\n };\r\n case n.COMMENT_NODE:\r\n return {\r\n type: NodeType.Comment,\r\n textContent: n.textContent || '',\r\n rootId,\r\n };\r\n default:\r\n return false;\r\n }\r\n}\r\nfunction getRootId(doc, mirror) {\r\n if (!mirror.hasNode(doc))\r\n return undefined;\r\n const docId = mirror.getId(doc);\r\n return docId === 1 ? undefined : docId;\r\n}\r\nfunction serializeTextNode(n, options) {\r\n const { maskAllText, maskTextClass, unmaskTextClass, maskTextSelector, unmaskTextSelector, maskTextFn, maskInputOptions, maskInputFn, rootId, } = options;\r\n const parentTagName = n.parentNode && n.parentNode.tagName;\r\n let textContent = n.textContent;\r\n const isStyle = parentTagName === 'STYLE' ? true : undefined;\r\n const isScript = parentTagName === 'SCRIPT' ? true : undefined;\r\n const isTextarea = parentTagName === 'TEXTAREA' ? true : undefined;\r\n if (isStyle && textContent) {\r\n try {\r\n if (n.nextSibling || n.previousSibling) {\r\n }\r\n else if (n.parentNode.sheet?.cssRules) {\r\n textContent = stringifyStylesheet(n.parentNode.sheet);\r\n }\r\n }\r\n catch (err) {\r\n console.warn(`Cannot get CSS styles from text's parentNode. Error: ${err}`, n);\r\n }\r\n textContent = absoluteToStylesheet(textContent, getHref());\r\n }\r\n if (isScript) {\r\n textContent = 'SCRIPT_PLACEHOLDER';\r\n }\r\n const forceMask = needMaskingText(n, maskTextClass, maskTextSelector, unmaskTextClass, unmaskTextSelector, maskAllText);\r\n if (!isStyle && !isScript && !isTextarea && textContent && forceMask) {\r\n textContent = maskTextFn\r\n ? maskTextFn(textContent, n.parentElement)\r\n : textContent.replace(/[\\S]/g, '*');\r\n }\r\n if (isTextarea && textContent && (maskInputOptions.textarea || forceMask)) {\r\n textContent = maskInputFn\r\n ? maskInputFn(textContent, n.parentNode)\r\n : textContent.replace(/[\\S]/g, '*');\r\n }\r\n if (parentTagName === 'OPTION' && textContent) {\r\n const isInputMasked = shouldMaskInput({\r\n type: null,\r\n tagName: parentTagName,\r\n maskInputOptions,\r\n });\r\n textContent = maskInputValue({\r\n isMasked: needMaskingText(n, maskTextClass, maskTextSelector, unmaskTextClass, unmaskTextSelector, isInputMasked),\r\n element: n,\r\n value: textContent,\r\n maskInputFn,\r\n });\r\n }\r\n return {\r\n type: NodeType.Text,\r\n textContent: textContent || '',\r\n isStyle,\r\n rootId,\r\n };\r\n}\r\nfunction serializeElementNode(n, options) {\r\n const { doc, blockClass, blockSelector, unblockSelector, inlineStylesheet, maskInputOptions = {}, maskAttributeFn, maskInputFn, dataURLOptions = {}, inlineImages, recordCanvas, keepIframeSrcFn, newlyAddedElement = false, rootId, maskAllText, maskTextClass, unmaskTextClass, maskTextSelector, unmaskTextSelector, } = options;\r\n const needBlock = _isBlockedElement(n, blockClass, blockSelector, unblockSelector);\r\n const tagName = getValidTagName(n);\r\n let attributes = {};\r\n const len = n.attributes.length;\r\n for (let i = 0; i < len; i++) {\r\n const attr = n.attributes[i];\r\n if (attr.name && !ignoreAttribute(tagName, attr.name, attr.value)) {\r\n attributes[attr.name] = transformAttribute(doc, tagName, toLowerCase(attr.name), attr.value, n, maskAttributeFn);\r\n }\r\n }\r\n if (tagName === 'link' && inlineStylesheet) {\r\n const stylesheet = Array.from(doc.styleSheets).find((s) => {\r\n return s.href === n.href;\r\n });\r\n let cssText = null;\r\n if (stylesheet) {\r\n cssText = stringifyStylesheet(stylesheet);\r\n }\r\n if (cssText) {\r\n delete attributes.rel;\r\n delete attributes.href;\r\n attributes._cssText = absoluteToStylesheet(cssText, stylesheet.href);\r\n }\r\n }\r\n if (tagName === 'style' &&\r\n n.sheet &&\r\n !(n.innerText || n.textContent || '').trim().length) {\r\n const cssText = stringifyStylesheet(n.sheet);\r\n if (cssText) {\r\n attributes._cssText = absoluteToStylesheet(cssText, getHref());\r\n }\r\n }\r\n if (tagName === 'input' ||\r\n tagName === 'textarea' ||\r\n tagName === 'select' ||\r\n tagName === 'option') {\r\n const el = n;\r\n const type = getInputType(el);\r\n const value = getInputValue(el, toUpperCase(tagName), type);\r\n const checked = el.checked;\r\n if (type !== 'submit' && type !== 'button' && value) {\r\n const forceMask = needMaskingText(el, maskTextClass, maskTextSelector, unmaskTextClass, unmaskTextSelector, shouldMaskInput({\r\n type,\r\n tagName: toUpperCase(tagName),\r\n maskInputOptions,\r\n }));\r\n attributes.value = maskInputValue({\r\n isMasked: forceMask,\r\n element: el,\r\n value,\r\n maskInputFn,\r\n });\r\n }\r\n if (checked) {\r\n attributes.checked = checked;\r\n }\r\n }\r\n if (tagName === 'option') {\r\n if (n.selected && !maskInputOptions['select']) {\r\n attributes.selected = true;\r\n }\r\n else {\r\n delete attributes.selected;\r\n }\r\n }\r\n if (tagName === 'canvas' && recordCanvas) {\r\n if (n.__context === '2d') {\r\n if (!is2DCanvasBlank(n)) {\r\n attributes.rr_dataURL = n.toDataURL(dataURLOptions.type, dataURLOptions.quality);\r\n }\r\n }\r\n else if (!('__context' in n)) {\r\n const canvasDataURL = n.toDataURL(dataURLOptions.type, dataURLOptions.quality);\r\n const blankCanvas = document.createElement('canvas');\r\n blankCanvas.width = n.width;\r\n blankCanvas.height = n.height;\r\n const blankCanvasDataURL = blankCanvas.toDataURL(dataURLOptions.type, dataURLOptions.quality);\r\n if (canvasDataURL !== blankCanvasDataURL) {\r\n attributes.rr_dataURL = canvasDataURL;\r\n }\r\n }\r\n }\r\n if (tagName === 'img' && inlineImages) {\r\n if (!canvasService) {\r\n canvasService = doc.createElement('canvas');\r\n canvasCtx = canvasService.getContext('2d');\r\n }\r\n const image = n;\r\n const oldValue = image.crossOrigin;\r\n image.crossOrigin = 'anonymous';\r\n const recordInlineImage = () => {\r\n image.removeEventListener('load', recordInlineImage);\r\n try {\r\n canvasService.width = image.naturalWidth;\r\n canvasService.height = image.naturalHeight;\r\n canvasCtx.drawImage(image, 0, 0);\r\n attributes.rr_dataURL = canvasService.toDataURL(dataURLOptions.type, dataURLOptions.quality);\r\n }\r\n catch (err) {\r\n console.warn(`Cannot inline img src=${image.currentSrc}! Error: ${err}`);\r\n }\r\n oldValue\r\n ? (attributes.crossOrigin = oldValue)\r\n : image.removeAttribute('crossorigin');\r\n };\r\n if (image.complete && image.naturalWidth !== 0)\r\n recordInlineImage();\r\n else\r\n image.addEventListener('load', recordInlineImage);\r\n }\r\n if (tagName === 'audio' || tagName === 'video') {\r\n attributes.rr_mediaState = n.paused\r\n ? 'paused'\r\n : 'played';\r\n attributes.rr_mediaCurrentTime = n.currentTime;\r\n }\r\n if (!newlyAddedElement) {\r\n if (n.scrollLeft) {\r\n attributes.rr_scrollLeft = n.scrollLeft;\r\n }\r\n if (n.scrollTop) {\r\n attributes.rr_scrollTop = n.scrollTop;\r\n }\r\n }\r\n if (needBlock) {\r\n const { width, height } = n.getBoundingClientRect();\r\n attributes = {\r\n class: attributes.class,\r\n rr_width: `${width}px`,\r\n rr_height: `${height}px`,\r\n };\r\n }\r\n if (tagName === 'iframe' && !keepIframeSrcFn(attributes.src)) {\r\n if (!n.contentDocument) {\r\n attributes.rr_src = attributes.src;\r\n }\r\n delete attributes.src;\r\n }\r\n let isCustomElement;\r\n try {\r\n if (customElements.get(tagName))\r\n isCustomElement = true;\r\n }\r\n catch (e) {\r\n }\r\n return {\r\n type: NodeType.Element,\r\n tagName,\r\n attributes,\r\n childNodes: [],\r\n isSVG: isSVGElement(n) || undefined,\r\n needBlock,\r\n rootId,\r\n isCustom: isCustomElement,\r\n };\r\n}\r\nfunction lowerIfExists(maybeAttr) {\r\n if (maybeAttr === undefined || maybeAttr === null) {\r\n return '';\r\n }\r\n else {\r\n return maybeAttr.toLowerCase();\r\n }\r\n}\r\nfunction slimDOMExcluded(sn, slimDOMOptions) {\r\n if (slimDOMOptions.comment && sn.type === NodeType.Comment) {\r\n return true;\r\n }\r\n else if (sn.type === NodeType.Element) {\r\n if (slimDOMOptions.script &&\r\n (sn.tagName === 'script' ||\r\n (sn.tagName === 'link' &&\r\n (sn.attributes.rel === 'preload' ||\r\n sn.attributes.rel === 'modulepreload') &&\r\n sn.attributes.as === 'script') ||\r\n (sn.tagName === 'link' &&\r\n sn.attributes.rel === 'prefetch' &&\r\n typeof sn.attributes.href === 'string' &&\r\n sn.attributes.href.endsWith('.js')))) {\r\n return true;\r\n }\r\n else if (slimDOMOptions.headFavicon &&\r\n ((sn.tagName === 'link' && sn.attributes.rel === 'shortcut icon') ||\r\n (sn.tagName === 'meta' &&\r\n (lowerIfExists(sn.attributes.name).match(/^msapplication-tile(image|color)$/) ||\r\n lowerIfExists(sn.attributes.name) === 'application-name' ||\r\n lowerIfExists(sn.attributes.rel) === 'icon' ||\r\n lowerIfExists(sn.attributes.rel) === 'apple-touch-icon' ||\r\n lowerIfExists(sn.attributes.rel) === 'shortcut icon')))) {\r\n return true;\r\n }\r\n else if (sn.tagName === 'meta') {\r\n if (slimDOMOptions.headMetaDescKeywords &&\r\n lowerIfExists(sn.attributes.name).match(/^description|keywords$/)) {\r\n return true;\r\n }\r\n else if (slimDOMOptions.headMetaSocial &&\r\n (lowerIfExists(sn.attributes.property).match(/^(og|twitter|fb):/) ||\r\n lowerIfExists(sn.attributes.name).match(/^(og|twitter):/) ||\r\n lowerIfExists(sn.attributes.name) === 'pinterest')) {\r\n return true;\r\n }\r\n else if (slimDOMOptions.headMetaRobots &&\r\n (lowerIfExists(sn.attributes.name) === 'robots' ||\r\n lowerIfExists(sn.attributes.name) === 'googlebot' ||\r\n lowerIfExists(sn.attributes.name) === 'bingbot')) {\r\n return true;\r\n }\r\n else if (slimDOMOptions.headMetaHttpEquiv &&\r\n sn.attributes['http-equiv'] !== undefined) {\r\n return true;\r\n }\r\n else if (slimDOMOptions.headMetaAuthorship &&\r\n (lowerIfExists(sn.attributes.name) === 'author' ||\r\n lowerIfExists(sn.attributes.name) === 'generator' ||\r\n lowerIfExists(sn.attributes.name) === 'framework' ||\r\n lowerIfExists(sn.attributes.name) === 'publisher' ||\r\n lowerIfExists(sn.attributes.name) === 'progid' ||\r\n lowerIfExists(sn.attributes.property).match(/^article:/) ||\r\n lowerIfExists(sn.attributes.property).match(/^product:/))) {\r\n return true;\r\n }\r\n else if (slimDOMOptions.headMetaVerification &&\r\n (lowerIfExists(sn.attributes.name) === 'google-site-verification' ||\r\n lowerIfExists(sn.attributes.name) === 'yandex-verification' ||\r\n lowerIfExists(sn.attributes.name) === 'csrf-token' ||\r\n lowerIfExists(sn.attributes.name) === 'p:domain_verify' ||\r\n lowerIfExists(sn.attributes.name) === 'verify-v1' ||\r\n lowerIfExists(sn.attributes.name) === 'verification' ||\r\n lowerIfExists(sn.attributes.name) === 'shopify-checkout-api-token')) {\r\n return true;\r\n }\r\n }\r\n }\r\n return false;\r\n}\r\nfunction serializeNodeWithId(n, options) {\r\n const { doc, mirror, blockClass, blockSelector, unblockSelector, maskAllText, maskTextClass, unmaskTextClass, maskTextSelector, unmaskTextSelector, skipChild = false, inlineStylesheet = true, maskInputOptions = {}, maskAttributeFn, maskTextFn, maskInputFn, slimDOMOptions, dataURLOptions = {}, inlineImages = false, recordCanvas = false, onSerialize, onIframeLoad, iframeLoadTimeout = 5000, onStylesheetLoad, stylesheetLoadTimeout = 5000, keepIframeSrcFn = () => false, newlyAddedElement = false, } = options;\r\n let { preserveWhiteSpace = true } = options;\r\n const _serializedNode = serializeNode(n, {\r\n doc,\r\n mirror,\r\n blockClass,\r\n blockSelector,\r\n maskAllText,\r\n unblockSelector,\r\n maskTextClass,\r\n unmaskTextClass,\r\n maskTextSelector,\r\n unmaskTextSelector,\r\n inlineStylesheet,\r\n maskInputOptions,\r\n maskAttributeFn,\r\n maskTextFn,\r\n maskInputFn,\r\n dataURLOptions,\r\n inlineImages,\r\n recordCanvas,\r\n keepIframeSrcFn,\r\n newlyAddedElement,\r\n });\r\n if (!_serializedNode) {\r\n console.warn(n, 'not serialized');\r\n return null;\r\n }\r\n let id;\r\n if (mirror.hasNode(n)) {\r\n id = mirror.getId(n);\r\n }\r\n else if (slimDOMExcluded(_serializedNode, slimDOMOptions) ||\r\n (!preserveWhiteSpace &&\r\n _serializedNode.type === NodeType.Text &&\r\n !_serializedNode.isStyle &&\r\n !_serializedNode.textContent.replace(/^\\s+|\\s+$/gm, '').length)) {\r\n id = IGNORED_NODE;\r\n }\r\n else {\r\n id = genId();\r\n }\r\n const serializedNode = Object.assign(_serializedNode, { id });\r\n mirror.add(n, serializedNode);\r\n if (id === IGNORED_NODE) {\r\n return null;\r\n }\r\n if (onSerialize) {\r\n onSerialize(n);\r\n }\r\n let recordChild = !skipChild;\r\n if (serializedNode.type === NodeType.Element) {\r\n recordChild = recordChild && !serializedNode.needBlock;\r\n delete serializedNode.needBlock;\r\n const shadowRoot = n.shadowRoot;\r\n if (shadowRoot && isNativeShadowDom(shadowRoot))\r\n serializedNode.isShadowHost = true;\r\n }\r\n if ((serializedNode.type === NodeType.Document ||\r\n serializedNode.type === NodeType.Element) &&\r\n recordChild) {\r\n if (slimDOMOptions.headWhitespace &&\r\n serializedNode.type === NodeType.Element &&\r\n serializedNode.tagName === 'head') {\r\n preserveWhiteSpace = false;\r\n }\r\n const bypassOptions = {\r\n doc,\r\n mirror,\r\n blockClass,\r\n blockSelector,\r\n maskAllText,\r\n unblockSelector,\r\n maskTextClass,\r\n unmaskTextClass,\r\n maskTextSelector,\r\n unmaskTextSelector,\r\n skipChild,\r\n inlineStylesheet,\r\n maskInputOptions,\r\n maskAttributeFn,\r\n maskTextFn,\r\n maskInputFn,\r\n slimDOMOptions,\r\n dataURLOptions,\r\n inlineImages,\r\n recordCanvas,\r\n preserveWhiteSpace,\r\n onSerialize,\r\n onIframeLoad,\r\n iframeLoadTimeout,\r\n onStylesheetLoad,\r\n stylesheetLoadTimeout,\r\n keepIframeSrcFn,\r\n };\r\n for (const childN of Array.from(n.childNodes)) {\r\n const serializedChildNode = serializeNodeWithId(childN, bypassOptions);\r\n if (serializedChildNode) {\r\n serializedNode.childNodes.push(serializedChildNode);\r\n }\r\n }\r\n if (isElement(n) && n.shadowRoot) {\r\n for (const childN of Array.from(n.shadowRoot.childNodes)) {\r\n const serializedChildNode = serializeNodeWithId(childN, bypassOptions);\r\n if (serializedChildNode) {\r\n isNativeShadowDom(n.shadowRoot) &&\r\n (serializedChildNode.isShadow = true);\r\n serializedNode.childNodes.push(serializedChildNode);\r\n }\r\n }\r\n }\r\n }\r\n if (n.parentNode &&\r\n isShadowRoot(n.parentNode) &&\r\n isNativeShadowDom(n.parentNode)) {\r\n serializedNode.isShadow = true;\r\n }\r\n if (serializedNode.type === NodeType.Element &&\r\n serializedNode.tagName === 'iframe') {\r\n onceIframeLoaded(n, () => {\r\n const iframeDoc = n.contentDocument;\r\n if (iframeDoc && onIframeLoad) {\r\n const serializedIframeNode = serializeNodeWithId(iframeDoc, {\r\n doc: iframeDoc,\r\n mirror,\r\n blockClass,\r\n blockSelector,\r\n unblockSelector,\r\n maskAllText,\r\n maskTextClass,\r\n unmaskTextClass,\r\n maskTextSelector,\r\n unmaskTextSelector,\r\n skipChild: false,\r\n inlineStylesheet,\r\n maskInputOptions,\r\n maskAttributeFn,\r\n maskTextFn,\r\n maskInputFn,\r\n slimDOMOptions,\r\n dataURLOptions,\r\n inlineImages,\r\n recordCanvas,\r\n preserveWhiteSpace,\r\n onSerialize,\r\n onIframeLoad,\r\n iframeLoadTimeout,\r\n onStylesheetLoad,\r\n stylesheetLoadTimeout,\r\n keepIframeSrcFn,\r\n });\r\n if (serializedIframeNode) {\r\n onIframeLoad(n, serializedIframeNode);\r\n }\r\n }\r\n }, iframeLoadTimeout);\r\n }\r\n if (serializedNode.type === NodeType.Element &&\r\n serializedNode.tagName === 'link' &&\r\n serializedNode.attributes.rel === 'stylesheet') {\r\n onceStylesheetLoaded(n, () => {\r\n if (onStylesheetLoad) {\r\n const serializedLinkNode = serializeNodeWithId(n, {\r\n doc,\r\n mirror,\r\n blockClass,\r\n blockSelector,\r\n unblockSelector,\r\n maskAllText,\r\n maskTextClass,\r\n unmaskTextClass,\r\n maskTextSelector,\r\n unmaskTextSelector,\r\n skipChild: false,\r\n inlineStylesheet,\r\n maskInputOptions,\r\n maskAttributeFn,\r\n maskTextFn,\r\n maskInputFn,\r\n slimDOMOptions,\r\n dataURLOptions,\r\n inlineImages,\r\n recordCanvas,\r\n preserveWhiteSpace,\r\n onSerialize,\r\n onIframeLoad,\r\n iframeLoadTimeout,\r\n onStylesheetLoad,\r\n stylesheetLoadTimeout,\r\n keepIframeSrcFn,\r\n });\r\n if (serializedLinkNode) {\r\n onStylesheetLoad(n, serializedLinkNode);\r\n }\r\n }\r\n }, stylesheetLoadTimeout);\r\n }\r\n return serializedNode;\r\n}\r\nfunction snapshot(n, options) {\r\n const { mirror = new Mirror(), blockClass = 'rr-block', blockSelector = null, unblockSelector = null, maskAllText = false, maskTextClass = 'rr-mask', unmaskTextClass = null, maskTextSelector = null, unmaskTextSelector = null, inlineStylesheet = true, inlineImages = false, recordCanvas = false, maskAllInputs = false, maskAttributeFn, maskTextFn, maskInputFn, slimDOM = false, dataURLOptions, preserveWhiteSpace, onSerialize, onIframeLoad, iframeLoadTimeout, onStylesheetLoad, stylesheetLoadTimeout, keepIframeSrcFn = () => false, } = options || {};\r\n const maskInputOptions = maskAllInputs === true\r\n ? {\r\n color: true,\r\n date: true,\r\n 'datetime-local': true,\r\n email: true,\r\n month: true,\r\n number: true,\r\n range: true,\r\n search: true,\r\n tel: true,\r\n text: true,\r\n time: true,\r\n url: true,\r\n week: true,\r\n textarea: true,\r\n select: true,\r\n }\r\n : maskAllInputs === false\r\n ? {}\r\n : maskAllInputs;\r\n const slimDOMOptions = slimDOM === true || slimDOM === 'all'\r\n ?\r\n {\r\n script: true,\r\n comment: true,\r\n headFavicon: true,\r\n headWhitespace: true,\r\n headMetaDescKeywords: slimDOM === 'all',\r\n headMetaSocial: true,\r\n headMetaRobots: true,\r\n headMetaHttpEquiv: true,\r\n headMetaAuthorship: true,\r\n headMetaVerification: true,\r\n }\r\n : slimDOM === false\r\n ? {}\r\n : slimDOM;\r\n return serializeNodeWithId(n, {\r\n doc: n,\r\n mirror,\r\n blockClass,\r\n blockSelector,\r\n unblockSelector,\r\n maskAllText,\r\n maskTextClass,\r\n unmaskTextClass,\r\n maskTextSelector,\r\n unmaskTextSelector,\r\n skipChild: false,\r\n inlineStylesheet,\r\n maskInputOptions,\r\n maskAttributeFn,\r\n maskTextFn,\r\n maskInputFn,\r\n slimDOMOptions,\r\n dataURLOptions,\r\n inlineImages,\r\n recordCanvas,\r\n preserveWhiteSpace,\r\n onSerialize,\r\n onIframeLoad,\r\n iframeLoadTimeout,\r\n onStylesheetLoad,\r\n stylesheetLoadTimeout,\r\n keepIframeSrcFn,\r\n newlyAddedElement: false,\r\n });\r\n}\r\n\nconst commentre = /\\/\\*[^*]*\\*+([^/*][^*]*\\*+)*\\//g;\r\nfunction parse(css, options = {}) {\r\n let lineno = 1;\r\n let column = 1;\r\n function updatePosition(str) {\r\n const lines = str.match(/\\n/g);\r\n if (lines) {\r\n lineno += lines.length;\r\n }\r\n const i = str.lastIndexOf('\\n');\r\n column = i === -1 ? column + str.length : str.length - i;\r\n }\r\n function position() {\r\n const start = { line: lineno, column };\r\n return (node) => {\r\n node.position = new Position(start);\r\n whitespace();\r\n return node;\r\n };\r\n }\r\n class Position {\r\n constructor(start) {\r\n this.start = start;\r\n this.end = { line: lineno, column };\r\n this.source = options.source;\r\n }\r\n }\r\n Position.prototype.content = css;\r\n const errorsList = [];\r\n function error(msg) {\r\n const err = new Error(`${options.source || ''}:${lineno}:${column}: ${msg}`);\r\n err.reason = msg;\r\n err.filename = options.source;\r\n err.line = lineno;\r\n err.column = column;\r\n err.source = css;\r\n if (options.silent) {\r\n errorsList.push(err);\r\n }\r\n else {\r\n throw err;\r\n }\r\n }\r\n function stylesheet() {\r\n const rulesList = rules();\r\n return {\r\n type: 'stylesheet',\r\n stylesheet: {\r\n source: options.source,\r\n rules: rulesList,\r\n parsingErrors: errorsList,\r\n },\r\n };\r\n }\r\n function open() {\r\n return match(/^{\\s*/);\r\n }\r\n function close() {\r\n return match(/^}/);\r\n }\r\n function rules() {\r\n let node;\r\n const rules = [];\r\n whitespace();\r\n comments(rules);\r\n while (css.length && css.charAt(0) !== '}' && (node = atrule() || rule())) {\r\n if (node) {\r\n rules.push(node);\r\n comments(rules);\r\n }\r\n }\r\n return rules;\r\n }\r\n function match(re) {\r\n const m = re.exec(css);\r\n if (!m) {\r\n return;\r\n }\r\n const str = m[0];\r\n updatePosition(str);\r\n css = css.slice(str.length);\r\n return m;\r\n }\r\n function whitespace() {\r\n match(/^\\s*/);\r\n }\r\n function comments(rules = []) {\r\n let c;\r\n while ((c = comment())) {\r\n if (c) {\r\n rules.push(c);\r\n }\r\n c = comment();\r\n }\r\n return rules;\r\n }\r\n function comment() {\r\n const pos = position();\r\n if ('/' !== css.charAt(0) || '*' !== css.charAt(1)) {\r\n return;\r\n }\r\n let i = 2;\r\n while ('' !== css.charAt(i) &&\r\n ('*' !== css.charAt(i) || '/' !== css.charAt(i + 1))) {\r\n ++i;\r\n }\r\n i += 2;\r\n if ('' === css.charAt(i - 1)) {\r\n return error('End of comment missing');\r\n }\r\n const str = css.slice(2, i - 2);\r\n column += 2;\r\n updatePosition(str);\r\n css = css.slice(i);\r\n column += 2;\r\n return pos({\r\n type: 'comment',\r\n comment: str,\r\n });\r\n }\r\n function selector() {\r\n whitespace();\r\n while (css[0] == '}') {\r\n error('extra closing bracket');\r\n css = css.slice(1);\r\n whitespace();\r\n }\r\n const m = match(/^((\"(?:\\\\\"|[^\"])*\"|'(?:\\\\'|[^'])*'|[^{])+)/);\r\n if (!m) {\r\n return;\r\n }\r\n const cleanedInput = m[0]\r\n .trim()\r\n .replace(/\\/\\*([^*]|[\\r\\n]|(\\*+([^*/]|[\\r\\n])))*\\*\\/+/g, '')\r\n .replace(/\"(?:\\\\\"|[^\"])*\"|'(?:\\\\'|[^'])*'/g, (m) => {\r\n return m.replace(/,/g, '\\u200C');\r\n });\r\n return customSplit(cleanedInput).map((s) => s.replace(/\\u200C/g, ',').trim());\r\n }\r\n function customSplit(input) {\r\n const result = [];\r\n let currentSegment = '';\r\n let depthParentheses = 0;\r\n let depthBrackets = 0;\r\n let currentStringChar = null;\r\n for (const char of input) {\r\n const hasStringEscape = currentSegment.endsWith('\\\\');\r\n if (currentStringChar) {\r\n if (currentStringChar === char && !hasStringEscape) {\r\n currentStringChar = null;\r\n }\r\n }\r\n else if (char === '(') {\r\n depthParentheses++;\r\n }\r\n else if (char === ')') {\r\n depthParentheses--;\r\n }\r\n else if (char === '[') {\r\n depthBrackets++;\r\n }\r\n else if (char === ']') {\r\n depthBrackets--;\r\n }\r\n else if ('\\'\"'.includes(char)) {\r\n currentStringChar = char;\r\n }\r\n if (char === ',' && depthParentheses === 0 && depthBrackets === 0) {\r\n result.push(currentSegment);\r\n currentSegment = '';\r\n }\r\n else {\r\n currentSegment += char;\r\n }\r\n }\r\n if (currentSegment) {\r\n result.push(currentSegment);\r\n }\r\n return result;\r\n }\r\n function declaration() {\r\n const pos = position();\r\n const propMatch = match(/^(\\*?[-#\\/\\*\\\\\\w]+(\\[[0-9a-z_-]+\\])?)\\s*/);\r\n if (!propMatch) {\r\n return;\r\n }\r\n const prop = trim(propMatch[0]);\r\n if (!match(/^:\\s*/)) {\r\n return error(`property missing ':'`);\r\n }\r\n const val = match(/^((?:'(?:\\\\'|.)*?'|\"(?:\\\\\"|.)*?\"|\\([^\\)]*?\\)|[^};])+)/);\r\n const ret = pos({\r\n type: 'declaration',\r\n property: prop.replace(commentre, ''),\r\n value: val ? trim(val[0]).replace(commentre, '') : '',\r\n });\r\n match(/^[;\\s]*/);\r\n return ret;\r\n }\r\n function declarations() {\r\n const decls = [];\r\n if (!open()) {\r\n return error(`missing '{'`);\r\n }\r\n comments(decls);\r\n let decl;\r\n while ((decl = declaration())) {\r\n if (decl !== false) {\r\n decls.push(decl);\r\n comments(decls);\r\n }\r\n decl = declaration();\r\n }\r\n if (!close()) {\r\n return error(`missing '}'`);\r\n }\r\n return decls;\r\n }\r\n function keyframe() {\r\n let m;\r\n const vals = [];\r\n const pos = position();\r\n while ((m = match(/^((\\d+\\.\\d+|\\.\\d+|\\d+)%?|[a-z]+)\\s*/))) {\r\n vals.push(m[1]);\r\n match(/^,\\s*/);\r\n }\r\n if (!vals.length) {\r\n return;\r\n }\r\n return pos({\r\n type: 'keyframe',\r\n values: vals,\r\n declarations: declarations(),\r\n });\r\n }\r\n function atkeyframes() {\r\n const pos = position();\r\n let m = match(/^@([-\\w]+)?keyframes\\s*/);\r\n if (!m) {\r\n return;\r\n }\r\n const vendor = m[1];\r\n m = match(/^([-\\w]+)\\s*/);\r\n if (!m) {\r\n return error('@keyframes missing name');\r\n }\r\n const name = m[1];\r\n if (!open()) {\r\n return error(`@keyframes missing '{'`);\r\n }\r\n let frame;\r\n let frames = comments();\r\n while ((frame = keyframe())) {\r\n frames.push(frame);\r\n frames = frames.concat(comments());\r\n }\r\n if (!close()) {\r\n return error(`@keyframes missing '}'`);\r\n }\r\n return pos({\r\n type: 'keyframes',\r\n name,\r\n vendor,\r\n keyframes: frames,\r\n });\r\n }\r\n function atsupports() {\r\n const pos = position();\r\n const m = match(/^@supports *([^{]+)/);\r\n if (!m) {\r\n return;\r\n }\r\n const supports = trim(m[1]);\r\n if (!open()) {\r\n return error(`@supports missing '{'`);\r\n }\r\n const style = comments().concat(rules());\r\n if (!close()) {\r\n return error(`@supports missing '}'`);\r\n }\r\n return pos({\r\n type: 'supports',\r\n supports,\r\n rules: style,\r\n });\r\n }\r\n function athost() {\r\n const pos = position();\r\n const m = match(/^@host\\s*/);\r\n if (!m) {\r\n return;\r\n }\r\n if (!open()) {\r\n return error(`@host missing '{'`);\r\n }\r\n const style = comments().concat(rules());\r\n if (!close()) {\r\n return error(`@host missing '}'`);\r\n }\r\n return pos({\r\n type: 'host',\r\n rules: style,\r\n });\r\n }\r\n function atmedia() {\r\n const pos = position();\r\n const m = match(/^@media *([^{]+)/);\r\n if (!m) {\r\n return;\r\n }\r\n const media = trim(m[1]);\r\n if (!open()) {\r\n return error(`@media missing '{'`);\r\n }\r\n const style = comments().concat(rules());\r\n if (!close()) {\r\n return error(`@media missing '}'`);\r\n }\r\n return pos({\r\n type: 'media',\r\n media,\r\n rules: style,\r\n });\r\n }\r\n function atcustommedia() {\r\n const pos = position();\r\n const m = match(/^@custom-media\\s+(--[^\\s]+)\\s*([^{;]+);/);\r\n if (!m) {\r\n return;\r\n }\r\n return pos({\r\n type: 'custom-media',\r\n name: trim(m[1]),\r\n media: trim(m[2]),\r\n });\r\n }\r\n function atpage() {\r\n const pos = position();\r\n const m = match(/^@page */);\r\n if (!m) {\r\n return;\r\n }\r\n const sel = selector() || [];\r\n if (!open()) {\r\n return error(`@page missing '{'`);\r\n }\r\n let decls = comments();\r\n let decl;\r\n while ((decl = declaration())) {\r\n decls.push(decl);\r\n decls = decls.concat(comments());\r\n }\r\n if (!close()) {\r\n return error(`@page missing '}'`);\r\n }\r\n return pos({\r\n type: 'page',\r\n selectors: sel,\r\n declarations: decls,\r\n });\r\n }\r\n function atdocument() {\r\n const pos = position();\r\n const m = match(/^@([-\\w]+)?document *([^{]+)/);\r\n if (!m) {\r\n return;\r\n }\r\n const vendor = trim(m[1]);\r\n const doc = trim(m[2]);\r\n if (!open()) {\r\n return error(`@document missing '{'`);\r\n }\r\n const style = comments().concat(rules());\r\n if (!close()) {\r\n return error(`@document missing '}'`);\r\n }\r\n return pos({\r\n type: 'document',\r\n document: doc,\r\n vendor,\r\n rules: style,\r\n });\r\n }\r\n function atfontface() {\r\n const pos = position();\r\n const m = match(/^@font-face\\s*/);\r\n if (!m) {\r\n return;\r\n }\r\n if (!open()) {\r\n return error(`@font-face missing '{'`);\r\n }\r\n let decls = comments();\r\n let decl;\r\n while ((decl = declaration())) {\r\n decls.push(decl);\r\n decls = decls.concat(comments());\r\n }\r\n if (!close()) {\r\n return error(`@font-face missing '}'`);\r\n }\r\n return pos({\r\n type: 'font-face',\r\n declarations: decls,\r\n });\r\n }\r\n const atimport = _compileAtrule('import');\r\n const atcharset = _compileAtrule('charset');\r\n const atnamespace = _compileAtrule('namespace');\r\n function _compileAtrule(name) {\r\n const re = new RegExp('^@' + name + '\\\\s*([^;]+);');\r\n return () => {\r\n const pos = position();\r\n const m = match(re);\r\n if (!m) {\r\n return;\r\n }\r\n const ret = { type: name };\r\n ret[name] = m[1].trim();\r\n return pos(ret);\r\n };\r\n }\r\n function atrule() {\r\n if (css[0] !== '@') {\r\n return;\r\n }\r\n return (atkeyframes() ||\r\n atmedia() ||\r\n atcustommedia() ||\r\n atsupports() ||\r\n atimport() ||\r\n atcharset() ||\r\n atnamespace() ||\r\n atdocument() ||\r\n atpage() ||\r\n athost() ||\r\n atfontface());\r\n }\r\n function rule() {\r\n const pos = position();\r\n const sel = selector();\r\n if (!sel) {\r\n return error('selector missing');\r\n }\r\n comments();\r\n return pos({\r\n type: 'rule',\r\n selectors: sel,\r\n declarations: declarations(),\r\n });\r\n }\r\n return addParent(stylesheet());\r\n}\r\nfunction trim(str) {\r\n return str ? str.replace(/^\\s+|\\s+$/g, '') : '';\r\n}\r\nfunction addParent(obj, parent) {\r\n const isNode = obj && typeof obj.type === 'string';\r\n const childParent = isNode ? obj : parent;\r\n for (const k of Object.keys(obj)) {\r\n const value = obj[k];\r\n if (Array.isArray(value)) {\r\n value.forEach((v) => {\r\n addParent(v, childParent);\r\n });\r\n }\r\n else if (value && typeof value === 'object') {\r\n addParent(value, childParent);\r\n }\r\n }\r\n if (isNode) {\r\n Object.defineProperty(obj, 'parent', {\r\n configurable: true,\r\n writable: true,\r\n enumerable: false,\r\n value: parent || null,\r\n });\r\n }\r\n return obj;\r\n}\n\nconst tagMap = {\r\n script: 'noscript',\r\n altglyph: 'altGlyph',\r\n altglyphdef: 'altGlyphDef',\r\n altglyphitem: 'altGlyphItem',\r\n animatecolor: 'animateColor',\r\n animatemotion: 'animateMotion',\r\n animatetransform: 'animateTransform',\r\n clippath: 'clipPath',\r\n feblend: 'feBlend',\r\n fecolormatrix: 'feColorMatrix',\r\n fecomponenttransfer: 'feComponentTransfer',\r\n fecomposite: 'feComposite',\r\n feconvolvematrix: 'feConvolveMatrix',\r\n fediffuselighting: 'feDiffuseLighting',\r\n fedisplacementmap: 'feDisplacementMap',\r\n fedistantlight: 'feDistantLight',\r\n fedropshadow: 'feDropShadow',\r\n feflood: 'feFlood',\r\n fefunca: 'feFuncA',\r\n fefuncb: 'feFuncB',\r\n fefuncg: 'feFuncG',\r\n fefuncr: 'feFuncR',\r\n fegaussianblur: 'feGaussianBlur',\r\n feimage: 'feImage',\r\n femerge: 'feMerge',\r\n femergenode: 'feMergeNode',\r\n femorphology: 'feMorphology',\r\n feoffset: 'feOffset',\r\n fepointlight: 'fePointLight',\r\n fespecularlighting: 'feSpecularLighting',\r\n fespotlight: 'feSpotLight',\r\n fetile: 'feTile',\r\n feturbulence: 'feTurbulence',\r\n foreignobject: 'foreignObject',\r\n glyphref: 'glyphRef',\r\n lineargradient: 'linearGradient',\r\n radialgradient: 'radialGradient',\r\n};\r\nfunction getTagName(n) {\r\n let tagName = tagMap[n.tagName] ? tagMap[n.tagName] : n.tagName;\r\n if (tagName === 'link' && n.attributes._cssText) {\r\n tagName = 'style';\r\n }\r\n return tagName;\r\n}\r\nfunction escapeRegExp(str) {\r\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\r\n}\r\nconst HOVER_SELECTOR = /([^\\\\]):hover/;\r\nconst HOVER_SELECTOR_GLOBAL = new RegExp(HOVER_SELECTOR.source, 'g');\r\nfunction addHoverClass(cssText, cache) {\r\n const cachedStyle = cache?.stylesWithHoverClass.get(cssText);\r\n if (cachedStyle)\r\n return cachedStyle;\r\n if (cssText.length >= 1000000) {\r\n return cssText;\r\n }\r\n const ast = parse(cssText, {\r\n silent: true,\r\n });\r\n if (!ast.stylesheet) {\r\n return cssText;\r\n }\r\n const selectors = [];\r\n ast.stylesheet.rules.forEach((rule) => {\r\n if ('selectors' in rule) {\r\n (rule.selectors || []).forEach((selector) => {\r\n if (HOVER_SELECTOR.test(selector)) {\r\n selectors.push(selector);\r\n }\r\n });\r\n }\r\n });\r\n if (selectors.length === 0) {\r\n return cssText;\r\n }\r\n const selectorMatcher = new RegExp(selectors\r\n .filter((selector, index) => selectors.indexOf(selector) === index)\r\n .sort((a, b) => b.length - a.length)\r\n .map((selector) => {\r\n return escapeRegExp(selector);\r\n })\r\n .join('|'), 'g');\r\n const result = cssText.replace(selectorMatcher, (selector) => {\r\n const newSelector = selector.replace(HOVER_SELECTOR_GLOBAL, '$1.\\\\:hover');\r\n return `${selector}, ${newSelector}`;\r\n });\r\n cache?.stylesWithHoverClass.set(cssText, result);\r\n return result;\r\n}\r\nfunction createCache() {\r\n const stylesWithHoverClass = new Map();\r\n return {\r\n stylesWithHoverClass,\r\n };\r\n}\r\nfunction buildNode(n, options) {\r\n const { doc, hackCss, cache } = options;\r\n switch (n.type) {\r\n case NodeType.Document:\r\n return doc.implementation.createDocument(null, '', null);\r\n case NodeType.DocumentType:\r\n return doc.implementation.createDocumentType(n.name || 'html', n.publicId, n.systemId);\r\n case NodeType.Element: {\r\n const tagName = getTagName(n);\r\n let node;\r\n if (n.isSVG) {\r\n node = doc.createElementNS('http://www.w3.org/2000/svg', tagName);\r\n }\r\n else {\r\n if (n.isCustom &&\r\n doc.defaultView?.customElements &&\r\n !doc.defaultView.customElements.get(n.tagName))\r\n doc.defaultView.customElements.define(n.tagName, class extends doc.defaultView.HTMLElement {\r\n });\r\n node = doc.createElement(tagName);\r\n }\r\n const specialAttributes = {};\r\n for (const name in n.attributes) {\r\n if (!Object.prototype.hasOwnProperty.call(n.attributes, name)) {\r\n continue;\r\n }\r\n let value = n.attributes[name];\r\n if (tagName === 'option' &&\r\n name === 'selected' &&\r\n value === false) {\r\n continue;\r\n }\r\n if (value === null) {\r\n continue;\r\n }\r\n if (value === true)\r\n value = '';\r\n if (name.startsWith('rr_')) {\r\n specialAttributes[name] = value;\r\n continue;\r\n }\r\n const isTextarea = tagName === 'textarea' && name === 'value';\r\n const isRemoteOrDynamicCss = tagName === 'style' && name === '_cssText';\r\n if (isRemoteOrDynamicCss && hackCss && typeof value === 'string') {\r\n value = addHoverClass(value, cache);\r\n }\r\n if ((isTextarea || isRemoteOrDynamicCss) && typeof value === 'string') {\r\n const child = doc.createTextNode(value);\r\n for (const c of Array.from(node.childNodes)) {\r\n if (c.nodeType === node.TEXT_NODE) {\r\n node.removeChild(c);\r\n }\r\n }\r\n node.appendChild(child);\r\n continue;\r\n }\r\n try {\r\n if (n.isSVG && name === 'xlink:href') {\r\n node.setAttributeNS('http://www.w3.org/1999/xlink', name, value.toString());\r\n }\r\n else if (name === 'onload' ||\r\n name === 'onclick' ||\r\n name.substring(0, 7) === 'onmouse') {\r\n node.setAttribute('_' + name, value.toString());\r\n }\r\n else if (tagName === 'meta' &&\r\n n.attributes['http-equiv'] === 'Content-Security-Policy' &&\r\n name === 'content') {\r\n node.setAttribute('csp-content', value.toString());\r\n continue;\r\n }\r\n else if (tagName === 'link' &&\r\n (n.attributes.rel === 'preload' ||\r\n n.attributes.rel === 'modulepreload') &&\r\n n.attributes.as === 'script') {\r\n }\r\n else if (tagName === 'link' &&\r\n n.attributes.rel === 'prefetch' &&\r\n typeof n.attributes.href === 'string' &&\r\n n.attributes.href.endsWith('.js')) {\r\n }\r\n else if (tagName === 'img' &&\r\n n.attributes.srcset &&\r\n n.attributes.rr_dataURL) {\r\n node.setAttribute('rrweb-original-srcset', n.attributes.srcset);\r\n }\r\n else {\r\n node.setAttribute(name, value.toString());\r\n }\r\n }\r\n catch (error) {\r\n }\r\n }\r\n for (const name in specialAttributes) {\r\n const value = specialAttributes[name];\r\n if (tagName === 'canvas' && name === 'rr_dataURL') {\r\n const image = document.createElement('img');\r\n image.onload = () => {\r\n const ctx = node.getContext('2d');\r\n if (ctx) {\r\n ctx.drawImage(image, 0, 0, image.width, image.height);\r\n }\r\n };\r\n image.src = value.toString();\r\n if (node.RRNodeType)\r\n node.rr_dataURL = value.toString();\r\n }\r\n else if (tagName === 'img' && name === 'rr_dataURL') {\r\n const image = node;\r\n if (!image.currentSrc.startsWith('data:')) {\r\n image.setAttribute('rrweb-original-src', n.attributes.src);\r\n image.src = value.toString();\r\n }\r\n }\r\n if (name === 'rr_width') {\r\n node.style.setProperty('width', value.toString());\r\n }\r\n else if (name === 'rr_height') {\r\n node.style.setProperty('height', value.toString());\r\n }\r\n else if (name === 'rr_mediaCurrentTime' &&\r\n typeof value === 'number') {\r\n node.currentTime = value;\r\n }\r\n else if (name === 'rr_mediaState') {\r\n switch (value) {\r\n case 'played':\r\n node\r\n .play()\r\n .catch((e) => console.warn('media playback error', e));\r\n break;\r\n case 'paused':\r\n node.pause();\r\n break;\r\n }\r\n }\r\n }\r\n if (n.isShadowHost) {\r\n if (!node.shadowRoot) {\r\n node.attachShadow({ mode: 'open' });\r\n }\r\n else {\r\n while (node.shadowRoot.firstChild) {\r\n node.shadowRoot.removeChild(node.shadowRoot.firstChild);\r\n }\r\n }\r\n }\r\n return node;\r\n }\r\n case NodeType.Text:\r\n return doc.createTextNode(n.isStyle && hackCss\r\n ? addHoverClass(n.textContent, cache)\r\n : n.textContent);\r\n case NodeType.CDATA:\r\n return doc.createCDATASection(n.textContent);\r\n case NodeType.Comment:\r\n return doc.createComment(n.textContent);\r\n default:\r\n return null;\r\n }\r\n}\r\nfunction buildNodeWithSN(n, options) {\r\n const { doc, mirror, skipChild = false, hackCss = true, afterAppend, cache, } = options;\r\n if (mirror.has(n.id)) {\r\n const nodeInMirror = mirror.getNode(n.id);\r\n const meta = mirror.getMeta(nodeInMirror);\r\n if (isNodeMetaEqual(meta, n))\r\n return mirror.getNode(n.id);\r\n }\r\n let node = buildNode(n, { doc, hackCss, cache });\r\n if (!node) {\r\n return null;\r\n }\r\n if (n.rootId && mirror.getNode(n.rootId) !== doc) {\r\n mirror.replace(n.rootId, doc);\r\n }\r\n if (n.type === NodeType.Document) {\r\n doc.close();\r\n doc.open();\r\n if (n.compatMode === 'BackCompat' &&\r\n n.childNodes &&\r\n n.childNodes[0].type !== NodeType.DocumentType) {\r\n if (n.childNodes[0].type === NodeType.Element &&\r\n 'xmlns' in n.childNodes[0].attributes &&\r\n n.childNodes[0].attributes.xmlns === 'http://www.w3.org/1999/xhtml') {\r\n doc.write('');\r\n }\r\n else {\r\n doc.write('');\r\n }\r\n }\r\n node = doc;\r\n }\r\n mirror.add(node, n);\r\n if ((n.type === NodeType.Document || n.type === NodeType.Element) &&\r\n !skipChild) {\r\n for (const childN of n.childNodes) {\r\n const childNode = buildNodeWithSN(childN, {\r\n doc,\r\n mirror,\r\n skipChild: false,\r\n hackCss,\r\n afterAppend,\r\n cache,\r\n });\r\n if (!childNode) {\r\n console.warn('Failed to rebuild', childN);\r\n continue;\r\n }\r\n if (childN.isShadow && isElement(node) && node.shadowRoot) {\r\n node.shadowRoot.appendChild(childNode);\r\n }\r\n else if (n.type === NodeType.Document &&\r\n childN.type == NodeType.Element) {\r\n const htmlElement = childNode;\r\n let body = null;\r\n htmlElement.childNodes.forEach((child) => {\r\n if (child.nodeName === 'BODY')\r\n body = child;\r\n });\r\n if (body) {\r\n htmlElement.removeChild(body);\r\n node.appendChild(childNode);\r\n htmlElement.appendChild(body);\r\n }\r\n else {\r\n node.appendChild(childNode);\r\n }\r\n }\r\n else {\r\n node.appendChild(childNode);\r\n }\r\n if (afterAppend) {\r\n afterAppend(childNode, childN.id);\r\n }\r\n }\r\n }\r\n return node;\r\n}\r\nfunction visit(mirror, onVisit) {\r\n function walk(node) {\r\n onVisit(node);\r\n }\r\n for (const id of mirror.getIds()) {\r\n if (mirror.has(id)) {\r\n walk(mirror.getNode(id));\r\n }\r\n }\r\n}\r\nfunction handleScroll(node, mirror) {\r\n const n = mirror.getMeta(node);\r\n if (n?.type !== NodeType.Element) {\r\n return;\r\n }\r\n const el = node;\r\n for (const name in n.attributes) {\r\n if (!(Object.prototype.hasOwnProperty.call(n.attributes, name) &&\r\n name.startsWith('rr_'))) {\r\n continue;\r\n }\r\n const value = n.attributes[name];\r\n if (name === 'rr_scrollLeft') {\r\n el.scrollLeft = value;\r\n }\r\n if (name === 'rr_scrollTop') {\r\n el.scrollTop = value;\r\n }\r\n }\r\n}\r\nfunction rebuild(n, options) {\r\n const { doc, onVisit, hackCss = true, afterAppend, cache, mirror = new Mirror(), } = options;\r\n const node = buildNodeWithSN(n, {\r\n doc,\r\n mirror,\r\n skipChild: false,\r\n hackCss,\r\n afterAppend,\r\n cache,\r\n });\r\n visit(mirror, (visitedNode) => {\r\n if (onVisit) {\r\n onVisit(visitedNode);\r\n }\r\n handleScroll(visitedNode, mirror);\r\n });\r\n return node;\r\n}\n\nexport { IGNORED_NODE, Mirror, NodeType, addHoverClass, buildNodeWithSN, createCache, createMatchPredicate, createMirror, distanceToMatch, escapeImportStatement, fixSafariColons, genId, getInputType, getInputValue, ignoreAttribute, is2DCanvasBlank, isCSSImportRule, isCSSStyleRule, isElement, isNativeShadowDom, isNodeMetaEqual, isShadowRoot, maskInputValue, needMaskingText, rebuild, serializeNodeWithId, shouldMaskInput, snapshot, stringifyRule, stringifyStylesheet, toLowerCase, toUpperCase, transformAttribute };\n", "import { distanceToMatch, IGNORED_NODE, isShadowRoot, createMatchPredicate } from '../../rrweb-snapshot/es/rrweb-snapshot.js';\n\nfunction on(type, fn, target = document) {\r\n const options = { capture: true, passive: true };\r\n target.addEventListener(type, fn, options);\r\n return () => target.removeEventListener(type, fn, options);\r\n}\r\nconst DEPARTED_MIRROR_ACCESS_WARNING = 'Please stop import mirror directly. Instead of that,' +\r\n '\\r\\n' +\r\n 'now you can use replayer.getMirror() to access the mirror instance of a replayer,' +\r\n '\\r\\n' +\r\n 'or you can use record.mirror to access the mirror instance during recording.';\r\nlet _mirror = {\r\n map: {},\r\n getId() {\r\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\r\n return -1;\r\n },\r\n getNode() {\r\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\r\n return null;\r\n },\r\n removeNodeFromMap() {\r\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\r\n },\r\n has() {\r\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\r\n return false;\r\n },\r\n reset() {\r\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\r\n },\r\n};\r\nif (typeof window !== 'undefined' && window.Proxy && window.Reflect) {\r\n _mirror = new Proxy(_mirror, {\r\n get(target, prop, receiver) {\r\n if (prop === 'map') {\r\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\r\n }\r\n return Reflect.get(target, prop, receiver);\r\n },\r\n });\r\n}\r\nfunction throttle(func, wait, options = {}) {\r\n let timeout = null;\r\n let previous = 0;\r\n return function (...args) {\r\n const now = Date.now();\r\n if (!previous && options.leading === false) {\r\n previous = now;\r\n }\r\n const remaining = wait - (now - previous);\r\n const context = this;\r\n if (remaining <= 0 || remaining > wait) {\r\n if (timeout) {\r\n clearTimeout(timeout);\r\n timeout = null;\r\n }\r\n previous = now;\r\n func.apply(context, args);\r\n }\r\n else if (!timeout && options.trailing !== false) {\r\n timeout = setTimeout(() => {\r\n previous = options.leading === false ? 0 : Date.now();\r\n timeout = null;\r\n func.apply(context, args);\r\n }, remaining);\r\n }\r\n };\r\n}\r\nfunction hookSetter(target, key, d, isRevoked, win = window) {\r\n const original = win.Object.getOwnPropertyDescriptor(target, key);\r\n win.Object.defineProperty(target, key, isRevoked\r\n ? d\r\n : {\r\n set(value) {\r\n setTimeout(() => {\r\n d.set.call(this, value);\r\n }, 0);\r\n if (original && original.set) {\r\n original.set.call(this, value);\r\n }\r\n },\r\n });\r\n return () => hookSetter(target, key, original || {}, true);\r\n}\r\nfunction patch(source, name, replacement) {\r\n try {\r\n if (!(name in source)) {\r\n return () => {\r\n };\r\n }\r\n const original = source[name];\r\n const wrapped = replacement(original);\r\n if (typeof wrapped === 'function') {\r\n wrapped.prototype = wrapped.prototype || {};\r\n Object.defineProperties(wrapped, {\r\n __rrweb_original__: {\r\n enumerable: false,\r\n value: original,\r\n },\r\n });\r\n }\r\n source[name] = wrapped;\r\n return () => {\r\n source[name] = original;\r\n };\r\n }\r\n catch {\r\n return () => {\r\n };\r\n }\r\n}\r\nlet nowTimestamp = Date.now;\r\nif (!(/[1-9][0-9]{12}/.test(Date.now().toString()))) {\r\n nowTimestamp = () => new Date().getTime();\r\n}\r\nfunction getWindowScroll(win) {\r\n const doc = win.document;\r\n return {\r\n left: doc.scrollingElement\r\n ? doc.scrollingElement.scrollLeft\r\n : win.pageXOffset !== undefined\r\n ? win.pageXOffset\r\n : doc?.documentElement.scrollLeft ||\r\n doc?.body?.parentElement?.scrollLeft ||\r\n doc?.body?.scrollLeft ||\r\n 0,\r\n top: doc.scrollingElement\r\n ? doc.scrollingElement.scrollTop\r\n : win.pageYOffset !== undefined\r\n ? win.pageYOffset\r\n : doc?.documentElement.scrollTop ||\r\n doc?.body?.parentElement?.scrollTop ||\r\n doc?.body?.scrollTop ||\r\n 0,\r\n };\r\n}\r\nfunction getWindowHeight() {\r\n return (window.innerHeight ||\r\n (document.documentElement && document.documentElement.clientHeight) ||\r\n (document.body && document.body.clientHeight));\r\n}\r\nfunction getWindowWidth() {\r\n return (window.innerWidth ||\r\n (document.documentElement && document.documentElement.clientWidth) ||\r\n (document.body && document.body.clientWidth));\r\n}\r\nfunction closestElementOfNode(node) {\r\n if (!node) {\r\n return null;\r\n }\r\n const el = node.nodeType === node.ELEMENT_NODE\r\n ? node\r\n : node.parentElement;\r\n return el;\r\n}\r\nfunction isBlocked(node, blockClass, blockSelector, unblockSelector, checkAncestors) {\r\n if (!node) {\r\n return false;\r\n }\r\n const el = closestElementOfNode(node);\r\n if (!el) {\r\n return false;\r\n }\r\n const blockedPredicate = createMatchPredicate(blockClass, blockSelector);\r\n if (!checkAncestors) {\r\n const isUnblocked = unblockSelector && el.matches(unblockSelector);\r\n return blockedPredicate(el) && !isUnblocked;\r\n }\r\n const blockDistance = distanceToMatch(el, blockedPredicate);\r\n let unblockDistance = -1;\r\n if (blockDistance < 0) {\r\n return false;\r\n }\r\n if (unblockSelector) {\r\n unblockDistance = distanceToMatch(el, createMatchPredicate(null, unblockSelector));\r\n }\r\n if (blockDistance > -1 && unblockDistance < 0) {\r\n return true;\r\n }\r\n return blockDistance < unblockDistance;\r\n}\r\nfunction isSerialized(n, mirror) {\r\n return mirror.getId(n) !== -1;\r\n}\r\nfunction isIgnored(n, mirror) {\r\n return mirror.getId(n) === IGNORED_NODE;\r\n}\r\nfunction isAncestorRemoved(target, mirror) {\r\n if (isShadowRoot(target)) {\r\n return false;\r\n }\r\n const id = mirror.getId(target);\r\n if (!mirror.has(id)) {\r\n return true;\r\n }\r\n if (target.parentNode &&\r\n target.parentNode.nodeType === target.DOCUMENT_NODE) {\r\n return false;\r\n }\r\n if (!target.parentNode) {\r\n return true;\r\n }\r\n return isAncestorRemoved(target.parentNode, mirror);\r\n}\r\nfunction legacy_isTouchEvent(event) {\r\n return Boolean(event.changedTouches);\r\n}\r\nfunction polyfill(win = window) {\r\n if ('NodeList' in win && !win.NodeList.prototype.forEach) {\r\n win.NodeList.prototype.forEach = Array.prototype\r\n .forEach;\r\n }\r\n if ('DOMTokenList' in win && !win.DOMTokenList.prototype.forEach) {\r\n win.DOMTokenList.prototype.forEach = Array.prototype\r\n .forEach;\r\n }\r\n if (!Node.prototype.contains) {\r\n Node.prototype.contains = (...args) => {\r\n let node = args[0];\r\n if (!(0 in args)) {\r\n throw new TypeError('1 argument is required');\r\n }\r\n do {\r\n if (this === node) {\r\n return true;\r\n }\r\n } while ((node = node && node.parentNode));\r\n return false;\r\n };\r\n }\r\n}\r\nfunction queueToResolveTrees(queue) {\r\n const queueNodeMap = {};\r\n const putIntoMap = (m, parent) => {\r\n const nodeInTree = {\r\n value: m,\r\n parent,\r\n children: [],\r\n };\r\n queueNodeMap[m.node.id] = nodeInTree;\r\n return nodeInTree;\r\n };\r\n const queueNodeTrees = [];\r\n for (const mutation of queue) {\r\n const { nextId, parentId } = mutation;\r\n if (nextId && nextId in queueNodeMap) {\r\n const nextInTree = queueNodeMap[nextId];\r\n if (nextInTree.parent) {\r\n const idx = nextInTree.parent.children.indexOf(nextInTree);\r\n nextInTree.parent.children.splice(idx, 0, putIntoMap(mutation, nextInTree.parent));\r\n }\r\n else {\r\n const idx = queueNodeTrees.indexOf(nextInTree);\r\n queueNodeTrees.splice(idx, 0, putIntoMap(mutation, null));\r\n }\r\n continue;\r\n }\r\n if (parentId in queueNodeMap) {\r\n const parentInTree = queueNodeMap[parentId];\r\n parentInTree.children.push(putIntoMap(mutation, parentInTree));\r\n continue;\r\n }\r\n queueNodeTrees.push(putIntoMap(mutation, null));\r\n }\r\n return queueNodeTrees;\r\n}\r\nfunction iterateResolveTree(tree, cb) {\r\n cb(tree.value);\r\n for (let i = tree.children.length - 1; i >= 0; i--) {\r\n iterateResolveTree(tree.children[i], cb);\r\n }\r\n}\r\nfunction isSerializedIframe(n, mirror) {\r\n return Boolean(n.nodeName === 'IFRAME' && mirror.getMeta(n));\r\n}\r\nfunction isSerializedStylesheet(n, mirror) {\r\n return Boolean(n.nodeName === 'LINK' &&\r\n n.nodeType === n.ELEMENT_NODE &&\r\n n.getAttribute &&\r\n n.getAttribute('rel') === 'stylesheet' &&\r\n mirror.getMeta(n));\r\n}\r\nfunction getBaseDimension(node, rootIframe) {\r\n const frameElement = node.ownerDocument?.defaultView?.frameElement;\r\n if (!frameElement || frameElement === rootIframe) {\r\n return {\r\n x: 0,\r\n y: 0,\r\n relativeScale: 1,\r\n absoluteScale: 1,\r\n };\r\n }\r\n const frameDimension = frameElement.getBoundingClientRect();\r\n const frameBaseDimension = getBaseDimension(frameElement, rootIframe);\r\n const relativeScale = frameDimension.height / frameElement.clientHeight;\r\n return {\r\n x: frameDimension.x * frameBaseDimension.relativeScale +\r\n frameBaseDimension.x,\r\n y: frameDimension.y * frameBaseDimension.relativeScale +\r\n frameBaseDimension.y,\r\n relativeScale,\r\n absoluteScale: frameBaseDimension.absoluteScale * relativeScale,\r\n };\r\n}\r\nfunction hasShadowRoot(n) {\r\n return Boolean(n?.shadowRoot);\r\n}\r\nfunction getNestedRule(rules, position) {\r\n const rule = rules[position[0]];\r\n if (position.length === 1) {\r\n return rule;\r\n }\r\n else {\r\n return getNestedRule(rule.cssRules[position[1]].cssRules, position.slice(2));\r\n }\r\n}\r\nfunction getPositionsAndIndex(nestedIndex) {\r\n const positions = [...nestedIndex];\r\n const index = positions.pop();\r\n return { positions, index };\r\n}\r\nfunction uniqueTextMutations(mutations) {\r\n const idSet = new Set();\r\n const uniqueMutations = [];\r\n for (let i = mutations.length; i--;) {\r\n const mutation = mutations[i];\r\n if (!idSet.has(mutation.id)) {\r\n uniqueMutations.push(mutation);\r\n idSet.add(mutation.id);\r\n }\r\n }\r\n return uniqueMutations;\r\n}\r\nclass StyleSheetMirror {\r\n constructor() {\r\n this.id = 1;\r\n this.styleIDMap = new WeakMap();\r\n this.idStyleMap = new Map();\r\n }\r\n getId(stylesheet) {\r\n return this.styleIDMap.get(stylesheet) ?? -1;\r\n }\r\n has(stylesheet) {\r\n return this.styleIDMap.has(stylesheet);\r\n }\r\n add(stylesheet, id) {\r\n if (this.has(stylesheet))\r\n return this.getId(stylesheet);\r\n let newId;\r\n if (id === undefined) {\r\n newId = this.id++;\r\n }\r\n else\r\n newId = id;\r\n this.styleIDMap.set(stylesheet, newId);\r\n this.idStyleMap.set(newId, stylesheet);\r\n return newId;\r\n }\r\n getStyle(id) {\r\n return this.idStyleMap.get(id) || null;\r\n }\r\n reset() {\r\n this.styleIDMap = new WeakMap();\r\n this.idStyleMap = new Map();\r\n this.id = 1;\r\n }\r\n generateId() {\r\n return this.id++;\r\n }\r\n}\r\nfunction getShadowHost(n) {\r\n let shadowHost = null;\r\n if (n.getRootNode?.()?.nodeType === Node.DOCUMENT_FRAGMENT_NODE &&\r\n n.getRootNode().host)\r\n shadowHost = n.getRootNode().host;\r\n return shadowHost;\r\n}\r\nfunction getRootShadowHost(n) {\r\n let rootShadowHost = n;\r\n let shadowHost;\r\n while ((shadowHost = getShadowHost(rootShadowHost)))\r\n rootShadowHost = shadowHost;\r\n return rootShadowHost;\r\n}\r\nfunction shadowHostInDom(n) {\r\n const doc = n.ownerDocument;\r\n if (!doc)\r\n return false;\r\n const shadowHost = getRootShadowHost(n);\r\n return doc.contains(shadowHost);\r\n}\r\nfunction inDom(n) {\r\n const doc = n.ownerDocument;\r\n if (!doc)\r\n return false;\r\n return doc.contains(n) || shadowHostInDom(n);\r\n}\r\nconst cachedImplementations = {};\r\nfunction getImplementation(name) {\r\n const cached = cachedImplementations[name];\r\n if (cached) {\r\n return cached;\r\n }\r\n const document = window.document;\r\n let impl = window[name];\r\n if (document && typeof document.createElement === 'function') {\r\n try {\r\n const sandbox = document.createElement('iframe');\r\n sandbox.hidden = true;\r\n document.head.appendChild(sandbox);\r\n const contentWindow = sandbox.contentWindow;\r\n if (contentWindow && contentWindow[name]) {\r\n impl =\r\n contentWindow[name];\r\n }\r\n document.head.removeChild(sandbox);\r\n }\r\n catch (e) {\r\n }\r\n }\r\n return (cachedImplementations[name] = impl.bind(window));\r\n}\r\nfunction onRequestAnimationFrame(...rest) {\r\n return getImplementation('requestAnimationFrame')(...rest);\r\n}\r\nfunction setTimeout(...rest) {\r\n return getImplementation('setTimeout')(...rest);\r\n}\r\nfunction clearTimeout(...rest) {\r\n return getImplementation('clearTimeout')(...rest);\r\n}\n\nexport { StyleSheetMirror, _mirror, clearTimeout, closestElementOfNode, getBaseDimension, getNestedRule, getPositionsAndIndex, getRootShadowHost, getShadowHost, getWindowHeight, getWindowScroll, getWindowWidth, hasShadowRoot, hookSetter, inDom, isAncestorRemoved, isBlocked, isIgnored, isSerialized, isSerializedIframe, isSerializedStylesheet, iterateResolveTree, legacy_isTouchEvent, nowTimestamp, on, onRequestAnimationFrame, patch, polyfill, queueToResolveTrees, setTimeout, shadowHostInDom, throttle, uniqueTextMutations };\n", "var EventType = /* @__PURE__ */ ((EventType2) => {\n EventType2[EventType2[\"DomContentLoaded\"] = 0] = \"DomContentLoaded\";\n EventType2[EventType2[\"Load\"] = 1] = \"Load\";\n EventType2[EventType2[\"FullSnapshot\"] = 2] = \"FullSnapshot\";\n EventType2[EventType2[\"IncrementalSnapshot\"] = 3] = \"IncrementalSnapshot\";\n EventType2[EventType2[\"Meta\"] = 4] = \"Meta\";\n EventType2[EventType2[\"Custom\"] = 5] = \"Custom\";\n EventType2[EventType2[\"Plugin\"] = 6] = \"Plugin\";\n return EventType2;\n})(EventType || {});\nvar IncrementalSource = /* @__PURE__ */ ((IncrementalSource2) => {\n IncrementalSource2[IncrementalSource2[\"Mutation\"] = 0] = \"Mutation\";\n IncrementalSource2[IncrementalSource2[\"MouseMove\"] = 1] = \"MouseMove\";\n IncrementalSource2[IncrementalSource2[\"MouseInteraction\"] = 2] = \"MouseInteraction\";\n IncrementalSource2[IncrementalSource2[\"Scroll\"] = 3] = \"Scroll\";\n IncrementalSource2[IncrementalSource2[\"ViewportResize\"] = 4] = \"ViewportResize\";\n IncrementalSource2[IncrementalSource2[\"Input\"] = 5] = \"Input\";\n IncrementalSource2[IncrementalSource2[\"TouchMove\"] = 6] = \"TouchMove\";\n IncrementalSource2[IncrementalSource2[\"MediaInteraction\"] = 7] = \"MediaInteraction\";\n IncrementalSource2[IncrementalSource2[\"StyleSheetRule\"] = 8] = \"StyleSheetRule\";\n IncrementalSource2[IncrementalSource2[\"CanvasMutation\"] = 9] = \"CanvasMutation\";\n IncrementalSource2[IncrementalSource2[\"Font\"] = 10] = \"Font\";\n IncrementalSource2[IncrementalSource2[\"Log\"] = 11] = \"Log\";\n IncrementalSource2[IncrementalSource2[\"Drag\"] = 12] = \"Drag\";\n IncrementalSource2[IncrementalSource2[\"StyleDeclaration\"] = 13] = \"StyleDeclaration\";\n IncrementalSource2[IncrementalSource2[\"Selection\"] = 14] = \"Selection\";\n IncrementalSource2[IncrementalSource2[\"AdoptedStyleSheet\"] = 15] = \"AdoptedStyleSheet\";\n IncrementalSource2[IncrementalSource2[\"CustomElement\"] = 16] = \"CustomElement\";\n return IncrementalSource2;\n})(IncrementalSource || {});\nvar MouseInteractions = /* @__PURE__ */ ((MouseInteractions2) => {\n MouseInteractions2[MouseInteractions2[\"MouseUp\"] = 0] = \"MouseUp\";\n MouseInteractions2[MouseInteractions2[\"MouseDown\"] = 1] = \"MouseDown\";\n MouseInteractions2[MouseInteractions2[\"Click\"] = 2] = \"Click\";\n MouseInteractions2[MouseInteractions2[\"ContextMenu\"] = 3] = \"ContextMenu\";\n MouseInteractions2[MouseInteractions2[\"DblClick\"] = 4] = \"DblClick\";\n MouseInteractions2[MouseInteractions2[\"Focus\"] = 5] = \"Focus\";\n MouseInteractions2[MouseInteractions2[\"Blur\"] = 6] = \"Blur\";\n MouseInteractions2[MouseInteractions2[\"TouchStart\"] = 7] = \"TouchStart\";\n MouseInteractions2[MouseInteractions2[\"TouchMove_Departed\"] = 8] = \"TouchMove_Departed\";\n MouseInteractions2[MouseInteractions2[\"TouchEnd\"] = 9] = \"TouchEnd\";\n MouseInteractions2[MouseInteractions2[\"TouchCancel\"] = 10] = \"TouchCancel\";\n return MouseInteractions2;\n})(MouseInteractions || {});\nvar PointerTypes = /* @__PURE__ */ ((PointerTypes2) => {\n PointerTypes2[PointerTypes2[\"Mouse\"] = 0] = \"Mouse\";\n PointerTypes2[PointerTypes2[\"Pen\"] = 1] = \"Pen\";\n PointerTypes2[PointerTypes2[\"Touch\"] = 2] = \"Touch\";\n return PointerTypes2;\n})(PointerTypes || {});\nvar CanvasContext = /* @__PURE__ */ ((CanvasContext2) => {\n CanvasContext2[CanvasContext2[\"2D\"] = 0] = \"2D\";\n CanvasContext2[CanvasContext2[\"WebGL\"] = 1] = \"WebGL\";\n CanvasContext2[CanvasContext2[\"WebGL2\"] = 2] = \"WebGL2\";\n return CanvasContext2;\n})(CanvasContext || {});\nvar ReplayerEvents = /* @__PURE__ */ ((ReplayerEvents2) => {\n ReplayerEvents2[\"Start\"] = \"start\";\n ReplayerEvents2[\"Pause\"] = \"pause\";\n ReplayerEvents2[\"Resume\"] = \"resume\";\n ReplayerEvents2[\"Resize\"] = \"resize\";\n ReplayerEvents2[\"Finish\"] = \"finish\";\n ReplayerEvents2[\"FullsnapshotRebuilded\"] = \"fullsnapshot-rebuilded\";\n ReplayerEvents2[\"LoadStylesheetStart\"] = \"load-stylesheet-start\";\n ReplayerEvents2[\"LoadStylesheetEnd\"] = \"load-stylesheet-end\";\n ReplayerEvents2[\"SkipStart\"] = \"skip-start\";\n ReplayerEvents2[\"SkipEnd\"] = \"skip-end\";\n ReplayerEvents2[\"MouseInteraction\"] = \"mouse-interaction\";\n ReplayerEvents2[\"EventCast\"] = \"event-cast\";\n ReplayerEvents2[\"CustomEvent\"] = \"custom-event\";\n ReplayerEvents2[\"Flush\"] = \"flush\";\n ReplayerEvents2[\"StateChange\"] = \"state-change\";\n ReplayerEvents2[\"PlayBack\"] = \"play-back\";\n ReplayerEvents2[\"Destroy\"] = \"destroy\";\n return ReplayerEvents2;\n})(ReplayerEvents || {});\n\nexport { CanvasContext, EventType, IncrementalSource, MouseInteractions, PointerTypes, ReplayerEvents };\n", "let errorHandler;\r\nfunction registerErrorHandler(handler) {\r\n errorHandler = handler;\r\n}\r\nfunction unregisterErrorHandler() {\r\n errorHandler = undefined;\r\n}\r\nconst callbackWrapper = (cb) => {\r\n if (!errorHandler) {\r\n return cb;\r\n }\r\n const rrwebWrapped = ((...rest) => {\r\n try {\r\n return cb(...rest);\r\n }\r\n catch (error) {\r\n if (errorHandler && errorHandler(error) === true) {\r\n return () => {\r\n };\r\n }\r\n throw error;\r\n }\r\n });\r\n return rrwebWrapped;\r\n};\n\nexport { callbackWrapper, registerErrorHandler, unregisterErrorHandler };\n", "/*\n * base64-arraybuffer 1.0.1 \n * Copyright (c) 2021 Niklas von Hertzen \n * Released under MIT License\n */\nvar chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n// Use a lookup table to find the index.\nvar lookup = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256);\nfor (var i = 0; i < chars.length; i++) {\n lookup[chars.charCodeAt(i)] = i;\n}\nvar encode = function (arraybuffer) {\n var bytes = new Uint8Array(arraybuffer), i, len = bytes.length, base64 = '';\n for (i = 0; i < len; i += 3) {\n base64 += chars[bytes[i] >> 2];\n base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];\n base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];\n base64 += chars[bytes[i + 2] & 63];\n }\n if (len % 3 === 2) {\n base64 = base64.substring(0, base64.length - 1) + '=';\n }\n else if (len % 3 === 1) {\n base64 = base64.substring(0, base64.length - 2) + '==';\n }\n return base64;\n};\nvar decode = function (base64) {\n var bufferLength = base64.length * 0.75, len = base64.length, i, p = 0, encoded1, encoded2, encoded3, encoded4;\n if (base64[base64.length - 1] === '=') {\n bufferLength--;\n if (base64[base64.length - 2] === '=') {\n bufferLength--;\n }\n }\n var arraybuffer = new ArrayBuffer(bufferLength), bytes = new Uint8Array(arraybuffer);\n for (i = 0; i < len; i += 4) {\n encoded1 = lookup[base64.charCodeAt(i)];\n encoded2 = lookup[base64.charCodeAt(i + 1)];\n encoded3 = lookup[base64.charCodeAt(i + 2)];\n encoded4 = lookup[base64.charCodeAt(i + 3)];\n bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);\n bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);\n bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);\n }\n return arraybuffer;\n};\n\nexport { decode, encode };\n", "import { encode } from './../../../../../../ext/base64-arraybuffer/dist/base64-arraybuffer.es5.js';\n\nconst canvasVarMap = new Map();\r\nfunction variableListFor(ctx, ctor) {\r\n let contextMap = canvasVarMap.get(ctx);\r\n if (!contextMap) {\r\n contextMap = new Map();\r\n canvasVarMap.set(ctx, contextMap);\r\n }\r\n if (!contextMap.has(ctor)) {\r\n contextMap.set(ctor, []);\r\n }\r\n return contextMap.get(ctor);\r\n}\r\nconst saveWebGLVar = (value, win, ctx) => {\r\n if (!value ||\r\n !(isInstanceOfWebGLObject(value, win) || typeof value === 'object'))\r\n return;\r\n const name = value.constructor.name;\r\n const list = variableListFor(ctx, name);\r\n let index = list.indexOf(value);\r\n if (index === -1) {\r\n index = list.length;\r\n list.push(value);\r\n }\r\n return index;\r\n};\r\nfunction serializeArg(value, win, ctx) {\r\n if (value instanceof Array) {\r\n return value.map((arg) => serializeArg(arg, win, ctx));\r\n }\r\n else if (value === null) {\r\n return value;\r\n }\r\n else if (value instanceof Float32Array ||\r\n value instanceof Float64Array ||\r\n value instanceof Int32Array ||\r\n value instanceof Uint32Array ||\r\n value instanceof Uint8Array ||\r\n value instanceof Uint16Array ||\r\n value instanceof Int16Array ||\r\n value instanceof Int8Array ||\r\n value instanceof Uint8ClampedArray) {\r\n const name = value.constructor.name;\r\n return {\r\n rr_type: name,\r\n args: [Object.values(value)],\r\n };\r\n }\r\n else if (value instanceof ArrayBuffer) {\r\n const name = value.constructor.name;\r\n const base64 = encode(value);\r\n return {\r\n rr_type: name,\r\n base64,\r\n };\r\n }\r\n else if (value instanceof DataView) {\r\n const name = value.constructor.name;\r\n return {\r\n rr_type: name,\r\n args: [\r\n serializeArg(value.buffer, win, ctx),\r\n value.byteOffset,\r\n value.byteLength,\r\n ],\r\n };\r\n }\r\n else if (value instanceof HTMLImageElement) {\r\n const name = value.constructor.name;\r\n const { src } = value;\r\n return {\r\n rr_type: name,\r\n src,\r\n };\r\n }\r\n else if (value instanceof HTMLCanvasElement) {\r\n const name = 'HTMLImageElement';\r\n const src = value.toDataURL();\r\n return {\r\n rr_type: name,\r\n src,\r\n };\r\n }\r\n else if (value instanceof ImageData) {\r\n const name = value.constructor.name;\r\n return {\r\n rr_type: name,\r\n args: [serializeArg(value.data, win, ctx), value.width, value.height],\r\n };\r\n }\r\n else if (isInstanceOfWebGLObject(value, win) || typeof value === 'object') {\r\n const name = value.constructor.name;\r\n const index = saveWebGLVar(value, win, ctx);\r\n return {\r\n rr_type: name,\r\n index: index,\r\n };\r\n }\r\n return value;\r\n}\r\nconst serializeArgs = (args, win, ctx) => {\r\n return args.map((arg) => serializeArg(arg, win, ctx));\r\n};\r\nconst isInstanceOfWebGLObject = (value, win) => {\r\n const webGLConstructorNames = [\r\n 'WebGLActiveInfo',\r\n 'WebGLBuffer',\r\n 'WebGLFramebuffer',\r\n 'WebGLProgram',\r\n 'WebGLRenderbuffer',\r\n 'WebGLShader',\r\n 'WebGLShaderPrecisionFormat',\r\n 'WebGLTexture',\r\n 'WebGLUniformLocation',\r\n 'WebGLVertexArrayObject',\r\n 'WebGLVertexArrayObjectOES',\r\n ];\r\n const supportedWebGLConstructorNames = webGLConstructorNames.filter((name) => typeof win[name] === 'function');\r\n return Boolean(supportedWebGLConstructorNames.find((name) => value instanceof win[name]));\r\n};\n\nexport { isInstanceOfWebGLObject, saveWebGLVar, serializeArg, serializeArgs, variableListFor };\n", "import { CanvasContext } from '../../../../../types/dist/rrweb-types.js';\nimport { patch, isBlocked, setTimeout, hookSetter } from '../../../utils.js';\nimport { serializeArgs } from './serialize-args.js';\n\nfunction initCanvas2DMutationObserver(cb, win, blockClass, blockSelector, unblockSelector) {\r\n const handlers = [];\r\n const props2D = Object.getOwnPropertyNames(win.CanvasRenderingContext2D.prototype);\r\n for (const prop of props2D) {\r\n try {\r\n if (typeof win.CanvasRenderingContext2D.prototype[prop] !== 'function') {\r\n continue;\r\n }\r\n const restoreHandler = patch(win.CanvasRenderingContext2D.prototype, prop, function (original) {\r\n return function (...args) {\r\n if (!isBlocked(this.canvas, blockClass, blockSelector, unblockSelector, true)) {\r\n setTimeout(() => {\r\n const recordArgs = serializeArgs(args, win, this);\r\n cb(this.canvas, {\r\n type: CanvasContext['2D'],\r\n property: prop,\r\n args: recordArgs,\r\n });\r\n }, 0);\r\n }\r\n return original.apply(this, args);\r\n };\r\n });\r\n handlers.push(restoreHandler);\r\n }\r\n catch {\r\n const hookHandler = hookSetter(win.CanvasRenderingContext2D.prototype, prop, {\r\n set(v) {\r\n cb(this.canvas, {\r\n type: CanvasContext['2D'],\r\n property: prop,\r\n args: [v],\r\n setter: true,\r\n });\r\n },\r\n });\r\n handlers.push(hookHandler);\r\n }\r\n }\r\n return () => {\r\n handlers.forEach((h) => h());\r\n };\r\n}\n\nexport { initCanvas2DMutationObserver as default };\n", "import { patch, isBlocked } from '../../../utils.js';\n\nfunction getNormalizedContextName(contextType) {\r\n return contextType === 'experimental-webgl' ? 'webgl' : contextType;\r\n}\r\nfunction initCanvasContextObserver(win, blockClass, blockSelector, unblockSelector, setPreserveDrawingBufferToTrue) {\r\n const handlers = [];\r\n try {\r\n const restoreHandler = patch(win.HTMLCanvasElement.prototype, 'getContext', function (original) {\r\n return function (contextType, ...args) {\r\n if (!isBlocked(this, blockClass, blockSelector, unblockSelector, true)) {\r\n const ctxName = getNormalizedContextName(contextType);\r\n if (!('__context' in this))\r\n this.__context = ctxName;\r\n if (setPreserveDrawingBufferToTrue &&\r\n ['webgl', 'webgl2'].includes(ctxName)) {\r\n if (args[0] && typeof args[0] === 'object') {\r\n const contextAttributes = args[0];\r\n if (!contextAttributes.preserveDrawingBuffer) {\r\n contextAttributes.preserveDrawingBuffer = true;\r\n }\r\n }\r\n else {\r\n args.splice(0, 1, {\r\n preserveDrawingBuffer: true,\r\n });\r\n }\r\n }\r\n }\r\n return original.apply(this, [contextType, ...args]);\r\n };\r\n });\r\n handlers.push(restoreHandler);\r\n }\r\n catch {\r\n console.error('failed to patch HTMLCanvasElement.prototype.getContext');\r\n }\r\n return () => {\r\n handlers.forEach((h) => h());\r\n };\r\n}\n\nexport { initCanvasContextObserver as default };\n", "import { CanvasContext } from '../../../../../types/dist/rrweb-types.js';\nimport { patch, isBlocked, hookSetter } from '../../../utils.js';\nimport { saveWebGLVar, serializeArgs } from './serialize-args.js';\n\nfunction patchGLPrototype(prototype, type, cb, blockClass, blockSelector, unblockSelector, mirror, win) {\r\n const handlers = [];\r\n const props = Object.getOwnPropertyNames(prototype);\r\n for (const prop of props) {\r\n if ([\r\n 'isContextLost',\r\n 'canvas',\r\n 'drawingBufferWidth',\r\n 'drawingBufferHeight',\r\n ].includes(prop)) {\r\n continue;\r\n }\r\n try {\r\n if (typeof prototype[prop] !== 'function') {\r\n continue;\r\n }\r\n const restoreHandler = patch(prototype, prop, function (original) {\r\n return function (...args) {\r\n const result = original.apply(this, args);\r\n saveWebGLVar(result, win, this);\r\n if ('tagName' in this.canvas &&\r\n !isBlocked(this.canvas, blockClass, blockSelector, unblockSelector, true)) {\r\n const recordArgs = serializeArgs(args, win, this);\r\n const mutation = {\r\n type,\r\n property: prop,\r\n args: recordArgs,\r\n };\r\n cb(this.canvas, mutation);\r\n }\r\n return result;\r\n };\r\n });\r\n handlers.push(restoreHandler);\r\n }\r\n catch {\r\n const hookHandler = hookSetter(prototype, prop, {\r\n set(v) {\r\n cb(this.canvas, {\r\n type,\r\n property: prop,\r\n args: [v],\r\n setter: true,\r\n });\r\n },\r\n });\r\n handlers.push(hookHandler);\r\n }\r\n }\r\n return handlers;\r\n}\r\nfunction initCanvasWebGLMutationObserver(cb, win, blockClass, blockSelector, unblockSelector, mirror) {\r\n const handlers = [];\r\n handlers.push(...patchGLPrototype(win.WebGLRenderingContext.prototype, CanvasContext.WebGL, cb, blockClass, blockSelector, unblockSelector, mirror, win));\r\n if (typeof win.WebGL2RenderingContext !== 'undefined') {\r\n handlers.push(...patchGLPrototype(win.WebGL2RenderingContext.prototype, CanvasContext.WebGL2, cb, blockClass, blockSelector, unblockSelector, mirror, win));\r\n }\r\n return () => {\r\n handlers.forEach((h) => h());\r\n };\r\n}\n\nexport { initCanvasWebGLMutationObserver as default };\n", "var r = `for(var e=\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\",t=\"undefined\"==typeof Uint8Array?[]:new Uint8Array(256),a=0;a<64;a++)t[e.charCodeAt(a)]=a;var n=function(t){var a,n=new Uint8Array(t),r=n.length,s=\"\";for(a=0;a>2],s+=e[(3&n[a])<<4|n[a+1]>>4],s+=e[(15&n[a+1])<<2|n[a+2]>>6],s+=e[63&n[a+2]];return r%3==2?s=s.substring(0,s.length-1)+\"=\":r%3==1&&(s=s.substring(0,s.length-2)+\"==\"),s};const r=new Map,s=new Map;const i=self;i.onmessage=async function(e){if(!(\"OffscreenCanvas\"in globalThis))return i.postMessage({id:e.data.id});{const{id:t,bitmap:a,width:o,height:f,maxCanvasSize:c,dataURLOptions:g}=e.data,u=async function(e,t,a){const r=e+\"-\"+t;if(\"OffscreenCanvas\"in globalThis){if(s.has(r))return s.get(r);const i=new OffscreenCanvas(e,t);i.getContext(\"2d\");const o=await i.convertToBlob(a),f=await o.arrayBuffer(),c=n(f);return s.set(r,c),c}return\"\"}(o,f,g),[h,d]=function(e,t,a){if(!a)return[e,t];const[n,r]=a;if(e<=n&&t<=r)return[e,t];let s=e,i=t;return s>n&&(i=Math.floor(n*t/e),s=n),i>r&&(s=Math.floor(r*e/t),i=r),[s,i]}(o,f,c),l=new OffscreenCanvas(h,d),w=l.getContext(\"bitmaprenderer\"),p=h===o&&d===f?a:await createImageBitmap(a,{resizeWidth:h,resizeHeight:d,resizeQuality:\"low\"});w.transferFromImageBitmap(p),a.close();const y=await l.convertToBlob(g),v=y.type,b=await y.arrayBuffer(),m=n(b);if(p.close(),!r.has(t)&&await u===m)return r.set(t,m),i.postMessage({id:t});if(r.get(t)===m)return i.postMessage({id:t});i.postMessage({id:t,type:v,base64:m,width:o,height:f}),r.set(t,m)}};`;\n\nexport { r as default };\n", "import r from './image-bitmap-data-url-worker.js';\n\nfunction t(){const t=new Blob([r]);return URL.createObjectURL(t)}\n\nexport { t as getImageBitmapDataUrlWorkerURL };\n", "import { onRequestAnimationFrame, isBlocked } from '../../../utils.js';\nimport { CanvasContext } from '../../../../../types/dist/rrweb-types.js';\nimport initCanvas2DMutationObserver from './2d.js';\nimport initCanvasContextObserver from './canvas.js';\nimport initCanvasWebGLMutationObserver from './webgl.js';\nimport { getImageBitmapDataUrlWorkerURL as t } from '../../../../../rrweb-worker/es/rrweb-worker/index.js';\nimport { callbackWrapper, registerErrorHandler } from '../../error-handler.js';\n\nclass CanvasManagerNoop {\r\n reset() {\r\n }\r\n freeze() {\r\n }\r\n unfreeze() {\r\n }\r\n lock() {\r\n }\r\n unlock() {\r\n }\r\n snapshot() {\r\n }\r\n}\r\nclass CanvasManager {\r\n reset() {\r\n this.pendingCanvasMutations.clear();\r\n this.resetObservers && this.resetObservers();\r\n }\r\n freeze() {\r\n this.frozen = true;\r\n }\r\n unfreeze() {\r\n this.frozen = false;\r\n }\r\n lock() {\r\n this.locked = true;\r\n }\r\n unlock() {\r\n this.locked = false;\r\n }\r\n constructor(options) {\r\n this.pendingCanvasMutations = new Map();\r\n this.rafStamps = { latestId: 0, invokeId: null };\r\n this.frozen = false;\r\n this.locked = false;\r\n this.processMutation = (target, mutation) => {\r\n const newFrame = this.rafStamps.invokeId &&\r\n this.rafStamps.latestId !== this.rafStamps.invokeId;\r\n if (newFrame || !this.rafStamps.invokeId)\r\n this.rafStamps.invokeId = this.rafStamps.latestId;\r\n if (!this.pendingCanvasMutations.has(target)) {\r\n this.pendingCanvasMutations.set(target, []);\r\n }\r\n this.pendingCanvasMutations.get(target).push(mutation);\r\n };\r\n const { sampling = 'all', win, blockClass, blockSelector, unblockSelector, maxCanvasSize, recordCanvas, dataURLOptions, errorHandler, } = options;\r\n this.mutationCb = options.mutationCb;\r\n this.mirror = options.mirror;\r\n this.options = options;\r\n if (errorHandler) {\r\n registerErrorHandler(errorHandler);\r\n }\r\n if (options.enableManualSnapshot) {\r\n return;\r\n }\r\n callbackWrapper(() => {\r\n if (recordCanvas && sampling === 'all')\r\n this.initCanvasMutationObserver(win, blockClass, blockSelector, unblockSelector);\r\n if (recordCanvas && typeof sampling === 'number')\r\n this.initCanvasFPSObserver(sampling, win, blockClass, blockSelector, unblockSelector, maxCanvasSize, {\r\n dataURLOptions,\r\n });\r\n })();\r\n }\r\n initCanvasFPSObserver(fps, win, blockClass, blockSelector, unblockSelector, maxCanvasSize, options) {\r\n const canvasContextReset = initCanvasContextObserver(win, blockClass, blockSelector, unblockSelector, true);\r\n const rafId = this.takeSnapshot(false, fps, win, blockClass, blockSelector, unblockSelector, maxCanvasSize, options.dataURLOptions);\r\n this.resetObservers = () => {\r\n canvasContextReset();\r\n cancelAnimationFrame(rafId);\r\n };\r\n }\r\n initCanvasMutationObserver(win, blockClass, blockSelector, unblockSelector) {\r\n this.startRAFTimestamping();\r\n this.startPendingCanvasMutationFlusher();\r\n const canvasContextReset = initCanvasContextObserver(win, blockClass, blockSelector, unblockSelector, false);\r\n const canvas2DReset = initCanvas2DMutationObserver(this.processMutation.bind(this), win, blockClass, blockSelector, unblockSelector);\r\n const canvasWebGL1and2Reset = initCanvasWebGLMutationObserver(this.processMutation.bind(this), win, blockClass, blockSelector, unblockSelector, this.mirror);\r\n this.resetObservers = () => {\r\n canvasContextReset();\r\n canvas2DReset();\r\n canvasWebGL1and2Reset();\r\n };\r\n }\r\n snapshot(canvasElement) {\r\n const { options } = this;\r\n const rafId = this.takeSnapshot(true, options.sampling === 'all' ? 2 : options.sampling || 2, options.win, options.blockClass, options.blockSelector, options.unblockSelector, options.maxCanvasSize, options.dataURLOptions, canvasElement);\r\n this.resetObservers = () => {\r\n cancelAnimationFrame(rafId);\r\n };\r\n }\r\n takeSnapshot(isManualSnapshot, fps, win, blockClass, blockSelector, unblockSelector, maxCanvasSize, dataURLOptions, canvasElement) {\r\n const snapshotInProgressMap = new Map();\r\n const worker = new Worker(t());\r\n worker.onmessage = (e) => {\r\n const data = e.data;\r\n const { id } = data;\r\n snapshotInProgressMap.set(id, false);\r\n if (!('base64' in data))\r\n return;\r\n const { base64, type, width, height } = data;\r\n this.mutationCb({\r\n id,\r\n type: CanvasContext['2D'],\r\n commands: [\r\n {\r\n property: 'clearRect',\r\n args: [0, 0, width, height],\r\n },\r\n {\r\n property: 'drawImage',\r\n args: [\r\n {\r\n rr_type: 'ImageBitmap',\r\n args: [\r\n {\r\n rr_type: 'Blob',\r\n data: [{ rr_type: 'ArrayBuffer', base64 }],\r\n type,\r\n },\r\n ],\r\n },\r\n 0,\r\n 0,\r\n width,\r\n height,\r\n ],\r\n },\r\n ],\r\n });\r\n };\r\n const timeBetweenSnapshots = 1000 / fps;\r\n let lastSnapshotTime = 0;\r\n let rafId;\r\n const getCanvas = (canvasElement) => {\r\n if (canvasElement) {\r\n return [canvasElement];\r\n }\r\n const matchedCanvas = [];\r\n win.document.querySelectorAll('canvas').forEach((canvas) => {\r\n if (!isBlocked(canvas, blockClass, blockSelector, unblockSelector, true)) {\r\n matchedCanvas.push(canvas);\r\n }\r\n });\r\n return matchedCanvas;\r\n };\r\n const takeCanvasSnapshots = (timestamp) => {\r\n if (lastSnapshotTime &&\r\n timestamp - lastSnapshotTime < timeBetweenSnapshots) {\r\n rafId = onRequestAnimationFrame(takeCanvasSnapshots);\r\n return;\r\n }\r\n lastSnapshotTime = timestamp;\r\n getCanvas(canvasElement).forEach((canvas) => {\r\n const id = this.mirror.getId(canvas);\r\n if (snapshotInProgressMap.get(id))\r\n return;\r\n if (!canvas.width || !canvas.height)\r\n return;\r\n snapshotInProgressMap.set(id, true);\r\n if (!isManualSnapshot &&\r\n ['webgl', 'webgl2'].includes(canvas.__context)) {\r\n const context = canvas.getContext(canvas.__context);\r\n if (context?.getContextAttributes()?.preserveDrawingBuffer === false) {\r\n context.clear(context.COLOR_BUFFER_BIT);\r\n }\r\n }\r\n createImageBitmap(canvas)\r\n .then((bitmap) => {\r\n worker.postMessage({\r\n id,\r\n bitmap,\r\n width: canvas.width,\r\n height: canvas.height,\r\n dataURLOptions,\r\n maxCanvasSize,\r\n }, [bitmap]);\r\n })\r\n .catch((error) => {\r\n callbackWrapper(() => {\r\n throw error;\r\n })();\r\n });\r\n });\r\n rafId = onRequestAnimationFrame(takeCanvasSnapshots);\r\n };\r\n rafId = onRequestAnimationFrame(takeCanvasSnapshots);\r\n return rafId;\r\n }\r\n startPendingCanvasMutationFlusher() {\r\n onRequestAnimationFrame(() => this.flushPendingCanvasMutations());\r\n }\r\n startRAFTimestamping() {\r\n const setLatestRAFTimestamp = (timestamp) => {\r\n this.rafStamps.latestId = timestamp;\r\n onRequestAnimationFrame(setLatestRAFTimestamp);\r\n };\r\n onRequestAnimationFrame(setLatestRAFTimestamp);\r\n }\r\n flushPendingCanvasMutations() {\r\n this.pendingCanvasMutations.forEach((values, canvas) => {\r\n const id = this.mirror.getId(canvas);\r\n this.flushPendingCanvasMutationFor(canvas, id);\r\n });\r\n onRequestAnimationFrame(() => this.flushPendingCanvasMutations());\r\n }\r\n flushPendingCanvasMutationFor(canvas, id) {\r\n if (this.frozen || this.locked) {\r\n return;\r\n }\r\n const valuesWithType = this.pendingCanvasMutations.get(canvas);\r\n if (!valuesWithType || id === -1)\r\n return;\r\n const values = valuesWithType.map((value) => {\r\n const { type, ...rest } = value;\r\n return rest;\r\n });\r\n const { type } = valuesWithType[0];\r\n this.mutationCb({ id, type, commands: values });\r\n this.pendingCanvasMutations.delete(canvas);\r\n }\r\n}\n\nexport { CanvasManager, CanvasManagerNoop };\n", "import { CanvasManager } from '@sentry-internal/rrweb';\nimport { convertIntegrationFnToClass, defineIntegration } from '@sentry/core';\nimport type { InternalCanvasManagerInterface, InternalCanvasManagerOptions } from '@sentry/replay';\nimport type { Integration, IntegrationClass, IntegrationFn } from '@sentry/types';\n\ninterface ReplayCanvasOptions {\n enableManualSnapshot?: boolean;\n maxCanvasSize?: [width: number, height: number];\n quality: 'low' | 'medium' | 'high';\n}\n\ntype GetCanvasManager = (options: InternalCanvasManagerOptions) => InternalCanvasManagerInterface;\nexport interface ReplayCanvasIntegrationOptions {\n enableManualSnapshot?: boolean;\n maxCanvasSize?: number;\n recordCanvas: true;\n getCanvasManager: GetCanvasManager;\n sampling: {\n canvas: number;\n };\n dataURLOptions: {\n type: string;\n quality: number;\n };\n}\n\nconst CANVAS_QUALITY = {\n low: {\n sampling: {\n canvas: 1,\n },\n dataURLOptions: {\n type: 'image/webp',\n quality: 0.25,\n },\n },\n medium: {\n sampling: {\n canvas: 2,\n },\n dataURLOptions: {\n type: 'image/webp',\n quality: 0.4,\n },\n },\n high: {\n sampling: {\n canvas: 4,\n },\n dataURLOptions: {\n type: 'image/webp',\n quality: 0.5,\n },\n },\n};\n\nconst INTEGRATION_NAME = 'ReplayCanvas';\nconst DEFAULT_MAX_CANVAS_SIZE = 1280;\n\n/** Exported only for type safe tests. */\nexport const _replayCanvasIntegration = ((options: Partial = {}) => {\n const [maxCanvasWidth, maxCanvasHeight] = options.maxCanvasSize || [];\n const _canvasOptions = {\n quality: options.quality || 'medium',\n enableManualSnapshot: options.enableManualSnapshot,\n maxCanvasSize: [\n maxCanvasWidth ? Math.min(maxCanvasWidth, DEFAULT_MAX_CANVAS_SIZE) : DEFAULT_MAX_CANVAS_SIZE,\n maxCanvasHeight ? Math.min(maxCanvasHeight, DEFAULT_MAX_CANVAS_SIZE) : DEFAULT_MAX_CANVAS_SIZE,\n ] as [number, number],\n };\n\n let canvasManagerResolve: (value: CanvasManager) => void;\n const _canvasManager: Promise = new Promise(resolve => (canvasManagerResolve = resolve));\n\n return {\n name: INTEGRATION_NAME,\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n setupOnce() {},\n getOptions(): ReplayCanvasIntegrationOptions {\n const { quality, enableManualSnapshot, maxCanvasSize } = _canvasOptions;\n\n return {\n enableManualSnapshot,\n recordCanvas: true,\n getCanvasManager: (getCanvasManagerOptions: InternalCanvasManagerOptions) => {\n const manager = new CanvasManager({\n ...getCanvasManagerOptions,\n enableManualSnapshot,\n maxCanvasSize,\n errorHandler: (err: unknown) => {\n try {\n if (typeof err === 'object') {\n (err as Error & { __rrweb__?: boolean }).__rrweb__ = true;\n }\n } catch (error) {\n // ignore errors here\n // this can happen if the error is frozen or does not allow mutation for other reasons\n }\n },\n });\n canvasManagerResolve(manager);\n return manager;\n },\n ...(CANVAS_QUALITY[quality || 'medium'] || CANVAS_QUALITY.medium),\n };\n },\n async snapshot(canvasElement?: HTMLCanvasElement) {\n const canvasManager = await _canvasManager;\n canvasManager.snapshot(canvasElement);\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * Add this in addition to `replayIntegration()` to enable canvas recording.\n */\nexport const replayCanvasIntegration = defineIntegration(_replayCanvasIntegration);\n\n/**\n * @deprecated Use `replayCanvasIntegration()` instead\n */\n// eslint-disable-next-line deprecation/deprecation\nexport const ReplayCanvas = convertIntegrationFnToClass(INTEGRATION_NAME, replayCanvasIntegration) as IntegrationClass<\n Integration & {\n getOptions: () => ReplayCanvasIntegrationOptions;\n }\n>;\n", "import { GLOBAL_OBJ } from '@sentry/utils';\n\n// exporting a separate copy of `WINDOW` rather than exporting the one from `@sentry/browser`\n// prevents the browser package from being bundled in the CDN bundle, and avoids a\n// circular dependency between the browser and feedback packages\nexport const WINDOW = GLOBAL_OBJ as typeof GLOBAL_OBJ & Window;\n\nconst LIGHT_BACKGROUND = '#ffffff';\nconst INHERIT = 'inherit';\nconst SUBMIT_COLOR = 'rgba(108, 95, 199, 1)';\nconst LIGHT_THEME = {\n fontFamily: \"system-ui, 'Helvetica Neue', Arial, sans-serif\",\n fontSize: '14px',\n\n background: LIGHT_BACKGROUND,\n backgroundHover: '#f6f6f7',\n foreground: '#2b2233',\n border: '1.5px solid rgba(41, 35, 47, 0.13)',\n borderRadius: '25px',\n boxShadow: '0px 4px 24px 0px rgba(43, 34, 51, 0.12)',\n\n success: '#268d75',\n error: '#df3338',\n\n submitBackground: 'rgba(88, 74, 192, 1)',\n submitBackgroundHover: SUBMIT_COLOR,\n submitBorder: SUBMIT_COLOR,\n submitOutlineFocus: '#29232f',\n submitForeground: LIGHT_BACKGROUND,\n submitForegroundHover: LIGHT_BACKGROUND,\n\n cancelBackground: 'transparent',\n cancelBackgroundHover: 'var(--background-hover)',\n cancelBorder: 'var(--border)',\n cancelOutlineFocus: 'var(--input-outline-focus)',\n cancelForeground: 'var(--foreground)',\n cancelForegroundHover: 'var(--foreground)',\n\n inputBackground: INHERIT,\n inputForeground: INHERIT,\n inputBorder: 'var(--border)',\n inputOutlineFocus: SUBMIT_COLOR,\n\n formBorderRadius: '20px',\n formContentBorderRadius: '6px',\n};\n\nexport const DEFAULT_THEME = {\n light: LIGHT_THEME,\n dark: {\n ...LIGHT_THEME,\n\n background: '#29232f',\n backgroundHover: '#352f3b',\n foreground: '#ebe6ef',\n border: '1.5px solid rgba(235, 230, 239, 0.15)',\n\n success: '#2da98c',\n error: '#f55459',\n },\n};\n\nexport const ACTOR_LABEL = 'Report a Bug';\nexport const CANCEL_BUTTON_LABEL = 'Cancel';\nexport const SUBMIT_BUTTON_LABEL = 'Send Bug Report';\nexport const FORM_TITLE = 'Report a Bug';\nexport const EMAIL_PLACEHOLDER = 'your.email@example.org';\nexport const EMAIL_LABEL = 'Email';\nexport const MESSAGE_PLACEHOLDER = \"What's the bug? What did you expect?\";\nexport const MESSAGE_LABEL = 'Description';\nexport const NAME_PLACEHOLDER = 'Your Name';\nexport const NAME_LABEL = 'Name';\nexport const IS_REQUIRED_LABEL = '(required)';\nexport const SUCCESS_MESSAGE_TEXT = 'Thank you for your report!';\n\nexport const FEEDBACK_WIDGET_SOURCE = 'widget';\nexport const FEEDBACK_API_SOURCE = 'api';\n", "import type { Scope } from '@sentry/core';\nimport { getIsolationScope } from '@sentry/core';\nimport { prepareEvent } from '@sentry/core';\nimport type { Client, FeedbackEvent } from '@sentry/types';\n\ninterface PrepareFeedbackEventParams {\n client: Client;\n event: FeedbackEvent;\n scope: Scope;\n}\n/**\n * Prepare a feedback event & enrich it with the SDK metadata.\n */\nexport async function prepareFeedbackEvent({\n client,\n scope,\n event,\n}: PrepareFeedbackEventParams): Promise {\n const eventHint = {};\n if (client.emit) {\n client.emit('preprocessEvent', event, eventHint);\n }\n\n const preparedEvent = (await prepareEvent(\n client.getOptions(),\n event,\n eventHint,\n scope,\n client,\n getIsolationScope(),\n )) as FeedbackEvent | null;\n\n if (preparedEvent === null) {\n // Taken from baseclient's `_processEvent` method, where this is handled for errors/transactions\n client.recordDroppedEvent('event_processor', 'feedback', event);\n return null;\n }\n\n // This normally happens in browser client \"_prepareEvent\"\n // but since we do not use this private method from the client, but rather the plain import\n // we need to do this manually.\n preparedEvent.platform = preparedEvent.platform || 'javascript';\n\n return preparedEvent;\n}\n", "import { createEventEnvelope, getClient, withScope } from '@sentry/core';\nimport type { FeedbackEvent, TransportMakeRequestResponse } from '@sentry/types';\n\nimport { FEEDBACK_API_SOURCE, FEEDBACK_WIDGET_SOURCE } from '../constants';\nimport type { SendFeedbackData, SendFeedbackOptions } from '../types';\nimport { prepareFeedbackEvent } from './prepareFeedbackEvent';\n\n/**\n * Send feedback using transport\n */\nexport async function sendFeedbackRequest(\n { feedback: { message, email, name, source, url } }: SendFeedbackData,\n { includeReplay = true }: SendFeedbackOptions = {},\n): Promise {\n const client = getClient();\n const transport = client && client.getTransport();\n const dsn = client && client.getDsn();\n\n if (!client || !transport || !dsn) {\n return;\n }\n\n const baseEvent: FeedbackEvent = {\n contexts: {\n feedback: {\n contact_email: email,\n name,\n message,\n url,\n source,\n },\n },\n type: 'feedback',\n };\n\n return withScope(async scope => {\n // No use for breadcrumbs in feedback\n scope.clearBreadcrumbs();\n\n if ([FEEDBACK_API_SOURCE, FEEDBACK_WIDGET_SOURCE].includes(String(source))) {\n scope.setLevel('info');\n }\n\n const feedbackEvent = await prepareFeedbackEvent({\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n scope: scope as any,\n client,\n event: baseEvent,\n });\n\n if (!feedbackEvent) {\n return;\n }\n\n if (client.emit) {\n client.emit('beforeSendFeedback', feedbackEvent, { includeReplay: Boolean(includeReplay) });\n }\n\n const envelope = createEventEnvelope(feedbackEvent, dsn, client.getOptions()._metadata, client.getOptions().tunnel);\n\n let response: void | TransportMakeRequestResponse;\n\n try {\n response = await transport.send(envelope);\n } catch (err) {\n const error = new Error('Unable to send Feedback');\n\n try {\n // In case browsers don't allow this property to be writable\n // @ts-expect-error This needs lib es2022 and newer\n error.cause = err;\n } catch {\n // nothing to do\n }\n throw error;\n }\n\n // TODO (v8): we can remove this guard once transport.send's type signature doesn't include void anymore\n if (!response) {\n return;\n }\n\n // Require valid status codes, otherwise can assume feedback was not sent successfully\n if (typeof response.statusCode === 'number' && (response.statusCode < 200 || response.statusCode >= 300)) {\n throw new Error('Unable to send Feedback');\n }\n\n return response;\n });\n}\n\n/*\n * For reference, the fully built event looks something like this:\n * {\n * \"type\": \"feedback\",\n * \"event_id\": \"d2132d31b39445f1938d7e21b6bf0ec4\",\n * \"timestamp\": 1597977777.6189718,\n * \"dist\": \"1.12\",\n * \"platform\": \"javascript\",\n * \"environment\": \"production\",\n * \"release\": 42,\n * \"tags\": {\"transaction\": \"/organizations/:orgId/performance/:eventSlug/\"},\n * \"sdk\": {\"name\": \"name\", \"version\": \"version\"},\n * \"user\": {\n * \"id\": \"123\",\n * \"username\": \"user\",\n * \"email\": \"user@site.com\",\n * \"ip_address\": \"192.168.11.12\",\n * },\n * \"request\": {\n * \"url\": None,\n * \"headers\": {\n * \"user-Agent\": \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.5 Safari/605.1.15\"\n * },\n * },\n * \"contexts\": {\n * \"feedback\": {\n * \"message\": \"test message\",\n * \"contact_email\": \"test@example.com\",\n * \"type\": \"feedback\",\n * },\n * \"trace\": {\n * \"trace_id\": \"4C79F60C11214EB38604F4AE0781BFB2\",\n * \"span_id\": \"FA90FDEAD5F74052\",\n * \"type\": \"trace\",\n * },\n * \"replay\": {\n * \"replay_id\": \"e2d42047b1c5431c8cba85ee2a8ab25d\",\n * },\n * },\n * }\n */\n", "import { getLocationHref } from '@sentry/utils';\n\nimport { FEEDBACK_API_SOURCE } from './constants';\nimport type { SendFeedbackOptions } from './types';\nimport { sendFeedbackRequest } from './util/sendFeedbackRequest';\n\ninterface SendFeedbackParams {\n message: string;\n name?: string;\n email?: string;\n url?: string;\n source?: string;\n}\n\n/**\n * Public API to send a Feedback item to Sentry\n */\nexport function sendFeedback(\n { name, email, message, source = FEEDBACK_API_SOURCE, url = getLocationHref() }: SendFeedbackParams,\n options: SendFeedbackOptions = {},\n): ReturnType {\n if (!message) {\n throw new Error('Unable to submit feedback with empty message');\n }\n\n return sendFeedbackRequest(\n {\n feedback: {\n name,\n email,\n message,\n url,\n source,\n },\n },\n options,\n );\n}\n", "declare const __DEBUG_BUILD__: boolean;\n\n/**\n * This serves as a build time flag that will be true by default, but false in non-debug builds or if users replace `__SENTRY_DEBUG__` in their generated code.\n *\n * ATTENTION: This constant must never cross package boundaries (i.e. be exported) to guarantee that it can be used for tree shaking.\n */\nexport const DEBUG_BUILD = __DEBUG_BUILD__;\n", "import type { FeedbackInternalOptions, OptionalFeedbackConfiguration } from '../types';\n\n/**\n * Quick and dirty deep merge for the Feedback integration options\n */\nexport function mergeOptions(\n defaultOptions: FeedbackInternalOptions,\n optionOverrides: OptionalFeedbackConfiguration,\n): FeedbackInternalOptions {\n return {\n ...defaultOptions,\n ...optionOverrides,\n themeDark: {\n ...defaultOptions.themeDark,\n ...optionOverrides.themeDark,\n },\n themeLight: {\n ...defaultOptions.themeLight,\n ...optionOverrides.themeLight,\n },\n };\n}\n", "/**\n * Creates