Skip to main content
Module

x/sentry/index.mjs

The Official Sentry Deno SDK
Go to Latest
File
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065
/// <reference types="./index.d.ts" />// eslint-disable-next-line @typescript-eslint/unbound-methodconst objectToString = Object.prototype.toString;
/** * Checks whether given value's type is one of a few Error or Error-like * {@link isError}. * * @param wat A value to be checked. * @returns A boolean representing the result. */function isError(wat) { switch (objectToString.call(wat)) { case '[object Error]': case '[object Exception]': case '[object DOMException]': return true; default: return isInstanceOf(wat, Error); }}/** * Checks whether given value is an instance of the given built-in class. * * @param wat The value to be checked * @param className * @returns A boolean representing the result. */function isBuiltin(wat, className) { return objectToString.call(wat) === `[object ${className}]`;}
/** * Checks whether given value's type is a string * {@link isString}. * * @param wat A value to be checked. * @returns A boolean representing the result. */function isString(wat) { return isBuiltin(wat, 'String');}
/** * Checks whether given string is parameterized * {@link isParameterizedString}. * * @param wat A value to be checked. * @returns A boolean representing the result. */function isParameterizedString(wat) { return ( typeof wat === 'object' && wat !== null && '__sentry_template_string__' in wat && '__sentry_template_values__' in wat );}
/** * Checks whether given value is a primitive (undefined, null, number, boolean, string, bigint, symbol) * {@link isPrimitive}. * * @param wat A value to be checked. * @returns A boolean representing the result. */function isPrimitive(wat) { return wat === null || isParameterizedString(wat) || (typeof wat !== 'object' && typeof wat !== 'function');}
/** * Checks whether given value's type is an object literal, or a class instance. * {@link isPlainObject}. * * @param wat A value to be checked. * @returns A boolean representing the result. */function isPlainObject(wat) { return isBuiltin(wat, 'Object');}
/** * Checks whether given value's type is an Event instance * {@link isEvent}. * * @param wat A value to be checked. * @returns A boolean representing the result. */function isEvent(wat) { return typeof Event !== 'undefined' && isInstanceOf(wat, Event);}
/** * Checks whether given value's type is an Element instance * {@link isElement}. * * @param wat A value to be checked. * @returns A boolean representing the result. */function isElement(wat) { return typeof Element !== 'undefined' && isInstanceOf(wat, Element);}
/** * Checks whether given value's type is an regexp * {@link isRegExp}. * * @param wat A value to be checked. * @returns A boolean representing the result. */function isRegExp(wat) { return isBuiltin(wat, 'RegExp');}
/** * Checks whether given value has a then function. * @param wat A value to be checked. */function isThenable(wat) { // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access return Boolean(wat && wat.then && typeof wat.then === 'function');}
/** * Checks whether given value's type is a SyntheticEvent * {@link isSyntheticEvent}. * * @param wat A value to be checked. * @returns A boolean representing the result. */function isSyntheticEvent(wat) { return isPlainObject(wat) && 'nativeEvent' in wat && 'preventDefault' in wat && 'stopPropagation' in wat;}
/** * Checks whether given value is NaN * {@link isNaN}. * * @param wat A value to be checked. * @returns A boolean representing the result. */function isNaN$1(wat) { return typeof wat === 'number' && wat !== wat;}
/** * Checks whether given value's type is an instance of provided constructor. * {@link isInstanceOf}. * * @param wat A value to be checked. * @param base A constructor to be used in a check. * @returns A boolean representing the result. */function isInstanceOf(wat, base) { try { return wat instanceof base; } catch (_e) { return false; }}
/** * Checks whether given value's type is a Vue ViewModel. * * @param wat A value to be checked. * @returns A boolean representing the result. */function isVueViewModel(wat) { // Not using Object.prototype.toString because in Vue 3 it would read the instance's Symbol(Symbol.toStringTag) property. return !!(typeof wat === 'object' && wat !== null && ((wat ).__isVue || (wat )._isVue));}
/** * Truncates given string to the maximum characters count * * @param str An object that contains serializable values * @param max Maximum number of characters in truncated string (0 = unlimited) * @returns string Encoded */function truncate(str, max = 0) { if (typeof str !== 'string' || max === 0) { return str; } return str.length <= max ? str : `${str.slice(0, max)}...`;}
/** * This is basically just `trim_line` from * https://github.com/getsentry/sentry/blob/master/src/sentry/lang/javascript/processor.py#L67 * * @param str An object that contains serializable values * @param max Maximum number of characters in truncated string * @returns string Encoded */function snipLine(line, colno) { let newLine = line; const lineLength = newLine.length; if (lineLength <= 150) { return newLine; } if (colno > lineLength) { // eslint-disable-next-line no-param-reassign colno = lineLength; } let start = Math.max(colno - 60, 0); if (start < 5) { start = 0; } let end = Math.min(start + 140, lineLength); if (end > lineLength - 5) { end = lineLength; } if (end === lineLength) { start = Math.max(end - 140, 0); } newLine = newLine.slice(start, end); if (start > 0) { newLine = `'{snip} ${newLine}`; } if (end < lineLength) { newLine += ' {snip}'; } return newLine;}
/** * Join values in array * @param input array of values to be joined together * @param delimiter string to be placed in-between values * @returns Joined values */// eslint-disable-next-line @typescript-eslint/no-explicit-anyfunction safeJoin(input, delimiter) { if (!Array.isArray(input)) { return ''; } const output = []; // eslint-disable-next-line @typescript-eslint/prefer-for-of for (let i = 0; i < input.length; i++) { const value = input[i]; try { // This is a hack to fix a Vue3-specific bug that causes an infinite loop of // console warnings. This happens when a Vue template is rendered with // an undeclared variable, which we try to stringify, ultimately causing // Vue to issue another warning which repeats indefinitely. // see: https://github.com/getsentry/sentry-javascript/pull/8981 if (isVueViewModel(value)) { output.push('[VueViewModel]'); } else { output.push(String(value)); } } catch (e) { output.push('[value cannot be serialized]'); } } return output.join(delimiter);}
/** * Checks if the given value matches a regex or string * * @param value The string to test * @param pattern Either a regex or a string against which `value` will be matched * @param requireExactStringMatch If true, `value` must match `pattern` exactly. If false, `value` will match * `pattern` if it contains `pattern`. Only applies to string-type patterns. */function isMatchingPattern( value, pattern, requireExactStringMatch = false,) { if (!isString(value)) { return false; } if (isRegExp(pattern)) { return pattern.test(value); } if (isString(pattern)) { return requireExactStringMatch ? value === pattern : value.includes(pattern); } return false;}
/** * Test the given string against an array of strings and regexes. By default, string matching is done on a * substring-inclusion basis rather than a strict equality basis * * @param testString The string to test * @param patterns The patterns against which to test the string * @param requireExactStringMatch If true, `testString` must match one of the given string patterns exactly in order to * count. If false, `testString` will match a string pattern if it contains that pattern. * @returns */function stringMatchesSomePattern( testString, patterns = [], requireExactStringMatch = false,) { return patterns.some(pattern => isMatchingPattern(testString, pattern, requireExactStringMatch));}
/** * Creates exceptions inside `event.exception.values` for errors that are nested on properties based on the `key` parameter. */function applyAggregateErrorsToEvent( exceptionFromErrorImplementation, parser, maxValueLimit = 250, key, limit, event, hint,) { if (!event.exception || !event.exception.values || !hint || !isInstanceOf(hint.originalException, Error)) { return; } // Generally speaking the last item in `event.exception.values` is the exception originating from the original Error const originalException = event.exception.values.length > 0 ? event.exception.values[event.exception.values.length - 1] : undefined; // We only create exception grouping if there is an exception in the event. if (originalException) { event.exception.values = truncateAggregateExceptions( aggregateExceptionsFromError( exceptionFromErrorImplementation, parser, limit, hint.originalException , key, event.exception.values, originalException, 0, ), maxValueLimit, ); }}
function aggregateExceptionsFromError( exceptionFromErrorImplementation, parser, limit, error, key, prevExceptions, exception, exceptionId,) { if (prevExceptions.length >= limit + 1) { return prevExceptions; } let newExceptions = [...prevExceptions]; // Recursively call this function in order to walk down a chain of errors if (isInstanceOf(error[key], Error)) { applyExceptionGroupFieldsForParentException(exception, exceptionId); const newException = exceptionFromErrorImplementation(parser, error[key]); const newExceptionId = newExceptions.length; applyExceptionGroupFieldsForChildException(newException, key, newExceptionId, exceptionId); newExceptions = aggregateExceptionsFromError( exceptionFromErrorImplementation, parser, limit, error[key], key, [newException, ...newExceptions], newException, newExceptionId, ); } // This will create exception grouping for AggregateErrors // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AggregateError if (Array.isArray(error.errors)) { error.errors.forEach((childError, i) => { if (isInstanceOf(childError, Error)) { applyExceptionGroupFieldsForParentException(exception, exceptionId); const newException = exceptionFromErrorImplementation(parser, childError); const newExceptionId = newExceptions.length; applyExceptionGroupFieldsForChildException(newException, `errors[${i}]`, newExceptionId, exceptionId); newExceptions = aggregateExceptionsFromError( exceptionFromErrorImplementation, parser, limit, childError, key, [newException, ...newExceptions], newException, newExceptionId, ); } }); } return newExceptions;}
function applyExceptionGroupFieldsForParentException(exception, exceptionId) { // Don't know if this default makes sense. The protocol requires us to set these values so we pick *some* default. exception.mechanism = exception.mechanism || { type: 'generic', handled: true }; exception.mechanism = { ...exception.mechanism, ...(exception.type === 'AggregateError' && { is_exception_group: true }), exception_id: exceptionId, };}
function applyExceptionGroupFieldsForChildException( exception, source, exceptionId, parentId,) { // Don't know if this default makes sense. The protocol requires us to set these values so we pick *some* default. exception.mechanism = exception.mechanism || { type: 'generic', handled: true }; exception.mechanism = { ...exception.mechanism, type: 'chained', source, exception_id: exceptionId, parent_id: parentId, };}
/** * Truncate the message (exception.value) of all exceptions in the event. * Because this event processor is ran after `applyClientOptions`, * we need to truncate the message of the added exceptions here. */function truncateAggregateExceptions(exceptions, maxValueLength) { return exceptions.map(exception => { if (exception.value) { exception.value = truncate(exception.value, maxValueLength); } return exception; });}
/** Internal global with common properties and Sentry extensions */
// The code below for 'isGlobalObj' and 'GLOBAL_OBJ' was copied from core-js before modification// https://github.com/zloirock/core-js/blob/1b944df55282cdc99c90db5f49eb0b6eda2cc0a3/packages/core-js/internals/global.js// core-js has the following licence://// Copyright (c) 2014-2022 Denis Pushkarev//// Permission is hereby granted, free of charge, to any person obtaining a copy// of this software and associated documentation files (the "Software"), to deal// in the Software without restriction, including without limitation the rights// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell// copies of the Software, and to permit persons to whom the Software is// furnished to do so, subject to the following conditions://// The above copyright notice and this permission notice shall be included in// all copies or substantial portions of the Software.//// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN// THE SOFTWARE.
/** Returns 'obj' if it's the global object, otherwise returns undefined */function isGlobalObj(obj) { return obj && obj.Math == Math ? obj : undefined;}
/** Get's the global object for the current JavaScript runtime */const GLOBAL_OBJ = (typeof globalThis == 'object' && isGlobalObj(globalThis)) || // eslint-disable-next-line no-restricted-globals (typeof window == 'object' && isGlobalObj(window)) || (typeof self == 'object' && isGlobalObj(self)) || (typeof global == 'object' && isGlobalObj(global)) || (function () { return this; })() || {};/** * @deprecated Use GLOBAL_OBJ instead or WINDOW from @sentry/browser. This will be removed in v8 */function getGlobalObject() { return GLOBAL_OBJ ;}
/** * Returns a global singleton contained in the global `__SENTRY__` object. * * If the singleton doesn't already exist in `__SENTRY__`, it will be created using the given factory * function and added to the `__SENTRY__` object. * * @param name name of the global singleton on __SENTRY__ * @param creator creator Factory function to create the singleton if it doesn't already exist on `__SENTRY__` * @param obj (Optional) The global object on which to look for `__SENTRY__`, if not `GLOBAL_OBJ`'s return value * @returns the singleton */function getGlobalSingleton(name, creator, obj) { const gbl = (obj || GLOBAL_OBJ) ; const __SENTRY__ = (gbl.__SENTRY__ = gbl.__SENTRY__ || {}); const singleton = __SENTRY__[name] || (__SENTRY__[name] = creator()); return singleton;}
// eslint-disable-next-line deprecation/deprecationconst WINDOW$6 = getGlobalObject();
const DEFAULT_MAX_STRING_LENGTH = 80;
/** * Given a child DOM element, returns a query-selector statement describing that * and its ancestors * e.g. [HTMLElement] => body > div > input#foo.btn[name=baz] * @returns generated DOM path */function htmlTreeAsString( elem, options = {},) { if (!elem) { return '<unknown>'; } // try/catch both: // - accessing event.target (see getsentry/raven-js#838, #768) // - `htmlTreeAsString` because it's complex, and just accessing the DOM incorrectly // - can throw an exception in some circumstances. try { let currentElem = elem ; const MAX_TRAVERSE_HEIGHT = 5; const out = []; let height = 0; let len = 0; const separator = ' > '; const sepLength = separator.length; let nextStr; const keyAttrs = Array.isArray(options) ? options : options.keyAttrs; const maxStringLength = (!Array.isArray(options) && options.maxStringLength) || DEFAULT_MAX_STRING_LENGTH; while (currentElem && height++ < MAX_TRAVERSE_HEIGHT) { nextStr = _htmlElementAsString(currentElem, keyAttrs); // bail out if // - nextStr is the 'html' element // - the length of the string that would be created exceeds maxStringLength // (ignore this limit if we are on the first iteration) if (nextStr === 'html' || (height > 1 && len + out.length * sepLength + nextStr.length >= maxStringLength)) { break; } out.push(nextStr); len += nextStr.length; currentElem = currentElem.parentNode; } return out.reverse().join(separator); } catch (_oO) { return '<unknown>'; }}
/** * Returns a simple, query-selector representation of a DOM element * e.g. [HTMLElement] => input#foo.btn[name=baz] * @returns generated DOM path */function _htmlElementAsString(el, keyAttrs) { const elem = el;
const out = []; let className; let classes; let key; let attr; let i; if (!elem || !elem.tagName) { return ''; } // @ts-expect-error WINDOW has HTMLElement if (WINDOW$6.HTMLElement) { // If using the component name annotation plugin, this value may be available on the DOM node if (elem instanceof HTMLElement && elem.dataset && elem.dataset['sentryComponent']) { return elem.dataset['sentryComponent']; } } out.push(elem.tagName.toLowerCase()); // Pairs of attribute keys defined in `serializeAttribute` and their values on element. const keyAttrPairs = keyAttrs && keyAttrs.length ? keyAttrs.filter(keyAttr => elem.getAttribute(keyAttr)).map(keyAttr => [keyAttr, elem.getAttribute(keyAttr)]) : null; if (keyAttrPairs && keyAttrPairs.length) { keyAttrPairs.forEach(keyAttrPair => { out.push(`[${keyAttrPair[0]}="${keyAttrPair[1]}"]`); }); } else { if (elem.id) { out.push(`#${elem.id}`); } // eslint-disable-next-line prefer-const className = elem.className; if (className && isString(className)) { classes = className.split(/\s+/); for (i = 0; i < classes.length; i++) { out.push(`.${classes[i]}`); } } } const allowedAttrs = ['aria-label', 'type', 'name', 'title', 'alt']; for (i = 0; i < allowedAttrs.length; i++) { key = allowedAttrs[i]; attr = elem.getAttribute(key); if (attr) { out.push(`[${key}="${attr}"]`); } } return out.join('');}
/** * Given a DOM element, traverses up the tree until it finds the first ancestor node * that has the `data-sentry-component` attribute. This attribute is added at build-time * by projects that have the component name annotation plugin installed. * * @returns a string representation of the component for the provided DOM element, or `null` if not found */function getComponentName(elem) { // @ts-expect-error WINDOW has HTMLElement if (!WINDOW$6.HTMLElement) { return null; } let currentElem = elem ; const MAX_TRAVERSE_HEIGHT = 5; for (let i = 0; i < MAX_TRAVERSE_HEIGHT; i++) { if (!currentElem) { return null; } if (currentElem instanceof HTMLElement && currentElem.dataset['sentryComponent']) { return currentElem.dataset['sentryComponent']; } currentElem = currentElem.parentNode; } return null;}
/** * 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. * * ATTENTION: This constant must never cross package boundaries (i.e. be exported) to guarantee that it can be used for tree shaking. */const DEBUG_BUILD$2 = (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__);
/** Prefix for logging strings */const PREFIX = 'Sentry Logger ';
const CONSOLE_LEVELS = [ 'debug', 'info', 'warn', 'error', 'log', 'assert', 'trace',] ;
/** This may be mutated by the console instrumentation. */const originalConsoleMethods
= {};/** JSDoc */
/** * Temporarily disable sentry console instrumentations. * * @param callback The function to run against the original `console` messages * @returns The results of the callback */function consoleSandbox(callback) { if (!('console' in GLOBAL_OBJ)) { return callback(); } const console = GLOBAL_OBJ.console ; const wrappedFuncs = {}; const wrappedLevels = Object.keys(originalConsoleMethods) ; // Restore all wrapped console methods wrappedLevels.forEach(level => { const originalConsoleMethod = originalConsoleMethods[level] ; wrappedFuncs[level] = console[level] ; console[level] = originalConsoleMethod; }); try { return callback(); } finally { // Revert restoration to wrapped state wrappedLevels.forEach(level => { console[level] = wrappedFuncs[level] ; }); }}
function makeLogger() { let enabled = false; const logger = { enable: () => { enabled = true; }, disable: () => { enabled = false; }, isEnabled: () => enabled, }; if (DEBUG_BUILD$2) { CONSOLE_LEVELS.forEach(name => { // eslint-disable-next-line @typescript-eslint/no-explicit-any logger[name] = (...args) => { if (enabled) { consoleSandbox(() => { GLOBAL_OBJ.console[name](`${PREFIX}[${name}]:`, ...args); }); } }; }); } else { CONSOLE_LEVELS.forEach(name => { logger[name] = () => undefined; }); } return logger ;}
const logger = makeLogger();
/** Regular expression used to parse a Dsn. */const DSN_REGEX = /^(?:(\w+):)\/\/(?:(\w+)(?::(\w+)?)?@)([\w.-]+)(?::(\d+))?\/(.+)/;
function isValidProtocol(protocol) { return protocol === 'http' || protocol === 'https';}
/** * Renders the string representation of this Dsn. * * By default, this will render the public representation without the password * component. To get the deprecated private representation, set `withPassword` * to true. * * @param withPassword When set to true, the password will be included. */function dsnToString(dsn, withPassword = false) { const { host, path, pass, port, projectId, protocol, publicKey } = dsn; return ( `${protocol}://${publicKey}${withPassword && pass ? `:${pass}` : ''}` + `@${host}${port ? `:${port}` : ''}/${path ? `${path}/` : path}${projectId}` );}
/** * Parses a Dsn from a given string. * * @param str A Dsn as string * @returns Dsn as DsnComponents or undefined if @param str is not a valid DSN string */function dsnFromString(str) { const match = DSN_REGEX.exec(str); if (!match) { // This should be logged to the console consoleSandbox(() => { // eslint-disable-next-line no-console console.error(`Invalid Sentry Dsn: ${str}`); }); return undefined; } const [protocol, publicKey, pass = '', host, port = '', lastPath] = match.slice(1); let path = ''; let projectId = lastPath; const split = projectId.split('/'); if (split.length > 1) { path = split.slice(0, -1).join('/'); projectId = split.pop() ; } if (projectId) { const projectMatch = projectId.match(/^\d+/); if (projectMatch) { projectId = projectMatch[0]; } } return dsnFromComponents({ host, pass, path, projectId, port, protocol: protocol , publicKey });}
function dsnFromComponents(components) { return { protocol: components.protocol, publicKey: components.publicKey || '', pass: components.pass || '', host: components.host, port: components.port || '', path: components.path || '', projectId: components.projectId, };}
function validateDsn(dsn) { if (!DEBUG_BUILD$2) { return true; } const { port, projectId, protocol } = dsn; const requiredComponents = ['protocol', 'publicKey', 'host', 'projectId']; const hasMissingRequiredComponent = requiredComponents.find(component => { if (!dsn[component]) { logger.error(`Invalid Sentry Dsn: ${component} missing`); return true; } return false; }); if (hasMissingRequiredComponent) { return false; } if (!projectId.match(/^\d+$/)) { logger.error(`Invalid Sentry Dsn: Invalid projectId ${projectId}`); return false; } if (!isValidProtocol(protocol)) { logger.error(`Invalid Sentry Dsn: Invalid protocol ${protocol}`); return false; } if (port && isNaN(parseInt(port, 10))) { logger.error(`Invalid Sentry Dsn: Invalid port ${port}`); return false; } return true;}
/** * Creates a valid Sentry Dsn object, identifying a Sentry instance and project. * @returns a valid DsnComponents object or `undefined` if @param from is an invalid DSN source */function makeDsn(from) { const components = typeof from === 'string' ? dsnFromString(from) : dsnFromComponents(from); if (!components || !validateDsn(components)) { return undefined; } return components;}
/** An error emitted by Sentry SDKs and related utilities. */class SentryError extends Error { /** Display name of this error instance. */ constructor( message, logLevel = 'warn') { super(message);this.message = message; this.name = new.target.prototype.constructor.name; // This sets the prototype to be `Error`, not `SentryError`. It's unclear why we do this, but commenting this line // out causes various (seemingly totally unrelated) playwright tests consistently time out. FYI, this makes // instances of `SentryError` fail `obj instanceof SentryError` checks. Object.setPrototypeOf(this, new.target.prototype); this.logLevel = logLevel; }}
/** * Replace a method in an object with a wrapped version of itself. * * @param source An object that contains a method to be wrapped. * @param name The name of the method to be wrapped. * @param replacementFactory A higher-order function that takes the original version of the given method and returns a * wrapped version. Note: The function returned by `replacementFactory` needs to be a non-arrow function, in order to * preserve the correct value of `this`, and the original method must be called using `origMethod.call(this, <other * args>)` or `origMethod.apply(this, [<other args>])` (rather than being called directly), again to preserve `this`. * @returns void */function fill(source, name, replacementFactory) { if (!(name in source)) { return; } const original = source[name] ; const wrapped = replacementFactory(original) ; // Make sure it's a function first, as we need to attach an empty prototype for `defineProperties` to work // otherwise it'll throw "TypeError: Object.defineProperties called on non-object" if (typeof wrapped === 'function') { markFunctionWrapped(wrapped, original); } source[name] = wrapped;}
/** * Defines a non-enumerable property on the given object. * * @param obj The object on which to set the property * @param name The name of the property to be set * @param value The value to which to set the property */function addNonEnumerableProperty(obj, name, value) { try { Object.defineProperty(obj, name, { // enumerable: false, // the default, so we can save on bundle size by not explicitly setting it value: value, writable: true, configurable: true, }); } catch (o_O) { DEBUG_BUILD$2 && logger.log(`Failed to add non-enumerable property "${name}" to object`, obj); }}
/** * Remembers the original function on the wrapped function and * patches up the prototype. * * @param wrapped the wrapper function * @param original the original function that gets wrapped */function markFunctionWrapped(wrapped, original) { try { const proto = original.prototype || {}; wrapped.prototype = original.prototype = proto; addNonEnumerableProperty(wrapped, '__sentry_original__', original); } catch (o_O) {} // eslint-disable-line no-empty}
/** * This extracts the original function if available. See * `markFunctionWrapped` for more information. * * @param func the function to unwrap * @returns the unwrapped version of the function if available. */function getOriginalFunction(func) { return func.__sentry_original__;}
/** * Encodes given object into url-friendly format * * @param object An object that contains serializable values * @returns string Encoded */function urlEncode(object) { return Object.keys(object) .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(object[key])}`) .join('&');}
/** * Transforms any `Error` or `Event` into a plain object with all of their enumerable properties, and some of their * non-enumerable properties attached. * * @param value Initial source that we have to transform in order for it to be usable by the serializer * @returns An Event or Error turned into an object - or the value argurment itself, when value is neither an Event nor * an Error. */function convertToPlainObject( value,)
{ if (isError(value)) { return { message: value.message, name: value.name, stack: value.stack, ...getOwnProperties(value), }; } else if (isEvent(value)) { const newObj = { type: value.type, target: serializeEventTarget(value.target), currentTarget: serializeEventTarget(value.currentTarget), ...getOwnProperties(value), }; if (typeof CustomEvent !== 'undefined' && isInstanceOf(value, CustomEvent)) { newObj.detail = value.detail; } return newObj; } else { return value; }}
/** Creates a string representation of the target of an `Event` object */function serializeEventTarget(target) { try { return isElement(target) ? htmlTreeAsString(target) : Object.prototype.toString.call(target); } catch (_oO) { return '<unknown>'; }}
/** Filters out all but an object's own properties */function getOwnProperties(obj) { if (typeof obj === 'object' && obj !== null) { const extractedProps = {}; for (const property in obj) { if (Object.prototype.hasOwnProperty.call(obj, property)) { extractedProps[property] = (obj )[property]; } } return extractedProps; } else { return {}; }}
/** * Given any captured exception, extract its keys and create a sorted * and truncated list that will be used inside the event message. * eg. `Non-error exception captured with keys: foo, bar, baz` */function extractExceptionKeysForMessage(exception, maxLength = 40) { const keys = Object.keys(convertToPlainObject(exception)); keys.sort(); if (!keys.length) { return '[object has no keys]'; } if (keys[0].length >= maxLength) { return truncate(keys[0], maxLength); } for (let includedKeys = keys.length; includedKeys > 0; includedKeys--) { const serialized = keys.slice(0, includedKeys).join(', '); if (serialized.length > maxLength) { continue; } if (includedKeys === keys.length) { return serialized; } return truncate(serialized, maxLength); } return '';}
/** * Given any object, return a new object having removed all fields whose value was `undefined`. * Works recursively on objects and arrays. * * Attention: This function keeps circular references in the returned object. */function dropUndefinedKeys(inputValue) { // This map keeps track of what already visited nodes map to. // Our Set - based memoBuilder doesn't work here because we want to the output object to have the same circular // references as the input object. const memoizationMap = new Map(); // This function just proxies `_dropUndefinedKeys` to keep the `memoBuilder` out of this function's API return _dropUndefinedKeys(inputValue, memoizationMap);}
function _dropUndefinedKeys(inputValue, memoizationMap) { if (isPojo(inputValue)) { // If this node has already been visited due to a circular reference, return the object it was mapped to in the new object const memoVal = memoizationMap.get(inputValue); if (memoVal !== undefined) { return memoVal ; } const returnValue = {}; // Store the mapping of this value in case we visit it again, in case of circular data memoizationMap.set(inputValue, returnValue); for (const key of Object.keys(inputValue)) { if (typeof inputValue[key] !== 'undefined') { returnValue[key] = _dropUndefinedKeys(inputValue[key], memoizationMap); } } return returnValue ; } if (Array.isArray(inputValue)) { // If this node has already been visited due to a circular reference, return the array it was mapped to in the new object const memoVal = memoizationMap.get(inputValue); if (memoVal !== undefined) { return memoVal ; } const returnValue = []; // Store the mapping of this value in case we visit it again, in case of circular data memoizationMap.set(inputValue, returnValue); inputValue.forEach((item) => { returnValue.push(_dropUndefinedKeys(item, memoizationMap)); }); return returnValue ; } return inputValue;}
function isPojo(input) { if (!isPlainObject(input)) { return false; } try { const name = (Object.getPrototypeOf(input) ).constructor.name; return !name || name === 'Object'; } catch (e) { return true; }}
/** * Does this filename look like it's part of the app code? */function filenameIsInApp(filename, isNative = false) { const isInternal = isNative || (filename && // It's not internal if it's an absolute linux path !filename.startsWith('/') && // It's not internal if it's an absolute windows path !filename.match(/^[A-Z]:/) && // It's not internal if the path is starting with a dot !filename.startsWith('.') && // 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 !filename.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//)); // Schema from: https://stackoverflow.com/a/3641782 // in_app is all that's not an internal Node function or a module within node_modules // note that isNative appears to return true even for node core libraries // see https://github.com/getsentry/raven-node/issues/176 return !isInternal && filename !== undefined && !filename.includes('node_modules/');}
/** Node Stack line parser */// eslint-disable-next-line complexityfunction node(getModule) { const FILENAME_MATCH = /^\s*[-]{4,}$/; const FULL_MATCH = /at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/; // eslint-disable-next-line complexity return (line) => { const lineMatch = line.match(FULL_MATCH); if (lineMatch) { let object; let method; let functionName; let typeName; let methodName; if (lineMatch[1]) { functionName = lineMatch[1]; let methodStart = functionName.lastIndexOf('.'); if (functionName[methodStart - 1] === '.') { methodStart--; } if (methodStart > 0) { object = functionName.slice(0, methodStart); method = functionName.slice(methodStart + 1); const objectEnd = object.indexOf('.Module'); if (objectEnd > 0) { functionName = functionName.slice(objectEnd + 1); object = object.slice(0, objectEnd); } } typeName = undefined; } if (method) { typeName = object; methodName = method; } if (method === '<anonymous>') { methodName = undefined; functionName = undefined; } if (functionName === undefined) { methodName = methodName || '<anonymous>'; functionName = typeName ? `${typeName}.${methodName}` : methodName; } let filename = lineMatch[2] && lineMatch[2].startsWith('file://') ? lineMatch[2].slice(7) : lineMatch[2]; const isNative = lineMatch[5] === 'native'; // If it's a Windows path, trim the leading slash so that `/C:/foo` becomes `C:/foo` if (filename && filename.match(/\/[A-Z]:/)) { filename = filename.slice(1); } if (!filename && lineMatch[5] && !isNative) { filename = lineMatch[5]; } return { filename, module: getModule ? getModule(filename) : undefined, function: functionName, lineno: parseInt(lineMatch[3], 10) || undefined, colno: parseInt(lineMatch[4], 10) || undefined, in_app: filenameIsInApp(filename, isNative), }; } if (line.match(FILENAME_MATCH)) { return { filename: line, }; } return undefined; };}
const STACKTRACE_FRAME_LIMIT = 50;// Used to sanitize webpack (error: *) wrapped stack errorsconst WEBPACK_ERROR_REGEXP = /\(error: (.*)\)/;const STRIP_FRAME_REGEXP = /captureMessage|captureException/;
/** * Creates a stack parser with the supplied line parsers * * StackFrames are returned in the correct order for Sentry Exception * frames and with Sentry SDK internal frames removed from the top and bottom * */function createStackParser(...parsers) { const sortedParsers = parsers.sort((a, b) => a[0] - b[0]).map(p => p[1]); return (stack, skipFirst = 0) => { const frames = []; const lines = stack.split('\n'); for (let i = skipFirst; i < lines.length; i++) { const line = lines[i]; // Ignore lines over 1kb as they are unlikely to be stack frames. // Many of the regular expressions use backtracking which results in run time that increases exponentially with // input size. Huge strings can result in hangs/Denial of Service: // https://github.com/getsentry/sentry-javascript/issues/2286 if (line.length > 1024) { continue; } // https://github.com/getsentry/sentry-javascript/issues/5459 // Remove webpack (error: *) wrappers const cleanedLine = WEBPACK_ERROR_REGEXP.test(line) ? line.replace(WEBPACK_ERROR_REGEXP, '$1') : line; // https://github.com/getsentry/sentry-javascript/issues/7813 // Skip Error: lines if (cleanedLine.match(/\S*Error: /)) { continue; } for (const parser of sortedParsers) { const frame = parser(cleanedLine); if (frame) { frames.push(frame); break; } } if (frames.length >= STACKTRACE_FRAME_LIMIT) { break; } } return stripSentryFramesAndReverse(frames); };}
/** * Gets a stack parser implementation from Options.stackParser * @see Options * * If options contains an array of line parsers, it is converted into a parser */function stackParserFromStackParserOptions(stackParser) { if (Array.isArray(stackParser)) { return createStackParser(...stackParser); } return stackParser;}
/** * Removes Sentry frames from the top and bottom of the stack if present and enforces a limit of max number of frames. * Assumes stack input is ordered from top to bottom and returns the reverse representation so call site of the * function that caused the crash is the last frame in the array. * @hidden */function stripSentryFramesAndReverse(stack) { if (!stack.length) { return []; } const localStack = Array.from(stack); // If stack starts with one of our API calls, remove it (starts, meaning it's the top of the stack - aka last call) if (/sentryWrapped/.test(localStack[localStack.length - 1].function || '')) { localStack.pop(); } // Reversing in the middle of the procedure allows us to just pop the values off the stack localStack.reverse(); // 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) if (STRIP_FRAME_REGEXP.test(localStack[localStack.length - 1].function || '')) { localStack.pop(); // When using synthetic events, we will have a 2 levels deep stack, as `new Error('Sentry syntheticException')` // is produced within the hub itself, making it: // // Sentry.captureException() // getCurrentHub().captureException() // // instead of just the top `Sentry` call itself. // This forces us to possibly strip an additional frame in the exact same was as above. if (STRIP_FRAME_REGEXP.test(localStack[localStack.length - 1].function || '')) { localStack.pop(); } } return localStack.slice(0, STACKTRACE_FRAME_LIMIT).map(frame => ({ ...frame, filename: frame.filename || localStack[localStack.length - 1].filename, function: frame.function || '?', }));}
const defaultFunctionName = '<anonymous>';
/** * Safely extract function name from itself */function getFunctionName(fn) { try { if (!fn || typeof fn !== 'function') { return defaultFunctionName; } return fn.name || defaultFunctionName; } catch (e) { // Just accessing custom props in some Selenium environments // can cause a "Permission denied" exception (see raven-js#495). return defaultFunctionName; }}
/** * Node.js stack line parser * * This is in @sentry/utils so it can be used from the Electron SDK in the browser for when `nodeIntegration == true`. * This allows it to be used without referencing or importing any node specific code which causes bundlers to complain */function nodeStackLineParser(getModule) { return [90, node(getModule)];}
// We keep the handlers globallyconst handlers = {};const instrumented = {};
/** Add a handler function. */function addHandler(type, handler) { handlers[type] = handlers[type] || []; (handlers[type] ).push(handler);}
/** Maybe run an instrumentation function, unless it was already called. */function maybeInstrument(type, instrumentFn) { if (!instrumented[type]) { instrumentFn(); instrumented[type] = true; }}
/** Trigger handlers for a given instrumentation type. */function triggerHandlers(type, data) { const typeHandlers = type && handlers[type]; if (!typeHandlers) { return; } for (const handler of typeHandlers) { try { handler(data); } catch (e) { DEBUG_BUILD$2 && logger.error( `Error while triggering instrumentation handler.\nType: ${type}\nName: ${getFunctionName(handler)}\nError:`, e, ); } }}
/** * Add an instrumentation handler for when a console.xxx method is called. * * Use at your own risk, this might break without changelog notice, only used internally. * @hidden */function addConsoleInstrumentationHandler(handler) { const type = 'console'; addHandler(type, handler); maybeInstrument(type, instrumentConsole);}
function instrumentConsole() { if (!('console' in GLOBAL_OBJ)) { return; } CONSOLE_LEVELS.forEach(function (level) { if (!(level in GLOBAL_OBJ.console)) { return; } fill(GLOBAL_OBJ.console, level, function (originalConsoleMethod) { originalConsoleMethods[level] = originalConsoleMethod; return function (...args) { const handlerData = { args, level }; triggerHandlers('console', handlerData); const log = originalConsoleMethods[level]; log && log.apply(GLOBAL_OBJ.console, args); }; }); });}
/** * UUID4 generator * * @returns string Generated UUID4. */function uuid4() { const gbl = GLOBAL_OBJ ; const crypto = gbl.crypto || gbl.msCrypto; let getRandomByte = () => Math.random() * 16; try { if (crypto && crypto.randomUUID) { return crypto.randomUUID().replace(/-/g, ''); } if (crypto && crypto.getRandomValues) { getRandomByte = () => { // crypto.getRandomValues might return undefined instead of the typed array // in old Chromium versions (e.g. 23.0.1235.0 (151422)) // However, `typedArray` is still filled in-place. // @see https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues#typedarray const typedArray = new Uint8Array(1); crypto.getRandomValues(typedArray); return typedArray[0]; }; } } catch (_) { // some runtimes can crash invoking crypto // https://github.com/getsentry/sentry-javascript/issues/8935 } // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#2117523 // Concatenating the following numbers as strings results in '10000000100040008000100000000000' return (([1e7] ) + 1e3 + 4e3 + 8e3 + 1e11).replace(/[018]/g, c => // eslint-disable-next-line no-bitwise ((c ) ^ ((getRandomByte() & 15) >> ((c ) / 4))).toString(16), );}
function getFirstException(event) { return event.exception && event.exception.values ? event.exception.values[0] : undefined;}
/** * Extracts either message or type+value from an event that can be used for user-facing logs * @returns event's description */function getEventDescription(event) { const { message, event_id: eventId } = event; if (message) { return message; } const firstException = getFirstException(event); if (firstException) { if (firstException.type && firstException.value) { return `${firstException.type}: ${firstException.value}`; } return firstException.type || firstException.value || eventId || '<unknown>'; } return eventId || '<unknown>';}
/** * Adds exception values, type and value to an synthetic Exception. * @param event The event to modify. * @param value Value of the exception. * @param type Type of the exception. * @hidden */function addExceptionTypeValue(event, value, type) { const exception = (event.exception = event.exception || {}); const values = (exception.values = exception.values || []); const firstException = (values[0] = values[0] || {}); if (!firstException.value) { firstException.value = value || ''; } if (!firstException.type) { firstException.type = type || 'Error'; }}
/** * Adds exception mechanism data to a given event. Uses defaults if the second parameter is not passed. * * @param event The event to modify. * @param newMechanism Mechanism data to add to the event. * @hidden */function addExceptionMechanism(event, newMechanism) { const firstException = getFirstException(event); if (!firstException) { return; } const defaultMechanism = { type: 'generic', handled: true }; const currentMechanism = firstException.mechanism; firstException.mechanism = { ...defaultMechanism, ...currentMechanism, ...newMechanism }; if (newMechanism && 'data' in newMechanism) { const mergedData = { ...(currentMechanism && currentMechanism.data), ...newMechanism.data }; firstException.mechanism.data = mergedData; }}
/** * This function adds context (pre/post/line) lines to the provided frame * * @param lines string[] containing all lines * @param frame StackFrame that will be mutated * @param linesOfContext number of context lines we want to add pre/post */function addContextToFrame(lines, frame, linesOfContext = 5) { // When there is no line number in the frame, attaching context is nonsensical and will even break grouping if (frame.lineno === undefined) { return; } const maxLines = lines.length; const sourceLine = Math.max(Math.min(maxLines - 1, frame.lineno - 1), 0); frame.pre_context = lines .slice(Math.max(0, sourceLine - linesOfContext), sourceLine) .map((line) => snipLine(line, 0)); frame.context_line = snipLine(lines[Math.min(maxLines - 1, sourceLine)], frame.colno || 0); frame.post_context = lines .slice(Math.min(sourceLine + 1, maxLines), sourceLine + 1 + linesOfContext) .map((line) => snipLine(line, 0));}
/** * Checks whether or not we've already captured the given exception (note: not an identical exception - the very object * in question), and marks it captured if not. * * This is useful because it's possible for an error to get captured by more than one mechanism. After we intercept and * record an error, we rethrow it (assuming we've intercepted it before it's reached the top-level global handlers), so * that we don't interfere with whatever effects the error might have had were the SDK not there. At that point, because * the error has been rethrown, it's possible for it to bubble up to some other code we've instrumented. If it's not * caught after that, it will bubble all the way up to the global handlers (which of course we also instrument). This * function helps us ensure that even if we encounter the same error more than once, we only record it the first time we * see it. * * Note: It will ignore primitives (always return `false` and not mark them as seen), as properties can't be set on * them. {@link: Object.objectify} can be used on exceptions to convert any that are primitives into their equivalent * object wrapper forms so that this check will always work. However, because we need to flag the exact object which * will get rethrown, and because that rethrowing happens outside of the event processing pipeline, the objectification * must be done before the exception captured. * * @param A thrown exception to check or flag as having been seen * @returns `true` if the exception has already been captured, `false` if not (with the side effect of marking it seen) */function checkOrSetAlreadyCaught(exception) { // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access if (exception && (exception ).__sentry_captured__) { return true; } try { // set it this way rather than by assignment so that it's not ennumerable and therefore isn't recorded by the // `ExtraErrorData` integration addNonEnumerableProperty(exception , '__sentry_captured__', true); } catch (err) { // `exception` is a primitive, so we can't mark it seen } return false;}
/** * Checks whether the given input is already an array, and if it isn't, wraps it in one. * * @param maybeArray Input to turn into an array, if necessary * @returns The input, if already an array, or an array with the input as the only element, if not */function arrayify(maybeArray) { return Array.isArray(maybeArray) ? maybeArray : [maybeArray];}
const WINDOW$5 = GLOBAL_OBJ ;const DEBOUNCE_DURATION = 1000;
let debounceTimerID;let lastCapturedEventType;let lastCapturedEventTargetId;
/** * Add an instrumentation handler for when a click or a keypress happens. * * Use at your own risk, this might break without changelog notice, only used internally. * @hidden */function addClickKeypressInstrumentationHandler(handler) { const type = 'dom'; addHandler(type, handler); maybeInstrument(type, instrumentDOM);}
/** Exported for tests only. */function instrumentDOM() { if (!WINDOW$5.document) { return; } // Make it so that any click or keypress that is unhandled / bubbled up all the way to the document triggers our dom // handlers. (Normally we have only one, which captures a breadcrumb for each click or keypress.) Do this before // we instrument `addEventListener` so that we don't end up attaching this handler twice. const triggerDOMHandler = triggerHandlers.bind(null, 'dom'); const globalDOMEventHandler = makeDOMEventHandler(triggerDOMHandler, true); WINDOW$5.document.addEventListener('click', globalDOMEventHandler, false); WINDOW$5.document.addEventListener('keypress', globalDOMEventHandler, false); // After hooking into click and keypress events bubbled up to `document`, we also hook into user-handled // clicks & keypresses, by adding an event listener of our own to any element to which they add a listener. That // way, whenever one of their handlers is triggered, ours will be, too. (This is needed because their handler // could potentially prevent the event from bubbling up to our global listeners. This way, our handler are still // guaranteed to fire at least once.) ['EventTarget', 'Node'].forEach((target) => { // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access const proto = (WINDOW$5 )[target] && (WINDOW$5 )[target].prototype; // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, no-prototype-builtins if (!proto || !proto.hasOwnProperty || !proto.hasOwnProperty('addEventListener')) { return; } fill(proto, 'addEventListener', function (originalAddEventListener) { return function ( type, listener, options, ) { if (type === 'click' || type == 'keypress') { try { const el = this ; const handlers = (el.__sentry_instrumentation_handlers__ = el.__sentry_instrumentation_handlers__ || {}); const handlerForType = (handlers[type] = handlers[type] || { refCount: 0 }); if (!handlerForType.handler) { const handler = makeDOMEventHandler(triggerDOMHandler); handlerForType.handler = handler; originalAddEventListener.call(this, type, handler, options); } handlerForType.refCount++; } catch (e) { // Accessing dom properties is always fragile. // Also allows us to skip `addEventListenrs` calls with no proper `this` context. } } return originalAddEventListener.call(this, type, listener, options); }; }); fill( proto, 'removeEventListener', function (originalRemoveEventListener) { return function ( type, listener, options, ) { if (type === 'click' || type == 'keypress') { try { const el = this ; const handlers = el.__sentry_instrumentation_handlers__ || {}; const handlerForType = handlers[type]; if (handlerForType) { handlerForType.refCount--; // If there are no longer any custom handlers of the current type on this element, we can remove ours, too. if (handlerForType.refCount <= 0) { originalRemoveEventListener.call(this, type, handlerForType.handler, options); handlerForType.handler = undefined; delete handlers[type]; // eslint-disable-line @typescript-eslint/no-dynamic-delete } // If there are no longer any custom handlers of any type on this element, cleanup everything. if (Object.keys(handlers).length === 0) { delete el.__sentry_instrumentation_handlers__; } } } catch (e) { // Accessing dom properties is always fragile. // Also allows us to skip `addEventListenrs` calls with no proper `this` context. } } return originalRemoveEventListener.call(this, type, listener, options); }; }, ); });}
/** * Check whether the event is similar to the last captured one. For example, two click events on the same button. */function isSimilarToLastCapturedEvent(event) { // If both events have different type, then user definitely performed two separate actions. e.g. click + keypress. if (event.type !== lastCapturedEventType) { return false; } try { // If both events have the same type, it's still possible that actions were performed on different targets. // e.g. 2 clicks on different buttons. if (!event.target || (event.target )._sentryId !== lastCapturedEventTargetId) { return false; } } catch (e) { // just accessing `target` property can throw an exception in some rare circumstances // see: https://github.com/getsentry/sentry-javascript/issues/838 } // If both events have the same type _and_ same `target` (an element which triggered an event, _not necessarily_ // to which an event listener was attached), we treat them as the same action, as we want to capture // only one breadcrumb. e.g. multiple clicks on the same button, or typing inside a user input box. return true;}
/** * Decide whether an event should be captured. * @param event event to be captured */function shouldSkipDOMEvent(eventType, target) { // We are only interested in filtering `keypress` events for now. if (eventType !== 'keypress') { return false; } if (!target || !target.tagName) { return true; } // Only consider keypress events on actual input elements. This will disregard keypresses targeting body // e.g.tabbing through elements, hotkeys, etc. if (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable) { return false; } return true;}
/** * Wraps addEventListener to capture UI breadcrumbs */function makeDOMEventHandler( handler, globalListener = false,) { return (event) => { // It's possible this handler might trigger multiple times for the same // event (e.g. event propagation through node ancestors). // Ignore if we've already captured that event. if (!event || event['_sentryCaptured']) { return; } const target = getEventTarget(event); // We always want to skip _some_ events. if (shouldSkipDOMEvent(event.type, target)) { return; } // Mark event as "seen" addNonEnumerableProperty(event, '_sentryCaptured', true); if (target && !target._sentryId) { // Add UUID to event target so we can identify if addNonEnumerableProperty(target, '_sentryId', uuid4()); } const name = event.type === 'keypress' ? 'input' : event.type; // If there is no last captured event, it means that we can safely capture the new event and store it for future comparisons. // If there is a last captured event, see if the new event is different enough to treat it as a unique one. // If that's the case, emit the previous event and store locally the newly-captured DOM event. if (!isSimilarToLastCapturedEvent(event)) { const handlerData = { event, name, global: globalListener }; handler(handlerData); lastCapturedEventType = event.type; lastCapturedEventTargetId = target ? target._sentryId : undefined; } // Start a new debounce timer that will prevent us from capturing multiple events that should be grouped together. clearTimeout(debounceTimerID); debounceTimerID = WINDOW$5.setTimeout(() => { lastCapturedEventTargetId = undefined; lastCapturedEventType = undefined; }, DEBOUNCE_DURATION); };}
function getEventTarget(event) { try { return event.target ; } catch (e) { // just accessing `target` property can throw an exception in some rare circumstances // see: https://github.com/getsentry/sentry-javascript/issues/838 return null; }}
// eslint-disable-next-line deprecation/deprecationconst WINDOW$4 = getGlobalObject();
/** * Tells whether current environment supports Fetch API * {@link supportsFetch}. * * @returns Answer to the given question. */function supportsFetch() { if (!('fetch' in WINDOW$4)) { return false; } try { new Headers(); new Request('http://www.example.com'); new Response(); return true; } catch (e) { return false; }}/** * isNativeFetch checks if the given function is a native implementation of fetch() */// eslint-disable-next-line @typescript-eslint/ban-typesfunction isNativeFetch(func) { return func && /^function fetch\(\)\s+\{\s+\[native code\]\s+\}$/.test(func.toString());}
/** * Tells whether current environment supports Fetch API natively * {@link supportsNativeFetch}. * * @returns true if `window.fetch` is natively implemented, false otherwise */function supportsNativeFetch() { if (typeof EdgeRuntime === 'string') { return true; } if (!supportsFetch()) { return false; } // Fast path to avoid DOM I/O // eslint-disable-next-line @typescript-eslint/unbound-method if (isNativeFetch(WINDOW$4.fetch)) { return true; } // window.fetch is implemented, but is polyfilled or already wrapped (e.g: by a chrome extension) // so create a "pure" iframe to see if that has native fetch let result = false; const doc = WINDOW$4.document; // eslint-disable-next-line deprecation/deprecation if (doc && typeof (doc.createElement ) === 'function') { try { const sandbox = doc.createElement('iframe'); sandbox.hidden = true; doc.head.appendChild(sandbox); if (sandbox.contentWindow && sandbox.contentWindow.fetch) { // eslint-disable-next-line @typescript-eslint/unbound-method result = isNativeFetch(sandbox.contentWindow.fetch); } doc.head.removeChild(sandbox); } catch (err) { DEBUG_BUILD$2 && logger.warn('Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ', err); } } return result;}
/** * Add an instrumentation handler for when a fetch request happens. * The handler function is called once when the request starts and once when it ends, * which can be identified by checking if it has an `endTimestamp`. * * Use at your own risk, this might break without changelog notice, only used internally. * @hidden */function addFetchInstrumentationHandler(handler) { const type = 'fetch'; addHandler(type, handler); maybeInstrument(type, instrumentFetch);}
function instrumentFetch() { if (!supportsNativeFetch()) { return; } fill(GLOBAL_OBJ, 'fetch', function (originalFetch) { return function (...args) { const { method, url } = parseFetchArgs(args); const handlerData = { args, fetchData: { method, url, }, startTimestamp: Date.now(), }; triggerHandlers('fetch', { ...handlerData, }); // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access return originalFetch.apply(GLOBAL_OBJ, args).then( (response) => { const finishedHandlerData = { ...handlerData, endTimestamp: Date.now(), response, }; triggerHandlers('fetch', finishedHandlerData); return response; }, (error) => { const erroredHandlerData = { ...handlerData, endTimestamp: Date.now(), error, }; triggerHandlers('fetch', erroredHandlerData); // NOTE: If you are a Sentry user, and you are seeing this stack frame, // it means the sentry.javascript SDK caught an error invoking your application code. // This is expected behavior and NOT indicative of a bug with sentry.javascript. throw error; }, ); }; });}
function hasProp(obj, prop) { return !!obj && typeof obj === 'object' && !!(obj )[prop];}
function getUrlFromResource(resource) { if (typeof resource === 'string') { return resource; } if (!resource) { return ''; } if (hasProp(resource, 'url')) { return resource.url; } if (resource.toString) { return resource.toString(); } return '';}
/** * Parses the fetch arguments to find the used Http method and the url of the request. * Exported for tests only. */function parseFetchArgs(fetchArgs) { if (fetchArgs.length === 0) { return { method: 'GET', url: '' }; } if (fetchArgs.length === 2) { const [url, options] = fetchArgs ; return { url: getUrlFromResource(url), method: hasProp(options, 'method') ? String(options.method).toUpperCase() : 'GET', }; } const arg = fetchArgs[0]; return { url: getUrlFromResource(arg ), method: hasProp(arg, 'method') ? String(arg.method).toUpperCase() : 'GET', };}
let _oldOnErrorHandler = null;
/** * Add an instrumentation handler for when an error is captured by the global error handler. * * Use at your own risk, this might break without changelog notice, only used internally. * @hidden */function addGlobalErrorInstrumentationHandler(handler) { const type = 'error'; addHandler(type, handler); maybeInstrument(type, instrumentError);}
function instrumentError() { _oldOnErrorHandler = GLOBAL_OBJ.onerror; GLOBAL_OBJ.onerror = function ( msg, url, line, column, error, ) { const handlerData = { column, error, line, msg, url, }; triggerHandlers('error', handlerData); if (_oldOnErrorHandler && !_oldOnErrorHandler.__SENTRY_LOADER__) { // eslint-disable-next-line prefer-rest-params return _oldOnErrorHandler.apply(this, arguments); } return false; }; GLOBAL_OBJ.onerror.__SENTRY_INSTRUMENTED__ = true;}
let _oldOnUnhandledRejectionHandler = null;
/** * Add an instrumentation handler for when an unhandled promise rejection is captured. * * Use at your own risk, this might break without changelog notice, only used internally. * @hidden */function addGlobalUnhandledRejectionInstrumentationHandler( handler,) { const type = 'unhandledrejection'; addHandler(type, handler); maybeInstrument(type, instrumentUnhandledRejection);}
function instrumentUnhandledRejection() { _oldOnUnhandledRejectionHandler = GLOBAL_OBJ.onunhandledrejection; GLOBAL_OBJ.onunhandledrejection = function (e) { const handlerData = e; triggerHandlers('unhandledrejection', handlerData); if (_oldOnUnhandledRejectionHandler && !_oldOnUnhandledRejectionHandler.__SENTRY_LOADER__) { // eslint-disable-next-line prefer-rest-params return _oldOnUnhandledRejectionHandler.apply(this, arguments); } return true; }; GLOBAL_OBJ.onunhandledrejection.__SENTRY_INSTRUMENTED__ = true;}
// Based on https://github.com/angular/angular.js/pull/13945/files
// eslint-disable-next-line deprecation/deprecationconst WINDOW$3 = getGlobalObject();
/** * Tells whether current environment supports History API * {@link supportsHistory}. * * @returns Answer to the given question. */function supportsHistory() { // NOTE: in Chrome App environment, touching history.pushState, *even inside // a try/catch block*, will cause Chrome to output an error to console.error // borrowed from: https://github.com/angular/angular.js/pull/13945/files /* eslint-disable @typescript-eslint/no-unsafe-member-access */ // eslint-disable-next-line @typescript-eslint/no-explicit-any const chromeVar = (WINDOW$3 ).chrome; const isChromePackagedApp = chromeVar && chromeVar.app && chromeVar.app.runtime; /* eslint-enable @typescript-eslint/no-unsafe-member-access */ const hasHistoryApi = 'history' in WINDOW$3 && !!WINDOW$3.history.pushState && !!WINDOW$3.history.replaceState; return !isChromePackagedApp && hasHistoryApi;}
const WINDOW$2 = GLOBAL_OBJ ;
let lastHref;
/** * Add an instrumentation handler for when a fetch request happens. * The handler function is called once when the request starts and once when it ends, * which can be identified by checking if it has an `endTimestamp`. * * Use at your own risk, this might break without changelog notice, only used internally. * @hidden */function addHistoryInstrumentationHandler(handler) { const type = 'history'; addHandler(type, handler); maybeInstrument(type, instrumentHistory);}
function instrumentHistory() { if (!supportsHistory()) { return; } const oldOnPopState = WINDOW$2.onpopstate; WINDOW$2.onpopstate = function ( ...args) { const to = WINDOW$2.location.href; // keep track of the current URL state, as we always receive only the updated state const from = lastHref; lastHref = to; const handlerData = { from, to }; triggerHandlers('history', handlerData); if (oldOnPopState) { // Apparently this can throw in Firefox when incorrectly implemented plugin is installed. // https://github.com/getsentry/sentry-javascript/issues/3344 // https://github.com/bugsnag/bugsnag-js/issues/469 try { return oldOnPopState.apply(this, args); } catch (_oO) { // no-empty } } }; function historyReplacementFunction(originalHistoryFunction) { return function ( ...args) { const url = args.length > 2 ? args[2] : undefined; if (url) { // coerce to string (this is what pushState does) const from = lastHref; const to = String(url); // keep track of the current URL state, as we always receive only the updated state lastHref = to; const handlerData = { from, to }; triggerHandlers('history', handlerData); } return originalHistoryFunction.apply(this, args); }; } fill(WINDOW$2.history, 'pushState', historyReplacementFunction); fill(WINDOW$2.history, 'replaceState', historyReplacementFunction);}
const WINDOW$1 = GLOBAL_OBJ ;
const SENTRY_XHR_DATA_KEY = '__sentry_xhr_v3__';
/** * Add an instrumentation handler for when an XHR request happens. * The handler function is called once when the request starts and once when it ends, * which can be identified by checking if it has an `endTimestamp`. * * Use at your own risk, this might break without changelog notice, only used internally. * @hidden */function addXhrInstrumentationHandler(handler) { const type = 'xhr'; addHandler(type, handler); maybeInstrument(type, instrumentXHR);}
/** Exported only for tests. */function instrumentXHR() { // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access if (!(WINDOW$1 ).XMLHttpRequest) { return; } const xhrproto = XMLHttpRequest.prototype; fill(xhrproto, 'open', function (originalOpen) { return function ( ...args) { const startTimestamp = Date.now(); // open() should always be called with two or more arguments // But to be on the safe side, we actually validate this and bail out if we don't have a method & url const method = isString(args[0]) ? args[0].toUpperCase() : undefined; const url = parseUrl$1(args[1]); if (!method || !url) { return originalOpen.apply(this, args); } this[SENTRY_XHR_DATA_KEY] = { method, url, request_headers: {}, }; // if Sentry key appears in URL, don't capture it as a request if (method === 'POST' && url.match(/sentry_key/)) { this.__sentry_own_request__ = true; } const onreadystatechangeHandler = () => { // For whatever reason, this is not the same instance here as from the outer method const xhrInfo = this[SENTRY_XHR_DATA_KEY]; if (!xhrInfo) { return; } if (this.readyState === 4) { try { // touching statusCode in some platforms throws // an exception xhrInfo.status_code = this.status; } catch (e) { /* do nothing */ } const handlerData = { args: [method, url], endTimestamp: Date.now(), startTimestamp, xhr: this, }; triggerHandlers('xhr', handlerData); } }; if ('onreadystatechange' in this && typeof this.onreadystatechange === 'function') { fill(this, 'onreadystatechange', function (original) { return function ( ...readyStateArgs) { onreadystatechangeHandler(); return original.apply(this, readyStateArgs); }; }); } else { this.addEventListener('readystatechange', onreadystatechangeHandler); } // Intercepting `setRequestHeader` to access the request headers of XHR instance. // This will only work for user/library defined headers, not for the default/browser-assigned headers. // Request cookies are also unavailable for XHR, as `Cookie` header can't be defined by `setRequestHeader`. fill(this, 'setRequestHeader', function (original) { return function ( ...setRequestHeaderArgs) { const [header, value] = setRequestHeaderArgs; const xhrInfo = this[SENTRY_XHR_DATA_KEY]; if (xhrInfo && isString(header) && isString(value)) { xhrInfo.request_headers[header.toLowerCase()] = value; } return original.apply(this, setRequestHeaderArgs); }; }); return originalOpen.apply(this, args); }; }); fill(xhrproto, 'send', function (originalSend) { return function ( ...args) { const sentryXhrData = this[SENTRY_XHR_DATA_KEY]; if (!sentryXhrData) { return originalSend.apply(this, args); } if (args[0] !== undefined) { sentryXhrData.body = args[0]; } const handlerData = { args: [sentryXhrData.method, sentryXhrData.url], startTimestamp: Date.now(), xhr: this, }; triggerHandlers('xhr', handlerData); return originalSend.apply(this, args); }; });}
function parseUrl$1(url) { if (isString(url)) { return url; } try { // url can be a string or URL // but since URL is not available in IE11, we do not check for it, // but simply assume it is an URL and return `toString()` from it (which returns the full URL) // If that fails, we just return undefined return (url ).toString(); } catch (e2) {} // eslint-disable-line no-empty return undefined;}
/* eslint-disable @typescript-eslint/no-unsafe-member-access *//* eslint-disable @typescript-eslint/no-explicit-any */
/** * Helper to decycle json objects */function memoBuilder() { const hasWeakSet = typeof WeakSet === 'function'; const inner = hasWeakSet ? new WeakSet() : []; function memoize(obj) { if (hasWeakSet) { if (inner.has(obj)) { return true; } inner.add(obj); return false; } // eslint-disable-next-line @typescript-eslint/prefer-for-of for (let i = 0; i < inner.length; i++) { const value = inner[i]; if (value === obj) { return true; } } inner.push(obj); return false; } function unmemoize(obj) { if (hasWeakSet) { inner.delete(obj); } else { for (let i = 0; i < inner.length; i++) { if (inner[i] === obj) { inner.splice(i, 1); break; } } } } return [memoize, unmemoize];}
/** * Recursively normalizes the given object. * * - Creates a copy to prevent original input mutation * - Skips non-enumerable properties * - When stringifying, calls `toJSON` if implemented * - Removes circular references * - Translates non-serializable values (`undefined`/`NaN`/functions) to serializable format * - Translates known global objects/classes to a string representations * - Takes care of `Error` object serialization * - Optionally limits depth of final output * - Optionally limits number of properties/elements included in any single object/array * * @param input The object to be normalized. * @param depth The max depth to which to normalize the object. (Anything deeper stringified whole.) * @param maxProperties The max number of elements or properties to be included in any single array or * object in the normallized output. * @returns A normalized version of the object, or `"**non-serializable**"` if any errors are thrown during normalization. */// eslint-disable-next-line @typescript-eslint/no-explicit-anyfunction normalize(input, depth = 100, maxProperties = +Infinity) { try { // since we're at the outermost level, we don't provide a key return visit('', input, depth, maxProperties); } catch (err) { return { ERROR: `**non-serializable** (${err})` }; }}
/** JSDoc */function normalizeToSize( // eslint-disable-next-line @typescript-eslint/no-explicit-any object, // Default Node.js REPL depth depth = 3, // 100kB, as 200kB is max payload size, so half sounds reasonable maxSize = 100 * 1024,) { const normalized = normalize(object, depth); if (jsonSize(normalized) > maxSize) { return normalizeToSize(object, depth - 1, maxSize); } return normalized ;}
/** * Visits a node to perform normalization on it * * @param key The key corresponding to the given node * @param value The node to be visited * @param depth Optional number indicating the maximum recursion depth * @param maxProperties Optional maximum number of properties/elements included in any single object/array * @param memo Optional Memo class handling decycling */function visit( key, value, depth = +Infinity, maxProperties = +Infinity, memo = memoBuilder(),) { const [memoize, unmemoize] = memo; // Get the simple cases out of the way first if ( value == null || // this matches null and undefined -> eqeq not eqeqeq (['number', 'boolean', 'string'].includes(typeof value) && !isNaN$1(value)) ) { return value ; } const stringified = stringifyValue(key, value); // Anything we could potentially dig into more (objects or arrays) will have come back as `"[object XXXX]"`. // Everything else will have already been serialized, so if we don't see that pattern, we're done. if (!stringified.startsWith('[object ')) { return stringified; } // From here on, we can assert that `value` is either an object or an array. // Do not normalize objects that we know have already been normalized. As a general rule, the // "__sentry_skip_normalization__" property should only be used sparingly and only should only be set on objects that // have already been normalized. if ((value )['__sentry_skip_normalization__']) { return value ; } // We can set `__sentry_override_normalization_depth__` on an object to ensure that from there // We keep a certain amount of depth. // This should be used sparingly, e.g. we use it for the redux integration to ensure we get a certain amount of state. const remainingDepth = typeof (value )['__sentry_override_normalization_depth__'] === 'number' ? ((value )['__sentry_override_normalization_depth__'] ) : depth; // We're also done if we've reached the max depth if (remainingDepth === 0) { // At this point we know `serialized` is a string of the form `"[object XXXX]"`. Clean it up so it's just `"[XXXX]"`. return stringified.replace('object ', ''); } // If we've already visited this branch, bail out, as it's circular reference. If not, note that we're seeing it now. if (memoize(value)) { return '[Circular ~]'; } // If the value has a `toJSON` method, we call it to extract more information const valueWithToJSON = value ; if (valueWithToJSON && typeof valueWithToJSON.toJSON === 'function') { try { const jsonValue = valueWithToJSON.toJSON(); // We need to normalize the return value of `.toJSON()` in case it has circular references return visit('', jsonValue, remainingDepth - 1, maxProperties, memo); } catch (err) { // pass (The built-in `toJSON` failed, but we can still try to do it ourselves) } } // 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 // because we haven't yet reached the max depth. Create an accumulator to hold the results of visiting each // property/entry, and keep track of the number of items we add to it. const normalized = (Array.isArray(value) ? [] : {}) ; let numAdded = 0; // Before we begin, convert`Error` and`Event` instances into plain objects, since some of each of their relevant // properties are non-enumerable and otherwise would get missed. const visitable = convertToPlainObject(value ); for (const visitKey in visitable) { // Avoid iterating over fields in the prototype if they've somehow been exposed to enumeration. if (!Object.prototype.hasOwnProperty.call(visitable, visitKey)) { continue; } if (numAdded >= maxProperties) { normalized[visitKey] = '[MaxProperties ~]'; break; } // Recursively visit all the child nodes const visitValue = visitable[visitKey]; normalized[visitKey] = visit(visitKey, visitValue, remainingDepth - 1, maxProperties, memo); numAdded++; } // Once we've visited all the branches, remove the parent from memo storage unmemoize(value); // Return accumulated values return normalized;}
/* eslint-disable complexity *//** * Stringify the given value. Handles various known special values and types. * * Not meant to be used on simple primitives which already have a string representation, as it will, for example, turn * the number 1231 into "[Object Number]", nor on `null`, as it will throw. * * @param value The value to stringify * @returns A stringified representation of the given value */function stringifyValue( key, // this type is a tiny bit of a cheat, since this function does handle NaN (which is technically a number), but for // our internal use, it'll do value,) { try { if (key === 'domain' && value && typeof value === 'object' && (value )._events) { return '[Domain]'; } if (key === 'domainEmitter') { return '[DomainEmitter]'; } // It's safe to use `global`, `window`, and `document` here in this manner, as we are asserting using `typeof` first // which won't throw if they are not present. if (typeof global !== 'undefined' && value === global) { return '[Global]'; } // eslint-disable-next-line no-restricted-globals if (typeof window !== 'undefined' && value === window) { return '[Window]'; } // eslint-disable-next-line no-restricted-globals if (typeof document !== 'undefined' && value === document) { return '[Document]'; } if (isVueViewModel(value)) { return '[VueViewModel]'; } // React's SyntheticEvent thingy if (isSyntheticEvent(value)) { return '[SyntheticEvent]'; } if (typeof value === 'number' && value !== value) { return '[NaN]'; } if (typeof value === 'function') { return `[Function: ${getFunctionName(value)}]`; } if (typeof value === 'symbol') { return `[${String(value)}]`; } // stringified BigInts are indistinguishable from regular numbers, so we need to label them to avoid confusion if (typeof value === 'bigint') { return `[BigInt: ${String(value)}]`; } // Now that we've knocked out all the special cases and the primitives, all we have left are objects. Simply casting // them to strings means that instances of classes which haven't defined their `toStringTag` will just come out as // `"[object Object]"`. If we instead look at the constructor's name (which is the same as the name of the class), // we can make sure that only plain objects come out that way. const objName = getConstructorName(value); // Handle HTML Elements if (/^HTML(\w*)Element$/.test(objName)) { return `[HTMLElement: ${objName}]`; } return `[object ${objName}]`; } catch (err) { return `**non-serializable** (${err})`; }}/* eslint-enable complexity */
function getConstructorName(value) { const prototype = Object.getPrototypeOf(value); return prototype ? prototype.constructor.name : 'null prototype';}
/** Calculates bytes size of input string */function utf8Length(value) { // eslint-disable-next-line no-bitwise return ~-encodeURI(value).split(/%..|./).length;}
/** Calculates bytes size of input object */// eslint-disable-next-line @typescript-eslint/no-explicit-anyfunction jsonSize(value) { return utf8Length(JSON.stringify(value));}
// Slightly modified (no IE8 support, ES6) and transcribed to TypeScript
// Split a filename into [root, dir, basename, ext], unix version// 'root' is just a slash, or nothing.const splitPathRe = /^(\S+:\\|\/?)([\s\S]*?)((?:\.{1,2}|[^/\\]+?|)(\.[^./\\]*|))(?:[/\\]*)$/;/** JSDoc */function splitPath(filename) { // Truncate files names greater than 1024 characters to avoid regex dos // https://github.com/getsentry/sentry-javascript/pull/8737#discussion_r1285719172 const truncated = filename.length > 1024 ? `<truncated>${filename.slice(-1024)}` : filename; const parts = splitPathRe.exec(truncated); return parts ? parts.slice(1) : [];}
/** JSDoc */function dirname(path) { const result = splitPath(path); const root = result[0]; let dir = result[1]; if (!root && !dir) { // No dirname whatsoever return '.'; } if (dir) { // It has a dirname, strip trailing slash dir = dir.slice(0, dir.length - 1); } return root + dir;}
/* eslint-disable @typescript-eslint/explicit-function-return-type */
/** SyncPromise internal states */var States; (function (States) { /** Pending */ const PENDING = 0; States[States["PENDING"] = PENDING] = "PENDING"; /** Resolved / OK */ const RESOLVED = 1; States[States["RESOLVED"] = RESOLVED] = "RESOLVED"; /** Rejected / Error */ const REJECTED = 2; States[States["REJECTED"] = REJECTED] = "REJECTED";})(States || (States = {}));
// Overloads so we can call resolvedSyncPromise without arguments and generic argument
/** * Creates a resolved sync promise. * * @param value the value to resolve the promise with * @returns the resolved sync promise */function resolvedSyncPromise(value) { return new SyncPromise(resolve => { resolve(value); });}
/** * Creates a rejected sync promise. * * @param value the value to reject the promise with * @returns the rejected sync promise */function rejectedSyncPromise(reason) { return new SyncPromise((_, reject) => { reject(reason); });}
/** * Thenable class that behaves like a Promise and follows it's interface * but is not async internally */class SyncPromise {
constructor( executor, ) {SyncPromise.prototype.__init.call(this);SyncPromise.prototype.__init2.call(this);SyncPromise.prototype.__init3.call(this);SyncPromise.prototype.__init4.call(this); this._state = States.PENDING; this._handlers = []; try { executor(this._resolve, this._reject); } catch (e) { this._reject(e); } } /** JSDoc */ then( onfulfilled, onrejected, ) { return new SyncPromise((resolve, reject) => { this._handlers.push([ false, result => { if (!onfulfilled) { // TODO: ¯\_(ツ)_/¯ // TODO: FIXME resolve(result ); } else { try { resolve(onfulfilled(result)); } catch (e) { reject(e); } } }, reason => { if (!onrejected) { reject(reason); } else { try { resolve(onrejected(reason)); } catch (e) { reject(e); } } }, ]); this._executeHandlers(); }); } /** JSDoc */ catch( onrejected, ) { return this.then(val => val, onrejected); } /** JSDoc */ finally(onfinally) { return new SyncPromise((resolve, reject) => { let val; let isRejected; return this.then( value => { isRejected = false; val = value; if (onfinally) { onfinally(); } }, reason => { isRejected = true; val = reason; if (onfinally) { onfinally(); } }, ).then(() => { if (isRejected) { reject(val); return; } resolve(val ); }); }); } /** JSDoc */ __init() {this._resolve = (value) => { this._setResult(States.RESOLVED, value); };} /** JSDoc */ __init2() {this._reject = (reason) => { this._setResult(States.REJECTED, reason); };} /** JSDoc */ __init3() {this._setResult = (state, value) => { if (this._state !== States.PENDING) { return; } if (isThenable(value)) { void (value ).then(this._resolve, this._reject); return; } this._state = state; this._value = value; this._executeHandlers(); };} /** JSDoc */ __init4() {this._executeHandlers = () => { if (this._state === States.PENDING) { return; } const cachedHandlers = this._handlers.slice(); this._handlers = []; cachedHandlers.forEach(handler => { if (handler[0]) { return; } if (this._state === States.RESOLVED) { // eslint-disable-next-line @typescript-eslint/no-floating-promises handler[1](this._value ); } if (this._state === States.REJECTED) { handler[2](this._value); } handler[0] = true; }); };}}
/** * Creates an new PromiseBuffer object with the specified limit * @param limit max number of promises that can be stored in the buffer */function makePromiseBuffer(limit) { const buffer = []; function isReady() { return limit === undefined || buffer.length < limit; } /** * Remove a promise from the queue. * * @param task Can be any PromiseLike<T> * @returns Removed promise. */ function remove(task) { return buffer.splice(buffer.indexOf(task), 1)[0]; } /** * Add a promise (representing an in-flight action) to the queue, and set it to remove itself on fulfillment. * * @param taskProducer A function producing any PromiseLike<T>; In previous versions this used to be `task: * PromiseLike<T>`, but under that model, Promises were instantly created on the call-site and their executor * functions therefore ran immediately. Thus, even if the buffer was full, the action still happened. By * requiring the promise to be wrapped in a function, we can defer promise creation until after the buffer * limit check. * @returns The original promise. */ function add(taskProducer) { if (!isReady()) { return rejectedSyncPromise(new SentryError('Not adding Promise because buffer limit was reached.')); } // start the task and add its promise to the queue const task = taskProducer(); if (buffer.indexOf(task) === -1) { buffer.push(task); } void task .then(() => remove(task)) // Use `then(null, rejectionHandler)` rather than `catch(rejectionHandler)` so that we can use `PromiseLike` // rather than `Promise`. `PromiseLike` doesn't have a `.catch` method, making its polyfill smaller. (ES5 didn't // have promises, so TS has to polyfill when down-compiling.) .then(null, () => remove(task).then(null, () => { // We have to add another catch here because `remove()` starts a new promise chain. }), ); return task; } /** * Wait for all promises in the queue to resolve or for timeout to expire, whichever comes first. * * @param timeout The time, in ms, after which to resolve to `false` if the queue is still non-empty. Passing `0` (or * not passing anything) will make the promise wait as long as it takes for the queue to drain before resolving to * `true`. * @returns A promise which will resolve to `true` if the queue is already empty or drains before the timeout, and * `false` otherwise */ function drain(timeout) { return new SyncPromise((resolve, reject) => { let counter = buffer.length; if (!counter) { return resolve(true); } // wait for `timeout` ms and then resolve to `false` (if not cancelled first) const capturedSetTimeout = setTimeout(() => { if (timeout && timeout > 0) { resolve(false); } }, timeout); // if all promises resolve in time, cancel the timer and resolve to `true` buffer.forEach(item => { void resolvedSyncPromise(item).then(() => { if (!--counter) { clearTimeout(capturedSetTimeout); resolve(true); } }, reject); }); }); } return { $: buffer, add, drain, };}
/** * This code was originally copied from the 'cookie` module at v0.5.0 and was simplified for our use case. * https://github.com/jshttp/cookie/blob/a0c84147aab6266bdb3996cf4062e93907c0b0fc/index.js * It had the following license: * * (The MIT License) * * Copyright (c) 2012-2014 Roman Shtylman <shtylman@gmail.com> * Copyright (c) 2015 Douglas Christopher Wilson <doug@somethingdoug.com> * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * 'Software'), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *//** * Parses a cookie string */function parseCookie(str) { const obj = {}; let index = 0; while (index < str.length) { const eqIdx = str.indexOf('=', index); // no more cookie pairs if (eqIdx === -1) { break; } let endIdx = str.indexOf(';', index); if (endIdx === -1) { endIdx = str.length; } else if (endIdx < eqIdx) { // backtrack on prior semicolon index = str.lastIndexOf(';', eqIdx - 1) + 1; continue; } const key = str.slice(index, eqIdx).trim(); // only assign once if (undefined === obj[key]) { let val = str.slice(eqIdx + 1, endIdx).trim(); // quoted values if (val.charCodeAt(0) === 0x22) { val = val.slice(1, -1); } try { obj[key] = val.indexOf('%') !== -1 ? decodeURIComponent(val) : val; } catch (e) { obj[key] = val; } } index = endIdx + 1; } return obj;}
/** * Parses string form of URL into an object * // borrowed from https://tools.ietf.org/html/rfc3986#appendix-B * // intentionally using regex and not <a/> href parsing trick because React Native and other * // environments where DOM might not be available * @returns parsed URL object */function parseUrl(url) { if (!url) { return {}; } const match = url.match(/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/); if (!match) { return {}; } // coerce to undefined values to empty string so we don't get 'undefined' const query = match[6] || ''; const fragment = match[8] || ''; return { host: match[4], path: match[5], protocol: match[2], search: query, hash: fragment, relative: match[5] + query + fragment, // everything minus origin };}
/** * Strip the query string and fragment off of a given URL or path (if present) * * @param urlPath Full URL or path, including possible query string and/or fragment * @returns URL or path without query string or fragment */function stripUrlQueryAndFragment(urlPath) { // eslint-disable-next-line no-useless-escape return urlPath.split(/[\?#]/, 1)[0];}
const DEFAULT_INCLUDES = { ip: false, request: true, transaction: true, user: true,};const DEFAULT_REQUEST_INCLUDES = ['cookies', 'data', 'headers', 'method', 'query_string', 'url'];const DEFAULT_USER_INCLUDES = ['id', 'username', 'email'];
/** * Extracts a complete and parameterized path from the request object and uses it to construct transaction name. * If the parameterized transaction name cannot be extracted, we fall back to the raw URL. * * Additionally, this function determines and returns the transaction name source * * eg. GET /mountpoint/user/:id * * @param req A request object * @param options What to include in the transaction name (method, path, or a custom route name to be * used instead of the request's route) * * @returns A tuple of the fully constructed transaction name [0] and its source [1] (can be either 'route' or 'url') */function extractPathForTransaction( req, options = {},) { const method = req.method && req.method.toUpperCase(); let path = ''; let source = 'url'; // Check to see if there's a parameterized route we can use (as there is in Express) if (options.customRoute || req.route) { path = options.customRoute || `${req.baseUrl || ''}${req.route && req.route.path}`; source = 'route'; } // Otherwise, just take the original URL else if (req.originalUrl || req.url) { path = stripUrlQueryAndFragment(req.originalUrl || req.url || ''); } let name = ''; if (options.method && method) { name += method; } if (options.method && options.path) { name += ' '; } if (options.path && path) { name += path; } return [name, source];}
/** JSDoc */function extractTransaction(req, type) { switch (type) { case 'path': { return extractPathForTransaction(req, { path: true })[0]; } case 'handler': { return (req.route && req.route.stack && req.route.stack[0] && req.route.stack[0].name) || '<anonymous>'; } case 'methodPath': default: { // if exist _reconstructedRoute return that path instead of route.path const customRoute = req._reconstructedRoute ? req._reconstructedRoute : undefined; return extractPathForTransaction(req, { path: true, method: true, customRoute })[0]; } }}
/** JSDoc */function extractUserData( user, keys,) { const extractedUser = {}; const attributes = Array.isArray(keys) ? keys : DEFAULT_USER_INCLUDES; attributes.forEach(key => { if (user && key in user) { extractedUser[key] = user[key]; } }); return extractedUser;}
/** * Normalize data from the request object, accounting for framework differences. * * @param req The request object from which to extract data * @param options.include An optional array of keys to include in the normalized data. Defaults to * DEFAULT_REQUEST_INCLUDES if not provided. * @param options.deps Injected, platform-specific dependencies * @returns An object containing normalized request data */function extractRequestData( req, options,) { const { include = DEFAULT_REQUEST_INCLUDES, deps } = options || {}; // eslint-disable-next-line @typescript-eslint/no-explicit-any const requestData = {}; // headers: // node, express, koa, nextjs: req.headers const headers = (req.headers || {}); // method: // node, express, koa, nextjs: req.method const method = req.method; // host: // express: req.hostname in > 4 and req.host in < 4 // koa: req.host // node, nextjs: req.headers.host // Express 4 mistakenly strips off port number from req.host / req.hostname so we can't rely on them // See: https://github.com/expressjs/express/issues/3047#issuecomment-236653223 // Also: https://github.com/getsentry/sentry-javascript/issues/1917 const host = headers.host || req.hostname || req.host || '<no host>'; // protocol: // node, nextjs: <n/a> // express, koa: req.protocol const protocol = req.protocol === 'https' || (req.socket && req.socket.encrypted) ? 'https' : 'http'; // url (including path and query string): // node, express: req.originalUrl // koa, nextjs: req.url const originalUrl = req.originalUrl || req.url || ''; // absolute url const absoluteUrl = originalUrl.startsWith(protocol) ? originalUrl : `${protocol}://${host}${originalUrl}`; include.forEach(key => { switch (key) { case 'headers': { requestData.headers = headers; // Remove the Cookie header in case cookie data should not be included in the event if (!include.includes('cookies')) { delete (requestData.headers ).cookie; } break; } case 'method': { requestData.method = method; break; } case 'url': { requestData.url = absoluteUrl; break; } case 'cookies': { // cookies: // node, express, koa: req.headers.cookie // vercel, sails.js, express (w/ cookie middleware), nextjs: req.cookies requestData.cookies = // TODO (v8 / #5257): We're only sending the empty object for backwards compatibility, so the last bit can // come off in v8 req.cookies || (headers.cookie && parseCookie(headers.cookie)) || {}; break; } case 'query_string': { // query string: // node: req.url (raw) // express, koa, nextjs: req.query // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access requestData.query_string = extractQueryParams(req, deps); break; } case 'data': { if (method === 'GET' || method === 'HEAD') { break; } // body data: // express, koa, nextjs: req.body // // when using node by itself, you have to read the incoming stream(see // https://nodejs.dev/learn/get-http-request-body-data-using-nodejs); if a user is doing that, we can't know // where they're going to store the final result, so they'll have to capture this data themselves if (req.body !== undefined) { requestData.data = isString(req.body) ? req.body : JSON.stringify(normalize(req.body)); } break; } default: { if ({}.hasOwnProperty.call(req, key)) { requestData[key] = (req )[key]; } } } }); return requestData;}
/** * Add data from the given request to the given event * * @param event The event to which the request data will be added * @param req Request object * @param options.include Flags to control what data is included * @param options.deps Injected platform-specific dependencies * @returns The mutated `Event` object */function addRequestDataToEvent( event, req, options,) { const include = { ...DEFAULT_INCLUDES, ...(options && options.include), }; if (include.request) { const extractedRequestData = Array.isArray(include.request) ? extractRequestData(req, { include: include.request, deps: options && options.deps }) : extractRequestData(req, { deps: options && options.deps }); event.request = { ...event.request, ...extractedRequestData, }; } if (include.user) { const extractedUser = req.user && isPlainObject(req.user) ? extractUserData(req.user, include.user) : {}; if (Object.keys(extractedUser).length) { event.user = { ...event.user, ...extractedUser, }; } } // client ip: // node, nextjs: req.socket.remoteAddress // express, koa: req.ip if (include.ip) { const ip = req.ip || (req.socket && req.socket.remoteAddress); if (ip) { event.user = { ...event.user, ip_address: ip, }; } } if (include.transaction && !event.transaction) { // TODO do we even need this anymore? // TODO make this work for nextjs event.transaction = extractTransaction(req, include.transaction); } return event;}
function extractQueryParams( req, deps,) { // url (including path and query string): // node, express: req.originalUrl // koa, nextjs: req.url let originalUrl = req.originalUrl || req.url || ''; if (!originalUrl) { return; } // The `URL` constructor can't handle internal URLs of the form `/some/path/here`, so stick a dummy protocol and // hostname on the beginning. Since the point here is just to grab the query string, it doesn't matter what we use. if (originalUrl.startsWith('/')) { originalUrl = `http://dogs.are.great${originalUrl}`; } try { return ( req.query || (typeof URL !== 'undefined' && new URL(originalUrl).search.slice(1)) || // In Node 8, `URL` isn't in the global scope, so we have to use the built-in module from Node (deps && deps.url && deps.url.parse(originalUrl).query) || undefined ); } catch (e2) { return undefined; }}
// Note: Ideally the `SeverityLevel` type would be derived from `validSeverityLevels`, but that would mean either//// a) moving `validSeverityLevels` to `@sentry/types`,// b) moving the`SeverityLevel` type here, or// c) importing `validSeverityLevels` from here into `@sentry/types`.//// Option A would make `@sentry/types` a runtime dependency of `@sentry/utils` (not good), and options B and C would// create a circular dependency between `@sentry/types` and `@sentry/utils` (also not good). So a TODO accompanying the// type, reminding anyone who changes it to change this list also, will have to do.
const validSeverityLevels = ['fatal', 'error', 'warning', 'log', 'info', 'debug'];
/** * Converts a string-based level into a `SeverityLevel`, normalizing it along the way. * * @param level String representation of desired `SeverityLevel`. * @returns The `SeverityLevel` corresponding to the given string, or 'log' if the string isn't a valid level. */function severityLevelFromString(level) { return (level === 'warn' ? 'warning' : validSeverityLevels.includes(level) ? level : 'log') ;}
const ONE_SECOND_IN_MS = 1000;
/** * A partial definition of the [Performance Web API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Performance} * for accessing a high-resolution monotonic clock. *//** * Returns a timestamp in seconds since the UNIX epoch using the Date API. * * TODO(v8): Return type should be rounded. */function dateTimestampInSeconds() { return Date.now() / ONE_SECOND_IN_MS;}
/** * Returns a wrapper around the native Performance API browser implementation, or undefined for browsers that do not * support the API. * * Wrapping the native API works around differences in behavior from different browsers. */function createUnixTimestampInSecondsFunc() { const { performance } = GLOBAL_OBJ ; if (!performance || !performance.now) { return dateTimestampInSeconds; } // Some browser and environments don't have a timeOrigin, so we fallback to // using Date.now() to compute the starting time. const approxStartingTimeOrigin = Date.now() - performance.now(); const timeOrigin = performance.timeOrigin == undefined ? approxStartingTimeOrigin : performance.timeOrigin; // performance.now() is a monotonic clock, which means it starts at 0 when the process begins. To get the current // wall clock time (actual UNIX timestamp), we need to add the starting time origin and the current time elapsed. // // TODO: This does not account for the case where the monotonic clock that powers performance.now() drifts from the // wall clock time, which causes the returned timestamp to be inaccurate. We should investigate how to detect and // correct for this. // See: https://github.com/getsentry/sentry-javascript/issues/2590 // See: https://github.com/mdn/content/issues/4713 // See: https://dev.to/noamr/when-a-millisecond-is-not-a-millisecond-3h6 return () => { return (timeOrigin + performance.now()) / ONE_SECOND_IN_MS; };}
/** * Returns a timestamp in seconds since the UNIX epoch using either the Performance or Date APIs, depending on the * availability of the Performance API. * * BUG: Note that because of how browsers implement the Performance API, the clock might stop when the computer is * asleep. This creates a skew between `dateTimestampInSeconds` and `timestampInSeconds`. The * skew can grow to arbitrary amounts like days, weeks or months. * See https://github.com/getsentry/sentry-javascript/issues/2590. */const timestampInSeconds = createUnixTimestampInSecondsFunc();
/** * The number of milliseconds since the UNIX epoch. This value is only usable in a browser, and only when the * performance API is available. */(() => { // Unfortunately browsers may report an inaccurate time origin data, through either performance.timeOrigin or // performance.timing.navigationStart, which results in poor results in performance data. We only treat time origin // data as reliable if they are within a reasonable threshold of the current time. const { performance } = GLOBAL_OBJ ; if (!performance || !performance.now) { return undefined; } const threshold = 3600 * 1000; const performanceNow = performance.now(); const dateNow = Date.now(); // if timeOrigin isn't available set delta to threshold so it isn't used const timeOriginDelta = performance.timeOrigin ? Math.abs(performance.timeOrigin + performanceNow - dateNow) : threshold; const timeOriginIsReliable = timeOriginDelta < threshold; // While performance.timing.navigationStart is deprecated in favor of performance.timeOrigin, performance.timeOrigin // is not as widely supported. Namely, performance.timeOrigin is undefined in Safari as of writing. // Also as of writing, performance.timing is not available in Web Workers in mainstream browsers, so it is not always // a valid fallback. In the absence of an initial time provided by the browser, fallback to the current time from the // Date API. // eslint-disable-next-line deprecation/deprecation const navigationStart = performance.timing && performance.timing.navigationStart; const hasNavigationStart = typeof navigationStart === 'number'; // if navigationStart isn't available set delta to threshold so it isn't used const navigationStartDelta = hasNavigationStart ? Math.abs(navigationStart + performanceNow - dateNow) : threshold; const navigationStartIsReliable = navigationStartDelta < threshold; if (timeOriginIsReliable || navigationStartIsReliable) { // Use the more reliable time origin if (timeOriginDelta <= navigationStartDelta) { return performance.timeOrigin; } else { return navigationStart; } } return dateNow;})();
const SENTRY_BAGGAGE_KEY_PREFIX = 'sentry-';
const SENTRY_BAGGAGE_KEY_PREFIX_REGEX = /^sentry-/;
/** * Takes a baggage header and turns it into Dynamic Sampling Context, by extracting all the "sentry-" prefixed values * from it. * * @param baggageHeader A very bread definition of a baggage header as it might appear in various frameworks. * @returns The Dynamic Sampling Context that was found on `baggageHeader`, if there was any, `undefined` otherwise. */function baggageHeaderToDynamicSamplingContext( // Very liberal definition of what any incoming header might look like baggageHeader,) { if (!isString(baggageHeader) && !Array.isArray(baggageHeader)) { return undefined; } // Intermediary object to store baggage key value pairs of incoming baggage headers on. // It is later used to read Sentry-DSC-values from. let baggageObject = {}; if (Array.isArray(baggageHeader)) { // Combine all baggage headers into one object containing the baggage values so we can later read the Sentry-DSC-values from it baggageObject = baggageHeader.reduce((acc, curr) => { const currBaggageObject = baggageHeaderToObject(curr); for (const key of Object.keys(currBaggageObject)) { acc[key] = currBaggageObject[key]; } return acc; }, {}); } else { // Return undefined if baggage header is an empty string (technically an empty baggage header is not spec conform but // this is how we choose to handle it) if (!baggageHeader) { return undefined; } baggageObject = baggageHeaderToObject(baggageHeader); } // Read all "sentry-" prefixed values out of the baggage object and put it onto a dynamic sampling context object. const dynamicSamplingContext = Object.entries(baggageObject).reduce((acc, [key, value]) => { if (key.match(SENTRY_BAGGAGE_KEY_PREFIX_REGEX)) { const nonPrefixedKey = key.slice(SENTRY_BAGGAGE_KEY_PREFIX.length); acc[nonPrefixedKey] = value; } return acc; }, {}); // Only return a dynamic sampling context object if there are keys in it. // A keyless object means there were no sentry values on the header, which means that there is no DSC. if (Object.keys(dynamicSamplingContext).length > 0) { return dynamicSamplingContext ; } else { return undefined; }}
/** * Will parse a baggage header, which is a simple key-value map, into a flat object. * * @param baggageHeader The baggage header to parse. * @returns a flat object containing all the key-value pairs from `baggageHeader`. */function baggageHeaderToObject(baggageHeader) { return baggageHeader .split(',') .map(baggageEntry => baggageEntry.split('=').map(keyOrValue => decodeURIComponent(keyOrValue.trim()))) .reduce((acc, [key, value]) => { acc[key] = value; return acc; }, {});}
// eslint-disable-next-line @sentry-internal/sdk/no-regexp-constructor -- RegExp is used for readability hereconst TRACEPARENT_REGEXP = new RegExp( '^[ \\t]*' + // whitespace '([0-9a-f]{32})?' + // trace_id '-?([0-9a-f]{16})?' + // span_id '-?([01])?' + // sampled '[ \\t]*$', // whitespace);
/** * Extract transaction context data from a `sentry-trace` header. * * @param traceparent Traceparent string * * @returns Object containing data from the header, or undefined if traceparent string is malformed */function extractTraceparentData$1(traceparent) { if (!traceparent) { return undefined; } const matches = traceparent.match(TRACEPARENT_REGEXP); if (!matches) { return undefined; } let parentSampled; if (matches[3] === '1') { parentSampled = true; } else if (matches[3] === '0') { parentSampled = false; } return { traceId: matches[1], parentSampled, parentSpanId: matches[2], };}
/** * Create tracing context from incoming headers. * * @deprecated Use `propagationContextFromHeaders` instead. */// TODO(v8): Remove this functionfunction tracingContextFromHeaders( sentryTrace, baggage,)
{ const traceparentData = extractTraceparentData$1(sentryTrace); const dynamicSamplingContext = baggageHeaderToDynamicSamplingContext(baggage); const { traceId, parentSpanId, parentSampled } = traceparentData || {}; if (!traceparentData) { return { traceparentData, dynamicSamplingContext: undefined, propagationContext: { traceId: traceId || uuid4(), spanId: uuid4().substring(16), }, }; } else { return { traceparentData, dynamicSamplingContext: dynamicSamplingContext || {}, // If we have traceparent data but no DSC it means we are not head of trace and we must freeze it propagationContext: { traceId: traceId || uuid4(), parentSpanId: parentSpanId || uuid4().substring(16), spanId: uuid4().substring(16), sampled: parentSampled, dsc: dynamicSamplingContext || {}, // If we have traceparent data but no DSC it means we are not head of trace and we must freeze it }, }; }}
/** * Create sentry-trace header from span context values. */function generateSentryTraceHeader( traceId = uuid4(), spanId = uuid4().substring(16), sampled,) { let sampledString = ''; if (sampled !== undefined) { sampledString = sampled ? '-1' : '-0'; } return `${traceId}-${spanId}${sampledString}`;}
/** * Creates an envelope. * Make sure to always explicitly provide the generic to this function * so that the envelope types resolve correctly. */function createEnvelope(headers, items = []) { return [headers, items] ;}
/** * Add an item to an envelope. * Make sure to always explicitly provide the generic to this function * so that the envelope types resolve correctly. */function addItemToEnvelope(envelope, newItem) { const [headers, items] = envelope; return [headers, [...items, newItem]] ;}
/** * Convenience function to loop through the items and item types of an envelope. * (This function was mostly created because working with envelope types is painful at the moment) * * If the callback returns true, the rest of the items will be skipped. */function forEachEnvelopeItem( envelope, callback,) { const envelopeItems = envelope[1]; for (const envelopeItem of envelopeItems) { const envelopeItemType = envelopeItem[0].type; const result = callback(envelopeItem, envelopeItemType); if (result) { return true; } } return false;}
/** * Encode a string to UTF8. */function encodeUTF8(input, textEncoder) { const utf8 = textEncoder || new TextEncoder(); return utf8.encode(input);}
/** * Serializes an envelope. */function serializeEnvelope(envelope, textEncoder) { const [envHeaders, items] = envelope; // Initially we construct our envelope as a string and only convert to binary chunks if we encounter binary data let parts = JSON.stringify(envHeaders); function append(next) { if (typeof parts === 'string') { parts = typeof next === 'string' ? parts + next : [encodeUTF8(parts, textEncoder), next]; } else { parts.push(typeof next === 'string' ? encodeUTF8(next, textEncoder) : next); } } for (const item of items) { const [itemHeaders, payload] = item; append(`\n${JSON.stringify(itemHeaders)}\n`); if (typeof payload === 'string' || payload instanceof Uint8Array) { append(payload); } else { let stringifiedPayload; try { stringifiedPayload = JSON.stringify(payload); } catch (e) { // In case, despite all our efforts to keep `payload` circular-dependency-free, `JSON.strinify()` still // fails, we try again after normalizing it again with infinite normalization depth. This of course has a // performance impact but in this case a performance hit is better than throwing. stringifiedPayload = JSON.stringify(normalize(payload)); } append(stringifiedPayload); } } return typeof parts === 'string' ? parts : concatBuffers(parts);}
function concatBuffers(buffers) { const totalLength = buffers.reduce((acc, buf) => acc + buf.length, 0); const merged = new Uint8Array(totalLength); let offset = 0; for (const buffer of buffers) { merged.set(buffer, offset); offset += buffer.length; } return merged;}
/** * Creates attachment envelope items */function createAttachmentEnvelopeItem( attachment, textEncoder,) { const buffer = typeof attachment.data === 'string' ? encodeUTF8(attachment.data, textEncoder) : attachment.data; return [ dropUndefinedKeys({ type: 'attachment', length: buffer.length, filename: attachment.filename, content_type: attachment.contentType, attachment_type: attachment.attachmentType, }), buffer, ];}
const ITEM_TYPE_TO_DATA_CATEGORY_MAP = { session: 'session', sessions: 'session', attachment: 'attachment', transaction: 'transaction', event: 'error', client_report: 'internal', user_report: 'default', profile: 'profile', replay_event: 'replay', replay_recording: 'replay', check_in: 'monitor', feedback: 'feedback', span: 'span', statsd: 'statsd',};
/** * Maps the type of an envelope item to a data category. */function envelopeItemTypeToDataCategory(type) { return ITEM_TYPE_TO_DATA_CATEGORY_MAP[type];}
/** Extracts the minimal SDK info from from the metadata or an events */function getSdkMetadataForEnvelopeHeader(metadataOrEvent) { if (!metadataOrEvent || !metadataOrEvent.sdk) { return; } const { name, version } = metadataOrEvent.sdk; return { name, version };}
/** * Creates event envelope headers, based on event, sdk info and tunnel * Note: This function was extracted from the core package to make it available in Replay */function createEventEnvelopeHeaders( event, sdkInfo, tunnel, dsn,) { const dynamicSamplingContext = event.sdkProcessingMetadata && event.sdkProcessingMetadata.dynamicSamplingContext; return { event_id: event.event_id , sent_at: new Date().toISOString(), ...(sdkInfo && { sdk: sdkInfo }), ...(!!tunnel && dsn && { dsn: dsnToString(dsn) }), ...(dynamicSamplingContext && { trace: dropUndefinedKeys({ ...dynamicSamplingContext }), }), };}
// Intentionally keeping the key broad, as we don't know for sure what rate limit headers get returned from backend
const DEFAULT_RETRY_AFTER = 60 * 1000; // 60 seconds
/** * Extracts Retry-After value from the request header or returns default value * @param header string representation of 'Retry-After' header * @param now current unix timestamp * */function parseRetryAfterHeader(header, now = Date.now()) { const headerDelay = parseInt(`${header}`, 10); if (!isNaN(headerDelay)) { return headerDelay * 1000; } const headerDate = Date.parse(`${header}`); if (!isNaN(headerDate)) { return headerDate - now; } return DEFAULT_RETRY_AFTER;}
/** * Gets the time that the given category is disabled until for rate limiting. * In case no category-specific limit is set but a general rate limit across all categories is active, * that time is returned. * * @return the time in ms that the category is disabled until or 0 if there's no active rate limit. */function disabledUntil(limits, category) { return limits[category] || limits.all || 0;}
/** * Checks if a category is rate limited */function isRateLimited(limits, category, now = Date.now()) { return disabledUntil(limits, category) > now;}
/** * Update ratelimits from incoming headers. * * @return the updated RateLimits object. */function updateRateLimits( limits, { statusCode, headers }, now = Date.now(),) { const updatedRateLimits = { ...limits, }; // "The name is case-insensitive." // https://developer.mozilla.org/en-US/docs/Web/API/Headers/get const rateLimitHeader = headers && headers['x-sentry-rate-limits']; const retryAfterHeader = headers && headers['retry-after']; if (rateLimitHeader) { /** * rate limit headers are of the form * <header>,<header>,.. * where each <header> is of the form * <retry_after>: <categories>: <scope>: <reason_code> * where * <retry_after> is a delay in seconds * <categories> is the event type(s) (error, transaction, etc) being rate limited and is of the form * <category>;<category>;... * <scope> is what's being limited (org, project, or key) - ignored by SDK * <reason_code> is an arbitrary string like "org_quota" - ignored by SDK */ for (const limit of rateLimitHeader.trim().split(',')) { const [retryAfter, categories] = limit.split(':', 2); const headerDelay = parseInt(retryAfter, 10); const delay = (!isNaN(headerDelay) ? headerDelay : 60) * 1000; // 60sec default if (!categories) { updatedRateLimits.all = now + delay; } else { for (const category of categories.split(';')) { updatedRateLimits[category] = now + delay; } } } } else if (retryAfterHeader) { updatedRateLimits.all = now + parseRetryAfterHeader(retryAfterHeader, now); } else if (statusCode === 429) { updatedRateLimits.all = now + 60 * 1000; } return updatedRateLimits;}
/** * Extracts stack frames from the error.stack string */function parseStackFrames(stackParser, error) { return stackParser(error.stack || '', 1);}
/** * Extracts stack frames from the error and builds a Sentry Exception */function exceptionFromError(stackParser, error) { const exception = { type: error.name || error.constructor.name, value: error.message, }; const frames = parseStackFrames(stackParser, error); if (frames.length) { exception.stacktrace = { frames }; } return exception;}
function getMessageForObject(exception) { if ('name' in exception && typeof exception.name === 'string') { let message = `'${exception.name}' captured as exception`; if ('message' in exception && typeof exception.message === 'string') { message += ` with message '${exception.message}'`; } return message; } else if ('message' in exception && typeof exception.message === 'string') { return exception.message; } else { // This will allow us to group events based on top-level keys // which is much better than creating new group when any key/value change return `Object captured as exception with keys: ${extractExceptionKeysForMessage( exception , )}`; }}
/** * Builds and Event from a Exception * * TODO(v8): Remove getHub fallback * @hidden */function eventFromUnknownInput( getHubOrClient, stackParser, exception, hint,) { const client = typeof getHubOrClient === 'function' ? // eslint-disable-next-line deprecation/deprecation getHubOrClient().getClient() : getHubOrClient; let ex = exception; const providedMechanism = hint && hint.data && (hint.data ).mechanism; const mechanism = providedMechanism || { handled: true, type: 'generic', }; let extras; if (!isError(exception)) { if (isPlainObject(exception)) { const normalizeDepth = client && client.getOptions().normalizeDepth; extras = { ['__serialized__']: normalizeToSize(exception , normalizeDepth) }; const message = getMessageForObject(exception); ex = (hint && hint.syntheticException) || new Error(message); (ex ).message = message; } else { // This handles when someone does: `throw "something awesome";` // We use synthesized Error here so we can extract a (rough) stack trace. ex = (hint && hint.syntheticException) || new Error(exception ); (ex ).message = exception ; } mechanism.synthetic = true; } const event = { exception: { values: [exceptionFromError(stackParser, ex )], }, }; if (extras) { event.extra = extras; } addExceptionTypeValue(event, undefined, undefined); addExceptionMechanism(event, mechanism); return { ...event, event_id: hint && hint.event_id, };}
/** * Builds and Event from a Message * @hidden */function eventFromMessage( stackParser, message, // eslint-disable-next-line deprecation/deprecation level = 'info', hint, attachStacktrace,) { const event = { event_id: hint && hint.event_id, level, }; if (attachStacktrace && hint && hint.syntheticException) { const frames = parseStackFrames(stackParser, hint.syntheticException); if (frames.length) { event.exception = { values: [ { value: message, stacktrace: { frames }, }, ], }; } } if (isParameterizedString(message)) { const { __sentry_template_string__, __sentry_template_values__ } = message; event.logentry = { message: __sentry_template_string__, params: __sentry_template_values__, }; return event; } event.message = message; return event;}
/** A simple Least Recently Used map */class LRUMap {
constructor( _maxSize) {this._maxSize = _maxSize; this._cache = new Map(); } /** Get the current size of the cache */ get size() { return this._cache.size; } /** Get an entry or undefined if it was not in the cache. Re-inserts to update the recently used order */ get(key) { const value = this._cache.get(key); if (value === undefined) { return undefined; } // Remove and re-insert to update the order this._cache.delete(key); this._cache.set(key, value); return value; } /** Insert an entry and evict an older entry if we've reached maxSize */ set(key, value) { if (this._cache.size >= this._maxSize) { // keys() returns an iterator in insertion order so keys().next() gives us the oldest key this._cache.delete(this._cache.keys().next().value); } this._cache.set(key, value); } /** Remove an entry and return the entry if it was in the cache */ remove(key) { const value = this._cache.get(key); if (value) { this._cache.delete(key); } return value; } /** Clear all entries */ clear() { this._cache.clear(); } /** Get all the keys */ keys() { return Array.from(this._cache.keys()); } /** Get all the values */ values() { const values = []; this._cache.forEach(value => values.push(value)); return values; }}
/** * 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. * * ATTENTION: This constant must never cross package boundaries (i.e. be exported) to guarantee that it can be used for tree shaking. */const DEBUG_BUILD$1 = (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__);
const DEFAULT_ENVIRONMENT = 'production';
/** * Returns the global event processors. * @deprecated Global event processors will be removed in v8. */function getGlobalEventProcessors() { return getGlobalSingleton('globalEventProcessors', () => []);}
/** * Add a EventProcessor to be kept globally. * @deprecated Use `addEventProcessor` instead. Global event processors will be removed in v8. */function addGlobalEventProcessor(callback) { // eslint-disable-next-line deprecation/deprecation getGlobalEventProcessors().push(callback);}
/** * Process an array of event processors, returning the processed event (or `null` if the event was dropped). */function notifyEventProcessors( processors, event, hint, index = 0,) { return new SyncPromise((resolve, reject) => { const processor = processors[index]; if (event === null || typeof processor !== 'function') { resolve(event); } else { const result = processor({ ...event }, hint) ; DEBUG_BUILD$1 && processor.id && result === null && logger.log(`Event processor "${processor.id}" dropped event`); if (isThenable(result)) { void result .then(final => notifyEventProcessors(processors, final, hint, index + 1).then(resolve)) .then(null, reject); } else { void notifyEventProcessors(processors, result, hint, index + 1) .then(resolve) .then(null, reject); } } });}
/** * Creates a new `Session` object by setting certain default parameters. If optional @param context * is passed, the passed properties are applied to the session object. * * @param context (optional) additional properties to be applied to the returned session object * * @returns a new `Session` object */function makeSession(context) { // Both timestamp and started are in seconds since the UNIX epoch. const startingTime = timestampInSeconds(); const session = { sid: uuid4(), init: true, timestamp: startingTime, started: startingTime, duration: 0, status: 'ok', errors: 0, ignoreDuration: false, toJSON: () => sessionToJSON(session), }; if (context) { updateSession(session, context); } return session;}
/** * Updates a session object with the properties passed in the context. * * Note that this function mutates the passed object and returns void. * (Had to do this instead of returning a new and updated session because closing and sending a session * makes an update to the session after it was passed to the sending logic. * @see BaseClient.captureSession ) * * @param session the `Session` to update * @param context the `SessionContext` holding the properties that should be updated in @param session */// eslint-disable-next-line complexityfunction updateSession(session, context = {}) { if (context.user) { if (!session.ipAddress && context.user.ip_address) { session.ipAddress = context.user.ip_address; } if (!session.did && !context.did) { session.did = context.user.id || context.user.email || context.user.username; } } session.timestamp = context.timestamp || timestampInSeconds(); if (context.abnormal_mechanism) { session.abnormal_mechanism = context.abnormal_mechanism; } if (context.ignoreDuration) { session.ignoreDuration = context.ignoreDuration; } if (context.sid) { // Good enough uuid validation. — Kamil session.sid = context.sid.length === 32 ? context.sid : uuid4(); } if (context.init !== undefined) { session.init = context.init; } if (!session.did && context.did) { session.did = `${context.did}`; } if (typeof context.started === 'number') { session.started = context.started; } if (session.ignoreDuration) { session.duration = undefined; } else if (typeof context.duration === 'number') { session.duration = context.duration; } else { const duration = session.timestamp - session.started; session.duration = duration >= 0 ? duration : 0; } if (context.release) { session.release = context.release; } if (context.environment) { session.environment = context.environment; } if (!session.ipAddress && context.ipAddress) { session.ipAddress = context.ipAddress; } if (!session.userAgent && context.userAgent) { session.userAgent = context.userAgent; } if (typeof context.errors === 'number') { session.errors = context.errors; } if (context.status) { session.status = context.status; }}
/** * Closes a session by setting its status and updating the session object with it. * Internally calls `updateSession` to update the passed session object. * * Note that this function mutates the passed session (@see updateSession for explanation). * * @param session the `Session` object to be closed * @param status the `SessionStatus` with which the session was closed. If you don't pass a status, * this function will keep the previously set status, unless it was `'ok'` in which case * it is changed to `'exited'`. */function closeSession(session, status) { let context = {}; if (status) { context = { status }; } else if (session.status === 'ok') { context = { status: 'exited' }; } updateSession(session, context);}
/** * Serializes a passed session object to a JSON object with a slightly different structure. * This is necessary because the Sentry backend requires a slightly different schema of a session * than the one the JS SDKs use internally. * * @param session the session to be converted * * @returns a JSON object of the passed session */function sessionToJSON(session) { return dropUndefinedKeys({ sid: `${session.sid}`, init: session.init, // Make sure that sec is converted to ms for date constructor started: new Date(session.started * 1000).toISOString(), timestamp: new Date(session.timestamp * 1000).toISOString(), status: session.status, errors: session.errors, did: typeof session.did === 'number' || typeof session.did === 'string' ? `${session.did}` : undefined, duration: session.duration, abnormal_mechanism: session.abnormal_mechanism, attrs: { release: session.release, environment: session.environment, ip_address: session.ipAddress, user_agent: session.userAgent, }, });}
// These are aligned with OpenTelemetry trace flagsconst TRACE_FLAG_NONE = 0x0;const TRACE_FLAG_SAMPLED = 0x1;
/** * Convert a span to a trace context, which can be sent as the `trace` context in an event. */function spanToTraceContext(span) { const { spanId: span_id, traceId: trace_id } = span.spanContext(); const { data, op, parent_span_id, status, tags, origin } = spanToJSON(span); return dropUndefinedKeys({ data, op, parent_span_id, span_id, status, tags, trace_id, origin, });}
/** * Convert a Span to a Sentry trace header. */function spanToTraceHeader(span) { const { traceId, spanId } = span.spanContext(); const sampled = spanIsSampled(span); return generateSentryTraceHeader(traceId, spanId, sampled);}
/** * Convert a span time input intp a timestamp in seconds. */function spanTimeInputToSeconds(input) { if (typeof input === 'number') { return ensureTimestampInSeconds(input); } if (Array.isArray(input)) { // See {@link HrTime} for the array-based time format return input[0] + input[1] / 1e9; } if (input instanceof Date) { return ensureTimestampInSeconds(input.getTime()); } return timestampInSeconds();}
/** * Converts a timestamp to second, if it was in milliseconds, or keeps it as second. */function ensureTimestampInSeconds(timestamp) { const isMs = timestamp > 9999999999; return isMs ? timestamp / 1000 : timestamp;}
/** * Convert a span to a JSON representation. * Note that all fields returned here are optional and need to be guarded against. * * Note: Because of this, we currently have a circular type dependency (which we opted out of in package.json). * This is not avoidable as we need `spanToJSON` in `spanUtils.ts`, which in turn is needed by `span.ts` for backwards compatibility. * And `spanToJSON` needs the Span class from `span.ts` to check here. * TODO v8: When we remove the deprecated stuff from `span.ts`, we can remove the circular dependency again. */function spanToJSON(span) { if (spanIsSpanClass(span)) { return span.getSpanJSON(); } // Fallback: We also check for `.toJSON()` here... // eslint-disable-next-line deprecation/deprecation if (typeof span.toJSON === 'function') { // eslint-disable-next-line deprecation/deprecation return span.toJSON(); } return {};}
/** * Sadly, due to circular dependency checks we cannot actually import the Span class here and check for instanceof. * :( So instead we approximate this by checking if it has the `getSpanJSON` method. */function spanIsSpanClass(span) { return typeof (span ).getSpanJSON === 'function';}
/** * Returns true if a span is sampled. * In most cases, you should just use `span.isRecording()` instead. * However, this has a slightly different semantic, as it also returns false if the span is finished. * So in the case where this distinction is important, use this method. */function spanIsSampled(span) { // We align our trace flags with the ones OpenTelemetry use // So we also check for sampled the same way they do. const { traceFlags } = span.spanContext(); // eslint-disable-next-line no-bitwise return Boolean(traceFlags & TRACE_FLAG_SAMPLED);}
/** * This type makes sure that we get either a CaptureContext, OR an EventHint. * It does not allow mixing them, which could lead to unexpected outcomes, e.g. this is disallowed: * { user: { id: '123' }, mechanism: { handled: false } } *//** * Adds common information to events. * * The information includes release and environment from `options`, * breadcrumbs and context (extra, tags and user) from the scope. * * Information that is already present in the event is never overwritten. For * nested objects, such as the context, keys are merged. * * Note: This also triggers callbacks for `addGlobalEventProcessor`, but not `beforeSend`. * * @param event The original event. * @param hint May contain additional information about the original exception. * @param scope A scope containing event metadata. * @returns A new event with more information. * @hidden */function prepareEvent( options, event, hint, scope, client, isolationScope,) { const { normalizeDepth = 3, normalizeMaxBreadth = 1000 } = options; const prepared = { ...event, event_id: event.event_id || hint.event_id || uuid4(), timestamp: event.timestamp || dateTimestampInSeconds(), }; const integrations = hint.integrations || options.integrations.map(i => i.name); applyClientOptions(prepared, options); applyIntegrationsMetadata(prepared, integrations); // Only put debug IDs onto frames for error events. if (event.type === undefined) { applyDebugIds(prepared, options.stackParser); } // If we have scope given to us, use it as the base for further modifications. // This allows us to prevent unnecessary copying of data if `captureContext` is not provided. const finalScope = getFinalScope(scope, hint.captureContext); if (hint.mechanism) { addExceptionMechanism(prepared, hint.mechanism); } const clientEventProcessors = client && client.getEventProcessors ? client.getEventProcessors() : []; // This should be the last thing called, since we want that // {@link Hub.addEventProcessor} gets the finished prepared event. // Merge scope data together const data = getGlobalScope().getScopeData(); if (isolationScope) { const isolationData = isolationScope.getScopeData(); mergeScopeData(data, isolationData); } if (finalScope) { const finalScopeData = finalScope.getScopeData(); mergeScopeData(data, finalScopeData); } const attachments = [...(hint.attachments || []), ...data.attachments]; if (attachments.length) { hint.attachments = attachments; } applyScopeDataToEvent(prepared, data); // TODO (v8): Update this order to be: Global > Client > Scope const eventProcessors = [ ...clientEventProcessors, // eslint-disable-next-line deprecation/deprecation ...getGlobalEventProcessors(), // Run scope event processors _after_ all other processors ...data.eventProcessors, ]; const result = notifyEventProcessors(eventProcessors, prepared, hint); return result.then(evt => { if (evt) { // We apply the debug_meta field only after all event processors have ran, so that if any event processors modified // file names (e.g.the RewriteFrames integration) the filename -> debug ID relationship isn't destroyed. // This should not cause any PII issues, since we're only moving data that is already on the event and not adding // any new data applyDebugMeta(evt); } if (typeof normalizeDepth === 'number' && normalizeDepth > 0) { return normalizeEvent(evt, normalizeDepth, normalizeMaxBreadth); } return evt; });}
/** * Enhances event using the client configuration. * It takes care of all "static" values like environment, release and `dist`, * as well as truncating overly long values. * @param event event instance to be enhanced */function applyClientOptions(event, options) { const { environment, release, dist, maxValueLength = 250 } = options; if (!('environment' in event)) { event.environment = 'environment' in options ? environment : DEFAULT_ENVIRONMENT; } if (event.release === undefined && release !== undefined) { event.release = release; } if (event.dist === undefined && dist !== undefined) { event.dist = dist; } if (event.message) { event.message = truncate(event.message, maxValueLength); } const exception = event.exception && event.exception.values && event.exception.values[0]; if (exception && exception.value) { exception.value = truncate(exception.value, maxValueLength); } const request = event.request; if (request && request.url) { request.url = truncate(request.url, maxValueLength); }}
const debugIdStackParserCache = new WeakMap();
/** * Puts debug IDs into the stack frames of an error event. */function applyDebugIds(event, stackParser) { const debugIdMap = GLOBAL_OBJ._sentryDebugIds; if (!debugIdMap) { return; } let debugIdStackFramesCache; const cachedDebugIdStackFrameCache = debugIdStackParserCache.get(stackParser); if (cachedDebugIdStackFrameCache) { debugIdStackFramesCache = cachedDebugIdStackFrameCache; } else { debugIdStackFramesCache = new Map(); debugIdStackParserCache.set(stackParser, debugIdStackFramesCache); } // Build a map of filename -> debug_id const filenameDebugIdMap = Object.keys(debugIdMap).reduce((acc, debugIdStackTrace) => { let parsedStack; const cachedParsedStack = debugIdStackFramesCache.get(debugIdStackTrace); if (cachedParsedStack) { parsedStack = cachedParsedStack; } else { parsedStack = stackParser(debugIdStackTrace); debugIdStackFramesCache.set(debugIdStackTrace, parsedStack); } for (let i = parsedStack.length - 1; i >= 0; i--) { const stackFrame = parsedStack[i]; if (stackFrame.filename) { acc[stackFrame.filename] = debugIdMap[debugIdStackTrace]; break; } } return acc; }, {}); try { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion event.exception.values.forEach(exception => { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion exception.stacktrace.frames.forEach(frame => { if (frame.filename) { frame.debug_id = filenameDebugIdMap[frame.filename]; } }); }); } catch (e) { // To save bundle size we're just try catching here instead of checking for the existence of all the different objects. }}
/** * Moves debug IDs from the stack frames of an error event into the debug_meta field. */function applyDebugMeta(event) { // Extract debug IDs and filenames from the stack frames on the event. const filenameDebugIdMap = {}; try { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion event.exception.values.forEach(exception => { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion exception.stacktrace.frames.forEach(frame => { if (frame.debug_id) { if (frame.abs_path) { filenameDebugIdMap[frame.abs_path] = frame.debug_id; } else if (frame.filename) { filenameDebugIdMap[frame.filename] = frame.debug_id; } delete frame.debug_id; } }); }); } catch (e) { // To save bundle size we're just try catching here instead of checking for the existence of all the different objects. } if (Object.keys(filenameDebugIdMap).length === 0) { return; } // Fill debug_meta information event.debug_meta = event.debug_meta || {}; event.debug_meta.images = event.debug_meta.images || []; const images = event.debug_meta.images; Object.keys(filenameDebugIdMap).forEach(filename => { images.push({ type: 'sourcemap', code_file: filename, debug_id: filenameDebugIdMap[filename], }); });}
/** * This function adds all used integrations to the SDK info in the event. * @param event The event that will be filled with all integrations. */function applyIntegrationsMetadata(event, integrationNames) { if (integrationNames.length > 0) { event.sdk = event.sdk || {}; event.sdk.integrations = [...(event.sdk.integrations || []), ...integrationNames]; }}
/** * Applies `normalize` function on necessary `Event` attributes to make them safe for serialization. * Normalized keys: * - `breadcrumbs.data` * - `user` * - `contexts` * - `extra` * @param event Event * @returns Normalized event */function normalizeEvent(event, depth, maxBreadth) { if (!event) { return null; } const normalized = { ...event, ...(event.breadcrumbs && { breadcrumbs: event.breadcrumbs.map(b => ({ ...b, ...(b.data && { data: normalize(b.data, depth, maxBreadth), }), })), }), ...(event.user && { user: normalize(event.user, depth, maxBreadth), }), ...(event.contexts && { contexts: normalize(event.contexts, depth, maxBreadth), }), ...(event.extra && { extra: normalize(event.extra, depth, maxBreadth), }), }; // event.contexts.trace stores information about a Transaction. Similarly, // event.spans[] stores information about child Spans. Given that a // Transaction is conceptually a Span, normalization should apply to both // Transactions and Spans consistently. // For now the decision is to skip normalization of Transactions and Spans, // so this block overwrites the normalized event to add back the original // Transaction information prior to normalization. if (event.contexts && event.contexts.trace && normalized.contexts) { normalized.contexts.trace = event.contexts.trace; // event.contexts.trace.data may contain circular/dangerous data so we need to normalize it if (event.contexts.trace.data) { normalized.contexts.trace.data = normalize(event.contexts.trace.data, depth, maxBreadth); } } // event.spans[].data may contain circular/dangerous data so we need to normalize it if (event.spans) { normalized.spans = event.spans.map(span => { const data = spanToJSON(span).data; if (data) { // This is a bit weird, as we generally have `Span` instances here, but to be safe we do not assume so // eslint-disable-next-line deprecation/deprecation span.data = normalize(data, depth, maxBreadth); } return span; }); } return normalized;}
function getFinalScope(scope, captureContext) { if (!captureContext) { return scope; } const finalScope = scope ? scope.clone() : new Scope(); finalScope.update(captureContext); return finalScope;}
/** * Parse either an `EventHint` directly, or convert a `CaptureContext` to an `EventHint`. * This is used to allow to update method signatures that used to accept a `CaptureContext` but should now accept an `EventHint`. */function parseEventHintOrCaptureContext( hint,) { if (!hint) { return undefined; } // If you pass a Scope or `() => Scope` as CaptureContext, we just return this as captureContext if (hintIsScopeOrFunction(hint)) { return { captureContext: hint }; } if (hintIsScopeContext(hint)) { return { captureContext: hint, }; } return hint;}
function hintIsScopeOrFunction( hint,) { return hint instanceof Scope || typeof hint === 'function';}
const captureContextKeys = [ 'user', 'level', 'extra', 'contexts', 'tags', 'fingerprint', 'requestSession', 'propagationContext',] ;
function hintIsScopeContext(hint) { return Object.keys(hint).some(key => captureContextKeys.includes(key ));}
/** * Captures an exception event and sends it to Sentry. * * @param exception The exception to capture. * @param hint Optional additional data to attach to the Sentry event. * @returns the id of the captured Sentry event. */function captureException( // eslint-disable-next-line @typescript-eslint/no-explicit-any exception, hint,) { // eslint-disable-next-line deprecation/deprecation return getCurrentHub().captureException(exception, parseEventHintOrCaptureContext(hint));}
/** * Captures a message event and sends it to Sentry. * * @param exception The exception to capture. * @param captureContext Define the level of the message or pass in additional data to attach to the message. * @returns the id of the captured message. */function captureMessage( message, // eslint-disable-next-line deprecation/deprecation captureContext,) { // This is necessary to provide explicit scopes upgrade, without changing the original // arity of the `captureMessage(message, level)` method. const level = typeof captureContext === 'string' ? captureContext : undefined; const context = typeof captureContext !== 'string' ? { captureContext } : undefined; // eslint-disable-next-line deprecation/deprecation return getCurrentHub().captureMessage(message, level, context);}
/** * Captures a manually created event and sends it to Sentry. * * @param exception The event to send to Sentry. * @param hint Optional additional data to attach to the Sentry event. * @returns the id of the captured event. */function captureEvent(event, hint) { // eslint-disable-next-line deprecation/deprecation return getCurrentHub().captureEvent(event, hint);}
/** * Callback to set context information onto the scope. * @param callback Callback function that receives Scope. * * @deprecated Use getCurrentScope() directly. */function configureScope(callback) { // eslint-disable-next-line deprecation/deprecation getCurrentHub().configureScope(callback);}
/** * Records a new breadcrumb which will be attached to future events. * * Breadcrumbs will be added to subsequent events to provide more context on * user's actions prior to an error or crash. * * @param breadcrumb The breadcrumb to record. */function addBreadcrumb(breadcrumb, hint) { // eslint-disable-next-line deprecation/deprecation getCurrentHub().addBreadcrumb(breadcrumb, hint);}
/** * Sets context data with the given name. * @param name of the context * @param context Any kind of data. This data will be normalized. */// eslint-disable-next-line @typescript-eslint/no-explicit-anyfunction setContext(name, context) { // eslint-disable-next-line deprecation/deprecation getCurrentHub().setContext(name, context);}
/** * Set an object that will be merged sent as extra data with the event. * @param extras Extras object to merge into current context. */function setExtras(extras) { // eslint-disable-next-line deprecation/deprecation getCurrentHub().setExtras(extras);}
/** * Set key:value that will be sent as extra data with the event. * @param key String of extra * @param extra Any kind of data. This data will be normalized. */function setExtra(key, extra) { // eslint-disable-next-line deprecation/deprecation getCurrentHub().setExtra(key, extra);}
/** * Set an object that will be merged sent as tags data with the event. * @param tags Tags context object to merge into current context. */function setTags(tags) { // eslint-disable-next-line deprecation/deprecation getCurrentHub().setTags(tags);}
/** * Set key:value that will be sent as tags data with the event. * * Can also be used to unset a tag, by passing `undefined`. * * @param key String key of tag * @param value Value of tag */function setTag(key, value) { // eslint-disable-next-line deprecation/deprecation getCurrentHub().setTag(key, value);}
/** * Updates user context information for future events. * * @param user User context object to be set in the current context. Pass `null` to unset the user. */function setUser(user) { // eslint-disable-next-line deprecation/deprecation getCurrentHub().setUser(user);}
/** * Creates a new scope with and executes the given operation within. * The scope is automatically removed once the operation * finishes or throws. * * This is essentially a convenience function for: * * pushScope(); * callback(); * popScope(); *//** * Either creates a new active scope, or sets the given scope as active scope in the given callback. */function withScope( ...rest) { // eslint-disable-next-line deprecation/deprecation const hub = getCurrentHub(); // If a scope is defined, we want to make this the active scope instead of the default one if (rest.length === 2) { const [scope, callback] = rest; if (!scope) { // eslint-disable-next-line deprecation/deprecation return hub.withScope(callback); } // eslint-disable-next-line deprecation/deprecation return hub.withScope(() => { // eslint-disable-next-line deprecation/deprecation hub.getStackTop().scope = scope ; return callback(scope ); }); } // eslint-disable-next-line deprecation/deprecation return hub.withScope(rest[0]);}
/** * Attempts to fork the current isolation scope and the current scope based on the current async context strategy. If no * async context strategy is set, the isolation scope and the current scope will not be forked (this is currently the * case, for example, in the browser). * * Usage of this function in environments without async context strategy is discouraged and may lead to unexpected behaviour. * * This function is intended for Sentry SDK and SDK integration development. It is not recommended to be used in "normal" * applications directly because it comes with pitfalls. Use at your own risk! * * @param callback The callback in which the passed isolation scope is active. (Note: In environments without async * context strategy, the currently active isolation scope may change within execution of the callback.) * @returns The same value that `callback` returns. */function withIsolationScope(callback) { return runWithAsyncContext(() => { return callback(getIsolationScope()); });}
/** * Starts a new `Transaction` and returns it. This is the entry point to manual tracing instrumentation. * * A tree structure can be built by adding child spans to the transaction, and child spans to other spans. To start a * new child span within the transaction or any span, call the respective `.startChild()` method. * * Every child span must be finished before the transaction is finished, otherwise the unfinished spans are discarded. * * The transaction must be finished with a call to its `.end()` method, at which point the transaction with all its * finished child spans will be sent to Sentry. * * NOTE: This function should only be used for *manual* instrumentation. Auto-instrumentation should call * `startTransaction` directly on the hub. * * @param context Properties of the new `Transaction`. * @param customSamplingContext Information given to the transaction sampling function (along with context-dependent * default values). See {@link Options.tracesSampler}. * * @returns The transaction which was just started * * @deprecated Use `startSpan()`, `startSpanManual()` or `startInactiveSpan()` instead. */function startTransaction( context, customSamplingContext,) { // eslint-disable-next-line deprecation/deprecation return getCurrentHub().startTransaction({ ...context }, customSamplingContext);}
/** * Create a cron monitor check in and send it to Sentry. * * @param checkIn An object that describes a check in. * @param upsertMonitorConfig An optional object that describes a monitor config. Use this if you want * to create a monitor automatically when sending a check in. */function captureCheckIn(checkIn, upsertMonitorConfig) { const scope = getCurrentScope(); const client = getClient(); if (!client) { DEBUG_BUILD$1 && logger.warn('Cannot capture check-in. No client defined.'); } else if (!client.captureCheckIn) { DEBUG_BUILD$1 && logger.warn('Cannot capture check-in. Client does not support sending check-ins.'); } else { return client.captureCheckIn(checkIn, upsertMonitorConfig, scope); } return uuid4();}
/** * Wraps a callback with a cron monitor check in. The check in will be sent to Sentry when the callback finishes. * * @param monitorSlug The distinct slug of the monitor. * @param upsertMonitorConfig An optional object that describes a monitor config. Use this if you want * to create a monitor automatically when sending a check in. */function withMonitor( monitorSlug, callback, upsertMonitorConfig,) { const checkInId = captureCheckIn({ monitorSlug, status: 'in_progress' }, upsertMonitorConfig); const now = timestampInSeconds(); function finishCheckIn(status) { captureCheckIn({ monitorSlug, status, checkInId, duration: timestampInSeconds() - now }); } let maybePromiseResult; try { maybePromiseResult = callback(); } catch (e) { finishCheckIn('error'); throw e; } if (isThenable(maybePromiseResult)) { Promise.resolve(maybePromiseResult).then( () => { finishCheckIn('ok'); }, () => { finishCheckIn('error'); }, ); } else { finishCheckIn('ok'); } return maybePromiseResult;}
/** * Call `flush()` on the current client, if there is one. See {@link Client.flush}. * * @param timeout Maximum time in ms the client should wait to flush its event queue. Omitting this parameter will cause * the client to wait until all events are sent before resolving the promise. * @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it * doesn't (or if there's no client defined). */async function flush(timeout) { const client = getClient(); if (client) { return client.flush(timeout); } DEBUG_BUILD$1 && logger.warn('Cannot flush events. No client defined.'); return Promise.resolve(false);}
/** * Call `close()` on the current client, if there is one. See {@link Client.close}. * * @param timeout Maximum time in ms the client should wait to flush its event queue before shutting down. Omitting this * parameter will cause the client to wait until all events are sent before disabling itself. * @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it * doesn't (or if there's no client defined). */async function close(timeout) { const client = getClient(); if (client) { return client.close(timeout); } DEBUG_BUILD$1 && logger.warn('Cannot flush events and disable SDK. No client defined.'); return Promise.resolve(false);}
/** * This is the getter for lastEventId. * * @returns The last event id of a captured event. * @deprecated This function will be removed in the next major version of the Sentry SDK. */function lastEventId() { // eslint-disable-next-line deprecation/deprecation return getCurrentHub().lastEventId();}
/** * Get the currently active client. */function getClient() { // eslint-disable-next-line deprecation/deprecation return getCurrentHub().getClient();}
/** * Returns true if Sentry has been properly initialized. */function isInitialized() { return !!getClient();}
/** * Get the currently active scope. */function getCurrentScope() { // eslint-disable-next-line deprecation/deprecation return getCurrentHub().getScope();}
/** * Start a session on the current isolation scope. * * @param context (optional) additional properties to be applied to the returned session object * * @returns the new active session */function startSession(context) { const client = getClient(); const isolationScope = getIsolationScope(); const currentScope = getCurrentScope(); const { release, environment = DEFAULT_ENVIRONMENT } = (client && client.getOptions()) || {}; // Will fetch userAgent if called from browser sdk const { userAgent } = GLOBAL_OBJ.navigator || {}; const session = makeSession({ release, environment, user: currentScope.getUser() || isolationScope.getUser(), ...(userAgent && { userAgent }), ...context, }); // End existing session if there's one const currentSession = isolationScope.getSession(); if (currentSession && currentSession.status === 'ok') { updateSession(currentSession, { status: 'exited' }); } endSession(); // Afterwards we set the new session on the scope isolationScope.setSession(session); // TODO (v8): Remove this and only use the isolation scope(?). // For v7 though, we can't "soft-break" people using getCurrentHub().getScope().setSession() currentScope.setSession(session); return session;}
/** * End the session on the current isolation scope. */function endSession() { const isolationScope = getIsolationScope(); const currentScope = getCurrentScope(); const session = currentScope.getSession() || isolationScope.getSession(); if (session) { closeSession(session); } _sendSessionUpdate(); // the session is over; take it off of the scope isolationScope.setSession(); // TODO (v8): Remove this and only use the isolation scope(?). // For v7 though, we can't "soft-break" people using getCurrentHub().getScope().setSession() currentScope.setSession();}
/** * Sends the current Session on the scope */function _sendSessionUpdate() { const isolationScope = getIsolationScope(); const currentScope = getCurrentScope(); const client = getClient(); // TODO (v8): Remove currentScope and only use the isolation scope(?). // For v7 though, we can't "soft-break" people using getCurrentHub().getScope().setSession() const session = currentScope.getSession() || isolationScope.getSession(); if (session && client && client.captureSession) { client.captureSession(session); }}
/** * Sends the current session on the scope to Sentry * * @param end If set the session will be marked as exited and removed from the scope. * Defaults to `false`. */function captureSession(end = false) { // both send the update and pull the session from the scope if (end) { endSession(); return; } // only send the update _sendSessionUpdate();}
/** * Returns the root span of a given span. * * As long as we use `Transaction`s internally, the returned root span * will be a `Transaction` but be aware that this might change in the future. * * If the given span has no root span or transaction, `undefined` is returned. */function getRootSpan(span) { // TODO (v8): Remove this check and just return span // eslint-disable-next-line deprecation/deprecation return span.transaction;}
/** * Creates a dynamic sampling context from a client. * * Dispatches the `createDsc` lifecycle hook as a side effect. */function getDynamicSamplingContextFromClient( trace_id, client, scope,) { const options = client.getOptions(); const { publicKey: public_key } = client.getDsn() || {}; // TODO(v8): Remove segment from User // eslint-disable-next-line deprecation/deprecation const { segment: user_segment } = (scope && scope.getUser()) || {}; const dsc = dropUndefinedKeys({ environment: options.environment || DEFAULT_ENVIRONMENT, release: options.release, user_segment, public_key, trace_id, }) ; client.emit && client.emit('createDsc', dsc); return dsc;}
/** * A Span with a frozen dynamic sampling context. *//** * Creates a dynamic sampling context from a span (and client and scope) * * @param span the span from which a few values like the root span name and sample rate are extracted. * * @returns a dynamic sampling context */function getDynamicSamplingContextFromSpan(span) { const client = getClient(); if (!client) { return {}; } // passing emit=false here to only emit later once the DSC is actually populated const dsc = getDynamicSamplingContextFromClient(spanToJSON(span).trace_id || '', client, getCurrentScope()); // TODO (v8): Remove v7FrozenDsc as a Transaction will no longer have _frozenDynamicSamplingContext const txn = getRootSpan(span) ; if (!txn) { return dsc; } // TODO (v8): Remove v7FrozenDsc as a Transaction will no longer have _frozenDynamicSamplingContext // For now we need to avoid breaking users who directly created a txn with a DSC, where this field is still set. // @see Transaction class constructor const v7FrozenDsc = txn && txn._frozenDynamicSamplingContext; if (v7FrozenDsc) { return v7FrozenDsc; } // TODO (v8): Replace txn.metadata with txn.attributes[] // We can't do this yet because attributes aren't always set yet. // eslint-disable-next-line deprecation/deprecation const { sampleRate: maybeSampleRate, source } = txn.metadata; if (maybeSampleRate != null) { dsc.sample_rate = `${maybeSampleRate}`; } // We don't want to have a transaction name in the DSC if the source is "url" because URLs might contain PII const jsonSpan = spanToJSON(txn); // after JSON conversion, txn.name becomes jsonSpan.description if (source && source !== 'url') { dsc.transaction = jsonSpan.description; } dsc.sampled = String(spanIsSampled(txn)); client.emit && client.emit('createDsc', dsc); return dsc;}
/** * Applies data from the scope to the event and runs all event processors on it. */function applyScopeDataToEvent(event, data) { const { fingerprint, span, breadcrumbs, sdkProcessingMetadata } = data; // Apply general data applyDataToEvent(event, data); // We want to set the trace context for normal events only if there isn't already // a trace context on the event. There is a product feature in place where we link // errors with transaction and it relies on that. if (span) { applySpanToEvent(event, span); } applyFingerprintToEvent(event, fingerprint); applyBreadcrumbsToEvent(event, breadcrumbs); applySdkMetadataToEvent(event, sdkProcessingMetadata);}
/** Merge data of two scopes together. */function mergeScopeData(data, mergeData) { const { extra, tags, user, contexts, level, sdkProcessingMetadata, breadcrumbs, fingerprint, eventProcessors, attachments, propagationContext, // eslint-disable-next-line deprecation/deprecation transactionName, span, } = mergeData; mergeAndOverwriteScopeData(data, 'extra', extra); mergeAndOverwriteScopeData(data, 'tags', tags); mergeAndOverwriteScopeData(data, 'user', user); mergeAndOverwriteScopeData(data, 'contexts', contexts); mergeAndOverwriteScopeData(data, 'sdkProcessingMetadata', sdkProcessingMetadata); if (level) { data.level = level; } if (transactionName) { // eslint-disable-next-line deprecation/deprecation data.transactionName = transactionName; } if (span) { data.span = span; } if (breadcrumbs.length) { data.breadcrumbs = [...data.breadcrumbs, ...breadcrumbs]; } if (fingerprint.length) { data.fingerprint = [...data.fingerprint, ...fingerprint]; } if (eventProcessors.length) { data.eventProcessors = [...data.eventProcessors, ...eventProcessors]; } if (attachments.length) { data.attachments = [...data.attachments, ...attachments]; } data.propagationContext = { ...data.propagationContext, ...propagationContext };}
/** * Merges certain scope data. Undefined values will overwrite any existing values. * Exported only for tests. */function mergeAndOverwriteScopeData
(data, prop, mergeVal) { if (mergeVal && Object.keys(mergeVal).length) { // Clone object data[prop] = { ...data[prop] }; for (const key in mergeVal) { if (Object.prototype.hasOwnProperty.call(mergeVal, key)) { data[prop][key] = mergeVal[key]; } } }}
function applyDataToEvent(event, data) { const { extra, tags, user, contexts, level, // eslint-disable-next-line deprecation/deprecation transactionName, } = data; const cleanedExtra = dropUndefinedKeys(extra); if (cleanedExtra && Object.keys(cleanedExtra).length) { event.extra = { ...cleanedExtra, ...event.extra }; } const cleanedTags = dropUndefinedKeys(tags); if (cleanedTags && Object.keys(cleanedTags).length) { event.tags = { ...cleanedTags, ...event.tags }; } const cleanedUser = dropUndefinedKeys(user); if (cleanedUser && Object.keys(cleanedUser).length) { event.user = { ...cleanedUser, ...event.user }; } const cleanedContexts = dropUndefinedKeys(contexts); if (cleanedContexts && Object.keys(cleanedContexts).length) { event.contexts = { ...cleanedContexts, ...event.contexts }; } if (level) { event.level = level; } if (transactionName) { event.transaction = transactionName; }}
function applyBreadcrumbsToEvent(event, breadcrumbs) { const mergedBreadcrumbs = [...(event.breadcrumbs || []), ...breadcrumbs]; event.breadcrumbs = mergedBreadcrumbs.length ? mergedBreadcrumbs : undefined;}
function applySdkMetadataToEvent(event, sdkProcessingMetadata) { event.sdkProcessingMetadata = { ...event.sdkProcessingMetadata, ...sdkProcessingMetadata, };}
function applySpanToEvent(event, span) { event.contexts = { trace: spanToTraceContext(span), ...event.contexts }; const rootSpan = getRootSpan(span); if (rootSpan) { event.sdkProcessingMetadata = { dynamicSamplingContext: getDynamicSamplingContextFromSpan(span), ...event.sdkProcessingMetadata, }; const transactionName = spanToJSON(rootSpan).description; if (transactionName) { event.tags = { transaction: transactionName, ...event.tags }; } }}
/** * Applies fingerprint from the scope to the event if there's one, * uses message if there's one instead or get rid of empty fingerprint */function applyFingerprintToEvent(event, fingerprint) { // Make sure it's an array first and we actually have something in place event.fingerprint = event.fingerprint ? arrayify(event.fingerprint) : []; // If we have something on the scope, then merge it with event if (fingerprint) { event.fingerprint = event.fingerprint.concat(fingerprint); } // If we have no data at all, remove empty array default if (event.fingerprint && !event.fingerprint.length) { delete event.fingerprint; }}
/** * Default value for maximum number of breadcrumbs added to an event. */const DEFAULT_MAX_BREADCRUMBS = 100;
/** * The global scope is kept in this module. * When accessing this via `getGlobalScope()` we'll make sure to set one if none is currently present. */let globalScope;
/** * Holds additional event information. {@link Scope.applyToEvent} will be * called by the client before an event will be sent. */class Scope { /** Flag if notifying is happening. */ /** Callback for client to receive scope changes. */ /** Callback list that will be called after {@link applyToEvent}. */ /** Array of breadcrumbs. */ /** User */ /** Tags */ /** Extra */ /** Contexts */ /** Attachments */ /** Propagation Context for distributed tracing */ /** * A place to stash data which is needed at some point in the SDK's event processing pipeline but which shouldn't get * sent to Sentry */ /** Fingerprint */ /** Severity */ // eslint-disable-next-line deprecation/deprecation /** * Transaction Name */ /** Span */ /** Session */ /** Request Mode Session Status */ /** The client on this scope */ // NOTE: Any field which gets added here should get added not only to the constructor but also to the `clone` method. constructor() { this._notifyingListeners = false; this._scopeListeners = []; this._eventProcessors = []; this._breadcrumbs = []; this._attachments = []; this._user = {}; this._tags = {}; this._extra = {}; this._contexts = {}; this._sdkProcessingMetadata = {}; this._propagationContext = generatePropagationContext(); } /** * Inherit values from the parent scope. * @deprecated Use `scope.clone()` and `new Scope()` instead. */ static clone(scope) { return scope ? scope.clone() : new Scope(); } /** * Clone this scope instance. */ clone() { const newScope = new Scope(); newScope._breadcrumbs = [...this._breadcrumbs]; newScope._tags = { ...this._tags }; newScope._extra = { ...this._extra }; newScope._contexts = { ...this._contexts }; newScope._user = this._user; newScope._level = this._level; newScope._span = this._span; newScope._session = this._session; newScope._transactionName = this._transactionName; newScope._fingerprint = this._fingerprint; newScope._eventProcessors = [...this._eventProcessors]; newScope._requestSession = this._requestSession; newScope._attachments = [...this._attachments]; newScope._sdkProcessingMetadata = { ...this._sdkProcessingMetadata }; newScope._propagationContext = { ...this._propagationContext }; newScope._client = this._client; return newScope; } /** Update the client on the scope. */ setClient(client) { this._client = client; } /** * Get the client assigned to this scope. * * It is generally recommended to use the global function `Sentry.getClient()` instead, unless you know what you are doing. */ getClient() { return this._client; } /** * Add internal on change listener. Used for sub SDKs that need to store the scope. * @hidden */ addScopeListener(callback) { this._scopeListeners.push(callback); } /** * @inheritDoc */ addEventProcessor(callback) { this._eventProcessors.push(callback); return this; } /** * @inheritDoc */ setUser(user) { // If null is passed we want to unset everything, but still define keys, // so that later down in the pipeline any existing values are cleared. this._user = user || { email: undefined, id: undefined, ip_address: undefined, segment: undefined, username: undefined, }; if (this._session) { updateSession(this._session, { user }); } this._notifyScopeListeners(); return this; } /** * @inheritDoc */ getUser() { return this._user; } /** * @inheritDoc */ getRequestSession() { return this._requestSession; } /** * @inheritDoc */ setRequestSession(requestSession) { this._requestSession = requestSession; return this; } /** * @inheritDoc */ setTags(tags) { this._tags = { ...this._tags, ...tags, }; this._notifyScopeListeners(); return this; } /** * @inheritDoc */ setTag(key, value) { this._tags = { ...this._tags, [key]: value }; this._notifyScopeListeners(); return this; } /** * @inheritDoc */ setExtras(extras) { this._extra = { ...this._extra, ...extras, }; this._notifyScopeListeners(); return this; } /** * @inheritDoc */ setExtra(key, extra) { this._extra = { ...this._extra, [key]: extra }; this._notifyScopeListeners(); return this; } /** * @inheritDoc */ setFingerprint(fingerprint) { this._fingerprint = fingerprint; this._notifyScopeListeners(); return this; } /** * @inheritDoc */ setLevel( // eslint-disable-next-line deprecation/deprecation level, ) { this._level = level; this._notifyScopeListeners(); return this; } /** * Sets the transaction name on the scope for future events. */ setTransactionName(name) { this._transactionName = name; this._notifyScopeListeners(); return this; } /** * @inheritDoc */ setContext(key, context) { if (context === null) { // eslint-disable-next-line @typescript-eslint/no-dynamic-delete delete this._contexts[key]; } else { this._contexts[key] = context; } this._notifyScopeListeners(); return this; } /** * Sets the Span on the scope. * @param span Span * @deprecated Instead of setting a span on a scope, use `startSpan()`/`startSpanManual()` instead. */ setSpan(span) { this._span = span; this._notifyScopeListeners(); return this; } /** * Returns the `Span` if there is one. * @deprecated Use `getActiveSpan()` instead. */ getSpan() { return this._span; } /** * Returns the `Transaction` attached to the scope (if there is one). * @deprecated You should not rely on the transaction, but just use `startSpan()` APIs instead. */ getTransaction() { // Often, this span (if it exists at all) will be a transaction, but it's not guaranteed to be. Regardless, it will // have a pointer to the currently-active transaction. const span = this._span; // Cannot replace with getRootSpan because getRootSpan returns a span, not a transaction // Also, this method will be removed anyway. // eslint-disable-next-line deprecation/deprecation return span && span.transaction; } /** * @inheritDoc */ setSession(session) { if (!session) { delete this._session; } else { this._session = session; } this._notifyScopeListeners(); return this; } /** * @inheritDoc */ getSession() { return this._session; } /** * @inheritDoc */ update(captureContext) { if (!captureContext) { return this; } const scopeToMerge = typeof captureContext === 'function' ? captureContext(this) : captureContext; if (scopeToMerge instanceof Scope) { const scopeData = scopeToMerge.getScopeData(); this._tags = { ...this._tags, ...scopeData.tags }; this._extra = { ...this._extra, ...scopeData.extra }; this._contexts = { ...this._contexts, ...scopeData.contexts }; if (scopeData.user && Object.keys(scopeData.user).length) { this._user = scopeData.user; } if (scopeData.level) { this._level = scopeData.level; } if (scopeData.fingerprint.length) { this._fingerprint = scopeData.fingerprint; } if (scopeToMerge.getRequestSession()) { this._requestSession = scopeToMerge.getRequestSession(); } if (scopeData.propagationContext) { this._propagationContext = scopeData.propagationContext; } } else if (isPlainObject(scopeToMerge)) { const scopeContext = captureContext ; this._tags = { ...this._tags, ...scopeContext.tags }; this._extra = { ...this._extra, ...scopeContext.extra }; this._contexts = { ...this._contexts, ...scopeContext.contexts }; if (scopeContext.user) { this._user = scopeContext.user; } if (scopeContext.level) { this._level = scopeContext.level; } if (scopeContext.fingerprint) { this._fingerprint = scopeContext.fingerprint; } if (scopeContext.requestSession) { this._requestSession = scopeContext.requestSession; } if (scopeContext.propagationContext) { this._propagationContext = scopeContext.propagationContext; } } return this; } /** * @inheritDoc */ clear() { this._breadcrumbs = []; this._tags = {}; this._extra = {}; this._user = {}; this._contexts = {}; this._level = undefined; this._transactionName = undefined; this._fingerprint = undefined; this._requestSession = undefined; this._span = undefined; this._session = undefined; this._notifyScopeListeners(); this._attachments = []; this._propagationContext = generatePropagationContext(); return this; } /** * @inheritDoc */ addBreadcrumb(breadcrumb, maxBreadcrumbs) { const maxCrumbs = typeof maxBreadcrumbs === 'number' ? maxBreadcrumbs : DEFAULT_MAX_BREADCRUMBS; // No data has been changed, so don't notify scope listeners if (maxCrumbs <= 0) { return this; } const mergedBreadcrumb = { timestamp: dateTimestampInSeconds(), ...breadcrumb, }; const breadcrumbs = this._breadcrumbs; breadcrumbs.push(mergedBreadcrumb); this._breadcrumbs = breadcrumbs.length > maxCrumbs ? breadcrumbs.slice(-maxCrumbs) : breadcrumbs; this._notifyScopeListeners(); return this; } /** * @inheritDoc */ getLastBreadcrumb() { return this._breadcrumbs[this._breadcrumbs.length - 1]; } /** * @inheritDoc */ clearBreadcrumbs() { this._breadcrumbs = []; this._notifyScopeListeners(); return this; } /** * @inheritDoc */ addAttachment(attachment) { this._attachments.push(attachment); return this; } /** * @inheritDoc * @deprecated Use `getScopeData()` instead. */ getAttachments() { const data = this.getScopeData(); return data.attachments; } /** * @inheritDoc */ clearAttachments() { this._attachments = []; return this; } /** @inheritDoc */ getScopeData() { const { _breadcrumbs, _attachments, _contexts, _tags, _extra, _user, _level, _fingerprint, _eventProcessors, _propagationContext, _sdkProcessingMetadata, _transactionName, _span, } = this; return { breadcrumbs: _breadcrumbs, attachments: _attachments, contexts: _contexts, tags: _tags, extra: _extra, user: _user, level: _level, fingerprint: _fingerprint || [], eventProcessors: _eventProcessors, propagationContext: _propagationContext, sdkProcessingMetadata: _sdkProcessingMetadata, transactionName: _transactionName, span: _span, }; } /** * Applies data from the scope to the event and runs all event processors on it. * * @param event Event * @param hint Object containing additional information about the original exception, for use by the event processors. * @hidden * @deprecated Use `applyScopeDataToEvent()` directly */ applyToEvent( event, hint = {}, additionalEventProcessors = [], ) { applyScopeDataToEvent(event, this.getScopeData()); // TODO (v8): Update this order to be: Global > Client > Scope const eventProcessors = [ ...additionalEventProcessors, // eslint-disable-next-line deprecation/deprecation ...getGlobalEventProcessors(), ...this._eventProcessors, ]; return notifyEventProcessors(eventProcessors, event, hint); } /** * Add data which will be accessible during event processing but won't get sent to Sentry */ setSDKProcessingMetadata(newData) { this._sdkProcessingMetadata = { ...this._sdkProcessingMetadata, ...newData }; return this; } /** * @inheritDoc */ setPropagationContext(context) { this._propagationContext = context; return this; } /** * @inheritDoc */ getPropagationContext() { return this._propagationContext; } /** * Capture an exception for this scope. * * @param exception The exception to capture. * @param hint Optinal additional data to attach to the Sentry event. * @returns the id of the captured Sentry event. */ captureException(exception, hint) { const eventId = hint && hint.event_id ? hint.event_id : uuid4(); if (!this._client) { logger.warn('No client configured on scope - will not capture exception!'); return eventId; } const syntheticException = new Error('Sentry syntheticException'); this._client.captureException( exception, { originalException: exception, syntheticException, ...hint, event_id: eventId, }, this, ); return eventId; } /** * Capture a message for this scope. * * @param message The message to capture. * @param level An optional severity level to report the message with. * @param hint Optional additional data to attach to the Sentry event. * @returns the id of the captured message. */ captureMessage(message, level, hint) { const eventId = hint && hint.event_id ? hint.event_id : uuid4(); if (!this._client) { logger.warn('No client configured on scope - will not capture message!'); return eventId; } const syntheticException = new Error(message); this._client.captureMessage( message, level, { originalException: message, syntheticException, ...hint, event_id: eventId, }, this, ); return eventId; } /** * Captures a manually created event for this scope and sends it to Sentry. * * @param exception The event to capture. * @param hint Optional additional data to attach to the Sentry event. * @returns the id of the captured event. */ captureEvent(event, hint) { const eventId = hint && hint.event_id ? hint.event_id : uuid4(); if (!this._client) { logger.warn('No client configured on scope - will not capture event!'); return eventId; } this._client.captureEvent(event, { ...hint, event_id: eventId }, this); return eventId; } /** * This will be called on every set call. */ _notifyScopeListeners() { // We need this check for this._notifyingListeners to be able to work on scope during updates // If this check is not here we'll produce endless recursion when something is done with the scope // during the callback. if (!this._notifyingListeners) { this._notifyingListeners = true; this._scopeListeners.forEach(callback => { callback(this); }); this._notifyingListeners = false; } }}
/** * Get the global scope. * This scope is applied to _all_ events. */function getGlobalScope() { if (!globalScope) { globalScope = new Scope(); } return globalScope;}
function generatePropagationContext() { return { traceId: uuid4(), spanId: uuid4().substring(16), };}
const SDK_VERSION = '7.109.0';
/** * API compatibility version of this hub. * * WARNING: This number should only be increased when the global interface * changes and new methods are introduced. * * @hidden */const API_VERSION = parseFloat(SDK_VERSION);
/** * Default maximum number of breadcrumbs added to an event. Can be overwritten * with {@link Options.maxBreadcrumbs}. */const DEFAULT_BREADCRUMBS = 100;
/** * @inheritDoc */class Hub { /** Is a {@link Layer}[] containing the client and scope */ /** Contains the last event id of a captured event. */ /** * Creates a new instance of the hub, will push one {@link Layer} into the * internal stack on creation. * * @param client bound to the hub. * @param scope bound to the hub. * @param version number, higher number means higher priority. * * @deprecated Instantiation of Hub objects is deprecated and the constructor will be removed in version 8 of the SDK. * * If you are currently using the Hub for multi-client use like so: * * ``` * // OLD * const hub = new Hub(); * hub.bindClient(client); * makeMain(hub) * ``` * * instead initialize the client as follows: * * ``` * // NEW * Sentry.withIsolationScope(() => { * Sentry.setCurrentClient(client); * client.init(); * }); * ``` * * If you are using the Hub to capture events like so: * * ``` * // OLD * const client = new Client(); * const hub = new Hub(client); * hub.captureException() * ``` * * instead capture isolated events as follows: * * ``` * // NEW * const client = new Client(); * const scope = new Scope(); * scope.setClient(client); * scope.captureException(); * ``` */ constructor( client, scope, isolationScope, _version = API_VERSION, ) {this._version = _version; let assignedScope; if (!scope) { assignedScope = new Scope(); assignedScope.setClient(client); } else { assignedScope = scope; } let assignedIsolationScope; if (!isolationScope) { assignedIsolationScope = new Scope(); assignedIsolationScope.setClient(client); } else { assignedIsolationScope = isolationScope; } this._stack = [{ scope: assignedScope }]; if (client) { // eslint-disable-next-line deprecation/deprecation this.bindClient(client); } this._isolationScope = assignedIsolationScope; } /** * Checks if this hub's version is older than the given version. * * @param version A version number to compare to. * @return True if the given version is newer; otherwise false. * * @deprecated This will be removed in v8. */ isOlderThan(version) { return this._version < version; } /** * This binds the given client to the current scope. * @param client An SDK client (client) instance. * * @deprecated Use `initAndBind()` directly, or `setCurrentClient()` and/or `client.init()` instead. */ bindClient(client) { // eslint-disable-next-line deprecation/deprecation const top = this.getStackTop(); top.client = client; top.scope.setClient(client); // eslint-disable-next-line deprecation/deprecation if (client && client.setupIntegrations) { // eslint-disable-next-line deprecation/deprecation client.setupIntegrations(); } } /** * @inheritDoc * * @deprecated Use `withScope` instead. */ pushScope() { // We want to clone the content of prev scope // eslint-disable-next-line deprecation/deprecation const scope = this.getScope().clone(); // eslint-disable-next-line deprecation/deprecation this.getStack().push({ // eslint-disable-next-line deprecation/deprecation client: this.getClient(), scope, }); return scope; } /** * @inheritDoc * * @deprecated Use `withScope` instead. */ popScope() { // eslint-disable-next-line deprecation/deprecation if (this.getStack().length <= 1) return false; // eslint-disable-next-line deprecation/deprecation return !!this.getStack().pop(); } /** * @inheritDoc * * @deprecated Use `Sentry.withScope()` instead. */ withScope(callback) { // eslint-disable-next-line deprecation/deprecation const scope = this.pushScope(); let maybePromiseResult; try { maybePromiseResult = callback(scope); } catch (e) { // eslint-disable-next-line deprecation/deprecation this.popScope(); throw e; } if (isThenable(maybePromiseResult)) { // @ts-expect-error - isThenable returns the wrong type return maybePromiseResult.then( res => { // eslint-disable-next-line deprecation/deprecation this.popScope(); return res; }, e => { // eslint-disable-next-line deprecation/deprecation this.popScope(); throw e; }, ); } // eslint-disable-next-line deprecation/deprecation this.popScope(); return maybePromiseResult; } /** * @inheritDoc * * @deprecated Use `Sentry.getClient()` instead. */ getClient() { // eslint-disable-next-line deprecation/deprecation return this.getStackTop().client ; } /** * Returns the scope of the top stack. * * @deprecated Use `Sentry.getCurrentScope()` instead. */ getScope() { // eslint-disable-next-line deprecation/deprecation return this.getStackTop().scope; } /** * @deprecated Use `Sentry.getIsolationScope()` instead. */ getIsolationScope() { return this._isolationScope; } /** * Returns the scope stack for domains or the process. * @deprecated This will be removed in v8. */ getStack() { return this._stack; } /** * Returns the topmost scope layer in the order domain > local > process. * @deprecated This will be removed in v8. */ getStackTop() { return this._stack[this._stack.length - 1]; } /** * @inheritDoc * * @deprecated Use `Sentry.captureException()` instead. */ captureException(exception, hint) { const eventId = (this._lastEventId = hint && hint.event_id ? hint.event_id : uuid4()); const syntheticException = new Error('Sentry syntheticException'); // eslint-disable-next-line deprecation/deprecation this.getScope().captureException(exception, { originalException: exception, syntheticException, ...hint, event_id: eventId, }); return eventId; } /** * @inheritDoc * * @deprecated Use `Sentry.captureMessage()` instead. */ captureMessage( message, // eslint-disable-next-line deprecation/deprecation level, hint, ) { const eventId = (this._lastEventId = hint && hint.event_id ? hint.event_id : uuid4()); const syntheticException = new Error(message); // eslint-disable-next-line deprecation/deprecation this.getScope().captureMessage(message, level, { originalException: message, syntheticException, ...hint, event_id: eventId, }); return eventId; } /** * @inheritDoc * * @deprecated Use `Sentry.captureEvent()` instead. */ captureEvent(event, hint) { const eventId = hint && hint.event_id ? hint.event_id : uuid4(); if (!event.type) { this._lastEventId = eventId; } // eslint-disable-next-line deprecation/deprecation this.getScope().captureEvent(event, { ...hint, event_id: eventId }); return eventId; } /** * @inheritDoc * * @deprecated This will be removed in v8. */ lastEventId() { return this._lastEventId; } /** * @inheritDoc * * @deprecated Use `Sentry.addBreadcrumb()` instead. */ addBreadcrumb(breadcrumb, hint) { // eslint-disable-next-line deprecation/deprecation const { scope, client } = this.getStackTop(); if (!client) return; const { beforeBreadcrumb = null, maxBreadcrumbs = DEFAULT_BREADCRUMBS } = (client.getOptions && client.getOptions()) || {}; if (maxBreadcrumbs <= 0) return; const timestamp = dateTimestampInSeconds(); const mergedBreadcrumb = { timestamp, ...breadcrumb }; const finalBreadcrumb = beforeBreadcrumb ? (consoleSandbox(() => beforeBreadcrumb(mergedBreadcrumb, hint)) ) : mergedBreadcrumb; if (finalBreadcrumb === null) return; if (client.emit) { client.emit('beforeAddBreadcrumb', finalBreadcrumb, hint); } // TODO(v8): I know this comment doesn't make much sense because the hub will be deprecated but I still wanted to // write it down. In theory, we would have to add the breadcrumbs to the isolation scope here, however, that would // duplicate all of the breadcrumbs. There was the possibility of adding breadcrumbs to both, the isolation scope // and the normal scope, and deduplicating it down the line in the event processing pipeline. However, that would // have been very fragile, because the breadcrumb objects would have needed to keep their identity all throughout // the event processing pipeline. // In the new implementation, the top level `Sentry.addBreadcrumb()` should ONLY write to the isolation scope. scope.addBreadcrumb(finalBreadcrumb, maxBreadcrumbs); } /** * @inheritDoc * @deprecated Use `Sentry.setUser()` instead. */ setUser(user) { // TODO(v8): The top level `Sentry.setUser()` function should write ONLY to the isolation scope. // eslint-disable-next-line deprecation/deprecation this.getScope().setUser(user); // eslint-disable-next-line deprecation/deprecation this.getIsolationScope().setUser(user); } /** * @inheritDoc * @deprecated Use `Sentry.setTags()` instead. */ setTags(tags) { // TODO(v8): The top level `Sentry.setTags()` function should write ONLY to the isolation scope. // eslint-disable-next-line deprecation/deprecation this.getScope().setTags(tags); // eslint-disable-next-line deprecation/deprecation this.getIsolationScope().setTags(tags); } /** * @inheritDoc * @deprecated Use `Sentry.setExtras()` instead. */ setExtras(extras) { // TODO(v8): The top level `Sentry.setExtras()` function should write ONLY to the isolation scope. // eslint-disable-next-line deprecation/deprecation this.getScope().setExtras(extras); // eslint-disable-next-line deprecation/deprecation this.getIsolationScope().setExtras(extras); } /** * @inheritDoc * @deprecated Use `Sentry.setTag()` instead. */ setTag(key, value) { // TODO(v8): The top level `Sentry.setTag()` function should write ONLY to the isolation scope. // eslint-disable-next-line deprecation/deprecation this.getScope().setTag(key, value); // eslint-disable-next-line deprecation/deprecation this.getIsolationScope().setTag(key, value); } /** * @inheritDoc * @deprecated Use `Sentry.setExtra()` instead. */ setExtra(key, extra) { // TODO(v8): The top level `Sentry.setExtra()` function should write ONLY to the isolation scope. // eslint-disable-next-line deprecation/deprecation this.getScope().setExtra(key, extra); // eslint-disable-next-line deprecation/deprecation this.getIsolationScope().setExtra(key, extra); } /** * @inheritDoc * @deprecated Use `Sentry.setContext()` instead. */ // eslint-disable-next-line @typescript-eslint/no-explicit-any setContext(name, context) { // TODO(v8): The top level `Sentry.setContext()` function should write ONLY to the isolation scope. // eslint-disable-next-line deprecation/deprecation this.getScope().setContext(name, context); // eslint-disable-next-line deprecation/deprecation this.getIsolationScope().setContext(name, context); } /** * @inheritDoc * * @deprecated Use `getScope()` directly. */ configureScope(callback) { // eslint-disable-next-line deprecation/deprecation const { scope, client } = this.getStackTop(); if (client) { callback(scope); } } /** * @inheritDoc */ run(callback) { // eslint-disable-next-line deprecation/deprecation const oldHub = makeMain(this); try { callback(this); } finally { // eslint-disable-next-line deprecation/deprecation makeMain(oldHub); } } /** * @inheritDoc * @deprecated Use `Sentry.getClient().getIntegrationByName()` instead. */ getIntegration(integration) { // eslint-disable-next-line deprecation/deprecation const client = this.getClient(); if (!client) return null; try { // eslint-disable-next-line deprecation/deprecation return client.getIntegration(integration); } catch (_oO) { DEBUG_BUILD$1 && logger.warn(`Cannot retrieve integration ${integration.id} from the current Hub`); return null; } } /** * Starts a new `Transaction` and returns it. This is the entry point to manual tracing instrumentation. * * A tree structure can be built by adding child spans to the transaction, and child spans to other spans. To start a * new child span within the transaction or any span, call the respective `.startChild()` method. * * Every child span must be finished before the transaction is finished, otherwise the unfinished spans are discarded. * * The transaction must be finished with a call to its `.end()` method, at which point the transaction with all its * finished child spans will be sent to Sentry. * * @param context Properties of the new `Transaction`. * @param customSamplingContext Information given to the transaction sampling function (along with context-dependent * default values). See {@link Options.tracesSampler}. * * @returns The transaction which was just started * * @deprecated Use `startSpan()`, `startSpanManual()` or `startInactiveSpan()` instead. */ startTransaction(context, customSamplingContext) { const result = this._callExtensionMethod('startTransaction', context, customSamplingContext); if (DEBUG_BUILD$1 && !result) { // eslint-disable-next-line deprecation/deprecation const client = this.getClient(); if (!client) { logger.warn( "Tracing extension 'startTransaction' is missing. You should 'init' the SDK before calling 'startTransaction'", ); } else { logger.warn(`Tracing extension 'startTransaction' has not been added. Call 'addTracingExtensions' before calling 'init':Sentry.addTracingExtensions();Sentry.init({...});`); } } return result; } /** * @inheritDoc * @deprecated Use `spanToTraceHeader()` instead. */ traceHeaders() { return this._callExtensionMethod('traceHeaders'); } /** * @inheritDoc * * @deprecated Use top level `captureSession` instead. */ captureSession(endSession = false) { // both send the update and pull the session from the scope if (endSession) { // eslint-disable-next-line deprecation/deprecation return this.endSession(); } // only send the update this._sendSessionUpdate(); } /** * @inheritDoc * @deprecated Use top level `endSession` instead. */ endSession() { // eslint-disable-next-line deprecation/deprecation const layer = this.getStackTop(); const scope = layer.scope; const session = scope.getSession(); if (session) { closeSession(session); } this._sendSessionUpdate(); // the session is over; take it off of the scope scope.setSession(); } /** * @inheritDoc * @deprecated Use top level `startSession` instead. */ startSession(context) { // eslint-disable-next-line deprecation/deprecation const { scope, client } = this.getStackTop(); const { release, environment = DEFAULT_ENVIRONMENT } = (client && client.getOptions()) || {}; // Will fetch userAgent if called from browser sdk const { userAgent } = GLOBAL_OBJ.navigator || {}; const session = makeSession({ release, environment, user: scope.getUser(), ...(userAgent && { userAgent }), ...context, }); // End existing session if there's one const currentSession = scope.getSession && scope.getSession(); if (currentSession && currentSession.status === 'ok') { updateSession(currentSession, { status: 'exited' }); } // eslint-disable-next-line deprecation/deprecation this.endSession(); // Afterwards we set the new session on the scope scope.setSession(session); return session; } /** * Returns if default PII should be sent to Sentry and propagated in ourgoing requests * when Tracing is used. * * @deprecated Use top-level `getClient().getOptions().sendDefaultPii` instead. This function * only unnecessarily increased API surface but only wrapped accessing the option. */ shouldSendDefaultPii() { // eslint-disable-next-line deprecation/deprecation const client = this.getClient(); const options = client && client.getOptions(); return Boolean(options && options.sendDefaultPii); } /** * Sends the current Session on the scope */ _sendSessionUpdate() { // eslint-disable-next-line deprecation/deprecation const { scope, client } = this.getStackTop(); const session = scope.getSession(); if (session && client && client.captureSession) { client.captureSession(session); } } /** * Calls global extension method and binding current instance to the function call */ // @ts-expect-error Function lacks ending return statement and return type does not include 'undefined'. ts(2366) // eslint-disable-next-line @typescript-eslint/no-explicit-any _callExtensionMethod(method, ...args) { const carrier = getMainCarrier(); const sentry = carrier.__SENTRY__; if (sentry && sentry.extensions && typeof sentry.extensions[method] === 'function') { return sentry.extensions[method].apply(this, args); } DEBUG_BUILD$1 && logger.warn(`Extension method ${method} couldn't be found, doing nothing.`); }}
/** * Returns the global shim registry. * * FIXME: This function is problematic, because despite always returning a valid Carrier, * it has an optional `__SENTRY__` property, which then in turn requires us to always perform an unnecessary check * at the call-site. We always access the carrier through this function, so we can guarantee that `__SENTRY__` is there. **/function getMainCarrier() { GLOBAL_OBJ.__SENTRY__ = GLOBAL_OBJ.__SENTRY__ || { extensions: {}, hub: undefined, }; return GLOBAL_OBJ;}
/** * Replaces the current main hub with the passed one on the global object * * @returns The old replaced hub * * @deprecated Use `setCurrentClient()` instead. */function makeMain(hub) { const registry = getMainCarrier(); const oldHub = getHubFromCarrier(registry); setHubOnCarrier(registry, hub); return oldHub;}
/** * Returns the default hub instance. * * If a hub is already registered in the global carrier but this module * contains a more recent version, it replaces the registered version. * Otherwise, the currently registered hub will be returned. * * @deprecated Use the respective replacement method directly instead. */function getCurrentHub() { // Get main carrier (global for every environment) const registry = getMainCarrier(); if (registry.__SENTRY__ && registry.__SENTRY__.acs) { const hub = registry.__SENTRY__.acs.getCurrentHub(); if (hub) { return hub; } } // Return hub that lives on a global object return getGlobalHub(registry);}
/** * Get the currently active isolation scope. * The isolation scope is active for the current exection context, * meaning that it will remain stable for the same Hub. */function getIsolationScope() { // eslint-disable-next-line deprecation/deprecation return getCurrentHub().getIsolationScope();}
function getGlobalHub(registry = getMainCarrier()) { // If there's no hub, or its an old API, assign a new one if ( !hasHubOnCarrier(registry) || // eslint-disable-next-line deprecation/deprecation getHubFromCarrier(registry).isOlderThan(API_VERSION) ) { // eslint-disable-next-line deprecation/deprecation setHubOnCarrier(registry, new Hub()); } // Return hub that lives on a global object return getHubFromCarrier(registry);}
/** * Runs the supplied callback in its own async context. Async Context strategies are defined per SDK. * * @param callback The callback to run in its own async context * @param options Options to pass to the async context strategy * @returns The result of the callback */function runWithAsyncContext(callback, options = {}) { const registry = getMainCarrier(); if (registry.__SENTRY__ && registry.__SENTRY__.acs) { return registry.__SENTRY__.acs.runWithAsyncContext(callback, options); } // if there was no strategy, fallback to just calling the callback return callback();}
/** * This will tell whether a carrier has a hub on it or not * @param carrier object */function hasHubOnCarrier(carrier) { return !!(carrier && carrier.__SENTRY__ && carrier.__SENTRY__.hub);}
/** * This will create a new {@link Hub} and add to the passed object on * __SENTRY__.hub. * @param carrier object * @hidden */function getHubFromCarrier(carrier) { // eslint-disable-next-line deprecation/deprecation return getGlobalSingleton('hub', () => new Hub(), carrier);}
/** * This will set passed {@link Hub} on the passed object's __SENTRY__.hub attribute * @param carrier object * @param hub Hub * @returns A boolean indicating success or failure */function setHubOnCarrier(carrier, hub) { if (!carrier) return false; const __SENTRY__ = (carrier.__SENTRY__ = carrier.__SENTRY__ || {}); __SENTRY__.hub = hub; return true;}
/** * Grabs active transaction off scope. * * @deprecated You should not rely on the transaction, but just use `startSpan()` APIs instead. */function getActiveTransaction(maybeHub) { // eslint-disable-next-line deprecation/deprecation const hub = maybeHub || getCurrentHub(); // eslint-disable-next-line deprecation/deprecation const scope = hub.getScope(); // eslint-disable-next-line deprecation/deprecation return scope.getTransaction() ;}
/** * The `extractTraceparentData` function and `TRACEPARENT_REGEXP` constant used * to be declared in this file. It was later moved into `@sentry/utils` as part of a * move to remove `@sentry/tracing` dependencies from `@sentry/node` (`extractTraceparentData` * is the only tracing function used by `@sentry/node`). * * These exports are kept here for backwards compatability's sake. * * See https://github.com/getsentry/sentry-javascript/issues/4642 for more details. * * @deprecated Import this function from `@sentry/utils` instead */const extractTraceparentData = extractTraceparentData$1;
let errorsInstrumented = false;
/** * Configures global error listeners */function registerErrorInstrumentation() { if (errorsInstrumented) { return; } errorsInstrumented = true; addGlobalErrorInstrumentationHandler(errorCallback); addGlobalUnhandledRejectionInstrumentationHandler(errorCallback);}
/** * If an error or unhandled promise occurs, we mark the active transaction as failed */function errorCallback() { // eslint-disable-next-line deprecation/deprecation const activeTransaction = getActiveTransaction(); if (activeTransaction) { const status = 'internal_error'; DEBUG_BUILD$1 && logger.log(`[Tracing] Transaction: ${status} -> Global error occured`); activeTransaction.setStatus(status); }}
// The function name will be lost when bundling but we need to be able to identify this listener later to maintain the// node.js default exit behaviourerrorCallback.tag = 'sentry_tracingErrorCallback';
/** The status of an Span. * * @deprecated Use string literals - if you require type casting, cast to SpanStatusType type */var SpanStatus; (function (SpanStatus) { /** The operation completed successfully. */ const Ok = 'ok'; SpanStatus["Ok"] = Ok; /** Deadline expired before operation could complete. */ const DeadlineExceeded = 'deadline_exceeded'; SpanStatus["DeadlineExceeded"] = DeadlineExceeded; /** 401 Unauthorized (actually does mean unauthenticated according to RFC 7235) */ const Unauthenticated = 'unauthenticated'; SpanStatus["Unauthenticated"] = Unauthenticated; /** 403 Forbidden */ const PermissionDenied = 'permission_denied'; SpanStatus["PermissionDenied"] = PermissionDenied; /** 404 Not Found. Some requested entity (file or directory) was not found. */ const NotFound = 'not_found'; SpanStatus["NotFound"] = NotFound; /** 429 Too Many Requests */ const ResourceExhausted = 'resource_exhausted'; SpanStatus["ResourceExhausted"] = ResourceExhausted; /** Client specified an invalid argument. 4xx. */ const InvalidArgument = 'invalid_argument'; SpanStatus["InvalidArgument"] = InvalidArgument; /** 501 Not Implemented */ const Unimplemented = 'unimplemented'; SpanStatus["Unimplemented"] = Unimplemented; /** 503 Service Unavailable */ const Unavailable = 'unavailable'; SpanStatus["Unavailable"] = Unavailable; /** Other/generic 5xx. */ const InternalError = 'internal_error'; SpanStatus["InternalError"] = InternalError; /** Unknown. Any non-standard HTTP status code. */ const UnknownError = 'unknown_error'; SpanStatus["UnknownError"] = UnknownError; /** The operation was cancelled (typically by the user). */ const Cancelled = 'cancelled'; SpanStatus["Cancelled"] = Cancelled; /** Already exists (409) */ const AlreadyExists = 'already_exists'; SpanStatus["AlreadyExists"] = AlreadyExists; /** Operation was rejected because the system is not in a state required for the operation's */ const FailedPrecondition = 'failed_precondition'; SpanStatus["FailedPrecondition"] = FailedPrecondition; /** The operation was aborted, typically due to a concurrency issue. */ const Aborted = 'aborted'; SpanStatus["Aborted"] = Aborted; /** Operation was attempted past the valid range. */ const OutOfRange = 'out_of_range'; SpanStatus["OutOfRange"] = OutOfRange; /** Unrecoverable data loss or corruption */ const DataLoss = 'data_loss'; SpanStatus["DataLoss"] = DataLoss;})(SpanStatus || (SpanStatus = {}));
/** * Converts a HTTP status code into a {@link SpanStatusType}. * * @param httpStatus The HTTP response status code. * @returns The span status or unknown_error. */function getSpanStatusFromHttpCode(httpStatus) { if (httpStatus < 400 && httpStatus >= 100) { return 'ok'; } if (httpStatus >= 400 && httpStatus < 500) { switch (httpStatus) { case 401: return 'unauthenticated'; case 403: return 'permission_denied'; case 404: return 'not_found'; case 409: return 'already_exists'; case 413: return 'failed_precondition'; case 429: return 'resource_exhausted'; default: return 'invalid_argument'; } } if (httpStatus >= 500 && httpStatus < 600) { switch (httpStatus) { case 501: return 'unimplemented'; case 503: return 'unavailable'; case 504: return 'deadline_exceeded'; default: return 'internal_error'; } } return 'unknown_error';}
/** * Converts a HTTP status code into a {@link SpanStatusType}. * * @deprecated Use {@link spanStatusFromHttpCode} instead. * This export will be removed in v8 as the signature contains a typo. * * @param httpStatus The HTTP response status code. * @returns The span status or unknown_error. */const spanStatusfromHttpCode = getSpanStatusFromHttpCode;
/** * Sets the Http status attributes on the current span based on the http code. * Additionally, the span's status is updated, depending on the http code. */function setHttpStatus(span, httpStatus) { // TODO (v8): Remove these calls // Relay does not require us to send the status code as a tag // For now, just because users might expect it to land as a tag we keep sending it. // Same with data. // In v8, we replace both, simply with // span.setAttribute('http.response.status_code', httpStatus); // eslint-disable-next-line deprecation/deprecation span.setTag('http.status_code', String(httpStatus)); // eslint-disable-next-line deprecation/deprecation span.setData('http.response.status_code', httpStatus); const spanStatus = getSpanStatusFromHttpCode(httpStatus); if (spanStatus !== 'unknown_error') { span.setStatus(spanStatus); }}
/** * Wrap a callback function with error handling. * If an error is thrown, it will be passed to the `onError` callback and re-thrown. * * If the return value of the function is a promise, it will be handled with `maybeHandlePromiseRejection`. * * If an `onFinally` callback is provided, this will be called when the callback has finished * - so if it returns a promise, once the promise resolved/rejected, * else once the callback has finished executing. * The `onFinally` callback will _always_ be called, no matter if an error was thrown or not. */function handleCallbackErrors
( fn, onError, // eslint-disable-next-line @typescript-eslint/no-empty-function onFinally = () => {},) { let maybePromiseResult; try { maybePromiseResult = fn(); } catch (e) { onError(e); onFinally(); throw e; } return maybeHandlePromiseRejection(maybePromiseResult, onError, onFinally);}
/** * Maybe handle a promise rejection. * This expects to be given a value that _may_ be a promise, or any other value. * If it is a promise, and it rejects, it will call the `onError` callback. * Other than this, it will generally return the given value as-is. */function maybeHandlePromiseRejection( value, onError, onFinally,) { if (isThenable(value)) { // @ts-expect-error - the isThenable check returns the "wrong" type here return value.then( res => { onFinally(); return res; }, e => { onError(e); onFinally(); throw e; }, ); } onFinally(); return value;}
// Treeshakable guard to remove all code related to tracing
/** * Determines if tracing is currently enabled. * * Tracing is enabled when at least one of `tracesSampleRate` and `tracesSampler` is defined in the SDK config. */function hasTracingEnabled( maybeOptions,) { if (typeof __SENTRY_TRACING__ === 'boolean' && !__SENTRY_TRACING__) { return false; } const client = getClient(); const options = maybeOptions || (client && client.getOptions()); return !!options && (options.enableTracing || 'tracesSampleRate' in options || 'tracesSampler' in options);}
/** * Wraps a function with a transaction/span and finishes the span after the function is done. * * Note that if you have not enabled tracing extensions via `addTracingExtensions` * or you didn't set `tracesSampleRate`, this function will not generate spans * and the `span` returned from the callback will be undefined. * * This function is meant to be used internally and may break at any time. Use at your own risk. * * @internal * @private * * @deprecated Use `startSpan` instead. */function trace( context, callback, // eslint-disable-next-line @typescript-eslint/no-empty-function onError = () => {}, // eslint-disable-next-line @typescript-eslint/no-empty-function afterFinish = () => {},) { // eslint-disable-next-line deprecation/deprecation const hub = getCurrentHub(); const scope = getCurrentScope(); // eslint-disable-next-line deprecation/deprecation const parentSpan = scope.getSpan(); const spanContext = normalizeContext(context); const activeSpan = createChildSpanOrTransaction(hub, { parentSpan, spanContext, forceTransaction: false, scope, }); // eslint-disable-next-line deprecation/deprecation scope.setSpan(activeSpan); return handleCallbackErrors( () => callback(activeSpan), error => { activeSpan && activeSpan.setStatus('internal_error'); onError(error, activeSpan); }, () => { activeSpan && activeSpan.end(); // eslint-disable-next-line deprecation/deprecation scope.setSpan(parentSpan); afterFinish(); }, );}
/** * Wraps a function with a transaction/span and finishes the span after the function is done. * The created span is the active span and will be used as parent by other spans created inside the function * and can be accessed via `Sentry.getSpan()`, as long as the function is executed while the scope is active. * * If you want to create a span that is not set as active, use {@link startInactiveSpan}. * * Note that if you have not enabled tracing extensions via `addTracingExtensions` * or you didn't set `tracesSampleRate`, this function will not generate spans * and the `span` returned from the callback will be undefined. */function startSpan(context, callback) { const spanContext = normalizeContext(context); return runWithAsyncContext(() => { return withScope(context.scope, scope => { // eslint-disable-next-line deprecation/deprecation const hub = getCurrentHub(); // eslint-disable-next-line deprecation/deprecation const parentSpan = scope.getSpan(); const shouldSkipSpan = context.onlyIfParent && !parentSpan; const activeSpan = shouldSkipSpan ? undefined : createChildSpanOrTransaction(hub, { parentSpan, spanContext, forceTransaction: context.forceTransaction, scope, }); return handleCallbackErrors( () => callback(activeSpan), () => { // Only update the span status if it hasn't been changed yet if (activeSpan) { const { status } = spanToJSON(activeSpan); if (!status || status === 'ok') { activeSpan.setStatus('internal_error'); } } }, () => activeSpan && activeSpan.end(), ); }); });}
/** * Similar to `Sentry.startSpan`. Wraps a function with a transaction/span, but does not finish the span * after the function is done automatically. You'll have to call `span.end()` manually. * * The created span is the active span and will be used as parent by other spans created inside the function * and can be accessed via `Sentry.getActiveSpan()`, as long as the function is executed while the scope is active. * * Note that if you have not enabled tracing extensions via `addTracingExtensions` * or you didn't set `tracesSampleRate`, this function will not generate spans * and the `span` returned from the callback will be undefined. */function startSpanManual( context, callback,) { const spanContext = normalizeContext(context); return runWithAsyncContext(() => { return withScope(context.scope, scope => { // eslint-disable-next-line deprecation/deprecation const hub = getCurrentHub(); // eslint-disable-next-line deprecation/deprecation const parentSpan = scope.getSpan(); const shouldSkipSpan = context.onlyIfParent && !parentSpan; const activeSpan = shouldSkipSpan ? undefined : createChildSpanOrTransaction(hub, { parentSpan, spanContext, forceTransaction: context.forceTransaction, scope, }); function finishAndSetSpan() { activeSpan && activeSpan.end(); } return handleCallbackErrors( () => callback(activeSpan, finishAndSetSpan), () => { // Only update the span status if it hasn't been changed yet, and the span is not yet finished if (activeSpan && activeSpan.isRecording()) { const { status } = spanToJSON(activeSpan); if (!status || status === 'ok') { activeSpan.setStatus('internal_error'); } } }, ); }); });}
/** * Creates a span. This span is not set as active, so will not get automatic instrumentation spans * as children or be able to be accessed via `Sentry.getSpan()`. * * If you want to create a span that is set as active, use {@link startSpan}. * * Note that if you have not enabled tracing extensions via `addTracingExtensions` * or you didn't set `tracesSampleRate` or `tracesSampler`, this function will not generate spans * and the `span` returned from the callback will be undefined. */function startInactiveSpan(context) { if (!hasTracingEnabled()) { return undefined; } const spanContext = normalizeContext(context); // eslint-disable-next-line deprecation/deprecation const hub = getCurrentHub(); const parentSpan = context.scope ? // eslint-disable-next-line deprecation/deprecation context.scope.getSpan() : getActiveSpan(); const shouldSkipSpan = context.onlyIfParent && !parentSpan; if (shouldSkipSpan) { return undefined; } const scope = context.scope || getCurrentScope(); // Even though we don't actually want to make this span active on the current scope, // we need to make it active on a temporary scope that we use for event processing // as otherwise, it won't pick the correct span for the event when processing it const temporaryScope = (scope ).clone(); return createChildSpanOrTransaction(hub, { parentSpan, spanContext, forceTransaction: context.forceTransaction, scope: temporaryScope, });}
/** * Returns the currently active span. */function getActiveSpan() { // eslint-disable-next-line deprecation/deprecation return getCurrentScope().getSpan();}
const continueTrace = ( { sentryTrace, baggage, }, callback,) => { // TODO(v8): Change this function so it doesn't do anything besides setting the propagation context on the current scope: /* return withScope((scope) => { const propagationContext = propagationContextFromHeaders(sentryTrace, baggage); scope.setPropagationContext(propagationContext); return callback(); }) */ const currentScope = getCurrentScope(); // eslint-disable-next-line deprecation/deprecation const { traceparentData, dynamicSamplingContext, propagationContext } = tracingContextFromHeaders( sentryTrace, baggage, ); currentScope.setPropagationContext(propagationContext); if (DEBUG_BUILD$1 && traceparentData) { logger.log(`[Tracing] Continuing trace ${traceparentData.traceId}.`); } const transactionContext = { ...traceparentData, metadata: dropUndefinedKeys({ dynamicSamplingContext, }), }; if (!callback) { return transactionContext; } return runWithAsyncContext(() => { return callback(transactionContext); });};
function createChildSpanOrTransaction( hub, { parentSpan, spanContext, forceTransaction, scope, },) { if (!hasTracingEnabled()) { return undefined; } const isolationScope = getIsolationScope(); let span; if (parentSpan && !forceTransaction) { // eslint-disable-next-line deprecation/deprecation span = parentSpan.startChild(spanContext); } else if (parentSpan) { // If we forced a transaction but have a parent span, make sure to continue from the parent span, not the scope const dsc = getDynamicSamplingContextFromSpan(parentSpan); const { traceId, spanId: parentSpanId } = parentSpan.spanContext(); const sampled = spanIsSampled(parentSpan); // eslint-disable-next-line deprecation/deprecation span = hub.startTransaction({ traceId, parentSpanId, parentSampled: sampled, ...spanContext, metadata: { dynamicSamplingContext: dsc, // eslint-disable-next-line deprecation/deprecation ...spanContext.metadata, }, }); } else { const { traceId, dsc, parentSpanId, sampled } = { ...isolationScope.getPropagationContext(), ...scope.getPropagationContext(), }; // eslint-disable-next-line deprecation/deprecation span = hub.startTransaction({ traceId, parentSpanId, parentSampled: sampled, ...spanContext, metadata: { dynamicSamplingContext: dsc, // eslint-disable-next-line deprecation/deprecation ...spanContext.metadata, }, }); } // We always set this as active span on the scope // In the case of this being an inactive span, we ensure to pass a detached scope in here in the first place // But by having this here, we can ensure that the lookup through `getCapturedScopesOnSpan` results in the correct scope & span combo // eslint-disable-next-line deprecation/deprecation scope.setSpan(span); setCapturedScopesOnSpan(span, scope, isolationScope); return span;}
/** * This converts StartSpanOptions to TransactionContext. * For the most part (for now) we accept the same options, * but some of them need to be transformed. * * Eventually the StartSpanOptions will be more aligned with OpenTelemetry. */function normalizeContext(context) { if (context.startTime) { const ctx = { ...context }; ctx.startTimestamp = spanTimeInputToSeconds(context.startTime); delete ctx.startTime; return ctx; } return context;}
const SCOPE_ON_START_SPAN_FIELD = '_sentryScope';const ISOLATION_SCOPE_ON_START_SPAN_FIELD = '_sentryIsolationScope';
function setCapturedScopesOnSpan(span, scope, isolationScope) { if (span) { addNonEnumerableProperty(span, ISOLATION_SCOPE_ON_START_SPAN_FIELD, isolationScope); addNonEnumerableProperty(span, SCOPE_ON_START_SPAN_FIELD, scope); }}
/** * Grabs the scope and isolation scope off a span that were active when the span was started. */function getCapturedScopesOnSpan(span) { return { scope: (span )[SCOPE_ON_START_SPAN_FIELD], isolationScope: (span )[ISOLATION_SCOPE_ON_START_SPAN_FIELD], };}
/** * key: bucketKey * value: [exportKey, MetricSummary] */let SPAN_METRIC_SUMMARY;
function getMetricStorageForSpan(span) { return SPAN_METRIC_SUMMARY ? SPAN_METRIC_SUMMARY.get(span) : undefined;}
/** * Fetches the metric summary if it exists for the passed span */function getMetricSummaryJsonForSpan(span) { const storage = getMetricStorageForSpan(span); if (!storage) { return undefined; } const output = {}; for (const [, [exportKey, summary]] of storage) { if (!output[exportKey]) { output[exportKey] = []; } output[exportKey].push(dropUndefinedKeys(summary)); } return output;}
/** * Updates the metric summary on the currently active span */function updateMetricSummaryOnActiveSpan( metricType, sanitizedName, value, unit, tags, bucketKey,) { const span = getActiveSpan(); if (span) { const storage = getMetricStorageForSpan(span) || new Map(); const exportKey = `${metricType}:${sanitizedName}@${unit}`; const bucketItem = storage.get(bucketKey); if (bucketItem) { const [, summary] = bucketItem; storage.set(bucketKey, [ exportKey, { min: Math.min(summary.min, value), max: Math.max(summary.max, value), count: (summary.count += 1), sum: (summary.sum += value), tags: summary.tags, }, ]); } else { storage.set(bucketKey, [ exportKey, { min: value, max: value, count: 1, sum: value, tags, }, ]); } if (!SPAN_METRIC_SUMMARY) { SPAN_METRIC_SUMMARY = new WeakMap(); } SPAN_METRIC_SUMMARY.set(span, storage); }}
/** * Use this attribute to represent the source of a span. * Should be one of: custom, url, route, view, component, task, unknown * */const SEMANTIC_ATTRIBUTE_SENTRY_SOURCE = 'sentry.source';
/** * Use this attribute to represent the sample rate used for a span. */const SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE = 'sentry.sample_rate';
/** * Use this attribute to represent the operation of a span. */const SEMANTIC_ATTRIBUTE_SENTRY_OP = 'sentry.op';
/** * Use this attribute to represent the origin of a span. */const SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN = 'sentry.origin';
/** * The id of the profile that this span occured in. */const SEMANTIC_ATTRIBUTE_PROFILE_ID = 'profile_id';
/** * Keeps track of finished spans for a given transaction * @internal * @hideconstructor * @hidden */class SpanRecorder {
constructor(maxlen = 1000) { this._maxlen = maxlen; this.spans = []; } /** * This is just so that we don't run out of memory while recording a lot * of spans. At some point we just stop and flush out the start of the * trace tree (i.e.the first n spans with the smallest * start_timestamp). */ add(span) { if (this.spans.length > this._maxlen) { // eslint-disable-next-line deprecation/deprecation span.spanRecorder = undefined; } else { this.spans.push(span); } }}
/** * Span contains all data about a span */class Span { /** * Tags for the span. * @deprecated Use `spanToJSON(span).atttributes` instead. */ /** * Data for the span. * @deprecated Use `spanToJSON(span).atttributes` instead. */ // eslint-disable-next-line @typescript-eslint/no-explicit-any /** * List of spans that were finalized * * @deprecated This property will no longer be public. Span recording will be handled internally. */ /** * @inheritDoc * @deprecated Use top level `Sentry.getRootSpan()` instead */ /** * The instrumenter that created this span. * * TODO (v8): This can probably be replaced by an `instanceOf` check of the span class. * the instrumenter can only be sentry or otel so we can check the span instance * to verify which one it is and remove this field entirely. * * @deprecated This field will be removed. */ /** Epoch timestamp in seconds when the span started. */ /** Epoch timestamp in seconds when the span ended. */ /** Internal keeper of the status */ /** * You should never call the constructor manually, always use `Sentry.startTransaction()` * or call `startChild()` on an existing span. * @internal * @hideconstructor * @hidden */ constructor(spanContext = {}) { this._traceId = spanContext.traceId || uuid4(); this._spanId = spanContext.spanId || uuid4().substring(16); this._startTime = spanContext.startTimestamp || timestampInSeconds(); // eslint-disable-next-line deprecation/deprecation this.tags = spanContext.tags ? { ...spanContext.tags } : {}; // eslint-disable-next-line deprecation/deprecation this.data = spanContext.data ? { ...spanContext.data } : {}; // eslint-disable-next-line deprecation/deprecation this.instrumenter = spanContext.instrumenter || 'sentry'; this._attributes = {}; this.setAttributes({ [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: spanContext.origin || 'manual', [SEMANTIC_ATTRIBUTE_SENTRY_OP]: spanContext.op, ...spanContext.attributes, }); // eslint-disable-next-line deprecation/deprecation this._name = spanContext.name || spanContext.description; if (spanContext.parentSpanId) { this._parentSpanId = spanContext.parentSpanId; } // We want to include booleans as well here if ('sampled' in spanContext) { this._sampled = spanContext.sampled; } if (spanContext.status) { this._status = spanContext.status; } if (spanContext.endTimestamp) { this._endTime = spanContext.endTimestamp; } if (spanContext.exclusiveTime) { this._exclusiveTime = spanContext.exclusiveTime; } this._measurements = spanContext.measurements ? { ...spanContext.measurements } : {}; } // This rule conflicts with another eslint rule :( /* eslint-disable @typescript-eslint/member-ordering */ /** * An alias for `description` of the Span. * @deprecated Use `spanToJSON(span).description` instead. */ get name() { return this._name || ''; } /** * Update the name of the span. * @deprecated Use `spanToJSON(span).description` instead. */ set name(name) { this.updateName(name); } /** * Get the description of the Span. * @deprecated Use `spanToJSON(span).description` instead. */ get description() { return this._name; } /** * Get the description of the Span. * @deprecated Use `spanToJSON(span).description` instead. */ set description(description) { this._name = description; } /** * The ID of the trace. * @deprecated Use `spanContext().traceId` instead. */ get traceId() { return this._traceId; } /** * The ID of the trace. * @deprecated You cannot update the traceId of a span after span creation. */ set traceId(traceId) { this._traceId = traceId; } /** * The ID of the span. * @deprecated Use `spanContext().spanId` instead. */ get spanId() { return this._spanId; } /** * The ID of the span. * @deprecated You cannot update the spanId of a span after span creation. */ set spanId(spanId) { this._spanId = spanId; } /** * @inheritDoc * * @deprecated Use `startSpan` functions instead. */ set parentSpanId(string) { this._parentSpanId = string; } /** * @inheritDoc * * @deprecated Use `spanToJSON(span).parent_span_id` instead. */ get parentSpanId() { return this._parentSpanId; } /** * Was this span chosen to be sent as part of the sample? * @deprecated Use `isRecording()` instead. */ get sampled() { return this._sampled; } /** * Was this span chosen to be sent as part of the sample? * @deprecated You cannot update the sampling decision of a span after span creation. */ set sampled(sampled) { this._sampled = sampled; } /** * Attributes for the span. * @deprecated Use `spanToJSON(span).atttributes` instead. */ get attributes() { return this._attributes; } /** * Attributes for the span. * @deprecated Use `setAttributes()` instead. */ set attributes(attributes) { this._attributes = attributes; } /** * Timestamp in seconds (epoch time) indicating when the span started. * @deprecated Use `spanToJSON()` instead. */ get startTimestamp() { return this._startTime; } /** * Timestamp in seconds (epoch time) indicating when the span started. * @deprecated In v8, you will not be able to update the span start time after creation. */ set startTimestamp(startTime) { this._startTime = startTime; } /** * Timestamp in seconds when the span ended. * @deprecated Use `spanToJSON()` instead. */ get endTimestamp() { return this._endTime; } /** * Timestamp in seconds when the span ended. * @deprecated Set the end time via `span.end()` instead. */ set endTimestamp(endTime) { this._endTime = endTime; } /** * The status of the span. * * @deprecated Use `spanToJSON().status` instead to get the status. */ get status() { return this._status; } /** * The status of the span. * * @deprecated Use `.setStatus()` instead to set or update the status. */ set status(status) { this._status = status; } /** * Operation of the span * * @deprecated Use `spanToJSON().op` to read the op instead. */ get op() { return this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_OP] ; } /** * Operation of the span * * @deprecated Use `startSpan()` functions to set or `span.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_OP, 'op') * to update the span instead. */ set op(op) { this.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_OP, op); } /** * The origin of the span, giving context about what created the span. * * @deprecated Use `spanToJSON().origin` to read the origin instead. */ get origin() { return this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN] ; } /** * The origin of the span, giving context about what created the span. * * @deprecated Use `startSpan()` functions to set the origin instead. */ set origin(origin) { this.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, origin); } /* eslint-enable @typescript-eslint/member-ordering */ /** @inheritdoc */ spanContext() { const { _spanId: spanId, _traceId: traceId, _sampled: sampled } = this; return { spanId, traceId, traceFlags: sampled ? TRACE_FLAG_SAMPLED : TRACE_FLAG_NONE, }; } /** * Creates a new `Span` while setting the current `Span.id` as `parentSpanId`. * Also the `sampled` decision will be inherited. * * @deprecated Use `startSpan()`, `startSpanManual()` or `startInactiveSpan()` instead. */ startChild( spanContext, ) { const childSpan = new Span({ ...spanContext, parentSpanId: this._spanId, sampled: this._sampled, traceId: this._traceId, }); // eslint-disable-next-line deprecation/deprecation childSpan.spanRecorder = this.spanRecorder; // eslint-disable-next-line deprecation/deprecation if (childSpan.spanRecorder) { // eslint-disable-next-line deprecation/deprecation childSpan.spanRecorder.add(childSpan); } const rootSpan = getRootSpan(this); // TODO: still set span.transaction here until we have a more permanent solution // Probably similarly to the weakmap we hold in node-experimental // eslint-disable-next-line deprecation/deprecation childSpan.transaction = rootSpan ; if (DEBUG_BUILD$1 && rootSpan) { const opStr = (spanContext && spanContext.op) || '< unknown op >'; const nameStr = spanToJSON(childSpan).description || '< unknown name >'; const idStr = rootSpan.spanContext().spanId; const logMessage = `[Tracing] Starting '${opStr}' span on transaction '${nameStr}' (${idStr}).`; logger.log(logMessage); this._logMessage = logMessage; } return childSpan; } /** * Sets the tag attribute on the current span. * * Can also be used to unset a tag, by passing `undefined`. * * @param key Tag key * @param value Tag value * @deprecated Use `setAttribute()` instead. */ setTag(key, value) { // eslint-disable-next-line deprecation/deprecation this.tags = { ...this.tags, [key]: value }; return this; } /** * Sets the data attribute on the current span * @param key Data key * @param value Data value * @deprecated Use `setAttribute()` instead. */ // eslint-disable-next-line @typescript-eslint/no-explicit-any setData(key, value) { // eslint-disable-next-line deprecation/deprecation this.data = { ...this.data, [key]: value }; return this; } /** @inheritdoc */ setAttribute(key, value) { if (value === undefined) { // eslint-disable-next-line @typescript-eslint/no-dynamic-delete delete this._attributes[key]; } else { this._attributes[key] = value; } } /** @inheritdoc */ setAttributes(attributes) { Object.keys(attributes).forEach(key => this.setAttribute(key, attributes[key])); } /** * @inheritDoc */ setStatus(value) { this._status = value; return this; } /** * @inheritDoc * @deprecated Use top-level `setHttpStatus()` instead. */ setHttpStatus(httpStatus) { setHttpStatus(this, httpStatus); return this; } /** * @inheritdoc * * @deprecated Use `.updateName()` instead. */ setName(name) { this.updateName(name); } /** * @inheritDoc */ updateName(name) { this._name = name; return this; } /** * @inheritDoc * * @deprecated Use `spanToJSON(span).status === 'ok'` instead. */ isSuccess() { return this._status === 'ok'; } /** * @inheritDoc * * @deprecated Use `.end()` instead. */ finish(endTimestamp) { return this.end(endTimestamp); } /** @inheritdoc */ end(endTimestamp) { // If already ended, skip if (this._endTime) { return; } const rootSpan = getRootSpan(this); if ( DEBUG_BUILD$1 && // Don't call this for transactions rootSpan && rootSpan.spanContext().spanId !== this._spanId ) { const logMessage = this._logMessage; if (logMessage) { logger.log((logMessage ).replace('Starting', 'Finishing')); } } this._endTime = spanTimeInputToSeconds(endTimestamp); } /** * @inheritDoc * * @deprecated Use `spanToTraceHeader()` instead. */ toTraceparent() { return spanToTraceHeader(this); } /** * @inheritDoc * * @deprecated Use `spanToJSON()` or access the fields directly instead. */ toContext() { return dropUndefinedKeys({ data: this._getData(), description: this._name, endTimestamp: this._endTime, // eslint-disable-next-line deprecation/deprecation op: this.op, parentSpanId: this._parentSpanId, sampled: this._sampled, spanId: this._spanId, startTimestamp: this._startTime, status: this._status, // eslint-disable-next-line deprecation/deprecation tags: this.tags, traceId: this._traceId, }); } /** * @inheritDoc * * @deprecated Update the fields directly instead. */ updateWithContext(spanContext) { // eslint-disable-next-line deprecation/deprecation this.data = spanContext.data || {}; // eslint-disable-next-line deprecation/deprecation this._name = spanContext.name || spanContext.description; this._endTime = spanContext.endTimestamp; // eslint-disable-next-line deprecation/deprecation this.op = spanContext.op; this._parentSpanId = spanContext.parentSpanId; this._sampled = spanContext.sampled; this._spanId = spanContext.spanId || this._spanId; this._startTime = spanContext.startTimestamp || this._startTime; this._status = spanContext.status; // eslint-disable-next-line deprecation/deprecation this.tags = spanContext.tags || {}; this._traceId = spanContext.traceId || this._traceId; return this; } /** * @inheritDoc * * @deprecated Use `spanToTraceContext()` util function instead. */ getTraceContext() { return spanToTraceContext(this); } /** * Get JSON representation of this span. * * @hidden * @internal This method is purely for internal purposes and should not be used outside * of SDK code. If you need to get a JSON representation of a span, * use `spanToJSON(span)` instead. */ getSpanJSON() { return dropUndefinedKeys({ data: this._getData(), description: this._name, op: this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_OP] , parent_span_id: this._parentSpanId, span_id: this._spanId, start_timestamp: this._startTime, status: this._status, // eslint-disable-next-line deprecation/deprecation tags: Object.keys(this.tags).length > 0 ? this.tags : undefined, timestamp: this._endTime, trace_id: this._traceId, origin: this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN] , _metrics_summary: getMetricSummaryJsonForSpan(this), profile_id: this._attributes[SEMANTIC_ATTRIBUTE_PROFILE_ID] , exclusive_time: this._exclusiveTime, measurements: Object.keys(this._measurements).length > 0 ? this._measurements : undefined, }); } /** @inheritdoc */ isRecording() { return !this._endTime && !!this._sampled; } /** * Convert the object to JSON. * @deprecated Use `spanToJSON(span)` instead. */ toJSON() { return this.getSpanJSON(); } /** * Get the merged data for this span. * For now, this combines `data` and `attributes` together, * until eventually we can ingest `attributes` directly. */ _getData() { // eslint-disable-next-line deprecation/deprecation const { data, _attributes: attributes } = this; const hasData = Object.keys(data).length > 0; const hasAttributes = Object.keys(attributes).length > 0; if (!hasData && !hasAttributes) { return undefined; } if (hasData && hasAttributes) { return { ...data, ...attributes, }; } return hasData ? data : attributes; }}
/** JSDoc */class Transaction extends Span { /** * The reference to the current hub. */ // DO NOT yet remove this property, it is used in a hack for v7 backwards compatibility. /** * This constructor should never be called manually. Those instrumenting tracing should use * `Sentry.startTransaction()`, and internal methods should use `hub.startTransaction()`. * @internal * @hideconstructor * @hidden * * @deprecated Transactions will be removed in v8. Use spans instead. */ constructor(transactionContext, hub) { super(transactionContext); this._contexts = {}; // eslint-disable-next-line deprecation/deprecation this._hub = hub || getCurrentHub(); this._name = transactionContext.name || ''; this._metadata = { // eslint-disable-next-line deprecation/deprecation ...transactionContext.metadata, }; this._trimEnd = transactionContext.trimEnd; // this is because transactions are also spans, and spans have a transaction pointer // TODO (v8): Replace this with another way to set the root span // eslint-disable-next-line deprecation/deprecation this.transaction = this; // If Dynamic Sampling Context is provided during the creation of the transaction, we freeze it as it usually means // there is incoming Dynamic Sampling Context. (Either through an incoming request, a baggage meta-tag, or other means) const incomingDynamicSamplingContext = this._metadata.dynamicSamplingContext; if (incomingDynamicSamplingContext) { // We shallow copy this in case anything writes to the original reference of the passed in `dynamicSamplingContext` this._frozenDynamicSamplingContext = { ...incomingDynamicSamplingContext }; } } // This sadly conflicts with the getter/setter ordering :( /* eslint-disable @typescript-eslint/member-ordering */ /** * Getter for `name` property. * @deprecated Use `spanToJSON(span).description` instead. */ get name() { return this._name; } /** * Setter for `name` property, which also sets `source` as custom. * @deprecated Use `updateName()` and `setMetadata()` instead. */ set name(newName) { // eslint-disable-next-line deprecation/deprecation this.setName(newName); } /** * Get the metadata for this transaction. * @deprecated Use `spanGetMetadata(transaction)` instead. */ get metadata() { // We merge attributes in for backwards compatibility return { // Defaults // eslint-disable-next-line deprecation/deprecation source: 'custom', spanMetadata: {}, // Legacy metadata ...this._metadata, // From attributes ...(this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE] && { source: this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE] , }), ...(this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE] && { sampleRate: this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE] , }), }; } /** * Update the metadata for this transaction. * @deprecated Use `spanGetMetadata(transaction)` instead. */ set metadata(metadata) { this._metadata = metadata; } /* eslint-enable @typescript-eslint/member-ordering */ /** * Setter for `name` property, which also sets `source` on the metadata. * * @deprecated Use `.updateName()` and `.setAttribute()` instead. */ setName(name, source = 'custom') { this._name = name; this.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, source); } /** @inheritdoc */ updateName(name) { this._name = name; return this; } /** * Attaches SpanRecorder to the span itself * @param maxlen maximum number of spans that can be recorded */ initSpanRecorder(maxlen = 1000) { // eslint-disable-next-line deprecation/deprecation if (!this.spanRecorder) { // eslint-disable-next-line deprecation/deprecation this.spanRecorder = new SpanRecorder(maxlen); } // eslint-disable-next-line deprecation/deprecation this.spanRecorder.add(this); } /** * Set the context of a transaction event. * @deprecated Use either `.setAttribute()`, or set the context on the scope before creating the transaction. */ setContext(key, context) { if (context === null) { // eslint-disable-next-line @typescript-eslint/no-dynamic-delete delete this._contexts[key]; } else { this._contexts[key] = context; } } /** * @inheritDoc * * @deprecated Use top-level `setMeasurement()` instead. */ setMeasurement(name, value, unit = '') { this._measurements[name] = { value, unit }; } /** * Store metadata on this transaction. * @deprecated Use attributes or store data on the scope instead. */ setMetadata(newMetadata) { this._metadata = { ...this._metadata, ...newMetadata }; } /** * @inheritDoc */ end(endTimestamp) { const timestampInS = spanTimeInputToSeconds(endTimestamp); const transaction = this._finishTransaction(timestampInS); if (!transaction) { return undefined; } // eslint-disable-next-line deprecation/deprecation return this._hub.captureEvent(transaction); } /** * @inheritDoc */ toContext() { // eslint-disable-next-line deprecation/deprecation const spanContext = super.toContext(); return dropUndefinedKeys({ ...spanContext, name: this._name, trimEnd: this._trimEnd, }); } /** * @inheritDoc */ updateWithContext(transactionContext) { // eslint-disable-next-line deprecation/deprecation super.updateWithContext(transactionContext); this._name = transactionContext.name || ''; this._trimEnd = transactionContext.trimEnd; return this; } /** * @inheritdoc * * @experimental * * @deprecated Use top-level `getDynamicSamplingContextFromSpan` instead. */ getDynamicSamplingContext() { return getDynamicSamplingContextFromSpan(this); } /** * Override the current hub with a new one. * Used if you want another hub to finish the transaction. * * @internal */ setHub(hub) { this._hub = hub; } /** * Get the profile id of the transaction. */ getProfileId() { if (this._contexts !== undefined && this._contexts['profile'] !== undefined) { return this._contexts['profile'].profile_id ; } return undefined; } /** * Finish the transaction & prepare the event to send to Sentry. */ _finishTransaction(endTimestamp) { // This transaction is already finished, so we should not flush it again. if (this._endTime !== undefined) { return undefined; } if (!this._name) { DEBUG_BUILD$1 && logger.warn('Transaction has no name, falling back to `<unlabeled transaction>`.'); this._name = '<unlabeled transaction>'; } // just sets the end timestamp super.end(endTimestamp); // eslint-disable-next-line deprecation/deprecation const client = this._hub.getClient(); if (client && client.emit) { client.emit('finishTransaction', this); } if (this._sampled !== true) { // At this point if `sampled !== true` we want to discard the transaction. DEBUG_BUILD$1 && logger.log('[Tracing] Discarding transaction because its trace was not chosen to be sampled.'); if (client) { client.recordDroppedEvent('sample_rate', 'transaction'); } return undefined; } // eslint-disable-next-line deprecation/deprecation const finishedSpans = this.spanRecorder ? // eslint-disable-next-line deprecation/deprecation this.spanRecorder.spans.filter(span => span !== this && spanToJSON(span).timestamp) : []; if (this._trimEnd && finishedSpans.length > 0) { const endTimes = finishedSpans.map(span => spanToJSON(span).timestamp).filter(Boolean) ; this._endTime = endTimes.reduce((prev, current) => { return prev > current ? prev : current; }); } const { scope: capturedSpanScope, isolationScope: capturedSpanIsolationScope } = getCapturedScopesOnSpan(this); // eslint-disable-next-line deprecation/deprecation const { metadata } = this; // eslint-disable-next-line deprecation/deprecation const { source } = metadata; const transaction = { contexts: { ...this._contexts, // We don't want to override trace context trace: spanToTraceContext(this), }, // TODO: Pass spans serialized via `spanToJSON()` here instead in v8. spans: finishedSpans, start_timestamp: this._startTime, // eslint-disable-next-line deprecation/deprecation tags: this.tags, timestamp: this._endTime, transaction: this._name, type: 'transaction', sdkProcessingMetadata: { ...metadata, capturedSpanScope, capturedSpanIsolationScope, ...dropUndefinedKeys({ dynamicSamplingContext: getDynamicSamplingContextFromSpan(this), }), }, _metrics_summary: getMetricSummaryJsonForSpan(this), ...(source && { transaction_info: { source, }, }), }; const hasMeasurements = Object.keys(this._measurements).length > 0; if (hasMeasurements) { DEBUG_BUILD$1 && logger.log( '[Measurements] Adding measurements to transaction', JSON.stringify(this._measurements, undefined, 2), ); transaction.measurements = this._measurements; } // eslint-disable-next-line deprecation/deprecation DEBUG_BUILD$1 && logger.log(`[Tracing] Finishing ${this.op} transaction: ${this._name}.`); return transaction; }}
/** * Makes a sampling decision for the given transaction and stores it on the transaction. * * Called every time a transaction is created. Only transactions which emerge with a `sampled` value of `true` will be * sent to Sentry. * * This method muttes the given `transaction` and will set the `sampled` value on it. * It returns the same transaction, for convenience. */function sampleTransaction( transaction, options, samplingContext,) { // nothing to do if tracing is not enabled if (!hasTracingEnabled(options)) { // eslint-disable-next-line deprecation/deprecation transaction.sampled = false; return transaction; } // if the user has forced a sampling decision by passing a `sampled` value in their transaction context, go with that // eslint-disable-next-line deprecation/deprecation if (transaction.sampled !== undefined) { // eslint-disable-next-line deprecation/deprecation transaction.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, Number(transaction.sampled)); return transaction; } // we would have bailed already if neither `tracesSampler` nor `tracesSampleRate` nor `enableTracing` were defined, so one of these should // work; prefer the hook if so let sampleRate; if (typeof options.tracesSampler === 'function') { sampleRate = options.tracesSampler(samplingContext); transaction.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, Number(sampleRate)); } else if (samplingContext.parentSampled !== undefined) { sampleRate = samplingContext.parentSampled; } else if (typeof options.tracesSampleRate !== 'undefined') { sampleRate = options.tracesSampleRate; transaction.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, Number(sampleRate)); } else { // When `enableTracing === true`, we use a sample rate of 100% sampleRate = 1; transaction.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, sampleRate); } // Since this is coming from the user (or from a function provided by the user), who knows what we might get. (The // only valid values are booleans or numbers between 0 and 1.) if (!isValidSampleRate(sampleRate)) { DEBUG_BUILD$1 && logger.warn('[Tracing] Discarding transaction because of invalid sample rate.'); // eslint-disable-next-line deprecation/deprecation transaction.sampled = false; return transaction; } // if the function returned 0 (or false), or if `tracesSampleRate` is 0, it's a sign the transaction should be dropped if (!sampleRate) { DEBUG_BUILD$1 && logger.log( `[Tracing] Discarding transaction because ${ typeof options.tracesSampler === 'function' ? 'tracesSampler returned 0 or false' : 'a negative sampling decision was inherited or tracesSampleRate is set to 0' }`, ); // eslint-disable-next-line deprecation/deprecation transaction.sampled = false; return transaction; } // Now we roll the dice. Math.random is inclusive of 0, but not of 1, so strict < is safe here. In case sampleRate is // a boolean, the < comparison will cause it to be automatically cast to 1 if it's true and 0 if it's false. // eslint-disable-next-line deprecation/deprecation transaction.sampled = Math.random() < (sampleRate ); // if we're not going to keep it, we're done // eslint-disable-next-line deprecation/deprecation if (!transaction.sampled) { DEBUG_BUILD$1 && logger.log( `[Tracing] Discarding transaction because it's not included in the random sample (sampling rate = ${Number( sampleRate, )})`, ); return transaction; } DEBUG_BUILD$1 && // eslint-disable-next-line deprecation/deprecation logger.log(`[Tracing] starting ${transaction.op} transaction - ${spanToJSON(transaction).description}`); return transaction;}
/** * Checks the given sample rate to make sure it is valid type and value (a boolean, or a number between 0 and 1). */function isValidSampleRate(rate) { // we need to check NaN explicitly because it's of type 'number' and therefore wouldn't get caught by this typecheck // eslint-disable-next-line @typescript-eslint/no-explicit-any if (isNaN$1(rate) || !(typeof rate === 'number' || typeof rate === 'boolean')) { DEBUG_BUILD$1 && logger.warn( `[Tracing] Given sample rate is invalid. Sample rate must be a boolean or a number between 0 and 1. Got ${JSON.stringify( rate, )} of type ${JSON.stringify(typeof rate)}.`, ); return false; } // in case sampleRate is a boolean, it will get automatically cast to 1 if it's true and 0 if it's false if (rate < 0 || rate > 1) { DEBUG_BUILD$1 && logger.warn(`[Tracing] Given sample rate is invalid. Sample rate must be between 0 and 1. Got ${rate}.`); return false; } return true;}
/** Returns all trace headers that are currently on the top scope. */function traceHeaders() { // eslint-disable-next-line deprecation/deprecation const scope = this.getScope(); // eslint-disable-next-line deprecation/deprecation const span = scope.getSpan(); return span ? { 'sentry-trace': spanToTraceHeader(span), } : {};}
/** * Creates a new transaction and adds a sampling decision if it doesn't yet have one. * * The Hub.startTransaction method delegates to this method to do its work, passing the Hub instance in as `this`, as if * it had been called on the hub directly. Exists as a separate function so that it can be injected into the class as an * "extension method." * * @param this: The Hub starting the transaction * @param transactionContext: Data used to configure the transaction * @param CustomSamplingContext: Optional data to be provided to the `tracesSampler` function (if any) * * @returns The new transaction * * @see {@link Hub.startTransaction} */function _startTransaction(
transactionContext, customSamplingContext,) { // eslint-disable-next-line deprecation/deprecation const client = this.getClient(); const options = (client && client.getOptions()) || {}; const configInstrumenter = options.instrumenter || 'sentry'; const transactionInstrumenter = transactionContext.instrumenter || 'sentry'; if (configInstrumenter !== transactionInstrumenter) { DEBUG_BUILD$1 && logger.error( `A transaction was started with instrumenter=\`${transactionInstrumenter}\`, but the SDK is configured with the \`${configInstrumenter}\` instrumenter.The transaction will not be sampled. Please use the ${configInstrumenter} instrumentation to start transactions.`, ); // eslint-disable-next-line deprecation/deprecation transactionContext.sampled = false; } // eslint-disable-next-line deprecation/deprecation let transaction = new Transaction(transactionContext, this); transaction = sampleTransaction(transaction, options, { name: transactionContext.name, parentSampled: transactionContext.parentSampled, transactionContext, attributes: { // eslint-disable-next-line deprecation/deprecation ...transactionContext.data, ...transactionContext.attributes, }, ...customSamplingContext, }); if (transaction.isRecording()) { transaction.initSpanRecorder(options._experiments && (options._experiments.maxSpans )); } if (client && client.emit) { client.emit('startTransaction', transaction); } return transaction;}
/** * Adds tracing extensions to the global hub. */function addTracingExtensions() { const carrier = getMainCarrier(); if (!carrier.__SENTRY__) { return; } carrier.__SENTRY__.extensions = carrier.__SENTRY__.extensions || {}; if (!carrier.__SENTRY__.extensions.startTransaction) { carrier.__SENTRY__.extensions.startTransaction = _startTransaction; } if (!carrier.__SENTRY__.extensions.traceHeaders) { carrier.__SENTRY__.extensions.traceHeaders = traceHeaders; } registerErrorInstrumentation();}
/** * Adds a measurement to the current active transaction. */function setMeasurement(name, value, unit) { // eslint-disable-next-line deprecation/deprecation const transaction = getActiveTransaction(); if (transaction) { // eslint-disable-next-line deprecation/deprecation transaction.setMeasurement(name, value, unit); }}
/** * Apply SdkInfo (name, version, packages, integrations) to the corresponding event key. * Merge with existing data if any. **/function enhanceEventWithSdkInfo(event, sdkInfo) { if (!sdkInfo) { return event; } event.sdk = event.sdk || {}; event.sdk.name = event.sdk.name || sdkInfo.name; event.sdk.version = event.sdk.version || sdkInfo.version; event.sdk.integrations = [...(event.sdk.integrations || []), ...(sdkInfo.integrations || [])]; event.sdk.packages = [...(event.sdk.packages || []), ...(sdkInfo.packages || [])]; return event;}
/** Creates an envelope from a Session */function createSessionEnvelope( session, dsn, metadata, tunnel,) { const sdkInfo = getSdkMetadataForEnvelopeHeader(metadata); const envelopeHeaders = { sent_at: new Date().toISOString(), ...(sdkInfo && { sdk: sdkInfo }), ...(!!tunnel && dsn && { dsn: dsnToString(dsn) }), }; const envelopeItem = 'aggregates' in session ? [{ type: 'sessions' }, session] : [{ type: 'session' }, session.toJSON()]; return createEnvelope(envelopeHeaders, [envelopeItem]);}
/** * Create an Envelope from an event. */function createEventEnvelope( event, dsn, metadata, tunnel,) { const sdkInfo = getSdkMetadataForEnvelopeHeader(metadata); /* Note: Due to TS, event.type may be `replay_event`, theoretically. In practice, we never call `createEventEnvelope` with `replay_event` type, and we'd have to adjut a looot of types to make this work properly. We want to avoid casting this around, as that could lead to bugs (e.g. when we add another type) So the safe choice is to really guard against the replay_event type here. */ const eventType = event.type && event.type !== 'replay_event' ? event.type : 'event'; enhanceEventWithSdkInfo(event, metadata && metadata.sdk); const envelopeHeaders = createEventEnvelopeHeaders(event, sdkInfo, tunnel, dsn); // Prevent this data (which, if it exists, was used in earlier steps in the processing pipeline) from being sent to // sentry. (Note: Our use of this property comes and goes with whatever we might be debugging, whatever hacks we may // 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 // of this `delete`, lest we miss putting it back in the next time the property is in use.) delete event.sdkProcessingMetadata; const eventItem = [{ type: eventType }, event]; return createEnvelope(envelopeHeaders, [eventItem]);}
/** * @inheritdoc */class SessionFlusher {
constructor(client, attrs) { this._client = client; this.flushTimeout = 60; this._pendingAggregates = {}; this._isEnabled = true; // Call to setInterval, so that flush is called every 60 seconds this._intervalId = setInterval(() => this.flush(), this.flushTimeout * 1000); this._sessionAttrs = attrs; } /** Checks if `pendingAggregates` has entries, and if it does flushes them by calling `sendSession` */ flush() { const sessionAggregates = this.getSessionAggregates(); if (sessionAggregates.aggregates.length === 0) { return; } this._pendingAggregates = {}; this._client.sendSession(sessionAggregates); } /** Massages the entries in `pendingAggregates` and returns aggregated sessions */ getSessionAggregates() { const aggregates = Object.keys(this._pendingAggregates).map((key) => { return this._pendingAggregates[parseInt(key)]; }); const sessionAggregates = { attrs: this._sessionAttrs, aggregates, }; return dropUndefinedKeys(sessionAggregates); } /** JSDoc */ close() { clearInterval(this._intervalId); this._isEnabled = false; this.flush(); } /** * Wrapper function for _incrementSessionStatusCount that checks if the instance of SessionFlusher is enabled then * fetches the session status of the request from `Scope.getRequestSession().status` on the scope and passes them to * `_incrementSessionStatusCount` along with the start date */ incrementSessionStatusCount() { if (!this._isEnabled) { return; } const scope = getCurrentScope(); const requestSession = scope.getRequestSession(); if (requestSession && requestSession.status) { this._incrementSessionStatusCount(requestSession.status, new Date()); // This is not entirely necessarily but is added as a safe guard to indicate the bounds of a request and so in // case captureRequestSession is called more than once to prevent double count scope.setRequestSession(undefined); /* eslint-enable @typescript-eslint/no-unsafe-member-access */ } } /** * Increments status bucket in pendingAggregates buffer (internal state) corresponding to status of * the session received */ _incrementSessionStatusCount(status, date) { // Truncate minutes and seconds on Session Started attribute to have one minute bucket keys const sessionStartedTrunc = new Date(date).setSeconds(0, 0); this._pendingAggregates[sessionStartedTrunc] = this._pendingAggregates[sessionStartedTrunc] || {}; // corresponds to aggregated sessions in one specific minute bucket // for example, {"started":"2021-03-16T08:00:00.000Z","exited":4, "errored": 1} const aggregationCounts = this._pendingAggregates[sessionStartedTrunc]; if (!aggregationCounts.started) { aggregationCounts.started = new Date(sessionStartedTrunc).toISOString(); } switch (status) { case 'errored': aggregationCounts.errored = (aggregationCounts.errored || 0) + 1; return aggregationCounts.errored; case 'ok': aggregationCounts.exited = (aggregationCounts.exited || 0) + 1; return aggregationCounts.exited; default: aggregationCounts.crashed = (aggregationCounts.crashed || 0) + 1; return aggregationCounts.crashed; } }}
const SENTRY_API_VERSION = '7';
/** Returns the prefix to construct Sentry ingestion API endpoints. */function getBaseApiEndpoint(dsn) { const protocol = dsn.protocol ? `${dsn.protocol}:` : ''; const port = dsn.port ? `:${dsn.port}` : ''; return `${protocol}//${dsn.host}${port}${dsn.path ? `/${dsn.path}` : ''}/api/`;}
/** Returns the ingest API endpoint for target. */function _getIngestEndpoint(dsn) { return `${getBaseApiEndpoint(dsn)}${dsn.projectId}/envelope/`;}
/** Returns a URL-encoded string with auth config suitable for a query string. */function _encodedAuth(dsn, sdkInfo) { return urlEncode({ // We send only the minimum set of required information. See // https://github.com/getsentry/sentry-javascript/issues/2572. sentry_key: dsn.publicKey, sentry_version: SENTRY_API_VERSION, ...(sdkInfo && { sentry_client: `${sdkInfo.name}/${sdkInfo.version}` }), });}
/** * Returns the envelope endpoint URL with auth in the query string. * * Sending auth as part of the query string and not as custom HTTP headers avoids CORS preflight requests. */function getEnvelopeEndpointWithUrlEncodedAuth( dsn, // TODO (v8): Remove `tunnelOrOptions` in favor of `options`, and use the substitute code below // options: ClientOptions = {} as ClientOptions, tunnelOrOptions = {} ,) { // TODO (v8): Use this code instead // const { tunnel, _metadata = {} } = options; // return tunnel ? tunnel : `${_getIngestEndpoint(dsn)}?${_encodedAuth(dsn, _metadata.sdk)}`; const tunnel = typeof tunnelOrOptions === 'string' ? tunnelOrOptions : tunnelOrOptions.tunnel; const sdkInfo = typeof tunnelOrOptions === 'string' || !tunnelOrOptions._metadata ? undefined : tunnelOrOptions._metadata.sdk; return tunnel ? tunnel : `${_getIngestEndpoint(dsn)}?${_encodedAuth(dsn, sdkInfo)}`;}
const installedIntegrations = [];
/** Map of integrations assigned to a client */
/** * Remove duplicates from the given array, preferring the last instance of any duplicate. Not guaranteed to * preseve the order of integrations in the array. * * @private */function filterDuplicates(integrations) { const integrationsByName = {}; integrations.forEach(currentInstance => { const { name } = currentInstance; const existingInstance = integrationsByName[name]; // We want integrations later in the array to overwrite earlier ones of the same type, except that we never want a // default instance to overwrite an existing user instance if (existingInstance && !existingInstance.isDefaultInstance && currentInstance.isDefaultInstance) { return; } integrationsByName[name] = currentInstance; }); return Object.keys(integrationsByName).map(k => integrationsByName[k]);}
/** Gets integrations to install */function getIntegrationsToSetup(options) { const defaultIntegrations = options.defaultIntegrations || []; const userIntegrations = options.integrations; // We flag default instances, so that later we can tell them apart from any user-created instances of the same class defaultIntegrations.forEach(integration => { integration.isDefaultInstance = true; }); let integrations; if (Array.isArray(userIntegrations)) { integrations = [...defaultIntegrations, ...userIntegrations]; } else if (typeof userIntegrations === 'function') { integrations = arrayify(userIntegrations(defaultIntegrations)); } else { integrations = defaultIntegrations; } const finalIntegrations = filterDuplicates(integrations); // The `Debug` integration prints copies of the `event` and `hint` which will be passed to `beforeSend` or // `beforeSendTransaction`. It therefore has to run after all other integrations, so that the changes of all event // processors will be reflected in the printed values. For lack of a more elegant way to guarantee that, we therefore // locate it and, assuming it exists, pop it out of its current spot and shove it onto the end of the array. const debugIndex = findIndex(finalIntegrations, integration => integration.name === 'Debug'); if (debugIndex !== -1) { const [debugInstance] = finalIntegrations.splice(debugIndex, 1); finalIntegrations.push(debugInstance); } return finalIntegrations;}
/** * Given a list of integration instances this installs them all. When `withDefaults` is set to `true` then all default * integrations are added unless they were already provided before. * @param integrations array of integration instances * @param withDefault should enable default integrations */function setupIntegrations(client, integrations) { const integrationIndex = {}; integrations.forEach(integration => { // guard against empty provided integrations if (integration) { setupIntegration(client, integration, integrationIndex); } }); return integrationIndex;}
/** * Execute the `afterAllSetup` hooks of the given integrations. */function afterSetupIntegrations(client, integrations) { for (const integration of integrations) { // guard against empty provided integrations if (integration && integration.afterAllSetup) { integration.afterAllSetup(client); } }}
/** Setup a single integration. */function setupIntegration(client, integration, integrationIndex) { if (integrationIndex[integration.name]) { DEBUG_BUILD$1 && logger.log(`Integration skipped because it was already installed: ${integration.name}`); return; } integrationIndex[integration.name] = integration; // `setupOnce` is only called the first time if (installedIntegrations.indexOf(integration.name) === -1) { // eslint-disable-next-line deprecation/deprecation integration.setupOnce(addGlobalEventProcessor, getCurrentHub); installedIntegrations.push(integration.name); } // `setup` is run for each client if (integration.setup && typeof integration.setup === 'function') { integration.setup(client); } if (client.on && typeof integration.preprocessEvent === 'function') { const callback = integration.preprocessEvent.bind(integration) ; client.on('preprocessEvent', (event, hint) => callback(event, hint, client)); } if (client.addEventProcessor && typeof integration.processEvent === 'function') { const callback = integration.processEvent.bind(integration) ; const processor = Object.assign((event, hint) => callback(event, hint, client), { id: integration.name, }); client.addEventProcessor(processor); } DEBUG_BUILD$1 && logger.log(`Integration installed: ${integration.name}`);}
// Polyfill for Array.findIndex(), which is not supported in ES5function findIndex(arr, callback) { for (let i = 0; i < arr.length; i++) { if (callback(arr[i]) === true) { return i; } } return -1;}
/** * Convert a new integration function to the legacy class syntax. * In v8, we can remove this and instead export the integration functions directly. * * @deprecated This will be removed in v8! */function convertIntegrationFnToClass( name, fn,) { return Object.assign( function ConvertedIntegration(...args) { return fn(...args); }, { id: name }, ) ;}
/** * Define an integration function that can be used to create an integration instance. * Note that this by design hides the implementation details of the integration, as they are considered internal. */function defineIntegration(fn) { return fn;}
const COUNTER_METRIC_TYPE = 'c' ;const GAUGE_METRIC_TYPE = 'g' ;const SET_METRIC_TYPE = 's' ;const DISTRIBUTION_METRIC_TYPE = 'd' ;
/** * Normalization regex for metric names and metric tag names. * * This enforces that names and tag keys only contain alphanumeric characters, * underscores, forward slashes, periods, and dashes. * * See: https://develop.sentry.dev/sdk/metrics/#normalization */const NAME_AND_TAG_KEY_NORMALIZATION_REGEX = /[^a-zA-Z0-9_/.-]+/g;
/** * Normalization regex for metric tag values. * * This enforces that values only contain words, digits, or the following * special characters: _:/@.{}[\]$- * * See: https://develop.sentry.dev/sdk/metrics/#normalization */const TAG_VALUE_NORMALIZATION_REGEX = /[^\w\d\s_:/@.{}[\]$-]+/g;
/** * This does not match spec in https://develop.sentry.dev/sdk/metrics * but was chosen to optimize for the most common case in browser environments. */const DEFAULT_BROWSER_FLUSH_INTERVAL = 5000;
/** * SDKs are required to bucket into 10 second intervals (rollup in seconds) * which is the current lower bound of metric accuracy. */const DEFAULT_FLUSH_INTERVAL = 10000;
/** * The maximum number of metrics that should be stored in memory. */const MAX_WEIGHT = 10000;
/** * Generate bucket key from metric properties. */function getBucketKey( metricType, name, unit, tags,) { const stringifiedTags = Object.entries(dropUndefinedKeys(tags)).sort((a, b) => a[0].localeCompare(b[0])); return `${metricType}${name}${unit}${stringifiedTags}`;}
/* eslint-disable no-bitwise *//** * Simple hash function for strings. */function simpleHash(s) { let rv = 0; for (let i = 0; i < s.length; i++) { const c = s.charCodeAt(i); rv = (rv << 5) - rv + c; rv &= rv; } return rv >>> 0;}/* eslint-enable no-bitwise */
/** * Serialize metrics buckets into a string based on statsd format. * * Example of format: * metric.name@second:1:1.2|d|#a:value,b:anothervalue|T12345677 * Segments: * name: metric.name * unit: second * value: [1, 1.2] * type of metric: d (distribution) * tags: { a: value, b: anothervalue } * timestamp: 12345677 */function serializeMetricBuckets(metricBucketItems) { let out = ''; for (const item of metricBucketItems) { const tagEntries = Object.entries(item.tags); const maybeTags = tagEntries.length > 0 ? `|#${tagEntries.map(([key, value]) => `${key}:${value}`).join(',')}` : ''; out += `${item.name}@${item.unit}:${item.metric}|${item.metricType}${maybeTags}|T${item.timestamp}\n`; } return out;}
/** * Sanitizes tags. */function sanitizeTags(unsanitizedTags) { const tags = {}; for (const key in unsanitizedTags) { if (Object.prototype.hasOwnProperty.call(unsanitizedTags, key)) { const sanitizedKey = key.replace(NAME_AND_TAG_KEY_NORMALIZATION_REGEX, '_'); tags[sanitizedKey] = String(unsanitizedTags[key]).replace(TAG_VALUE_NORMALIZATION_REGEX, ''); } } return tags;}
/** * Create envelope from a metric aggregate. */function createMetricEnvelope( metricBucketItems, dsn, metadata, tunnel,) { const headers = { sent_at: new Date().toISOString(), }; if (metadata && metadata.sdk) { headers.sdk = { name: metadata.sdk.name, version: metadata.sdk.version, }; } if (!!tunnel && dsn) { headers.dsn = dsnToString(dsn); } const item = createMetricEnvelopeItem(metricBucketItems); return createEnvelope(headers, [item]);}
function createMetricEnvelopeItem(metricBucketItems) { const payload = serializeMetricBuckets(metricBucketItems); const metricHeaders = { type: 'statsd', length: payload.length, }; return [metricHeaders, payload];}
const ALREADY_SEEN_ERROR = "Not capturing exception because it's already been captured.";
/** * Base implementation for all JavaScript SDK clients. * * Call the constructor with the corresponding options * specific to the client subclass. To access these options later, use * {@link Client.getOptions}. * * If a Dsn is specified in the options, it will be parsed and stored. Use * {@link Client.getDsn} to retrieve the Dsn at any moment. In case the Dsn is * invalid, the constructor will throw a {@link SentryException}. Note that * without a valid Dsn, the SDK will not send any events to Sentry. * * Before sending an event, it is passed through * {@link BaseClient._prepareEvent} to add SDK information and scope data * (breadcrumbs and context). To add more custom information, override this * method and extend the resulting prepared event. * * To issue automatically created events (e.g. via instrumentation), use * {@link Client.captureEvent}. It will prepare the event and pass it through * the callback lifecycle. To issue auto-breadcrumbs, use * {@link Client.addBreadcrumb}. * * @example * class NodeClient extends BaseClient<NodeOptions> { * public constructor(options: NodeOptions) { * super(options); * } * * // ... * } */class BaseClient { /** * A reference to a metrics aggregator * * @experimental Note this is alpha API. It may experience breaking changes in the future. */ /** Options passed to the SDK. */ /** The client Dsn, if specified in options. Without this Dsn, the SDK will be disabled. */ /** Array of set up integrations. */ /** Indicates whether this client's integrations have been set up. */ /** Number of calls being processed */ /** Holds flushable */ // eslint-disable-next-line @typescript-eslint/ban-types /** * Initializes this client instance. * * @param options Options for the client. */ constructor(options) { this._options = options; this._integrations = {}; this._integrationsInitialized = false; this._numProcessing = 0; this._outcomes = {}; this._hooks = {}; this._eventProcessors = []; if (options.dsn) { this._dsn = makeDsn(options.dsn); } else { DEBUG_BUILD$1 && logger.warn('No DSN provided, client will not send events.'); } if (this._dsn) { const url = getEnvelopeEndpointWithUrlEncodedAuth(this._dsn, options); this._transport = options.transport({ recordDroppedEvent: this.recordDroppedEvent.bind(this), ...options.transportOptions, url, }); } } /** * @inheritDoc */ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types captureException(exception, hint, scope) { // ensure we haven't captured this very object before if (checkOrSetAlreadyCaught(exception)) { DEBUG_BUILD$1 && logger.log(ALREADY_SEEN_ERROR); return; } let eventId = hint && hint.event_id; this._process( this.eventFromException(exception, hint) .then(event => this._captureEvent(event, hint, scope)) .then(result => { eventId = result; }), ); return eventId; } /** * @inheritDoc */ captureMessage( message, // eslint-disable-next-line deprecation/deprecation level, hint, scope, ) { let eventId = hint && hint.event_id; const eventMessage = isParameterizedString(message) ? message : String(message); const promisedEvent = isPrimitive(message) ? this.eventFromMessage(eventMessage, level, hint) : this.eventFromException(message, hint); this._process( promisedEvent .then(event => this._captureEvent(event, hint, scope)) .then(result => { eventId = result; }), ); return eventId; } /** * @inheritDoc */ captureEvent(event, hint, scope) { // ensure we haven't captured this very object before if (hint && hint.originalException && checkOrSetAlreadyCaught(hint.originalException)) { DEBUG_BUILD$1 && logger.log(ALREADY_SEEN_ERROR); return; } let eventId = hint && hint.event_id; const sdkProcessingMetadata = event.sdkProcessingMetadata || {}; const capturedSpanScope = sdkProcessingMetadata.capturedSpanScope; this._process( this._captureEvent(event, hint, capturedSpanScope || scope).then(result => { eventId = result; }), ); return eventId; } /** * @inheritDoc */ captureSession(session) { if (!(typeof session.release === 'string')) { DEBUG_BUILD$1 && logger.warn('Discarded session because of missing or non-string release'); } else { this.sendSession(session); // After sending, we set init false to indicate it's not the first occurrence updateSession(session, { init: false }); } } /** * @inheritDoc */ getDsn() { return this._dsn; } /** * @inheritDoc */ getOptions() { return this._options; } /** * @see SdkMetadata in @sentry/types * * @return The metadata of the SDK */ getSdkMetadata() { return this._options._metadata; } /** * @inheritDoc */ getTransport() { return this._transport; } /** * @inheritDoc */ flush(timeout) { const transport = this._transport; if (transport) { if (this.metricsAggregator) { this.metricsAggregator.flush(); } return this._isClientDoneProcessing(timeout).then(clientFinished => { return transport.flush(timeout).then(transportFlushed => clientFinished && transportFlushed); }); } else { return resolvedSyncPromise(true); } } /** * @inheritDoc */ close(timeout) { return this.flush(timeout).then(result => { this.getOptions().enabled = false; if (this.metricsAggregator) { this.metricsAggregator.close(); } return result; }); } /** Get all installed event processors. */ getEventProcessors() { return this._eventProcessors; } /** @inheritDoc */ addEventProcessor(eventProcessor) { this._eventProcessors.push(eventProcessor); } /** * This is an internal function to setup all integrations that should run on the client. * @deprecated Use `client.init()` instead. */ setupIntegrations(forceInitialize) { if ((forceInitialize && !this._integrationsInitialized) || (this._isEnabled() && !this._integrationsInitialized)) { this._setupIntegrations(); } } /** @inheritdoc */ init() { if (this._isEnabled()) { this._setupIntegrations(); } } /** * Gets an installed integration by its `id`. * * @returns The installed integration or `undefined` if no integration with that `id` was installed. * @deprecated Use `getIntegrationByName()` instead. */ getIntegrationById(integrationId) { return this.getIntegrationByName(integrationId); } /** * Gets an installed integration by its name. * * @returns The installed integration or `undefined` if no integration with that `name` was installed. */ getIntegrationByName(integrationName) { return this._integrations[integrationName] ; } /** * Returns the client's instance of the given integration class, it any. * @deprecated Use `getIntegrationByName()` instead. */ getIntegration(integration) { try { return (this._integrations[integration.id] ) || null; } catch (_oO) { DEBUG_BUILD$1 && logger.warn(`Cannot retrieve integration ${integration.id} from the current Client`); return null; } } /** * @inheritDoc */ addIntegration(integration) { const isAlreadyInstalled = this._integrations[integration.name]; // This hook takes care of only installing if not already installed setupIntegration(this, integration, this._integrations); // Here we need to check manually to make sure to not run this multiple times if (!isAlreadyInstalled) { afterSetupIntegrations(this, [integration]); } } /** * @inheritDoc */ sendEvent(event, hint = {}) { this.emit('beforeSendEvent', event, hint); let env = createEventEnvelope(event, this._dsn, this._options._metadata, this._options.tunnel); for (const attachment of hint.attachments || []) { env = addItemToEnvelope( env, createAttachmentEnvelopeItem( attachment, this._options.transportOptions && this._options.transportOptions.textEncoder, ), ); } const promise = this._sendEnvelope(env); if (promise) { promise.then(sendResponse => this.emit('afterSendEvent', event, sendResponse), null); } } /** * @inheritDoc */ sendSession(session) { const env = createSessionEnvelope(session, this._dsn, this._options._metadata, this._options.tunnel); // _sendEnvelope should not throw // eslint-disable-next-line @typescript-eslint/no-floating-promises this._sendEnvelope(env); } /** * @inheritDoc */ recordDroppedEvent(reason, category, _event) { // Note: we use `event` in replay, where we overwrite this hook. if (this._options.sendClientReports) { // We want to track each category (error, transaction, session, replay_event) separately // but still keep the distinction between different type of outcomes. // We could use nested maps, but it's much easier to read and type this way. // A correct type for map-based implementation if we want to go that route // would be `Partial<Record<SentryRequestType, Partial<Record<Outcome, number>>>>` // With typescript 4.1 we could even use template literal types const key = `${reason}:${category}`; DEBUG_BUILD$1 && logger.log(`Adding outcome: "${key}"`); // The following works because undefined + 1 === NaN and NaN is falsy this._outcomes[key] = this._outcomes[key] + 1 || 1; } } /** * @inheritDoc */ captureAggregateMetrics(metricBucketItems) { DEBUG_BUILD$1 && logger.log(`Flushing aggregated metrics, number of metrics: ${metricBucketItems.length}`); const metricsEnvelope = createMetricEnvelope( metricBucketItems, this._dsn, this._options._metadata, this._options.tunnel, ); // _sendEnvelope should not throw // eslint-disable-next-line @typescript-eslint/no-floating-promises this._sendEnvelope(metricsEnvelope); } // Keep on() & emit() signatures in sync with types' client.ts interface /* eslint-disable @typescript-eslint/unified-signatures */ /** @inheritdoc */ /** @inheritdoc */ on(hook, callback) { if (!this._hooks[hook]) { this._hooks[hook] = []; } // @ts-expect-error We assue the types are correct this._hooks[hook].push(callback); } /** @inheritdoc */ /** @inheritdoc */ emit(hook, ...rest) { if (this._hooks[hook]) { this._hooks[hook].forEach(callback => callback(...rest)); } } /* eslint-enable @typescript-eslint/unified-signatures */ /** Setup integrations for this client. */ _setupIntegrations() { const { integrations } = this._options; this._integrations = setupIntegrations(this, integrations); afterSetupIntegrations(this, integrations); // TODO v8: We don't need this flag anymore this._integrationsInitialized = true; } /** Updates existing session based on the provided event */ _updateSessionFromEvent(session, event) { let crashed = false; let errored = false; const exceptions = event.exception && event.exception.values; if (exceptions) { errored = true; for (const ex of exceptions) { const mechanism = ex.mechanism; if (mechanism && mechanism.handled === false) { crashed = true; break; } } } // A session is updated and that session update is sent in only one of the two following scenarios: // 1. Session with non terminal status and 0 errors + an error occurred -> Will set error count to 1 and send update // 2. Session with non terminal status and 1 error + a crash occurred -> Will set status crashed and send update const sessionNonTerminal = session.status === 'ok'; const shouldUpdateAndSend = (sessionNonTerminal && session.errors === 0) || (sessionNonTerminal && crashed); if (shouldUpdateAndSend) { updateSession(session, { ...(crashed && { status: 'crashed' }), errors: session.errors || Number(errored || crashed), }); this.captureSession(session); } } /** * Determine if the client is finished processing. Returns a promise because it will wait `timeout` ms before saying * "no" (resolving to `false`) in order to give the client a chance to potentially finish first. * * @param timeout The time, in ms, after which to resolve to `false` if the client is still busy. Passing `0` (or not * passing anything) will make the promise wait as long as it takes for processing to finish before resolving to * `true`. * @returns A promise which will resolve to `true` if processing is already done or finishes before the timeout, and * `false` otherwise */ _isClientDoneProcessing(timeout) { return new SyncPromise(resolve => { let ticked = 0; const tick = 1; const interval = setInterval(() => { if (this._numProcessing == 0) { clearInterval(interval); resolve(true); } else { ticked += tick; if (timeout && ticked >= timeout) { clearInterval(interval); resolve(false); } } }, tick); }); } /** Determines whether this SDK is enabled and a transport is present. */ _isEnabled() { return this.getOptions().enabled !== false && this._transport !== undefined; } /** * Adds common information to events. * * The information includes release and environment from `options`, * breadcrumbs and context (extra, tags and user) from the scope. * * Information that is already present in the event is never overwritten. For * nested objects, such as the context, keys are merged. * * @param event The original event. * @param hint May contain additional information about the original exception. * @param scope A scope containing event metadata. * @returns A new event with more information. */ _prepareEvent( event, hint, scope, isolationScope = getIsolationScope(), ) { const options = this.getOptions(); const integrations = Object.keys(this._integrations); if (!hint.integrations && integrations.length > 0) { hint.integrations = integrations; } this.emit('preprocessEvent', event, hint); return prepareEvent(options, event, hint, scope, this, isolationScope).then(evt => { if (evt === null) { return evt; } const propagationContext = { ...isolationScope.getPropagationContext(), ...(scope ? scope.getPropagationContext() : undefined), }; const trace = evt.contexts && evt.contexts.trace; if (!trace && propagationContext) { const { traceId: trace_id, spanId, parentSpanId, dsc } = propagationContext; evt.contexts = { trace: { trace_id, span_id: spanId, parent_span_id: parentSpanId, }, ...evt.contexts, }; const dynamicSamplingContext = dsc ? dsc : getDynamicSamplingContextFromClient(trace_id, this, scope); evt.sdkProcessingMetadata = { dynamicSamplingContext, ...evt.sdkProcessingMetadata, }; } return evt; }); } /** * Processes the event and logs an error in case of rejection * @param event * @param hint * @param scope */ _captureEvent(event, hint = {}, scope) { return this._processEvent(event, hint, scope).then( finalEvent => { return finalEvent.event_id; }, reason => { if (DEBUG_BUILD$1) { // If something's gone wrong, log the error as a warning. If it's just us having used a `SentryError` for // control flow, log just the message (no stack) as a log-level log. const sentryError = reason ; if (sentryError.logLevel === 'log') { logger.log(sentryError.message); } else { logger.warn(sentryError); } } return undefined; }, ); } /** * Processes an event (either error or message) and sends it to Sentry. * * This also adds breadcrumbs and context information to the event. However, * platform specific meta data (such as the User's IP address) must be added * by the SDK implementor. * * * @param event The event to send to Sentry. * @param hint May contain additional information about the original exception. * @param scope A scope containing event metadata. * @returns A SyncPromise that resolves with the event or rejects in case event was/will not be send. */ _processEvent(event, hint, scope) { const options = this.getOptions(); const { sampleRate } = options; const isTransaction = isTransactionEvent(event); const isError = isErrorEvent(event); const eventType = event.type || 'error'; const beforeSendLabel = `before send for type \`${eventType}\``; // 1.0 === 100% events are sent // 0.0 === 0% events are sent // Sampling for transaction happens somewhere else if (isError && typeof sampleRate === 'number' && Math.random() > sampleRate) { this.recordDroppedEvent('sample_rate', 'error', event); return rejectedSyncPromise( new SentryError( `Discarding event because it's not included in the random sample (sampling rate = ${sampleRate})`, 'log', ), ); } const dataCategory = eventType === 'replay_event' ? 'replay' : eventType; const sdkProcessingMetadata = event.sdkProcessingMetadata || {}; const capturedSpanIsolationScope = sdkProcessingMetadata.capturedSpanIsolationScope; return this._prepareEvent(event, hint, scope, capturedSpanIsolationScope) .then(prepared => { if (prepared === null) { this.recordDroppedEvent('event_processor', dataCategory, event); throw new SentryError('An event processor returned `null`, will not send event.', 'log'); } const isInternalException = hint.data && (hint.data ).__sentry__ === true; if (isInternalException) { return prepared; } const result = processBeforeSend(options, prepared, hint); return _validateBeforeSendResult(result, beforeSendLabel); }) .then(processedEvent => { if (processedEvent === null) { this.recordDroppedEvent('before_send', dataCategory, event); throw new SentryError(`${beforeSendLabel} returned \`null\`, will not send event.`, 'log'); } const session = scope && scope.getSession(); if (!isTransaction && session) { this._updateSessionFromEvent(session, processedEvent); } // None of the Sentry built event processor will update transaction name, // so if the transaction name has been changed by an event processor, we know // it has to come from custom event processor added by a user const transactionInfo = processedEvent.transaction_info; if (isTransaction && transactionInfo && processedEvent.transaction !== event.transaction) { const source = 'custom'; processedEvent.transaction_info = { ...transactionInfo, source, }; } this.sendEvent(processedEvent, hint); return processedEvent; }) .then(null, reason => { if (reason instanceof SentryError) { throw reason; } this.captureException(reason, { data: { __sentry__: true, }, originalException: reason, }); throw new SentryError( `Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event.\nReason: ${reason}`, ); }); } /** * Occupies the client with processing and event */ _process(promise) { this._numProcessing++; void promise.then( value => { this._numProcessing--; return value; }, reason => { this._numProcessing--; return reason; }, ); } /** * @inheritdoc */ _sendEnvelope(envelope) { this.emit('beforeEnvelope', envelope); if (this._isEnabled() && this._transport) { return this._transport.send(envelope).then(null, reason => { DEBUG_BUILD$1 && logger.error('Error while sending event:', reason); }); } else { DEBUG_BUILD$1 && logger.error('Transport disabled'); } } /** * Clears outcomes on this client and returns them. */ _clearOutcomes() { const outcomes = this._outcomes; this._outcomes = {}; return Object.keys(outcomes).map(key => { const [reason, category] = key.split(':') ; return { reason, category, quantity: outcomes[key], }; }); } /** * @inheritDoc */ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types}
/** * Verifies that return value of configured `beforeSend` or `beforeSendTransaction` is of expected type, and returns the value if so. */function _validateBeforeSendResult( beforeSendResult, beforeSendLabel,) { const invalidValueError = `${beforeSendLabel} must return \`null\` or a valid event.`; if (isThenable(beforeSendResult)) { return beforeSendResult.then( event => { if (!isPlainObject(event) && event !== null) { throw new SentryError(invalidValueError); } return event; }, e => { throw new SentryError(`${beforeSendLabel} rejected with ${e}`); }, ); } else if (!isPlainObject(beforeSendResult) && beforeSendResult !== null) { throw new SentryError(invalidValueError); } return beforeSendResult;}
/** * Process the matching `beforeSendXXX` callback. */function processBeforeSend( options, event, hint,) { const { beforeSend, beforeSendTransaction } = options; if (isErrorEvent(event) && beforeSend) { return beforeSend(event, hint); } if (isTransactionEvent(event) && beforeSendTransaction) { return beforeSendTransaction(event, hint); } return event;}
function isErrorEvent(event) { return event.type === undefined;}
function isTransactionEvent(event) { return event.type === 'transaction';}
/** * Add an event processor to the current client. * This event processor will run for all events processed by this client. */function addEventProcessor(callback) { const client = getClient(); if (!client || !client.addEventProcessor) { return; } client.addEventProcessor(callback);}
/** * Create envelope from check in item. */function createCheckInEnvelope( checkIn, dynamicSamplingContext, metadata, tunnel, dsn,) { const headers = { sent_at: new Date().toISOString(), }; if (metadata && metadata.sdk) { headers.sdk = { name: metadata.sdk.name, version: metadata.sdk.version, }; } if (!!tunnel && !!dsn) { headers.dsn = dsnToString(dsn); } if (dynamicSamplingContext) { headers.trace = dropUndefinedKeys(dynamicSamplingContext) ; } const item = createCheckInEnvelopeItem(checkIn); return createEnvelope(headers, [item]);}
function createCheckInEnvelopeItem(checkIn) { const checkInHeaders = { type: 'check_in', }; return [checkInHeaders, checkIn];}
/** * A metric instance representing a counter. */class CounterMetric { constructor( _value) {this._value = _value;} /** @inheritDoc */ get weight() { return 1; } /** @inheritdoc */ add(value) { this._value += value; } /** @inheritdoc */ toString() { return `${this._value}`; }}
/** * A metric instance representing a gauge. */class GaugeMetric {
constructor(value) { this._last = value; this._min = value; this._max = value; this._sum = value; this._count = 1; } /** @inheritDoc */ get weight() { return 5; } /** @inheritdoc */ add(value) { this._last = value; if (value < this._min) { this._min = value; } if (value > this._max) { this._max = value; } this._sum += value; this._count++; } /** @inheritdoc */ toString() { return `${this._last}:${this._min}:${this._max}:${this._sum}:${this._count}`; }}
/** * A metric instance representing a distribution. */class DistributionMetric {
constructor(first) { this._value = [first]; } /** @inheritDoc */ get weight() { return this._value.length; } /** @inheritdoc */ add(value) { this._value.push(value); } /** @inheritdoc */ toString() { return this._value.join(':'); }}
/** * A metric instance representing a set. */class SetMetric {
constructor( first) {this.first = first; this._value = new Set([first]); } /** @inheritDoc */ get weight() { return this._value.size; } /** @inheritdoc */ add(value) { this._value.add(value); } /** @inheritdoc */ toString() { return Array.from(this._value) .map(val => (typeof val === 'string' ? simpleHash(val) : val)) .join(':'); }}
const METRIC_MAP = { [COUNTER_METRIC_TYPE]: CounterMetric, [GAUGE_METRIC_TYPE]: GaugeMetric, [DISTRIBUTION_METRIC_TYPE]: DistributionMetric, [SET_METRIC_TYPE]: SetMetric,};
/** * A metrics aggregator that aggregates metrics in memory and flushes them periodically. */class MetricsAggregator$1 { // TODO(@anonrig): Use FinalizationRegistry to have a proper way of flushing the buckets // when the aggregator is garbage collected. // Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry // Different metrics have different weights. We use this to limit the number of metrics // that we store in memory. // SDKs are required to shift the flush interval by random() * rollup_in_seconds. // That shift is determined once per startup to create jittering. // An SDK is required to perform force flushing ahead of scheduled time if the memory // pressure is too high. There is no rule for this other than that SDKs should be tracking // abstract aggregation complexity (eg: a counter only carries a single float, whereas a // distribution is a float per emission). // // Force flush is used on either shutdown, flush() or when we exceed the max weight. constructor( _client) {this._client = _client; this._buckets = new Map(); this._bucketsTotalWeight = 0; this._interval = setInterval(() => this._flush(), DEFAULT_FLUSH_INTERVAL); this._flushShift = Math.floor((Math.random() * DEFAULT_FLUSH_INTERVAL) / 1000); this._forceFlush = false; } /** * @inheritDoc */ add( metricType, unsanitizedName, value, unit = 'none', unsanitizedTags = {}, maybeFloatTimestamp = timestampInSeconds(), ) { const timestamp = Math.floor(maybeFloatTimestamp); const name = unsanitizedName.replace(NAME_AND_TAG_KEY_NORMALIZATION_REGEX, '_'); const tags = sanitizeTags(unsanitizedTags); const bucketKey = getBucketKey(metricType, name, unit, tags); let bucketItem = this._buckets.get(bucketKey); // If this is a set metric, we need to calculate the delta from the previous weight. const previousWeight = bucketItem && metricType === SET_METRIC_TYPE ? bucketItem.metric.weight : 0; if (bucketItem) { bucketItem.metric.add(value); // TODO(abhi): Do we need this check? if (bucketItem.timestamp < timestamp) { bucketItem.timestamp = timestamp; } } else { bucketItem = { // @ts-expect-error we don't need to narrow down the type of value here, saves bundle size. metric: new METRIC_MAP[metricType](value), timestamp, metricType, name, unit, tags, }; this._buckets.set(bucketKey, bucketItem); } // If value is a string, it's a set metric so calculate the delta from the previous weight. const val = typeof value === 'string' ? bucketItem.metric.weight - previousWeight : value; updateMetricSummaryOnActiveSpan(metricType, name, val, unit, unsanitizedTags, bucketKey); // We need to keep track of the total weight of the buckets so that we can // flush them when we exceed the max weight. this._bucketsTotalWeight += bucketItem.metric.weight; if (this._bucketsTotalWeight >= MAX_WEIGHT) { this.flush(); } } /** * Flushes the current metrics to the transport via the transport. */ flush() { this._forceFlush = true; this._flush(); } /** * Shuts down metrics aggregator and clears all metrics. */ close() { this._forceFlush = true; clearInterval(this._interval); this._flush(); } /** * Flushes the buckets according to the internal state of the aggregator. * If it is a force flush, which happens on shutdown, it will flush all buckets. * Otherwise, it will only flush buckets that are older than the flush interval, * and according to the flush shift. * * This function mutates `_forceFlush` and `_bucketsTotalWeight` properties. */ _flush() { // TODO(@anonrig): Add Atomics for locking to avoid having force flush and regular flush // running at the same time. // Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Atomics // This path eliminates the need for checking for timestamps since we're forcing a flush. // Remember to reset the flag, or it will always flush all metrics. if (this._forceFlush) { this._forceFlush = false; this._bucketsTotalWeight = 0; this._captureMetrics(this._buckets); this._buckets.clear(); return; } const cutoffSeconds = Math.floor(timestampInSeconds()) - DEFAULT_FLUSH_INTERVAL / 1000 - this._flushShift; // TODO(@anonrig): Optimization opportunity. // Convert this map to an array and store key in the bucketItem. const flushedBuckets = new Map(); for (const [key, bucket] of this._buckets) { if (bucket.timestamp <= cutoffSeconds) { flushedBuckets.set(key, bucket); this._bucketsTotalWeight -= bucket.metric.weight; } } for (const [key] of flushedBuckets) { this._buckets.delete(key); } this._captureMetrics(flushedBuckets); } /** * Only captures a subset of the buckets passed to this function. * @param flushedBuckets */ _captureMetrics(flushedBuckets) { if (flushedBuckets.size > 0 && this._client.captureAggregateMetrics) { // TODO(@anonrig): Optimization opportunity. // This copy operation can be avoided if we store the key in the bucketItem. const buckets = Array.from(flushedBuckets).map(([, bucketItem]) => bucketItem); this._client.captureAggregateMetrics(buckets); } }}
/** * The Sentry Server Runtime Client SDK. */class ServerRuntimeClient
extends BaseClient { /** * Creates a new Edge SDK instance. * @param options Configuration options for this SDK. */ constructor(options) { // Server clients always support tracing addTracingExtensions(); super(options); if (options._experiments && options._experiments['metricsAggregator']) { this.metricsAggregator = new MetricsAggregator$1(this); } } /** * @inheritDoc */ eventFromException(exception, hint) { return resolvedSyncPromise(eventFromUnknownInput(getClient(), this._options.stackParser, exception, hint)); } /** * @inheritDoc */ eventFromMessage( message, // eslint-disable-next-line deprecation/deprecation level = 'info', hint, ) { return resolvedSyncPromise( eventFromMessage(this._options.stackParser, message, level, hint, this._options.attachStacktrace), ); } /** * @inheritDoc */ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types captureException(exception, hint, scope) { // Check if the flag `autoSessionTracking` is enabled, and if `_sessionFlusher` exists because it is initialised only // when the `requestHandler` middleware is used, and hence the expectation is to have SessionAggregates payload // sent to the Server only when the `requestHandler` middleware is used if (this._options.autoSessionTracking && this._sessionFlusher && scope) { const requestSession = scope.getRequestSession(); // Necessary checks to ensure this is code block is executed only within a request // Should override the status only if `requestSession.status` is `Ok`, which is its initial stage if (requestSession && requestSession.status === 'ok') { requestSession.status = 'errored'; } } return super.captureException(exception, hint, scope); } /** * @inheritDoc */ captureEvent(event, hint, scope) { // Check if the flag `autoSessionTracking` is enabled, and if `_sessionFlusher` exists because it is initialised only // when the `requestHandler` middleware is used, and hence the expectation is to have SessionAggregates payload // sent to the Server only when the `requestHandler` middleware is used if (this._options.autoSessionTracking && this._sessionFlusher && scope) { const eventType = event.type || 'exception'; const isException = eventType === 'exception' && event.exception && event.exception.values && event.exception.values.length > 0; // If the event is of type Exception, then a request session should be captured if (isException) { const requestSession = scope.getRequestSession(); // Ensure that this is happening within the bounds of a request, and make sure not to override // Session Status if Errored / Crashed if (requestSession && requestSession.status === 'ok') { requestSession.status = 'errored'; } } } return super.captureEvent(event, hint, scope); } /** * * @inheritdoc */ close(timeout) { if (this._sessionFlusher) { this._sessionFlusher.close(); } return super.close(timeout); } /** Method that initialises an instance of SessionFlusher on Client */ initSessionFlusher() { const { release, environment } = this._options; if (!release) { DEBUG_BUILD$1 && logger.warn('Cannot initialise an instance of SessionFlusher if no release is provided!'); } else { this._sessionFlusher = new SessionFlusher(this, { release, environment, }); } } /** * Create a cron monitor check in and send it to Sentry. * * @param checkIn An object that describes a check in. * @param upsertMonitorConfig An optional object that describes a monitor config. Use this if you want * to create a monitor automatically when sending a check in. */ captureCheckIn(checkIn, monitorConfig, scope) { const id = 'checkInId' in checkIn && checkIn.checkInId ? checkIn.checkInId : uuid4(); if (!this._isEnabled()) { DEBUG_BUILD$1 && logger.warn('SDK not enabled, will not capture checkin.'); return id; } const options = this.getOptions(); const { release, environment, tunnel } = options; const serializedCheckIn = { check_in_id: id, monitor_slug: checkIn.monitorSlug, status: checkIn.status, release, environment, }; if ('duration' in checkIn) { serializedCheckIn.duration = checkIn.duration; } if (monitorConfig) { serializedCheckIn.monitor_config = { schedule: monitorConfig.schedule, checkin_margin: monitorConfig.checkinMargin, max_runtime: monitorConfig.maxRuntime, timezone: monitorConfig.timezone, }; } const [dynamicSamplingContext, traceContext] = this._getTraceInfoFromScope(scope); if (traceContext) { serializedCheckIn.contexts = { trace: traceContext, }; } const envelope = createCheckInEnvelope( serializedCheckIn, dynamicSamplingContext, this.getSdkMetadata(), tunnel, this.getDsn(), ); DEBUG_BUILD$1 && logger.info('Sending checkin:', checkIn.monitorSlug, checkIn.status); // _sendEnvelope should not throw // eslint-disable-next-line @typescript-eslint/no-floating-promises this._sendEnvelope(envelope); return id; } /** * Method responsible for capturing/ending a request session by calling `incrementSessionStatusCount` to increment * appropriate session aggregates bucket */ _captureRequestSession() { if (!this._sessionFlusher) { DEBUG_BUILD$1 && logger.warn('Discarded request mode session because autoSessionTracking option was disabled'); } else { this._sessionFlusher.incrementSessionStatusCount(); } } /** * @inheritDoc */ _prepareEvent( event, hint, scope, isolationScope, ) { if (this._options.platform) { event.platform = event.platform || this._options.platform; } if (this._options.runtime) { event.contexts = { ...event.contexts, runtime: (event.contexts || {}).runtime || this._options.runtime, }; } if (this._options.serverName) { event.server_name = event.server_name || this._options.serverName; } return super._prepareEvent(event, hint, scope, isolationScope); } /** Extract trace information from scope */ _getTraceInfoFromScope( scope, ) { if (!scope) { return [undefined, undefined]; } // eslint-disable-next-line deprecation/deprecation const span = scope.getSpan(); if (span) { const samplingContext = getRootSpan(span) ? getDynamicSamplingContextFromSpan(span) : undefined; return [samplingContext, spanToTraceContext(span)]; } const { traceId, spanId, parentSpanId, dsc } = scope.getPropagationContext(); const traceContext = { trace_id: traceId, span_id: spanId, parent_span_id: parentSpanId, }; if (dsc) { return [dsc, traceContext]; } return [getDynamicSamplingContextFromClient(traceId, this, scope), traceContext]; }}
/** A class object that can instantiate Client objects. */
/** * Internal function to create a new SDK client instance. The client is * installed and then bound to the current scope. * * @param clientClass The client class to instantiate. * @param options Options to pass to the client. */function initAndBind( clientClass, options,) { if (options.debug === true) { if (DEBUG_BUILD$1) { logger.enable(); } else { // use `console.warn` rather than `logger.warn` since by non-debug bundles have all `logger.x` statements stripped consoleSandbox(() => { // eslint-disable-next-line no-console console.warn('[Sentry] Cannot initialize SDK with `debug` option using a non-debug bundle.'); }); } } const scope = getCurrentScope(); scope.update(options.initialScope); const client = new clientClass(options); setCurrentClient(client); initializeClient(client);}
/** * Make the given client the current client. */function setCurrentClient(client) { // eslint-disable-next-line deprecation/deprecation const hub = getCurrentHub(); // eslint-disable-next-line deprecation/deprecation const top = hub.getStackTop(); top.client = client; top.scope.setClient(client);}
/** * Initialize the client for the current scope. * Make sure to call this after `setCurrentClient()`. */function initializeClient(client) { if (client.init) { client.init(); // TODO v8: Remove this fallback // eslint-disable-next-line deprecation/deprecation } else if (client.setupIntegrations) { // eslint-disable-next-line deprecation/deprecation client.setupIntegrations(); }}
const DEFAULT_TRANSPORT_BUFFER_SIZE = 30;
/** * Creates an instance of a Sentry `Transport` * * @param options * @param makeRequest */function createTransport( options, makeRequest, buffer = makePromiseBuffer( options.bufferSize || DEFAULT_TRANSPORT_BUFFER_SIZE, ),) { let rateLimits = {}; const flush = (timeout) => buffer.drain(timeout); function send(envelope) { const filteredEnvelopeItems = []; // Drop rate limited items from envelope forEachEnvelopeItem(envelope, (item, type) => { const envelopeItemDataCategory = envelopeItemTypeToDataCategory(type); if (isRateLimited(rateLimits, envelopeItemDataCategory)) { const event = getEventForEnvelopeItem(item, type); options.recordDroppedEvent('ratelimit_backoff', envelopeItemDataCategory, event); } else { filteredEnvelopeItems.push(item); } }); // Skip sending if envelope is empty after filtering out rate limited events if (filteredEnvelopeItems.length === 0) { return resolvedSyncPromise(); } // eslint-disable-next-line @typescript-eslint/no-explicit-any const filteredEnvelope = createEnvelope(envelope[0], filteredEnvelopeItems ); // Creates client report for each item in an envelope const recordEnvelopeLoss = (reason) => { forEachEnvelopeItem(filteredEnvelope, (item, type) => { const event = getEventForEnvelopeItem(item, type); options.recordDroppedEvent(reason, envelopeItemTypeToDataCategory(type), event); }); }; const requestTask = () => makeRequest({ body: serializeEnvelope(filteredEnvelope, options.textEncoder) }).then( response => { // We don't want to throw on NOK responses, but we want to at least log them if (response.statusCode !== undefined && (response.statusCode < 200 || response.statusCode >= 300)) { DEBUG_BUILD$1 && logger.warn(`Sentry responded with status code ${response.statusCode} to sent event.`); } rateLimits = updateRateLimits(rateLimits, response); return response; }, error => { recordEnvelopeLoss('network_error'); throw error; }, ); return buffer.add(requestTask).then( result => result, error => { if (error instanceof SentryError) { DEBUG_BUILD$1 && logger.error('Skipped sending event because buffer is full.'); recordEnvelopeLoss('queue_overflow'); return resolvedSyncPromise(); } else { throw error; } }, ); } // We use this to identifify if the transport is the base transport // TODO (v8): Remove this again as we'll no longer need it send.__sentry__baseTransport__ = true; return { send, flush, };}
function getEventForEnvelopeItem(item, type) { if (type !== 'event' && type !== 'transaction') { return undefined; } return Array.isArray(item) ? (item )[1] : undefined;}
const DEFAULT_OPTIONS = { include: { cookies: true, data: true, headers: true, ip: false, query_string: true, url: true, user: { id: true, username: true, email: true, }, }, transactionNamingScheme: 'methodPath',};
const INTEGRATION_NAME$b = 'RequestData';
const _requestDataIntegration = ((options = {}) => { const _addRequestData = addRequestDataToEvent; const _options = { ...DEFAULT_OPTIONS, ...options, include: { // @ts-expect-error It's mad because `method` isn't a known `include` key. (It's only here and not set by default in // `addRequestDataToEvent` for legacy reasons. TODO (v8): Change that.) method: true, ...DEFAULT_OPTIONS.include, ...options.include, user: options.include && typeof options.include.user === 'boolean' ? options.include.user : { ...DEFAULT_OPTIONS.include.user, // Unclear why TS still thinks `options.include.user` could be a boolean at this point ...((options.include || {}).user ), }, }, }; return { name: INTEGRATION_NAME$b, // TODO v8: Remove this setupOnce() {}, // eslint-disable-line @typescript-eslint/no-empty-function processEvent(event, _hint, client) { // Note: In the long run, most of the logic here should probably move into the request data utility functions. For // the moment it lives here, though, until https://github.com/getsentry/sentry-javascript/issues/5718 is addressed. // (TL;DR: Those functions touch many parts of the repo in many different ways, and need to be clened up. Once // that's happened, it will be easier to add this logic in without worrying about unexpected side effects.) const { transactionNamingScheme } = _options; const { sdkProcessingMetadata = {} } = event; const req = sdkProcessingMetadata.request; if (!req) { return event; } // The Express request handler takes a similar `include` option to that which can be passed to this integration. // If passed there, we store it in `sdkProcessingMetadata`. TODO(v8): Force express and GCP people to use this // integration, so that all of this passing and conversion isn't necessary const addRequestDataOptions = sdkProcessingMetadata.requestDataOptionsFromExpressHandler || sdkProcessingMetadata.requestDataOptionsFromGCPWrapper || convertReqDataIntegrationOptsToAddReqDataOpts(_options); const processedEvent = _addRequestData(event, req, addRequestDataOptions); // Transaction events already have the right `transaction` value if (event.type === 'transaction' || transactionNamingScheme === 'handler') { return processedEvent; } // In all other cases, use the request's associated transaction (if any) to overwrite the event's `transaction` // value with a high-quality one const reqWithTransaction = req ; const transaction = reqWithTransaction._sentryTransaction; if (transaction) { const name = spanToJSON(transaction).description || ''; // TODO (v8): Remove the nextjs check and just base it on `transactionNamingScheme` for all SDKs. (We have to // keep it the way it is for the moment, because changing the names of transactions in Sentry has the potential // to break things like alert rules.) const shouldIncludeMethodInTransactionName = getSDKName(client) === 'sentry.javascript.nextjs' ? name.startsWith('/api') : transactionNamingScheme !== 'path'; const [transactionValue] = extractPathForTransaction(req, { path: true, method: shouldIncludeMethodInTransactionName, customRoute: name, }); processedEvent.transaction = transactionValue; } return processedEvent; }, };}) ;
const requestDataIntegration = defineIntegration(_requestDataIntegration);
/** * Add data about a request to an event. Primarily for use in Node-based SDKs, but included in `@sentry/integrations` * so it can be used in cross-platform SDKs like `@sentry/nextjs`. * @deprecated Use `requestDataIntegration()` instead. */// eslint-disable-next-line deprecation/deprecationconvertIntegrationFnToClass(INTEGRATION_NAME$b, requestDataIntegration)
;
/** Convert this integration's options to match what `addRequestDataToEvent` expects *//** TODO: Can possibly be deleted once https://github.com/getsentry/sentry-javascript/issues/5718 is fixed */function convertReqDataIntegrationOptsToAddReqDataOpts( integrationOptions,) { const { transactionNamingScheme, include: { ip, user, ...requestOptions }, } = integrationOptions; const requestIncludeKeys = []; for (const [key, value] of Object.entries(requestOptions)) { if (value) { requestIncludeKeys.push(key); } } let addReqDataUserOpt; if (user === undefined) { addReqDataUserOpt = true; } else if (typeof user === 'boolean') { addReqDataUserOpt = user; } else { const userIncludeKeys = []; for (const [key, value] of Object.entries(user)) { if (value) { userIncludeKeys.push(key); } } addReqDataUserOpt = userIncludeKeys; } return { include: { ip, user: addReqDataUserOpt, request: requestIncludeKeys.length !== 0 ? requestIncludeKeys : undefined, transaction: transactionNamingScheme, }, };}
function getSDKName(client) { try { // For a long chain like this, it's fewer bytes to combine a try-catch with assuming everything is there than to // write out a long chain of `a && a.b && a.b.c && ...` // eslint-disable-next-line @typescript-eslint/no-non-null-assertion return client.getOptions()._metadata.sdk.name; } catch (err) { // In theory we should never get here return undefined; }}
// "Script error." is hard coded into browsers for errors that it can't read.// this is the result of a script being pulled in from an external domain and CORS.const DEFAULT_IGNORE_ERRORS = [ /^Script error\.?$/, /^Javascript error: Script error\.? on line 0$/, /^ResizeObserver loop completed with undelivered notifications.$/, /^Cannot redefine property: googletag$/,];
const DEFAULT_IGNORE_TRANSACTIONS = [ /^.*\/healthcheck$/, /^.*\/healthy$/, /^.*\/live$/, /^.*\/ready$/, /^.*\/heartbeat$/, /^.*\/health$/, /^.*\/healthz$/,];
/** Options for the InboundFilters integration */
const INTEGRATION_NAME$a = 'InboundFilters';const _inboundFiltersIntegration = ((options = {}) => { return { name: INTEGRATION_NAME$a, // TODO v8: Remove this setupOnce() {}, // eslint-disable-line @typescript-eslint/no-empty-function processEvent(event, _hint, client) { const clientOptions = client.getOptions(); const mergedOptions = _mergeOptions(options, clientOptions); return _shouldDropEvent$1(event, mergedOptions) ? null : event; }, };}) ;
const inboundFiltersIntegration = defineIntegration(_inboundFiltersIntegration);
/** * Inbound filters configurable by the user. * @deprecated Use `inboundFiltersIntegration()` instead. */// eslint-disable-next-line deprecation/deprecationconst InboundFilters = convertIntegrationFnToClass( INTEGRATION_NAME$a, inboundFiltersIntegration,)
;
function _mergeOptions( internalOptions = {}, clientOptions = {},) { return { allowUrls: [...(internalOptions.allowUrls || []), ...(clientOptions.allowUrls || [])], denyUrls: [...(internalOptions.denyUrls || []), ...(clientOptions.denyUrls || [])], ignoreErrors: [ ...(internalOptions.ignoreErrors || []), ...(clientOptions.ignoreErrors || []), ...(internalOptions.disableErrorDefaults ? [] : DEFAULT_IGNORE_ERRORS), ], ignoreTransactions: [ ...(internalOptions.ignoreTransactions || []), ...(clientOptions.ignoreTransactions || []), ...(internalOptions.disableTransactionDefaults ? [] : DEFAULT_IGNORE_TRANSACTIONS), ], ignoreInternal: internalOptions.ignoreInternal !== undefined ? internalOptions.ignoreInternal : true, };}
function _shouldDropEvent$1(event, options) { if (options.ignoreInternal && _isSentryError(event)) { DEBUG_BUILD$1 && logger.warn(`Event dropped due to being internal Sentry Error.\nEvent: ${getEventDescription(event)}`); return true; } if (_isIgnoredError(event, options.ignoreErrors)) { DEBUG_BUILD$1 && logger.warn( `Event dropped due to being matched by \`ignoreErrors\` option.\nEvent: ${getEventDescription(event)}`, ); return true; } if (_isIgnoredTransaction(event, options.ignoreTransactions)) { DEBUG_BUILD$1 && logger.warn( `Event dropped due to being matched by \`ignoreTransactions\` option.\nEvent: ${getEventDescription(event)}`, ); return true; } if (_isDeniedUrl(event, options.denyUrls)) { DEBUG_BUILD$1 && logger.warn( `Event dropped due to being matched by \`denyUrls\` option.\nEvent: ${getEventDescription( event, )}.\nUrl: ${_getEventFilterUrl(event)}`, ); return true; } if (!_isAllowedUrl(event, options.allowUrls)) { DEBUG_BUILD$1 && logger.warn( `Event dropped due to not being matched by \`allowUrls\` option.\nEvent: ${getEventDescription( event, )}.\nUrl: ${_getEventFilterUrl(event)}`, ); return true; } return false;}
function _isIgnoredError(event, ignoreErrors) { // If event.type, this is not an error if (event.type || !ignoreErrors || !ignoreErrors.length) { return false; } return _getPossibleEventMessages(event).some(message => stringMatchesSomePattern(message, ignoreErrors));}
function _isIgnoredTransaction(event, ignoreTransactions) { if (event.type !== 'transaction' || !ignoreTransactions || !ignoreTransactions.length) { return false; } const name = event.transaction; return name ? stringMatchesSomePattern(name, ignoreTransactions) : false;}
function _isDeniedUrl(event, denyUrls) { // TODO: Use Glob instead? if (!denyUrls || !denyUrls.length) { return false; } const url = _getEventFilterUrl(event); return !url ? false : stringMatchesSomePattern(url, denyUrls);}
function _isAllowedUrl(event, allowUrls) { // TODO: Use Glob instead? if (!allowUrls || !allowUrls.length) { return true; } const url = _getEventFilterUrl(event); return !url ? true : stringMatchesSomePattern(url, allowUrls);}
function _getPossibleEventMessages(event) { const possibleMessages = []; if (event.message) { possibleMessages.push(event.message); } let lastException; try { // @ts-expect-error Try catching to save bundle size // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access lastException = event.exception.values[event.exception.values.length - 1]; } catch (e) { // try catching to save bundle size checking existence of variables } if (lastException) { if (lastException.value) { possibleMessages.push(lastException.value); if (lastException.type) { possibleMessages.push(`${lastException.type}: ${lastException.value}`); } } } if (DEBUG_BUILD$1 && possibleMessages.length === 0) { logger.error(`Could not extract message for event ${getEventDescription(event)}`); } return possibleMessages;}
function _isSentryError(event) { try { // @ts-expect-error can't be a sentry error if undefined // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access return event.exception.values[0].type === 'SentryError'; } catch (e) { // ignore } return false;}
function _getLastValidUrl(frames = []) { for (let i = frames.length - 1; i >= 0; i--) { const frame = frames[i]; if (frame && frame.filename !== '<anonymous>' && frame.filename !== '[native code]') { return frame.filename || null; } } return null;}
function _getEventFilterUrl(event) { try { let frames; try { // @ts-expect-error we only care about frames if the whole thing here is defined frames = event.exception.values[0].stacktrace.frames; } catch (e) { // ignore } return frames ? _getLastValidUrl(frames) : null; } catch (oO) { DEBUG_BUILD$1 && logger.error(`Cannot extract url for event ${getEventDescription(event)}`); return null; }}
let originalFunctionToString;
const INTEGRATION_NAME$9 = 'FunctionToString';
const SETUP_CLIENTS$1 = new WeakMap();
const _functionToStringIntegration = (() => { return { name: INTEGRATION_NAME$9, setupOnce() { // eslint-disable-next-line @typescript-eslint/unbound-method originalFunctionToString = Function.prototype.toString; // intrinsics (like Function.prototype) might be immutable in some environments // e.g. Node with --frozen-intrinsics, XS (an embedded JavaScript engine) or SES (a JavaScript proposal) try { // eslint-disable-next-line @typescript-eslint/no-explicit-any Function.prototype.toString = function ( ...args) { const originalFunction = getOriginalFunction(this); const context = SETUP_CLIENTS$1.has(getClient() ) && originalFunction !== undefined ? originalFunction : this; return originalFunctionToString.apply(context, args); }; } catch (e) { // ignore errors here, just don't patch this } }, setup(client) { SETUP_CLIENTS$1.set(client, true); }, };}) ;
/** * Patch toString calls to return proper name for wrapped functions. * * ```js * Sentry.init({ * integrations: [ * functionToStringIntegration(), * ], * }); * ``` */const functionToStringIntegration = defineIntegration(_functionToStringIntegration);
/** * Patch toString calls to return proper name for wrapped functions. * * @deprecated Use `functionToStringIntegration()` instead. */// eslint-disable-next-line deprecation/deprecationconst FunctionToString = convertIntegrationFnToClass( INTEGRATION_NAME$9, functionToStringIntegration,) ;
const DEFAULT_KEY = 'cause';const DEFAULT_LIMIT = 5;
const INTEGRATION_NAME$8 = 'LinkedErrors';
const _linkedErrorsIntegration = ((options = {}) => { const limit = options.limit || DEFAULT_LIMIT; const key = options.key || DEFAULT_KEY; return { name: INTEGRATION_NAME$8, // TODO v8: Remove this setupOnce() {}, // eslint-disable-line @typescript-eslint/no-empty-function preprocessEvent(event, hint, client) { const options = client.getOptions(); applyAggregateErrorsToEvent( exceptionFromError, options.stackParser, options.maxValueLength, key, limit, event, hint, ); }, };}) ;
const linkedErrorsIntegration = defineIntegration(_linkedErrorsIntegration);
/** * Adds SDK info to an event. * @deprecated Use `linkedErrorsIntegration()` instead. */// eslint-disable-next-line deprecation/deprecationconst LinkedErrors = convertIntegrationFnToClass(INTEGRATION_NAME$8, linkedErrorsIntegration)
;
/* eslint-disable deprecation/deprecation */
var index = { __proto__: null, FunctionToString: FunctionToString, InboundFilters: InboundFilters, LinkedErrors: LinkedErrors};
/** * A simple metrics aggregator that aggregates metrics in memory and flushes them periodically. * Default flush interval is 5 seconds. * * @experimental This API is experimental and might change in the future. */class BrowserMetricsAggregator { // TODO(@anonrig): Use FinalizationRegistry to have a proper way of flushing the buckets // when the aggregator is garbage collected. // Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry constructor( _client) {this._client = _client; this._buckets = new Map(); this._interval = setInterval(() => this.flush(), DEFAULT_BROWSER_FLUSH_INTERVAL); } /** * @inheritDoc */ add( metricType, unsanitizedName, value, unit = 'none', unsanitizedTags = {}, maybeFloatTimestamp = timestampInSeconds(), ) { const timestamp = Math.floor(maybeFloatTimestamp); const name = unsanitizedName.replace(NAME_AND_TAG_KEY_NORMALIZATION_REGEX, '_'); const tags = sanitizeTags(unsanitizedTags); const bucketKey = getBucketKey(metricType, name, unit, tags); let bucketItem = this._buckets.get(bucketKey); // If this is a set metric, we need to calculate the delta from the previous weight. const previousWeight = bucketItem && metricType === SET_METRIC_TYPE ? bucketItem.metric.weight : 0; if (bucketItem) { bucketItem.metric.add(value); // TODO(abhi): Do we need this check? if (bucketItem.timestamp < timestamp) { bucketItem.timestamp = timestamp; } } else { bucketItem = { // @ts-expect-error we don't need to narrow down the type of value here, saves bundle size. metric: new METRIC_MAP[metricType](value), timestamp, metricType, name, unit, tags, }; this._buckets.set(bucketKey, bucketItem); } // If value is a string, it's a set metric so calculate the delta from the previous weight. const val = typeof value === 'string' ? bucketItem.metric.weight - previousWeight : value; updateMetricSummaryOnActiveSpan(metricType, name, val, unit, unsanitizedTags, bucketKey); } /** * @inheritDoc */ flush() { // short circuit if buckets are empty. if (this._buckets.size === 0) { return; } if (this._client.captureAggregateMetrics) { // TODO(@anonrig): Use Object.values() when we support ES6+ const metricBuckets = Array.from(this._buckets).map(([, bucketItem]) => bucketItem); this._client.captureAggregateMetrics(metricBuckets); } this._buckets.clear(); } /** * @inheritDoc */ close() { clearInterval(this._interval); this.flush(); }}
const INTEGRATION_NAME$7 = 'MetricsAggregator';
const _metricsAggregatorIntegration = (() => { return { name: INTEGRATION_NAME$7, // TODO v8: Remove this setupOnce() {}, // eslint-disable-line @typescript-eslint/no-empty-function setup(client) { client.metricsAggregator = new BrowserMetricsAggregator(client); }, };}) ;
const metricsAggregatorIntegration = defineIntegration(_metricsAggregatorIntegration);
/** * Enables Sentry metrics monitoring. * * @experimental This API is experimental and might having breaking changes in the future. * @deprecated Use `metricsAggegratorIntegration()` instead. */// eslint-disable-next-line deprecation/deprecationconst MetricsAggregator = convertIntegrationFnToClass( INTEGRATION_NAME$7, metricsAggregatorIntegration,) ;
function addToMetricsAggregator( metricType, name, value, data = {},) { const client = getClient(); const scope = getCurrentScope(); if (client) { if (!client.metricsAggregator) { DEBUG_BUILD$1 && logger.warn('No metrics aggregator enabled. Please add the MetricsAggregator integration to use metrics APIs'); return; } const { unit, tags, timestamp } = data; const { release, environment } = client.getOptions(); // eslint-disable-next-line deprecation/deprecation const transaction = scope.getTransaction(); const metricTags = {}; if (release) { metricTags.release = release; } if (environment) { metricTags.environment = environment; } if (transaction) { metricTags.transaction = spanToJSON(transaction).description || ''; } DEBUG_BUILD$1 && logger.log(`Adding value of ${value} to ${metricType} metric ${name}`); client.metricsAggregator.add(metricType, name, value, unit, { ...metricTags, ...tags }, timestamp); }}
/** * Adds a value to a counter metric * * @experimental This API is experimental and might have breaking changes in the future. */function increment(name, value = 1, data) { addToMetricsAggregator(COUNTER_METRIC_TYPE, name, value, data);}
/** * Adds a value to a distribution metric * * @experimental This API is experimental and might have breaking changes in the future. */function distribution(name, value, data) { addToMetricsAggregator(DISTRIBUTION_METRIC_TYPE, name, value, data);}
/** * Adds a value to a set metric. Value must be a string or integer. * * @experimental This API is experimental and might have breaking changes in the future. */function set(name, value, data) { addToMetricsAggregator(SET_METRIC_TYPE, name, value, data);}
/** * Adds a value to a gauge metric * * @experimental This API is experimental and might have breaking changes in the future. */function gauge(name, value, data) { addToMetricsAggregator(GAUGE_METRIC_TYPE, name, value, data);}
const metrics = { increment, distribution, set, gauge, /** @deprecated Use `metrics.metricsAggregratorIntegration()` instead. */ // eslint-disable-next-line deprecation/deprecation MetricsAggregator, metricsAggregatorIntegration,};
/** @deprecated Import the integration function directly, e.g. `inboundFiltersIntegration()` instead of `new Integrations.InboundFilter(). */const Integrations$1 = index;
function getHostName() { const result = Deno.permissions.querySync({ name: 'sys', kind: 'hostname' }); return result.state === 'granted' ? Deno.hostname() : undefined;}
/** * The Sentry Deno SDK Client. * * @see DenoClientOptions for documentation on configuration options. * @see SentryClient for usage documentation. */class DenoClient extends ServerRuntimeClient { /** * Creates a new Deno SDK instance. * @param options Configuration options for this SDK. */ constructor(options) { options._metadata = options._metadata || {}; options._metadata.sdk = options._metadata.sdk || { name: 'sentry.javascript.deno', packages: [ { name: 'denoland:sentry', version: SDK_VERSION, }, ], version: SDK_VERSION, }; const clientOptions = { ...options, platform: 'javascript', runtime: { name: 'deno', version: Deno.version.deno }, serverName: options.serverName || getHostName(), }; super(clientOptions); }}
const WINDOW = GLOBAL_OBJ ;
/** * 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. * * ATTENTION: This constant must never cross package boundaries (i.e. be exported) to guarantee that it can be used for tree shaking. */const DEBUG_BUILD = (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__);
/* eslint-disable max-lines */
/** maxStringLength gets capped to prevent 100 breadcrumbs exceeding 1MB event payload size */const MAX_ALLOWED_STRING_LENGTH = 1024;
const INTEGRATION_NAME$6 = 'Breadcrumbs';
const _breadcrumbsIntegration = ((options = {}) => { const _options = { console: true, dom: true, fetch: true, history: true, sentry: true, xhr: true, ...options, }; return { name: INTEGRATION_NAME$6, // TODO v8: Remove this setupOnce() {}, // eslint-disable-line @typescript-eslint/no-empty-function setup(client) { if (_options.console) { addConsoleInstrumentationHandler(_getConsoleBreadcrumbHandler(client)); } if (_options.dom) { addClickKeypressInstrumentationHandler(_getDomBreadcrumbHandler(client, _options.dom)); } if (_options.xhr) { addXhrInstrumentationHandler(_getXhrBreadcrumbHandler(client)); } if (_options.fetch) { addFetchInstrumentationHandler(_getFetchBreadcrumbHandler(client)); } if (_options.history) { addHistoryInstrumentationHandler(_getHistoryBreadcrumbHandler(client)); } if (_options.sentry && client.on) { client.on('beforeSendEvent', _getSentryBreadcrumbHandler(client)); } }, };}) ;
const breadcrumbsIntegration = defineIntegration(_breadcrumbsIntegration);
/** * Default Breadcrumbs instrumentations * * @deprecated Use `breadcrumbsIntegration()` instead. */// eslint-disable-next-line deprecation/deprecationconvertIntegrationFnToClass(INTEGRATION_NAME$6, breadcrumbsIntegration)
;
/** * Adds a breadcrumb for Sentry events or transactions if this option is enabled. */function _getSentryBreadcrumbHandler(client) { return function addSentryBreadcrumb(event) { if (getClient() !== client) { return; } addBreadcrumb( { category: `sentry.${event.type === 'transaction' ? 'transaction' : 'event'}`, event_id: event.event_id, level: event.level, message: getEventDescription(event), }, { event, }, ); };}
/** * A HOC that creaes a function that creates breadcrumbs from DOM API calls. * This is a HOC so that we get access to dom options in the closure. */function _getDomBreadcrumbHandler( client, dom,) { return function _innerDomBreadcrumb(handlerData) { if (getClient() !== client) { return; } let target; let componentName; let keyAttrs = typeof dom === 'object' ? dom.serializeAttribute : undefined; let maxStringLength = typeof dom === 'object' && typeof dom.maxStringLength === 'number' ? dom.maxStringLength : undefined; if (maxStringLength && maxStringLength > MAX_ALLOWED_STRING_LENGTH) { DEBUG_BUILD && logger.warn( `\`dom.maxStringLength\` cannot exceed ${MAX_ALLOWED_STRING_LENGTH}, but a value of ${maxStringLength} was configured. Sentry will use ${MAX_ALLOWED_STRING_LENGTH} instead.`, ); maxStringLength = MAX_ALLOWED_STRING_LENGTH; } if (typeof keyAttrs === 'string') { keyAttrs = [keyAttrs]; } // Accessing event.target can throw (see getsentry/raven-js#838, #768) try { const event = handlerData.event ; const element = _isEvent(event) ? event.target : event; target = htmlTreeAsString(element, { keyAttrs, maxStringLength }); componentName = getComponentName(element); } catch (e) { target = '<unknown>'; } if (target.length === 0) { return; } const breadcrumb = { category: `ui.${handlerData.name}`, message: target, }; if (componentName) { breadcrumb.data = { 'ui.component_name': componentName }; } addBreadcrumb(breadcrumb, { event: handlerData.event, name: handlerData.name, global: handlerData.global, }); };}
/** * Creates breadcrumbs from console API calls */function _getConsoleBreadcrumbHandler(client) { return function _consoleBreadcrumb(handlerData) { if (getClient() !== client) { return; } const breadcrumb = { category: 'console', data: { arguments: handlerData.args, logger: 'console', }, level: severityLevelFromString(handlerData.level), message: safeJoin(handlerData.args, ' '), }; if (handlerData.level === 'assert') { if (handlerData.args[0] === false) { breadcrumb.message = `Assertion failed: ${safeJoin(handlerData.args.slice(1), ' ') || 'console.assert'}`; breadcrumb.data.arguments = handlerData.args.slice(1); } else { // Don't capture a breadcrumb for passed assertions return; } } addBreadcrumb(breadcrumb, { input: handlerData.args, level: handlerData.level, }); };}
/** * Creates breadcrumbs from XHR API calls */function _getXhrBreadcrumbHandler(client) { return function _xhrBreadcrumb(handlerData) { if (getClient() !== client) { return; } const { startTimestamp, endTimestamp } = handlerData; const sentryXhrData = handlerData.xhr[SENTRY_XHR_DATA_KEY]; // We only capture complete, non-sentry requests if (!startTimestamp || !endTimestamp || !sentryXhrData) { return; } const { method, url, status_code, body } = sentryXhrData; const data = { method, url, status_code, }; const hint = { xhr: handlerData.xhr, input: body, startTimestamp, endTimestamp, }; addBreadcrumb( { category: 'xhr', data, type: 'http', }, hint, ); };}
/** * Creates breadcrumbs from fetch API calls */function _getFetchBreadcrumbHandler(client) { return function _fetchBreadcrumb(handlerData) { if (getClient() !== client) { return; } const { startTimestamp, endTimestamp } = handlerData; // We only capture complete fetch requests if (!endTimestamp) { return; } if (handlerData.fetchData.url.match(/sentry_key/) && handlerData.fetchData.method === 'POST') { // We will not create breadcrumbs for fetch requests that contain `sentry_key` (internal sentry requests) return; } if (handlerData.error) { const data = handlerData.fetchData; const hint = { data: handlerData.error, input: handlerData.args, startTimestamp, endTimestamp, }; addBreadcrumb( { category: 'fetch', data, level: 'error', type: 'http', }, hint, ); } else { const response = handlerData.response ; const data = { ...handlerData.fetchData, status_code: response && response.status, }; const hint = { input: handlerData.args, response, startTimestamp, endTimestamp, }; addBreadcrumb( { category: 'fetch', data, type: 'http', }, hint, ); } };}
/** * Creates breadcrumbs from history API calls */function _getHistoryBreadcrumbHandler(client) { return function _historyBreadcrumb(handlerData) { if (getClient() !== client) { return; } let from = handlerData.from; let to = handlerData.to; const parsedLoc = parseUrl(WINDOW.location.href); let parsedFrom = from ? parseUrl(from) : undefined; const parsedTo = parseUrl(to); // Initial pushState doesn't provide `from` information if (!parsedFrom || !parsedFrom.path) { parsedFrom = parsedLoc; } // Use only the path component of the URL if the URL matches the current // document (almost all the time when using pushState) if (parsedLoc.protocol === parsedTo.protocol && parsedLoc.host === parsedTo.host) { to = parsedTo.relative; } if (parsedLoc.protocol === parsedFrom.protocol && parsedLoc.host === parsedFrom.host) { from = parsedFrom.relative; } addBreadcrumb({ category: 'navigation', data: { from, to, }, }); };}
function _isEvent(event) { return !!event && !!(event ).target;}
const INTEGRATION_NAME$5 = 'Dedupe';
const _dedupeIntegration = (() => { let previousEvent; return { name: INTEGRATION_NAME$5, // TODO v8: Remove this setupOnce() {}, // eslint-disable-line @typescript-eslint/no-empty-function processEvent(currentEvent) { // We want to ignore any non-error type events, e.g. transactions or replays // These should never be deduped, and also not be compared against as _previousEvent. if (currentEvent.type) { return currentEvent; } // Juuust in case something goes wrong try { if (_shouldDropEvent(currentEvent, previousEvent)) { DEBUG_BUILD && logger.warn('Event dropped due to being a duplicate of previously captured event.'); return null; } } catch (_oO) {} // eslint-disable-line no-empty return (previousEvent = currentEvent); }, };}) ;
const dedupeIntegration = defineIntegration(_dedupeIntegration);
/** * Deduplication filter. * @deprecated Use `dedupeIntegration()` instead. */// eslint-disable-next-line deprecation/deprecationconvertIntegrationFnToClass(INTEGRATION_NAME$5, dedupeIntegration)
;
function _shouldDropEvent(currentEvent, previousEvent) { if (!previousEvent) { return false; } if (_isSameMessageEvent(currentEvent, previousEvent)) { return true; } if (_isSameExceptionEvent(currentEvent, previousEvent)) { return true; } return false;}
function _isSameMessageEvent(currentEvent, previousEvent) { const currentMessage = currentEvent.message; const previousMessage = previousEvent.message; // If neither event has a message property, they were both exceptions, so bail out if (!currentMessage && !previousMessage) { return false; } // If only one event has a stacktrace, but not the other one, they are not the same if ((currentMessage && !previousMessage) || (!currentMessage && previousMessage)) { return false; } if (currentMessage !== previousMessage) { return false; } if (!_isSameFingerprint(currentEvent, previousEvent)) { return false; } if (!_isSameStacktrace(currentEvent, previousEvent)) { return false; } return true;}
function _isSameExceptionEvent(currentEvent, previousEvent) { const previousException = _getExceptionFromEvent(previousEvent); const currentException = _getExceptionFromEvent(currentEvent); if (!previousException || !currentException) { return false; } if (previousException.type !== currentException.type || previousException.value !== currentException.value) { return false; } if (!_isSameFingerprint(currentEvent, previousEvent)) { return false; } if (!_isSameStacktrace(currentEvent, previousEvent)) { return false; } return true;}
function _isSameStacktrace(currentEvent, previousEvent) { let currentFrames = _getFramesFromEvent(currentEvent); let previousFrames = _getFramesFromEvent(previousEvent); // If neither event has a stacktrace, they are assumed to be the same if (!currentFrames && !previousFrames) { return true; } // If only one event has a stacktrace, but not the other one, they are not the same if ((currentFrames && !previousFrames) || (!currentFrames && previousFrames)) { return false; } currentFrames = currentFrames ; previousFrames = previousFrames ; // If number of frames differ, they are not the same if (previousFrames.length !== currentFrames.length) { return false; } // Otherwise, compare the two for (let i = 0; i < previousFrames.length; i++) { const frameA = previousFrames[i]; const frameB = currentFrames[i]; if ( frameA.filename !== frameB.filename || frameA.lineno !== frameB.lineno || frameA.colno !== frameB.colno || frameA.function !== frameB.function ) { return false; } } return true;}
function _isSameFingerprint(currentEvent, previousEvent) { let currentFingerprint = currentEvent.fingerprint; let previousFingerprint = previousEvent.fingerprint; // If neither event has a fingerprint, they are assumed to be the same if (!currentFingerprint && !previousFingerprint) { return true; } // If only one event has a fingerprint, but not the other one, they are not the same if ((currentFingerprint && !previousFingerprint) || (!currentFingerprint && previousFingerprint)) { return false; } currentFingerprint = currentFingerprint ; previousFingerprint = previousFingerprint ; // Otherwise, compare the two try { return !!(currentFingerprint.join('') === previousFingerprint.join('')); } catch (_oO) { return false; }}
function _getExceptionFromEvent(event) { return event.exception && event.exception.values && event.exception.values[0];}
function _getFramesFromEvent(event) { const exception = event.exception; if (exception) { try { // @ts-expect-error Object could be undefined return exception.values[0].stacktrace.frames; } catch (_oO) { return undefined; } } return undefined;}
const INTEGRATION_NAME$4 = 'DenoContext';
function getOSName() { switch (Deno.build.os) { case 'darwin': return 'macOS'; case 'linux': return 'Linux'; case 'windows': return 'Windows'; default: return Deno.build.os; }}
function getOSRelease() { return Deno.permissions.querySync({ name: 'sys', kind: 'osRelease' }).state === 'granted' ? Deno.osRelease() : undefined;}
async function addDenoRuntimeContext(event) { event.contexts = { ...{ app: { app_start_time: new Date(Date.now() - performance.now()).toISOString(), }, device: { arch: Deno.build.arch, // eslint-disable-next-line no-restricted-globals processor_count: navigator.hardwareConcurrency, }, os: { name: getOSName(), version: getOSRelease(), }, v8: { name: 'v8', version: Deno.version.v8, }, typescript: { name: 'TypeScript', version: Deno.version.typescript, }, }, ...event.contexts, }; return event;}
const _denoContextIntegration = (() => { return { name: INTEGRATION_NAME$4, // TODO v8: Remove this setupOnce() {}, // eslint-disable-line @typescript-eslint/no-empty-function processEvent(event) { return addDenoRuntimeContext(event); }, };}) ;
const denoContextIntegration = defineIntegration(_denoContextIntegration);
/** * Adds Deno context to events. * @deprecated Use `denoContextintegration()` instead. */// eslint-disable-next-line deprecation/deprecationconst DenoContext = convertIntegrationFnToClass(INTEGRATION_NAME$4, denoContextIntegration)
;
// eslint-disable-next-line deprecation/deprecation
const INTEGRATION_NAME$3 = 'ContextLines';const FILE_CONTENT_CACHE = new LRUMap(100);const DEFAULT_LINES_OF_CONTEXT = 7;
/** * Reads file contents and caches them in a global LRU cache. * * @param filename filepath to read content from. */async function readSourceFile(filename) { const cachedFile = FILE_CONTENT_CACHE.get(filename); // We have a cache hit if (cachedFile !== undefined) { return cachedFile; } let content = null; try { content = await Deno.readTextFile(filename); } catch (_) { // } FILE_CONTENT_CACHE.set(filename, content); return content;}










const _contextLinesIntegration = ((options = {}) => { const contextLines = options.frameContextLines !== undefined ? options.frameContextLines : DEFAULT_LINES_OF_CONTEXT; return { name: INTEGRATION_NAME$3, // TODO v8: Remove this setupOnce() {}, // eslint-disable-line @typescript-eslint/no-empty-function processEvent(event) { return addSourceContext(event, contextLines); }, };}) ;
const contextLinesIntegration = defineIntegration(_contextLinesIntegration);
/** * Add node modules / packages to the event. * @deprecated Use `contextLinesIntegration()` instead. */// eslint-disable-next-line deprecation/deprecationconst ContextLines = convertIntegrationFnToClass(INTEGRATION_NAME$3, contextLinesIntegration)
;
// eslint-disable-next-line deprecation/deprecation /** Processes an event and adds context lines */async function addSourceContext(event, contextLines) { if (contextLines > 0 && event.exception && event.exception.values) { for (const exception of event.exception.values) { if (exception.stacktrace && exception.stacktrace.frames) { await addSourceContextToFrames(exception.stacktrace.frames, contextLines); } } } return event;}
/** Adds context lines to frames */async function addSourceContextToFrames(frames, contextLines) { for (const frame of frames) { // Only add context if we have a filename and it hasn't already been added if (frame.filename && frame.in_app && frame.context_line === undefined) { const permission = await Deno.permissions.query({ name: 'read', path: frame.filename, }); if (permission.state == 'granted') { const sourceFile = await readSourceFile(frame.filename); if (sourceFile) { try { const lines = sourceFile.split('\n'); addContextToFrame(lines, frame, contextLines); } catch (_) { // anomaly, being defensive in case // unlikely to ever happen in practice but can definitely happen in theory } } } } }}
const INTEGRATION_NAME$2 = 'GlobalHandlers';let isExiting = false;
const _globalHandlersIntegration = ((options) => { const _options = { error: true, unhandledrejection: true, ...options, }; return { name: INTEGRATION_NAME$2, // TODO v8: Remove this setupOnce() {}, // eslint-disable-line @typescript-eslint/no-empty-function setup(client) { if (_options.error) { installGlobalErrorHandler(client); } if (_options.unhandledrejection) { installGlobalUnhandledRejectionHandler(client); } }, };}) ;
const globalHandlersIntegration = defineIntegration(_globalHandlersIntegration);
/** * Global handlers. * @deprecated Use `globalHandlersIntegration()` instead. */// eslint-disable-next-line deprecation/deprecationconst GlobalHandlers = convertIntegrationFnToClass( INTEGRATION_NAME$2, globalHandlersIntegration,) ;
// eslint-disable-next-line deprecation/deprecation function installGlobalErrorHandler(client) { globalThis.addEventListener('error', data => { if (getClient() !== client || isExiting) { return; } const stackParser = getStackParser(); const { message, error } = data; const event = eventFromUnknownInput(getClient(), stackParser, error || message); event.level = 'fatal'; captureEvent(event, { originalException: error, mechanism: { handled: false, type: 'error', }, }); // Stop the app from exiting for now data.preventDefault(); isExiting = true; flush().then( () => { // rethrow to replicate Deno default behavior throw error; }, () => { // rethrow to replicate Deno default behavior throw error; }, ); });}
function installGlobalUnhandledRejectionHandler(client) { globalThis.addEventListener('unhandledrejection', (e) => { if (getClient() !== client || isExiting) { return; } const stackParser = getStackParser(); let error = e; // dig the object of the rejection out of known event types try { if ('reason' in e) { error = e.reason; } } catch (_oO) { // no-empty } const event = isPrimitive(error) ? eventFromRejectionWithPrimitive(error) : eventFromUnknownInput(getClient(), stackParser, error, undefined); event.level = 'fatal'; captureEvent(event, { originalException: error, mechanism: { handled: false, type: 'unhandledrejection', }, }); // Stop the app from exiting for now e.preventDefault(); isExiting = true; flush().then( () => { // rethrow to replicate Deno default behavior throw error; }, () => { // rethrow to replicate Deno default behavior throw error; }, ); });}
/** * Create an event from a promise rejection where the `reason` is a primitive. * * @param reason: The `reason` property of the promise rejection * @returns An Event object with an appropriate `exception` value */function eventFromRejectionWithPrimitive(reason) { return { exception: { values: [ { type: 'UnhandledRejection', // String() is needed because the Primitive type includes symbols (which can't be automatically stringified) value: `Non-Error promise rejection captured with value: ${String(reason)}`, }, ], }, };}
function getStackParser() { const client = getClient(); if (!client) { return () => []; } return client.getOptions().stackParser;}
function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }const INTEGRATION_NAME$1 = 'NormalizePaths';
function appRootFromErrorStack(error) { // We know at the other end of the stack from here is the entry point that called 'init' // We assume that this stacktrace will traverse the root of the app const frames = createStackParser(nodeStackLineParser())(error.stack || ''); const paths = frames // We're only interested in frames that are in_app with filenames .filter(f => f.in_app && f.filename) .map( f => (f.filename ) .replace(/^[A-Z]:/, '') // remove Windows-style prefix .replace(/\\/g, '/') // replace all `\` instances with `/` .split('/') .filter(seg => seg !== ''), // remove empty segments ) ; if (paths.length == 0) { return undefined; } if (paths.length == 1) { // Assume the single file is in the root return dirname(paths[0].join('/')); } // Iterate over the paths and bail out when they no longer have a common root let i = 0; while (paths[0][i] && paths.every(w => w[i] === paths[0][i])) { i++; } return paths[0].slice(0, i).join('/');}
function getCwd() { // We don't want to prompt for permissions so we only get the cwd if // permissions are already granted const permission = Deno.permissions.querySync({ name: 'read', path: './' }); try { if (permission.state == 'granted') { return Deno.cwd(); } } catch (_) { // } return undefined;}
const _normalizePathsIntegration = (() => { // Cached here let appRoot; /** Get the app root, and cache it after it was first fetched. */ function getAppRoot(error) { if (appRoot === undefined) { appRoot = getCwd() || appRootFromErrorStack(error); } return appRoot; } return { name: INTEGRATION_NAME$1, // TODO v8: Remove this setupOnce() {}, // eslint-disable-line @typescript-eslint/no-empty-function processEvent(event) { // This error.stack hopefully contains paths that traverse the app cwd const error = new Error(); const appRoot = getAppRoot(error); if (appRoot) { for (const exception of _optionalChain([event, 'access', _2 => _2.exception, 'optionalAccess', _3 => _3.values]) || []) { for (const frame of _optionalChain([exception, 'access', _4 => _4.stacktrace, 'optionalAccess', _5 => _5.frames]) || []) { if (frame.filename && frame.in_app) { const startIndex = frame.filename.indexOf(appRoot); if (startIndex > -1) { const endIndex = startIndex + appRoot.length; frame.filename = `app://${frame.filename.substring(endIndex)}`; } } } } } return event; }, };}) ;
const normalizePathsIntegration = defineIntegration(_normalizePathsIntegration);
/** * Normalises paths to the app root directory. * @deprecated Use `normalizePathsIntegration()` instead. */// eslint-disable-next-line deprecation/deprecationconst NormalizePaths = convertIntegrationFnToClass( INTEGRATION_NAME$1, normalizePathsIntegration,) ;
// eslint-disable-next-line deprecation/deprecation
/** * Creates a Transport that uses the Fetch API to send events to Sentry. */function makeFetchTransport(options) { const url = new URL(options.url); if (Deno.permissions.querySync({ name: 'net', host: url.host }).state !== 'granted') { consoleSandbox(() => { // eslint-disable-next-line no-console console.warn(`Sentry SDK requires 'net' permission to send events. Run with '--allow-net=${url.host}' to grant the requires permissions.`); }); } function makeRequest(request) { const requestOptions = { body: request.body, method: 'POST', referrerPolicy: 'origin', headers: options.headers, }; try { return fetch(options.url, requestOptions).then(response => { return { statusCode: response.status, headers: { 'x-sentry-rate-limits': response.headers.get('X-Sentry-Rate-Limits'), 'retry-after': response.headers.get('Retry-After'), }, }; }); } catch (e) { return rejectedSyncPromise(e); } } return createTransport(options, makeRequest);}
/** @deprecated Use `getDefaultIntegrations(options)` instead. */const defaultIntegrations = [ // Common inboundFiltersIntegration(), functionToStringIntegration(), linkedErrorsIntegration(), // From Browser dedupeIntegration(), breadcrumbsIntegration({ dom: false, history: false, xhr: false, }), // Deno Specific denoContextIntegration(), contextLinesIntegration(), normalizePathsIntegration(), globalHandlersIntegration(),];
/** Get the default integrations for the Deno SDK. */function getDefaultIntegrations(_options) { // We return a copy of the defaultIntegrations here to avoid mutating this return [ // eslint-disable-next-line deprecation/deprecation ...defaultIntegrations, ];}
const defaultStackParser = createStackParser(nodeStackLineParser());
/** * The Sentry Deno SDK Client. * * To use this SDK, call the {@link init} function as early as possible in the * main entry module. To set context information or send manual events, use the * provided methods. * * @example * ``` * * import { init } from 'npm:@sentry/deno'; * * init({ * dsn: '__DSN__', * // ... * }); * ``` * * @example * ``` * * import { configureScope } from 'npm:@sentry/deno'; * configureScope((scope: Scope) => { * scope.setExtra({ battery: 0.7 }); * scope.setTag({ user_mode: 'admin' }); * scope.setUser({ id: '4711' }); * }); * ``` * * @example * ``` * * import { addBreadcrumb } from 'npm:@sentry/deno'; * addBreadcrumb({ * message: 'My Breadcrumb', * // ... * }); * ``` * * @example * ``` * * import * as Sentry from 'npm:@sentry/deno'; * Sentry.captureMessage('Hello, world!'); * Sentry.captureException(new Error('Good bye')); * Sentry.captureEvent({ * message: 'Manual', * stacktrace: [ * // ... * ], * }); * ``` * * @see {@link DenoOptions} for documentation on configuration options. */function init(options = {}) { if (options.defaultIntegrations === undefined) { options.defaultIntegrations = getDefaultIntegrations(); } const clientOptions = { ...options, stackParser: stackParserFromStackParserOptions(options.stackParser || defaultStackParser), integrations: getIntegrationsToSetup(options), transport: options.transport || makeFetchTransport, }; initAndBind(DenoClient, clientOptions);}
/** * These functions were copied from the Deno source code here: * https://github.com/denoland/deno/blob/cd480b481ee1b4209910aa7a8f81ffa996e7b0f9/ext/cron/01_cron.ts * Below is the original license: * * MIT License * * Copyright 2018-2023 the Deno authors * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */function formatToCronSchedule( value




,) { if (value === undefined) { return '*'; } else if (typeof value === 'number') { return value.toString(); } else { const { exact } = value ; if (exact === undefined) { const { start, end, every } = value

; if (start !== undefined && end !== undefined && every !== undefined) { return `${start}-${end}/${every}`; } else if (start !== undefined && end !== undefined) { return `${start}-${end}`; } else if (start !== undefined && every !== undefined) { return `${start}/${every}`; } else if (start !== undefined) { return `${start}/1`; } else if (end === undefined && every !== undefined) { return `*/${every}`; } else { throw new TypeError('Invalid cron schedule'); } } else { if (typeof exact === 'number') { return exact.toString(); } else { return exact.join(','); } } }}
/** */function parseScheduleToString(schedule) { if (typeof schedule === 'string') { return schedule; } else { const { minute, hour, dayOfMonth, month, dayOfWeek } = schedule; return `${formatToCronSchedule(minute)} ${formatToCronSchedule(hour)} ${formatToCronSchedule( dayOfMonth, )} ${formatToCronSchedule(month)} ${formatToCronSchedule(dayOfWeek)}`; }}
const INTEGRATION_NAME = 'DenoCron';
const SETUP_CLIENTS = new WeakMap();
const _denoCronIntegration = (() => { return { name: INTEGRATION_NAME, setupOnce() { // eslint-disable-next-line deprecation/deprecation if (!Deno.cron) { // The cron API is not available in this Deno version use --unstable flag! return; } // eslint-disable-next-line deprecation/deprecation Deno.cron = new Proxy(Deno.cron, { apply(target, thisArg, argArray) { const [monitorSlug, schedule, opt1, opt2] = argArray; let options; let fn; if (typeof opt1 === 'function' && typeof opt2 !== 'function') { fn = opt1; options = opt2; } else if (typeof opt1 !== 'function' && typeof opt2 === 'function') { fn = opt2; options = opt1; } async function cronCalled() { if (!SETUP_CLIENTS.has(getClient() )) { return fn(); } await withMonitor(monitorSlug, async () => fn(), { schedule: { type: 'crontab', value: parseScheduleToString(schedule) }, // (minutes) so 12 hours - just a very high arbitrary number since we don't know the actual duration of the users cron job maxRuntime: 60 * 12, // Deno Deploy docs say that the cron job will be called within 1 minute of the scheduled time checkinMargin: 1, }); } return target.call(thisArg, monitorSlug, schedule, options || {}, cronCalled); }, }); }, setup(client) { SETUP_CLIENTS.set(client, true); }, };}) ;
const denoCronIntegration = defineIntegration(_denoCronIntegration);
/** * Instruments Deno.cron to automatically capture cron check-ins. * @deprecated Use `denoCronIntegration()` instead. */// eslint-disable-next-line deprecation/deprecationconst DenoCron = convertIntegrationFnToClass(INTEGRATION_NAME, denoCronIntegration)
;
// eslint-disable-next-line deprecation/deprecation
/* eslint-disable deprecation/deprecation */
var DenoIntegrations = { __proto__: null, DenoContext: DenoContext, GlobalHandlers: GlobalHandlers, NormalizePaths: NormalizePaths, ContextLines: ContextLines, DenoCron: DenoCron};
/** @deprecated Import the integration function directly, e.g. `inboundFiltersIntegration()` instead of `new Integrations.InboundFilter(). */const Integrations = { // eslint-disable-next-line deprecation/deprecation ...Integrations$1, ...DenoIntegrations,};
export { DenoClient, Hub, Integrations, SDK_VERSION, SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, Scope, addBreadcrumb, addEventProcessor, addGlobalEventProcessor, breadcrumbsIntegration, captureCheckIn, captureEvent, captureException, captureMessage, captureSession, close, configureScope, contextLinesIntegration, continueTrace, createTransport, dedupeIntegration, defaultIntegrations, denoContextIntegration, denoCronIntegration, endSession, extractTraceparentData, flush, functionToStringIntegration, getActiveSpan, getActiveTransaction, getClient, getCurrentHub, getCurrentScope, getDefaultIntegrations, getGlobalScope, getHubFromCarrier, getIsolationScope, getSpanStatusFromHttpCode, globalHandlersIntegration, inboundFiltersIntegration, init, isInitialized, lastEventId, linkedErrorsIntegration, makeMain, metrics, normalizePathsIntegration, requestDataIntegration, runWithAsyncContext, setContext, setCurrentClient, setExtra, setExtras, setHttpStatus, setMeasurement, setTag, setTags, setUser, spanStatusfromHttpCode, startInactiveSpan, startSession, startSpan, startSpanManual, startTransaction, trace, withIsolationScope, withMonitor, withScope };//# sourceMappingURL=index.mjs.map